date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/20 | 1,248 | 3,300 | <issue_start>username_0: [](https://i.stack.imgur.com/vQprs.png)
I can't able to align remove icon to the top. This is what I have tried
```css
.skills ul {
width: 100%;
margin: 10px 0px 0px 0px;
padding: 0px;
float: left;
}
.skills li {
border: 1px solid #a7dbf5;
list-style: none;
text-decoration: none;
text-transform: capitalize;
padding: 7px 10px 0px 10px;
background: #bee5f9;
color: #074c6f;
font-size: 13px;
text-align: left;
float: left;
border-radius: 50px;
margin: 3px 6px;
height: 31px;
}
```
```html
* AJAX
[x](#)
* Action Script 3.0 (Mac Version)
[x](#)
```<issue_comment>username_1: Try add to your css:
```
.skills_selector {
position: relative;
}
.skills_selector a {
position: absolute;
top: 0;
left: 25px;
transform: translateY(-50%);
}
```
Upvotes: 2 <issue_comment>username_2: Try this.
```css
.skills ul {
width: 100%;
margin: 10px 0px 0px 0px;
padding: 0px;
float: left;
}
.skills li {
border: 1px solid #a7dbf5;
list-style: none;
text-decoration: none;
text-transform: capitalize;
padding: 7px 40px;
background: #bee5f9;
color: #074c6f;
font-size: 13px;
text-align: left;
float: left;
border-radius: 50px;
margin: 3px 6px;
position: relative;
}
.skills .remove {
position: absolute;
top: 0;
transform: translate(0, -50%);
color: red;
left: 20px;
text-decoration: none;
}
```
```html
* AJAX
[x](#)
* Action Script 3.0 (Mac Version)
[x](#)
```
Upvotes: 1 <issue_comment>username_3: You will need to use `position:absolute` for the close icon and use `top` and `left` values to align it...Also remember set the `position:relative` to its parent `li`
```css
.skills ul {
width: 100%;
margin: 10px 0px 0px 0px;
padding: 0px;
float: left;
}
.skills li {
border: 1px solid #a7dbf5;
list-style: none;
text-decoration: none;
text-transform: capitalize;
padding: 7px 10px 0px 10px;
background: #bee5f9;
color: #074c6f;
font-size: 13px;
text-align: left;
float: left;
border-radius: 50px;
margin: 3px 6px;
height: 31px;
position: relative;
}
.skills li a {
position: absolute;
top: -10px;
left: 0px;
background: red;
width: 20px;
height: 20px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
}
```
```html
* AJAX
[x](#)
* Action Script 3.0 (Mac Version)
[x](#)
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: Hope this will work for what you want
```
.skills ul {
width: 100%;
margin: 10px 0px 0px 0px;
padding: 0px;
float: left;
}
.skills li {
position:relative;
border: 1px solid #a7dbf5;
list-style: none;
text-decoration: none;
text-transform: capitalize;
padding: 7px 10px 0px 10px;
background: #bee5f9;
color: #074c6f;
font-size: 13px;
text-align: left;
float: left;
border-radius: 50px;
margin: 3px 6px;
height: 31px;
}
.skills li>a{
position:absolute;
padding:3px;
top:-15px;
background-color:orange;
color:white;
border-radius:50%;
}
```
Upvotes: 1 |
2018/03/20 | 605 | 2,298 | <issue_start>username_0: I was just looking into the basics of functional programming. I want to convert the below code using lambda in Java. I am using java 8. any help will be appreciated.
Thanks.
```
String reinBranches = (String) application.getAttribute("xx_xx_xx");
if(reinBranches != null && reinBranches.length() > 0)
{
String reinBranchArray[] = reinBranches.split(",");
for(int i = 0; i < reinBranchArray.length; i++)
{
if(reinBranchArray[i].equals((String) session.getAttribute("xyz_xyz_xyz"))) {
return true;
}
}
}
return false;
```<issue_comment>username_1: Magic
```
BooleanSupplier r = () -> {
String reinBranches = (String) application.getAttribute("xx_xx_xx");
if(reinBranches != null && reinBranches.length() > 0)
{
String reinBranchArray[] = reinBranches.split(",");
for(int i = 0; i < reinBranchArray.length; i++)
{
if(reinBranchArray[i].equals((String) session.getAttribute("xyz_xyz_xyz"))) {
return true;
}
}
}
return false;
}
```
Upvotes: 0 <issue_comment>username_2: First I would get the attribute you want to match against and save it (before the lambda). Then `stream` the `String[]` from your `split` and return `true` if `anyMatch` your criteria. Finally, use a logical and to prevent NPE on the `return`. Like,
```
String reinBranches = (String) application.getAttribute("xx_xx_xx");
String xyz3 = (String) session.getAttribute("xyz_xyz_xyz");
return reinBranches != null && Arrays.stream(reinBranches.split(",")).anyMatch(xyz3::equals);
```
**or** as suggested in the comments using `Pattern.splitAsStream` which can short-circuit if a match is found without building the array from splitting
```
return reinBranches != null && Pattern.compile(",").splitAsStream(reinBranches).anyMatch(xyz3::equals);
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Just another way of doing same without any overhead of using streams:-
```
String reinBranches = (String) application.getAttribute("xx_xx_xx");
String xyz3 = (String) session.getAttribute("xyz_xyz_xyz");
return reinBranches != null && Pattern.compile(xyz3).matcher(reinBranches).find(0);
```
Upvotes: 0 |
2018/03/20 | 2,223 | 9,048 | <issue_start>username_0: My structure
[](https://i.stack.imgur.com/E61Eg.png)
So I have an app in which users upload posts in my adapter. I can retrieve the post description and the post picture, but when I try to retrieve the poster's name the app seems to crash, to retrieve the name with every post there is a child added to the database with the uploader's id. This is my class file:
```
public String image_thumb;
public String user_id;
public String image_url;
public String desc;
public BlogPost(){}
public BlogPost(String user_id, String image_url, String desc, String image_thumb) {
this.user_id = user_id;
this.image_url = image_url;
this.desc = desc;
this.image_thumb = image_thumb;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage_thumb() {
return image_thumb;
}
public void setImage_thumb(String image_thumb) {
this.image_thumb = image_thumb;
}
```
and this is some of my adapter:
```
public void onBindViewHolder(final ViewHolder holder, int position) {
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);//this works
String image_url = blog_list.get(position).getImage_url();
holder.setBlogImage(image_url);//this works
String user_id = blog_list.get(position).getUser_id();
firebaseDatabase.child("Users").child(user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String userName = dataSnapshot.child("name").getValue().toString();
holder.setUserName(userName);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
public void setUserName(String name){
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
}
```
What I basically wanna do is look inside the user\_id for the name and retrieve it inside my `TextView`<issue_comment>username_1: Its better to not include any firebase calls inside your ViewBinder for recycler view.
What you can do is update your BlogPost and include a field name with getter and setter. Then inside your activity where you are adding the BlogPost to the recycler adapter you can fetch the user name add the name to the blog post and notify adapter of data change.
In your activity do this
```
// adding BlogPost to list
// Create BlogPost object with the data.
blogList.add(blogPostObject)
firebaseDatabase.child("Users").child(user_id).child("name").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
blogPostObject.setName(dataSnapshot.getValue().toString());
adapter..notifyItemChanged(indexOfblogPostObject);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```
Upvotes: 2 <issue_comment>username_2: In order to make it work correctly, I recommend you to do some changes in you model class as well as in your code. Your model class should look like:
```
public class BlogPost {
public String imageThumb, userId, imageUrl, desc;
public BlogPost() {}
public BlogPost(String imageThumb, String userId, String imageUrl, String desc) {
this.imageThumb = imageThumb;
this.userId = userId;
this.imageUrl = imageUrl;
this.desc = desc;
}
public String getImageThumb() {return imageThumb;}
public String getUserId() {return userId;}
public String getImageUrl() {return imageUrl;}
public String getDesc() {return desc;}
}
```
Please see the naming convention of the fields and getters.
>
> In order to make it work, don't forget the remove the old data and add fresh one.
>
>
>
Assuming your have a .XML file for your activity that contains a `RecyclerView` which looks like this:
```
```
And a .XML file for your item file, which looks like this:
```
```
To display your data in a `RecyclerView` using a `FriebaseRecyclerAdapter`, please follow the next steps:
First, you need to find the `RecyclerView` in your activity and set the `LinearLayoutManager` like this:
```
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
```
Then you need to create the root reference of your Firebase database and a `Query` object like this:
```
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users");
```
Then you'll have to create a `FirebaseRecyclerOptions` object like this:
```
FirebaseRecyclerOptions firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder()
.setQuery(query, BlogPost.class)
.build();
```
In your activity class, create a `holder` class that looks like this:
```
private class BlogPostHolder extends RecyclerView.ViewHolder {
private TextView imageThumbtextView, userIdTextView, imageUrlTextView, descTextView;
BlogPostHolder(View itemView) {
super(itemView);
imageThumbtextView = itemView.findViewById(R.id.image_thumb_text_view);
userIdTextView = itemView.findViewById(R.id.user_id_text_view);
imageUrlTextView = itemView.findViewById(R.id.image_url_text_view);
descTextView = itemView.findViewById(R.id.desc_text_view);
}
void setBlogPost(BlogPost blogPost) {
String imageThumb = blogPost.getImageThumb();
imageThumbtextView.setText(imageThumb);
String userId = blogPost.getUserId();
userIdTextView.setText(userId);
String imageUrl = blogPost.getImageUrl();
imageUrlTextView.setText(imageUrl);
String desc = blogPost.getDesc();
descTextView.setText(desc);
}
}
```
Then create an adapter which is declared as global:
```
private FirebaseRecyclerAdapter firebaseRecyclerAdapter;
```
And instantiate it in your activity like this:
```
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter(firebaseRecyclerOptions) {
@Override
protected void onBindViewHolder(@NonNull BlogPostHolder blogPostHolder, int position, @NonNull BlogPost blogPost) {
blogPostHolder.setBlogPost(blogPost);
}
@Override
public BlogPostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new BlogPostHolder(view);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
```
In the end, don't forget to override the following two methods and start listening for changes:
```
@Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
if (firebaseRecyclerAdapter!= null) {
firebaseRecyclerAdapter.stopListening();
}
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_3: The code below goes inside onBindviewhoder() under this line:
```
String user_id = . . .. . . .
```
I guess its the way you refer to your data and the way you attach the listener. Try to initialize the database ref like this:
```
DatabaseReference firebaseDatabase= FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
```
and now try to listen like this:
```
firebaseDatabase.addValueEventListener(new ValueEvent....{
onDataChange(.....){
//your same code
}
})
```
Upvotes: 1 <issue_comment>username_4: ```
public void checklocation() {
recyclerView=findViewById(R.id.recy);
FirebaseDatabase database = FirebaseDatabase.getInstance();
databaseReference = database.getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1: snapshot.getChildren()){
Model_lats model_lats=snapshot1.child("location").getValue(Model_lats.class);
latslist.add(model_lats);
}
adapter_lats=new Adapter_lats(MapsActivity.this,latslist);
recyclerView.setAdapter(adapter_lats);
adapter_lats.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError error) {
Toast.makeText(MapsActivity.this, "cant read"+error, Toast.LENGTH_SHORT).show();
}
});
}
```
Upvotes: 0 |
2018/03/20 | 690 | 2,524 | <issue_start>username_0: Basically,I am trying to make a Multi-Language app in Qt. For that, I created `hindi.ts` file and `hindi.qm` file using `lupdate` and `lrelease` commands in `qt 5.10.0 msvsc(2015)` cmd terminal. I have a Language Settings Widget in which I have a combo box and based on the language selected, I load that value into a registry.
As Shown in Below fig
fig 1 is Structure of My program
fig2 is UI of Language Settings
[1. Block Diagram of Widgets in my Project](https://i.stack.imgur.com/h23AZ.jpg)
[2. Language Gui Page](https://i.stack.imgur.com/NgdIk.jpg)
**CODE:**
```
void Form_LanguageSettings::on_pbtn_Submit_clicked()
{
QSettings settings("HKEY_CURRENT_USER\\MyProject\\Employee", QSettings::NativeFormat);
settings.setValue("language", ui->cmb_Language->currentText());
}
```
So, there are no problems while updating.
However, when I want to retrieve it from the Registry into `ListOfDepartment` Widget, I retrieve it in this way :
```
QSettings settings("HKEY_CURRENT_USER\\MyProject\\Employee", QSettings::NativeFormat);
QApplication *app;
QString SelectedLanguage;
SelectedLanguage=settings.value("language").toString();
if(SelectedLanguage.toLower() != "english")
{
if(SelectedLanguage=="hindi")
{
QTranslator translation;
translation.load("C:/MyProject/LanguagePack/ObjectFiles/HindiDevanagari.qm");
app->installTranslator(&translation);
}
}
```
In this way I am unable to load the corresponding language. If I load a particular language manually in `main.cpp` file it loads but if I do it via the settings widgets from my app, it doesn't work. How can I deal with this when the language settings are to be done in a separate widget ? I am new to multilanguage of QT. Please, any help?<issue_comment>username_1: Try to use:
```
QTranslator* translation = new QTranslator();
translation->load("C:/MyProject/LanguagePack/ObjectFiles/HindiDevanagari.qm");
QApplication::instance()->installTranslator(translation);
//or also QApplication::installTranslator(translation), it is static
```
In your code, the `QTranslator` instance is destroyed at the end of the `if` block, and the `app` variable is not assigned
Upvotes: 1 <issue_comment>username_2: Possible you should load your translation using brief file name and QDir e.g.
```
QTranslator * translation =new QTranslator();
QString dir ("C:/MyProject/LanguagePack/ObjectFiles");
translation->load ("HindiDevanagari", dir);
app->installTranslator (translation);
```
Upvotes: 0 |
2018/03/20 | 555 | 2,327 | <issue_start>username_0: I'm trying to use TestBed from to test a Angular component that has a ng-select in its HTML.
I've first got the error saying that **Can't bind to 'items' since it isn't a known property of 'ng-select'.** so I've imported NgSelectModule and added it to imports in TestBed configurations.
It now returns **Can't bind to 'ngModel' since it isn't a known property of 'ng-select'**
```
import { getTestBed, TestBed } from '@angular/core/testing';
import { ProductGenericGridComponent } from './product-generic-grid.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ProductGridService } from './product-generic-grid.service';
import { NgSelectModule } from '@ng-select/ng-select';
import { ProductItemComponent } from './../product-item/product-item.component';
describe('Product Generic Grid Component', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ProductGenericGridComponent],
imports: [HttpClientTestingModule, NgSelectModule],
providers: []
});
});
afterEach(() => {
getTestBed().resetTestingModule();
});
it('should return true', () => {
const fixture = TestBed.createComponent(ProductGenericGridComponent);
expect(true).toBe(true);
});
});
```<issue_comment>username_1: Import the forms module into your testbed.
```
TestBed.configureTestingModule({
declarations: [ProductGenericGridComponent],
imports: [HttpClientTestingModule, NgSelectModule, FormsModule],
providers: []
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Step 1: Install ng-select:
npm install --save @ng-select/ng-select
Step 2: Import the NgSelectModule and angular FormsModule module
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
Upvotes: 1 <issue_comment>username_3: For me too, it happened while unit testing and the following changes helped to resolve the errors
```
...
beforeEach((() => {
TestBed.configureTestingModule({
imports:[
MatDialogModule,
BrowserAnimationsModule,
FormsModule,
AgGridModule.withComponents([]),
NgSelectModule
],
...
```
Upvotes: 0 |
2018/03/20 | 1,778 | 6,392 | <issue_start>username_0: I have configured the following route configuration in `WebApiConfig` file to call the web api controller method by actual method(action) name as well as default calling pattern.
```
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
//By specifying action name
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Default calling pattern
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "DefaultAction", id = RouteParameter.Optional }
);
}
}
```
following is the controller
```
public class TestController
{
List \_lst;
[ActionName("DefaultAction")]
public HttpResponseMessage Get()
{
\_lst = new List() { 1, 2, 3, 4, 5 };
return ToJson(\_lst);
}
[ActionName("DefaultAction")]
public HttpResponseMessage Post(int id)
{
\_lst.Add(id);
return ToJson(1);
}
[ActionName("DefaultAction")]
public HttpResponseMessage Put(int id)
{
//doing sothing
return ToJson(1);
}
[ActionName("DefaultAction")]
public HttpResponseMessage Delete(int id)
{
//doing sothing
return ToJson(1);
}
public HttpResponseMessage Save(int id)
{
//doing sothing
return ToJson(1);
}
private HttpResponseMessage ToJson(dynamic obj)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
return response;
}
}
```
Calling the webapi controller `Post` or 'Get' method with below url is working fine resulting as expected.
POST -> <http://localhost:56114/api/Test/>
GET -> <http://localhost:56114/api/Test/>
Calling the webapi controller `Save` method with below url is also working fine resulting as expected.
POST -> <http://localhost:56114/api/Test/Save/1>
but when I call the PUT or DELETE method of api controller by below given url it does not call the any of the (PUT/DELETE) method
PUT -> <http://localhost:56114/api/Test/3>
DELETE -> <http://localhost:56114/api/Test/4>
it gives following error message
```
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:56114/api/Test/3'.",
"MessageDetail": "No action was found on the controller 'Test' that matches the name '3'."
}
```
can anyone help me on this why PUT and DELETE method are not getting called by default URL pattern.
I want to call all my above metods by using following URL pattern
```
POST -> http://localhost:56114/api/Test/ -> should call Post
GET -> http://localhost:56114/api/Test/ -> should call Get
PUT -> http://localhost:56114/api/Test/3 -> should call Put
DELETE -> http://localhost:56114/api/Test/4 -> should call Delete
POST -> http://localhost:56114/api/Test/Save/1 -> should call Save
```<issue_comment>username_1: It looks like the request paths to PUT and DELETE are matching the route template for "api/{controller}/{action}/{id}". Even though the request paths can match either defined route template, the template that was registered with "MapHttpRoute()" first will take priority. Here is how the PUT and DELETE request paths are being interpreted by the routing:
PUT: /api/Test/3 -> /api//
DELETE: /api/Test/4 -> /api//
With an optional "id" value that has been omitted in this case.
You could potentially solve this by switching the registration order of the routes, though it could affect other routing that you haven't listed here. Alternatively you could explicitly add the target action to the request path as such:
PUT: /api/Test/DefaultAction/3 -> /api///
DELETE: /api/Test/DefaultAction/4 -> /api///
Your requests to GET and POST are working due to the fact that the paths match the second route template with both an optional "action" and "id" parameter. The usage of an "id" in the PUT and DELETE commands causes the request paths to match the first route template instead.
I'm also not exactly sure why the "Save" action was successfully called in your example (unless you have a controller called "SaveController" that you did not show here). According to your routing logic that path would be interpreted as:
/api/Save/1 -> /api//
So the "Save" method in "TestController" is not actually being called by this request.
Upvotes: 1 <issue_comment>username_2: Converting to an answer.
I think the `ActionNameAtrribute` you are using is from MVC, not web api, so remove it, it wont do anything in this case.
Here is what I believe should work for you:
```
[HttpGet]
public HttpResponseMessage Get()
{
_lst = new List() { 1, 2, 3, 4, 5 };
return ToJson(\_lst);
}
[HttpPost]
public HttpResponseMessage Post(int id)
{
\_lst.Add(id);
return ToJson(1);
}
[HttpPut]
public HttpResponseMessage Put(int id)
{
//doing sothing
return ToJson(1);
}
[HttpDelete]
public HttpResponseMessage Delete(int id)
{
//doing sothing
return ToJson(1);
}
[HttpPost, Route("~/api/tests/save/{id}")]
public HttpResponseMessage Save(int id)
{
//doing sothing
return ToJson(1);
}
```
webapiconfig.cs:
```
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
```
The following patterns should now work, note that I've amended your first `post` call as the parameter `id` is present.
```
POST -> http://localhost:56114/api/Test/1 -> should call Post
GET -> http://localhost:56114/api/Test/ -> should call Get
PUT -> http://localhost:56114/api/Test/3 -> should call Put
DELETE -> http://localhost:56114/api/Test/4 -> should call Delete
POST -> http://localhost:56114/api/Test/Save/1 -> should call Save
```
Your default routing is still applied as well as the more specific `api/{controller}/{action}/{id}` route.
Upvotes: 3 [selected_answer] |
2018/03/20 | 642 | 2,273 | <issue_start>username_0: I'm creating a React app, and I have a code segment that looks like this:
```
import React, { Component } from 'react';
import { RaisedButton } from 'material-ui';
let isZero = false;
class Button extends Component {
render() {
const { value } = this.props;
isZero = false;
if (value === 0) {
isZero = true;
}
// removed for brevity
}
}
const styles = {
otherStyles: {
minWidth: isZero ? '120px' : '60px',
margin: '5px 5px 5px 0',
lineHeight: isZero ? '120px' : '60px',
},
};
export default Button;
```
But, apparently the conditional statement is not applied inside the object, as when `value` is 0, I still get the `60px` instead of `120px`. Any ideas?<issue_comment>username_1: The ternary operator is applied **at the time it is evaluated**.
That's before an instance of the class is created.
Move the `styles` constant **inside** the `render` function **after** you give `isZero` a value.
Upvotes: 2 <issue_comment>username_2: Your styles are defined outside of render and hence are not calculated everytime the variable isZero change, define it inside your render if you want it to be dynamic
```
import React, { Component } from 'react';
import { RaisedButton } from 'material-ui';
class KeyPadButton extends Component {
isZero = false;
render() {
const { click, disabled, value } = this.props;
this.isZero = false;
if (value === 0) {
this.isZero = true;
console.log(value);
console.log(isZero);
console.log(styles.buttonStyles);
console.log(styles.otherStyles);
}
const styles = {
buttonStyles: {
float: 'left',
width: this.isZero ? '120px' : '60px',
height: this.isZero ? '120px' : '60px',
border: '1px solid #f9f9f9',
borderRadius: '5px',
},
otherStyles: {
minWidth: this.isZero ? '120px' : '60px',
margin: '5px 5px 5px 0',
lineHeight: this.isZero ? '120px' : '60px',
},
};
return (
click(value)}
/>
);
}
}
export default KeyPadButton;
```
Upvotes: 4 [selected_answer] |
2018/03/20 | 1,929 | 6,644 | <issue_start>username_0: I have three entites, let’s call them `Site`, `Category` and `Tag`. In this scenario, `Category` and `Tag` have a composite ID generated from the `Site` entity and an external ID which is not unique (`site` and `id` together are unique). `Category` has a many-to-many relation on `Tag`. (Although my issue is also reproducible with ManyToOne relations.)
The `Site` entity:
```
/**
* @ORM\Entity
*/
class Site
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string")
*/
private $name;
}
```
The `Category` entity:
```
/**
* @ORM\Entity
*/
class Category extends AbstractSiteAwareEntity
{
/**
* @ORM\Column(type="string")
*/
private $name;
/**
* @ORM\ManyToMany(targetEntity="Tag")
*/
private $tags;
}
```
The `Tag` entity:
```
/**
* @ORM\Entity
*/
class Tag extends AbstractSiteAwareEntity
{
/**
* @ORM\Column(type="string")
*/
private $name;
}
```
The last two entities inherit from the `AbstractSiteAwareEntity` class, which defines the composite index:
```
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
}
```
As an example of a ManyToOne relation, let’s imagine a `Post` entity, which has an auto-increment ID and a reference to `Category`:
```
/**
* @ORM\Entity
*/
class Post
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Category")
*/
private $category;
/**
* @ORM\Column(type="string")
*/
private $title;
/**
* @ORM\Column(type="string")
*/
private $content;
}
```
When updating the schema with `bin/console doctrine:schema:update --dump-sql --force --complete`, I get the following exception:
>
> An exception occurred while executing 'ALTER TABLE category\_tag ADD
> CONSTRAINT FK\_D80F351812469DE2 FOREIGN KEY (category\_id) REFERENCES
> Category (id) ON DELETE CASCADE':
>
>
> SQLSTATE[HY000]: General error: 1005 Can't create table
> `xxxxxxx`.`#sql-3cf_14b6` (errno: 150 "Foreign key constraint is
> incorrectly formed")
>
>
>
I’m not sure what might be wrong … is there an error in my entity definitions? Or is this a Doctrine bug?
NOTE: I’m using doctrine/dbal 2.6.3 on Symfony 3.4.<issue_comment>username_1: You can't use composite PrK key for relations.
Instead, define an ID, and a composite UNI key (or just UNI key in this case)
`**Composite UNI key example**`
```
/**
* SiteAware
*
* @ORM\Table(name="site_aware",
* uniqueConstraints={@ORM\UniqueConstraint(columns={"site_id", "random_entity_id"})})
* @UniqueEntity(fields={"site", "randomEntity"}, message="This pair combination is already listed")
*/
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
/**
* @ORM\ManyToOne(targetEntity="RandomEntity")
*/
public $randomEntity;
}
```
`**Simple unique key**`
```
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Site")
* @ORM\JoinColumn(unique=true)
*/
public $site;
}
```
Upvotes: 0 <issue_comment>username_2: You have to define the **joined columns** in the annotation to make it work:
For a ManyToOne relation:
```
/**
* @ORM\ManyToOne(targetEntity="Tag")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="tag_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* })
**/
protected $tag;
```
For a ManyToMany relation:
```
/**
* @ORM\ManyToMany(targetEntity="Tag")
* @ORM\JoinTable(name="category_tags",
* joinColumns={
* @ORM\JoinColumn(name="category_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="tag_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* }
* )
**/
protected $tags;
```
How it works: 2 columns are created as a **FOREIGN KEY** that **REFERENCES** the composite foreign key.
Note: In "@ORM\JoinColumn" setting:
* "referencedColumnName" setting is an id column name on the related table, so this should already exist.
* "name" is the column name that stores the foreign key and to be created and in case of ManyToOne, it should not conflict with any of the columns of the entity.
The order of your **joinColumns** definitions is important. The composite foreign key should start with a column that has **an index** in the referenced table. In this case, **"@ORM\JoinColumn" to "site\_id"** should be **first**. [Reference](https://stackoverflow.com/questions/27150911/error-code-mysql-workbench-1215-cannot-add-foreign-key-constraint)
Upvotes: 1 <issue_comment>username_3: Based on [Jannis’ answer](https://stackoverflow.com/a/49395873/3908235), I was finally able to find a solution for this. The solution consists of two parts:
The first part is bit weird: Apparently Doctrine needs the `$id` before the `$site` reference in the composite primary key defined in `AbstractSiteEntity`. This sounds strange, but it’s definitely true, because I tried swapping them several times back and forth, and only this order works for some reason.
```
abstract class AbstractSiteAwareEntity
{
// $id must come before $site
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
}
```
For ManyToMany relations, the indices in the JoinTable must be declared explicitely, because Doctrine failed to create a composite foreign key by itself. I used Jannis’ proposal for this with a few modifications (column names aren’t actually neccessary):
```
/**
* @ORM\ManyToMany(targetEntity="Tag")
* @ORM\JoinTable(
* joinColumns={
* @ORM\JoinColumn(referencedColumnName="id"),
* @ORM\JoinColumn(referencedColumnName="site_id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(referencedColumnName="id"),
* @ORM\JoinColumn(referencedColumnName="site_id")
* }
* )
*/
private $tags;
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 1,925 | 5,673 | <issue_start>username_0: I'm trying to implement <NAME> in code for a school project and I have a problem.It outputs a weird number and I don't know why.The rest of them are good but this one is bad.Sorry if the post is bad but it's my first post here and I really need help.Thanks
```
#include
#define dim 100
using namespace std;
void inputMatrix(int \*n, int \*m, double x[dim][dim]){
int i,j;
for(i = 0; i < \*n; i++){
cout << "V" << i << ":";
for(j = 0; j < \*m; j++)
cin >> x[i][j];
}
}
void outputMatrix(int \*n, int \*m, double x[dim][dim]){
int i,j;
for(i=0;i<\*n;i++){
for(j=0;j<\*m;j++)
cout<> n;
cout << "Introduceti numarul de elemente: ";cin >> m;
inputMatrix(&n,&m,v);
double div = 0;
for(i = 0; i < m; i++){
f[0][i] = v[0][i];
}
outputMatrix(&n,&m,v);
cout << endl;
outputMatrix(&n,&m,f);
for(i = 1;i < n; i++){
z = 0;
initialize(&m,a);
mk1:
p1 = 0;
p2 = 0;
for(j = 0; j < m; j++){
p1 = f[z][j] \* v[i][j] + p1;
p2 = f[z][j] \* f[z][j] + p2;
}
div = p1 / p2;
for(j = 0; j < m; j++){
a[j] = f[z][j] \* div + a[j];
}
z++;
if( z < i){
goto mk1;
}
else{
for(j = 0; j < m;j++){
f[i][j] = v[i][j] - a[j];
}
}
cout << endl;
outputMatrix(&n,&m,f);
return 0;
}
```
Output:
```
Introduceti numarul de vectori: 3
Introduceti numarul de elemente: 4
V0:1
2
3
0
V1:1
2
0
0
V2:1
0
0
1
1 2 3 0
1 2 0 0
1 0 0 1
1 2 3 0
0 0 0 0
0 0 0 0
1 2 3 0
0.642857 1.28571 -1.07143 0
0.8 -0.4 5.55112e-17 1
```
I don't understand why it outputs this "5.55112e-17"
Thanks for help!<issue_comment>username_1: You can't use composite PrK key for relations.
Instead, define an ID, and a composite UNI key (or just UNI key in this case)
`**Composite UNI key example**`
```
/**
* SiteAware
*
* @ORM\Table(name="site_aware",
* uniqueConstraints={@ORM\UniqueConstraint(columns={"site_id", "random_entity_id"})})
* @UniqueEntity(fields={"site", "randomEntity"}, message="This pair combination is already listed")
*/
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
/**
* @ORM\ManyToOne(targetEntity="RandomEntity")
*/
public $randomEntity;
}
```
`**Simple unique key**`
```
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Site")
* @ORM\JoinColumn(unique=true)
*/
public $site;
}
```
Upvotes: 0 <issue_comment>username_2: You have to define the **joined columns** in the annotation to make it work:
For a ManyToOne relation:
```
/**
* @ORM\ManyToOne(targetEntity="Tag")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="tag_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* })
**/
protected $tag;
```
For a ManyToMany relation:
```
/**
* @ORM\ManyToMany(targetEntity="Tag")
* @ORM\JoinTable(name="category_tags",
* joinColumns={
* @ORM\JoinColumn(name="category_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="tag_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* }
* )
**/
protected $tags;
```
How it works: 2 columns are created as a **FOREIGN KEY** that **REFERENCES** the composite foreign key.
Note: In "@ORM\JoinColumn" setting:
* "referencedColumnName" setting is an id column name on the related table, so this should already exist.
* "name" is the column name that stores the foreign key and to be created and in case of ManyToOne, it should not conflict with any of the columns of the entity.
The order of your **joinColumns** definitions is important. The composite foreign key should start with a column that has **an index** in the referenced table. In this case, **"@ORM\JoinColumn" to "site\_id"** should be **first**. [Reference](https://stackoverflow.com/questions/27150911/error-code-mysql-workbench-1215-cannot-add-foreign-key-constraint)
Upvotes: 1 <issue_comment>username_3: Based on [Jannis’ answer](https://stackoverflow.com/a/49395873/3908235), I was finally able to find a solution for this. The solution consists of two parts:
The first part is bit weird: Apparently Doctrine needs the `$id` before the `$site` reference in the composite primary key defined in `AbstractSiteEntity`. This sounds strange, but it’s definitely true, because I tried swapping them several times back and forth, and only this order works for some reason.
```
abstract class AbstractSiteAwareEntity
{
// $id must come before $site
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
}
```
For ManyToMany relations, the indices in the JoinTable must be declared explicitely, because Doctrine failed to create a composite foreign key by itself. I used Jannis’ proposal for this with a few modifications (column names aren’t actually neccessary):
```
/**
* @ORM\ManyToMany(targetEntity="Tag")
* @ORM\JoinTable(
* joinColumns={
* @ORM\JoinColumn(referencedColumnName="id"),
* @ORM\JoinColumn(referencedColumnName="site_id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(referencedColumnName="id"),
* @ORM\JoinColumn(referencedColumnName="site_id")
* }
* )
*/
private $tags;
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 2,565 | 9,253 | <issue_start>username_0: Could some one please help how to remove the repeated code.
I have four dashboard as a sample I have mentioned two here.
For all the dashboard same logic applies but when I try to apply the css depending upon condition using css class it does not work.
So, I have used ids and it works fine.
But I have to repeat and write the same conditions four times. which makes 48 if and else which is not at all good to go ahead with. Please help.
```
if(dashboard1!=null)
{
var status1 =$('#div-dashboard1. dashboard-table tbody tr:nth-child(2) td:nth-child(1)').text();
var status2 =$('#div-dashboard1. dashboard-table tbody tr:nth-child(2) td:nth-child(2)').text();
var status3 =$('#div-dashboard1. dashboard-table tbody tr:nth-child(4) td:nth-child(1)').text();
var status4 =$('#div-dashboard1. dashboard-table tbody tr:nth-child(4) td:nth-child(2)').text();
if(status1 ==minCount)
{
$('#div-dashboard1. dashboard-table tbody tr td #hlStatus1').addClass("div-circle-green1");
}
else if ((status1 > minCount) && (status1 <=avgCount))
{
$('#div-dashboard1. dashboard-table td #hlStatus1').addClass("div-circle-amber");
}
else if (status1 >avgCount)
{
$('#div-dashboard1 .dashboard-table td #hlStatus1').addClass("div-circle_red1");
}
if(status2==minCount)
{
$('#div-dashboard1 .dashboard-table td #hlStatus2').addClass("div-circle-green1");
}
else if ((status2> minCount) && (status2<=avgCount))
{
$('#div-dashboard1.dashboard-table td #hlStatus2').addClass("div-circle-amber");
}
else if (status2>avgCount)
{
$('#div-dashboard1.dashboard-table td #hlStatus2').addClass("div-circle_red1");
}
if(status3==minCount)
{
$('#div-dashboard1 .dashboard-table tbody tr td #hlStatus3).addClass("div-circle-green1");
}
else if ((status3> minCount) && (status3<=avgCount))
{
$('#div-dashboard1 .dashboard-table tbody tr td #hlStatus3).addClass("div-circle-amber");
}
else if (status3>avgCount)
{
$('#div-dashboard1 .dashboard-table td #hlStatus3').addClass("div-circle_red1");
}
if(status4==minCount)
{
$('#div-dashboard1 .dashboard-table td #hlStatus4').addClass("div-circle-green1");
}
else if ((status4> minCount) && (status4<=avgCount))
{
$('#div-dashboard1 .dashboard-table td #hlStatus4').addClass("div-circle-amber");
}
else if (status4>avgCount)
{
$('#div-dashboard1 .dashboard-table td #hlStatus4').addClass("div-circle_red1");
}
}
if(dashboard2!=null)
{
var status1=$('#div-dashboard2 .dashboard-table tbody tr:nth-child(2) td:nth-child(1)').text();
var status2=$('#div-dashboard2 .dashboard-table tbody tr:nth-child(2) td:nth-child(2)').text();
var status3=$('#div-dashboard2 .dashboard-table tbody tr:nth-child(4) td:nth-child(1)').text();
var status4=$('#div-dashboard2 .dashboard-table tbody tr:nth-child(4) td:nth-child(2)').text();
if(status1 ==minCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus1').addClass("div-circle-green1");
}
else if ((status1 > minCount) && (status1 <=avgCount))
{
$('#div-dashboard2 .dashboard-table td #hlStatus1').addClass("div-circle-amber");
}
else if (status1 >avgCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus1').addClass("div-circle_red1");
}
if(status2==minCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus2').addClass("div-circle-green1");
}
else if ((status2> minCount) && (status2<=avgCount))
{
$('#div-dashboard2 .dashboard-table td #hlStatus2').addClass("div-circle-amber");
}
else if (status2>avgCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus2').addClass("div-circle_red1");
}
if(status3==minCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus3').addClass("div-circle-green1");
}
else if ((status3> minCount) && (status3<=avgCount))
{
$('#div-dashboard2 .dashboard-table td #hlStatus3').addClass("div-circle-amber");
}
else if (status3>avgCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus3').addClass("div-circle_red1");
}
if(status4==minCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus4').addClass("div-circle-green1");
}
else if ((status4> minCount) && (status4<=avgCount))
{
$('#div-dashboard2 .dashboard-table td #hlStatus4').addClass("div-circle-amber");
}
else if (status4>avgCount)
{
$('#div-dashboard2 .dashboard-table td #hlStatus4').addClass("div-circle_red1");
}
}
```<issue_comment>username_1: You can't use composite PrK key for relations.
Instead, define an ID, and a composite UNI key (or just UNI key in this case)
`**Composite UNI key example**`
```
/**
* SiteAware
*
* @ORM\Table(name="site_aware",
* uniqueConstraints={@ORM\UniqueConstraint(columns={"site_id", "random_entity_id"})})
* @UniqueEntity(fields={"site", "randomEntity"}, message="This pair combination is already listed")
*/
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
/**
* @ORM\ManyToOne(targetEntity="RandomEntity")
*/
public $randomEntity;
}
```
`**Simple unique key**`
```
abstract class AbstractSiteAwareEntity
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Site")
* @ORM\JoinColumn(unique=true)
*/
public $site;
}
```
Upvotes: 0 <issue_comment>username_2: You have to define the **joined columns** in the annotation to make it work:
For a ManyToOne relation:
```
/**
* @ORM\ManyToOne(targetEntity="Tag")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="tag_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* })
**/
protected $tag;
```
For a ManyToMany relation:
```
/**
* @ORM\ManyToMany(targetEntity="Tag")
* @ORM\JoinTable(name="category_tags",
* joinColumns={
* @ORM\JoinColumn(name="category_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="tag_site_id", referencedColumnName="site_id"),
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* }
* )
**/
protected $tags;
```
How it works: 2 columns are created as a **FOREIGN KEY** that **REFERENCES** the composite foreign key.
Note: In "@ORM\JoinColumn" setting:
* "referencedColumnName" setting is an id column name on the related table, so this should already exist.
* "name" is the column name that stores the foreign key and to be created and in case of ManyToOne, it should not conflict with any of the columns of the entity.
The order of your **joinColumns** definitions is important. The composite foreign key should start with a column that has **an index** in the referenced table. In this case, **"@ORM\JoinColumn" to "site\_id"** should be **first**. [Reference](https://stackoverflow.com/questions/27150911/error-code-mysql-workbench-1215-cannot-add-foreign-key-constraint)
Upvotes: 1 <issue_comment>username_3: Based on [Jannis’ answer](https://stackoverflow.com/a/49395873/3908235), I was finally able to find a solution for this. The solution consists of two parts:
The first part is bit weird: Apparently Doctrine needs the `$id` before the `$site` reference in the composite primary key defined in `AbstractSiteEntity`. This sounds strange, but it’s definitely true, because I tried swapping them several times back and forth, and only this order works for some reason.
```
abstract class AbstractSiteAwareEntity
{
// $id must come before $site
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
public $id;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Site")
*/
public $site;
}
```
For ManyToMany relations, the indices in the JoinTable must be declared explicitely, because Doctrine failed to create a composite foreign key by itself. I used Jannis’ proposal for this with a few modifications (column names aren’t actually neccessary):
```
/**
* @ORM\ManyToMany(targetEntity="Tag")
* @ORM\JoinTable(
* joinColumns={
* @ORM\JoinColumn(referencedColumnName="id"),
* @ORM\JoinColumn(referencedColumnName="site_id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(referencedColumnName="id"),
* @ORM\JoinColumn(referencedColumnName="site_id")
* }
* )
*/
private $tags;
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 388 | 1,047 | <issue_start>username_0: I'm new to Python and I was wondering, what is the best way to extract the region's name from a zone name.
For example:
```
GCP:
- us-east1-c
- europe-west2-b
AWS:
- eu-west-2
- ap-northeast-1
```
In bash, I would use:
```
echo "zone"|rev|cut -f2- -d-|rev"
```
In Python, I used:
```
'-'.join(zone.split('-')[:-1]),
```
I know it doesn't really matter, but I would like to do it in the pythonic way.
Thanks in advance!
Oh, expected output is if zone is us-east1-b
us-east1<issue_comment>username_1: I think this is enough using `rsplit`:
```
zone = 'us-east1-b'
print(zone.rsplit('-', 1)[0])
# us-east1
```
Or simply `split` will do:
```
zone = 'us-east1-b'
lst = zone.split('-')
print("{}-{}".format(lst[0], lst[1]))
# us-east1
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: ok based on your comments I see `String slicing` will do the work for you.
Read more about it [here](https://docs.python.org/2.3/whatsnew/section-slices.html)
Try this - `print "us-east1-b"[:-2]`
Upvotes: 0 |
2018/03/20 | 1,048 | 4,178 | <issue_start>username_0: I have a WPF application which sends data to a web application through POST requests. Currently this is done with `PostAsync` and that works. However, I see that certain requests finish earlier before another request finishes and that causes errors in the web application.
So I need to wait for until POST request is finished before sending the next request. I know I need to use `Task`, `await` and `async` for this, but I'm struggling in my specific situation.
The code below is the current code, without any `async` or `await`, because I'm unsure how to do this due to the chaining of objects.
First I have a button click event which calls an object for exporting the data:
```
private void exportButton_Click(object sender, RoutedEventArgs e)
{
var dataExtractor = new DataExtractor();
// First API call
dataExtractor.ExportTestSteps(testblockId, testCase);
// Second API call
dataExtractor.ExportReportTestSteps(testCase, executionList);
}
```
These call a method in the DataExtractor class and after getting the right data these methods call the actual sending of the POST request:
```
public class DataExtractor
{
public void ExportTestSteps(string testblockId, string testCaseUniqueId)
{
...
new QualityMonitorApi().StoreReportItem(content);
}
public void ExportReportTestSteps(string testCaseUniqueId, ExecutionList executionList)
{
...
new QualityMonitorApi().StoreReportItem(content);
}
}
```
And the `QualityMonitorApi` looks like this:
```
public class QualityMonitorApi
{
private string baseUrl = "http://localhost:3000/api/v1";
private static readonly HttpClient Client = new HttpClient();
public void StoreReportItem(string content)
{
string url = baseUrl + "/data_extractor/store_report_item";
var json = new StringContent(content, Encoding.UTF8, "application/json");
Client.PostAsync(url, json);
}
}
```
Due to the chaining of the classes I'm confused how to make sure API call 2 waits for API call 1 to finish?<issue_comment>username_1: Use [async/await](https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await)
Your async method should look like this:
```
public async Task StoreReportItem(string content)
{
string url = baseUrl + "/data_extractor/store_report_item";
var json = new StringContent(content, Encoding.UTF8, "application/json");
await Client.PostAsync(url, json);
}
```
Next use async/await in every method:
```
public async Task ExportReportTestSteps(string testCaseUniqueId, ExecutionList executionList)
{
...
await new QualityMonitorApi().StoreReportItem(content);
}
```
and so on..
Upvotes: 1 <issue_comment>username_2: You cannot do that way ? `async void` is okay, as long as it is an event handler method.
Also, you can store the objects that calls the API (i.e. DataExtractor) to avoid re-instantiating.
```cs
private async void exportButton_Click(object sender, RoutedEventArgs e)
{
var dataExtractor = new DataExtractor();
// First API call
await dataExtractor.ExportTestStepsAsync(testblockId, testCase);
// Second API call
await dataExtractor.ExportReportTestStepsAsync(testCase, executionList);
}
public class DataExtractor
{
public async Task ExportTestStepsAsync(string testblockId, string testCaseUniqueId)
{
...
await new QualityMonitorApi().StoreReportItemAsync(content);
}
public async Task ExportReportTestStepsAsync(string testCaseUniqueId, ExecutionList executionList)
{
...
await new QualityMonitorApi().StoreReportItemAsync(content);
}
}
public class QualityMonitorApi
{
private string baseUrl = "http://localhost:3000/api/v1";
private static readonly HttpClient Client = new HttpClient();
public async Task StoreReportItemAsync(string content)
{
string url = baseUrl + "/data_extractor/store_report_item";
var json = new StringContent(content, Encoding.UTF8, "application/json");
await Client.PostAsync(url, json);
}
}
```
See more here about async programmation: <https://learn.microsoft.com/en-us/dotnet/csharp/async>
Upvotes: 1 [selected_answer] |
2018/03/20 | 416 | 1,509 | <issue_start>username_0: I'm writing test script with Selenium WebDrvier. I have a problem with success/failure messages. Here's part of the code where i shout get the message. I don't know where I made a mistake so I would appreciate if someone could help me with it.
```
WebElement msg=driver.findElement(By.xpath("/html/body/div[4]/div/div[1]/div/p"));
String text=msg.getText();
Object expectedText;
Asserts.assertEquals(text,expectedText);
```<issue_comment>username_1: If you want to *Assert* two *String* values try to *Assert* through :
```
void org.testng.Assert.assertEquals(String actual, String expected)
```
* Defination :
```
void org.testng.Assert.assertEquals(String actual, String expected)
Asserts that two Strings are equal. If they are not, an AssertionError is thrown.
Parameters:
actual the actual value
expected the expected value
```
* Your code will be :
```
import org.testng.Assert;
WebElement msg = driver.findElement(By.xpath("/html/body/div[4]/div/div[1]/div/p"));
String text = msg.getText();
Asserts.assertEquals(text,expectedText);
```
Upvotes: 0 <issue_comment>username_2: ```
WebElement msg=driver.findElement(By.xpath("/html/body/div[4]/div/div[1]/div/p"));
// Get the text value of an element
String actualTxt = msg.getText();
// Expected [instead of Object expectedText ==> String expected]
String expecteTxt = "";
// Assertion (String, String)
Asserts.assertEquals(actualTxt,expectedTxt);
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 439 | 1,496 | <issue_start>username_0: As I am learner of Java.. I came across the following code
```
public static void main(String[] args) {
ArrayList a = new ArrayList<>();
a.add("1");
a.add("2");
for(String str: a){
a = new ArrayList<>();
System.out.println(str);
}
}
```
I guessed the answer to be
>
> 1
> null (since the reference is now pointing another object)
>
>
>
but the answer is
>
> 1
> 2
>
>
>
I am unable understand the behavior of enhanced for loop here.<issue_comment>username_1: The enhanced for loop creates an `Iterator` to iterate of the elements of your `ArrayList`. Changing the `a` reference to refer to a new `ArrayList` doesn't affect the `Iterator` that was created by the loop.
Your loop is equivalent to
```
Iterator iter = a.iterator();
while (iter.hasNext()) {
String str = iter.next();
a = new ArrayList<>();
System.out.println(str);
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: When you run
```
for(String str: a)
```
It gets an iterator from `a`, then iterates using that iterator. Reassigning `a` after it has the iterator will have no effect since it isn't using the `a` reference, it's using the iterator that `a` returned when the loop started.
Upvotes: 2 <issue_comment>username_3: This is because, enhanced for loop uses iterator. So changing the reference will not have any impact.
You can check different scenarios [here](https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work)
Upvotes: 0 |
2018/03/20 | 548 | 2,045 | <issue_start>username_0: I have the following warning :
>
> Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor).
>
>
>
with React-redux-router that I understand, but do not know how to fix.
This is the component that is generating the warning.
```
const Lobby = props => {
console.log("props", props)
if (!props.currentGame)
return (
(roomName = input)} />
{
props.createRoom(roomName.value)
}}
>
Create a room
)
else
return (
{props.history.push(`/${props.currentGame}[${props.username}]`)}
)
}
export default Lobby
```
What I'm doing here is that my component receives the *currentGame* property from the Redux store. This property is initialized as null.
When the user creates a game, I want to redirect him on a new URL generated by the server that I assign inside the property *currentGame* with a socket.io action event that is already listening when the container of the component Lobby is initialized.
However, since the *currentGame* property changes, the component is re-rendered, and therefore the line
```
{props.history.push(`/${props.currentGame}[${props.username}]`)}
```
generates a warning since the property *currentGame* now has a value, and the *history* property should not get modified during the re-render.
Any idea on how to fix it ?
Thanks!<issue_comment>username_1: You should not write `props.history.push` in render, instead use `Redirect`
```
const Lobby = props => {
console.log("props", props)
if (!props.currentGame)
return (
(roomName = input)} />
{
props.createRoom(roomName.value)
}}
>
Create a room
)
else
return (
)
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Do one thing, instead of writing the condition and pushing with history.push(), just put the code inside componentDidMount() if you are trying to do in the beginning.
```
componentDidMount(){
if(condition){
history.push('/my-url');
}
}
```
Upvotes: 1 |
2018/03/20 | 1,735 | 4,969 | <issue_start>username_0: I'm running a project which has Azure function, but it's not running my azure function. I have put the breakpoint, its also not hitting the breakpoint. Also, the output is not clear so that I can debug my code. Is there any way to debug the code to find the root cause of the issue?
**Output:**
>
> [3/20/2018 9:39:31 AM] Reading host configuration file
> 'C:\Users\myname\Source\MyProject\aspnet-core\src\Nec.MyProject.Processors\bin\Debug\netstandard2.0\host.json' [3/20/2018 9:39:31 AM] Host configuration file read: [3/20/2018
> 9:39:31 AM] { [3/20/2018 9:39:31 AM] "queues": { [3/20/2018 9:39:31
> AM] "maxPollingInterval": 1000, [3/20/2018 9:39:31 AM]
>
> "visibilityTimeout": "00:00:00", [3/20/2018 9:39:31 AM]
>
> "batchSize": 1, [3/20/2018 9:39:31 AM] "maxDequeueCount": 5
> [3/20/2018 9:39:31 AM] } [3/20/2018 9:39:31 AM] } [3/20/2018 9:39:48
> AM] Generating 15 job function(s) [3/20/2018 9:39:48 AM] Starting Host
> (HostId=windowsmyname-655615619, Version=2.0.11415.0, ProcessId=6320,
> Debug=False, ConsecutiveErrors=0, StartupCount=1,
> FunctionsExtensionVersion=) [3/20/2018 9:39:49 AM] Found the following
> functions: [3/20/2018 9:39:49 AM]
> MyCompany.MyProject.Processors.BackOfficeFilesGeneratorJobs.RunTestGeneratorAsync
> [3/20/2018 9:39:49 AM] [3/20/2018 9:39:49 AM] Job host started
> Listening on <http://localhost:7071/> Hit CTRL-C to exit... [3/20/2018
> 9:39:50 AM] Host lock lease acquired by instance ID
> '000000000000000000000000C78D3496'.
>
>
>
**Azure Function:**
```
[FunctionName("GenerateTestOfficeMasterDataFiles")]
public static async Task RunTestGeneratorAsync(
[QueueTrigger("%MasterDataFiles:Supplier:QueueName%", Connection = "ConnectionStrings:BlobStorageAccount")] BackOfficeFileGeneratorMessage message,
ExecutionContext context,
TraceWriter log)
```
**Note:** It was working fine when it was `BackOfficeFileGeneratorMessage` instead of `BackOfficeFileGeneratorMessage`.
**Update:**
```
public class BackOfficeFileGeneratorMessage
{
public BackOfficeFileGeneratorMessage()
{
Items = new MasterDataFileOperationItem [0];
}
public bool UseStaging { get; set; }
public string StoreNo { get; set; }
public bool RefreshAll { get; set; }
public IEnumerable> Items { get; set; }
}
```<issue_comment>username_1: Functions runtime acquires lease on the [storage account](https://learn.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.blob.cloudblobcontainer.acquireleaseasync?view=azure-dotnet) attached to the function app using an unique Id that is specific to your function App. This is an internal implementation detail.
Deserializing to a generic type should work as long as the queue trigger data matches the POCO. For e.g, here is generic type
```
public class GenericInput
{
public T OrderId { get; set; }
public T CustomerName { get; set; }
}
```
and the function
```
public static void ProcessQueueMessage([QueueTrigger("queuea")] GenericInput message, TextWriter log)
{
log.WriteLine(message);
}
```
Sample queue data
```
{
"OrderId" : 1,
"CustomerName" : "john"
}
```
you would get serialization errors if queue data cannot be serialized to the expected GenericType. For e.g following function would fail trying to process the bad queue input:
function:
```
public static void ProcessQueueMessage([QueueTrigger("queuea")] GenericInput message, TextWriter log)
{
log.WriteLine(message);
}
```
bad input:
```
{
"OrderId" : 1,
"CustomerName" : "cannot covert string to number"
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: just add the next key:value to the `hosts.json`:
```
"singleton": {
"listenerLockPeriod": "00:00:15"
}
```
Upvotes: 2 <issue_comment>username_3: If you upload a file on blob and run a trigger against it, the file will be read one time only. If you need to run the function again for the same file it is not possible.
You can either remove the file from blob and put it there again using UI (which will serve as a new trigger) or change the path of your function on your machine and keep the file on the blob as it is.
Upvotes: 0 <issue_comment>username_4: If this happens on localhost you can try to clear Azurite emulator (Visual Studio 2022) or Azure Storage Emulator
Azurite emulator:
Goto
```
%temp%\Azurite
```
Clear everything so you only have these two empty folders left:
[](https://i.stack.imgur.com/SS21C.png)
<https://stackoverflow.com/a/70157089/3850405>
<https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite?toc=%2Fazure%2Fstorage%2Fblobs%2Ftoc.json&tabs=visual-studio>
Azure Storage Emulator:
```
cd C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator
.\AzureStorageEmulator.exe clear all
```
<https://stackoverflow.com/a/38331066/3850405>
<https://learn.microsoft.com/en-us/azure/storage/common/storage-use-emulator>
Upvotes: 0 |
2018/03/20 | 954 | 3,284 | <issue_start>username_0: We are developing an iOS app that makes VoIP calls using pjsip.
All works fine when the app is in the foreground or if we start the call in the foreground and then put the app in the background.
But when the app is in the background we need to start a VoIP call when a certain connection is made from a BLE device.
So basically the BLE devices talks to the app and it asks it to start the call.
This is not working.
The audio in bg is enabled.
Is this at all possible on iOS?
I cannot find any reference to this situation in the Apple's docs
We are using TCP for the VoIP connection.<issue_comment>username_1: Functions runtime acquires lease on the [storage account](https://learn.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.blob.cloudblobcontainer.acquireleaseasync?view=azure-dotnet) attached to the function app using an unique Id that is specific to your function App. This is an internal implementation detail.
Deserializing to a generic type should work as long as the queue trigger data matches the POCO. For e.g, here is generic type
```
public class GenericInput
{
public T OrderId { get; set; }
public T CustomerName { get; set; }
}
```
and the function
```
public static void ProcessQueueMessage([QueueTrigger("queuea")] GenericInput message, TextWriter log)
{
log.WriteLine(message);
}
```
Sample queue data
```
{
"OrderId" : 1,
"CustomerName" : "john"
}
```
you would get serialization errors if queue data cannot be serialized to the expected GenericType. For e.g following function would fail trying to process the bad queue input:
function:
```
public static void ProcessQueueMessage([QueueTrigger("queuea")] GenericInput message, TextWriter log)
{
log.WriteLine(message);
}
```
bad input:
```
{
"OrderId" : 1,
"CustomerName" : "cannot covert string to number"
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: just add the next key:value to the `hosts.json`:
```
"singleton": {
"listenerLockPeriod": "00:00:15"
}
```
Upvotes: 2 <issue_comment>username_3: If you upload a file on blob and run a trigger against it, the file will be read one time only. If you need to run the function again for the same file it is not possible.
You can either remove the file from blob and put it there again using UI (which will serve as a new trigger) or change the path of your function on your machine and keep the file on the blob as it is.
Upvotes: 0 <issue_comment>username_4: If this happens on localhost you can try to clear Azurite emulator (Visual Studio 2022) or Azure Storage Emulator
Azurite emulator:
Goto
```
%temp%\Azurite
```
Clear everything so you only have these two empty folders left:
[](https://i.stack.imgur.com/SS21C.png)
<https://stackoverflow.com/a/70157089/3850405>
<https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite?toc=%2Fazure%2Fstorage%2Fblobs%2Ftoc.json&tabs=visual-studio>
Azure Storage Emulator:
```
cd C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator
.\AzureStorageEmulator.exe clear all
```
<https://stackoverflow.com/a/38331066/3850405>
<https://learn.microsoft.com/en-us/azure/storage/common/storage-use-emulator>
Upvotes: 0 |
2018/03/20 | 1,073 | 3,363 | <issue_start>username_0: ---
I've created an API in Laravel. I have some tables with relationships and I'm receiving JSON like this:
```js
{
content: "Lorem ipsum",
created_at: "2018-03-13 16:51:21",
deleted_at: null,
group_id: 1,
rating: 6,
updated_at: "2018-03-13 16:51:21",
user_id: 1
}
```
But I'd like to receive something like this:
```js
{
content: "Lorem ipsum",
created_at: "2018-03-13 16:51:21",
deleted_at: null,
group_id: 1,
rating: 6,
updated_at: "2018-03-13 16:51:21",
user: {
name: "John",
surname: "Doe",
avatar: "file.jpg"
}
}
```
What is the best way to do this?<issue_comment>username_1: Functions runtime acquires lease on the [storage account](https://learn.microsoft.com/en-us/dotnet/api/microsoft.windowsazure.storage.blob.cloudblobcontainer.acquireleaseasync?view=azure-dotnet) attached to the function app using an unique Id that is specific to your function App. This is an internal implementation detail.
Deserializing to a generic type should work as long as the queue trigger data matches the POCO. For e.g, here is generic type
```
public class GenericInput
{
public T OrderId { get; set; }
public T CustomerName { get; set; }
}
```
and the function
```
public static void ProcessQueueMessage([QueueTrigger("queuea")] GenericInput message, TextWriter log)
{
log.WriteLine(message);
}
```
Sample queue data
```
{
"OrderId" : 1,
"CustomerName" : "john"
}
```
you would get serialization errors if queue data cannot be serialized to the expected GenericType. For e.g following function would fail trying to process the bad queue input:
function:
```
public static void ProcessQueueMessage([QueueTrigger("queuea")] GenericInput message, TextWriter log)
{
log.WriteLine(message);
}
```
bad input:
```
{
"OrderId" : 1,
"CustomerName" : "cannot covert string to number"
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: just add the next key:value to the `hosts.json`:
```
"singleton": {
"listenerLockPeriod": "00:00:15"
}
```
Upvotes: 2 <issue_comment>username_3: If you upload a file on blob and run a trigger against it, the file will be read one time only. If you need to run the function again for the same file it is not possible.
You can either remove the file from blob and put it there again using UI (which will serve as a new trigger) or change the path of your function on your machine and keep the file on the blob as it is.
Upvotes: 0 <issue_comment>username_4: If this happens on localhost you can try to clear Azurite emulator (Visual Studio 2022) or Azure Storage Emulator
Azurite emulator:
Goto
```
%temp%\Azurite
```
Clear everything so you only have these two empty folders left:
[](https://i.stack.imgur.com/SS21C.png)
<https://stackoverflow.com/a/70157089/3850405>
<https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azurite?toc=%2Fazure%2Fstorage%2Fblobs%2Ftoc.json&tabs=visual-studio>
Azure Storage Emulator:
```
cd C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator
.\AzureStorageEmulator.exe clear all
```
<https://stackoverflow.com/a/38331066/3850405>
<https://learn.microsoft.com/en-us/azure/storage/common/storage-use-emulator>
Upvotes: 0 |
2018/03/20 | 593 | 2,141 | <issue_start>username_0: [Enter image description here](https://i.stack.imgur.com/YxuIY.jpg).
How to use the function of `fprint` to draw the image?
The equation is `x(t)= -2 * t * sin( t * t )`<issue_comment>username_1: You cannot do that in *standard* C11 (read [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf)) because it does not know about graphics. In practice, *your question is operating system specific*.
Practically speaking, you could use some GUI or graphics library (or [widget toolkit](https://en.wikipedia.org/wiki/Widget_toolkit)) like [GTK](http://gtk.org/) or [SDL](https://www.libsdl.org/) (and many others).
Another approach is to communicate (using some kind of [inter-process communication](https://en.wikipedia.org/wiki/Inter-process_communication)) with some existing program able to draw such graphics. You might (at least on Linux) use [popen(3)](http://man7.org/linux/man-pages/man3/popen.3.html) with [gnuplot](http://www.gnuplot.info/).
Upvotes: 0 <issue_comment>username_2: There is no built-in plotting functions in C.
You have to check the plotting and graph libraries and see if they fit your needs:
[MathGL](http://mathgl.sourceforge.net/doc_en/Main.html)
a library for making high-quality scientific graphics under Linux and Window.
[PLplot](http://plplot.sourceforge.net/)
PLplot works on the following platforms:
Linux, Mac OS X, and other Unices
MSVC IDE on the Microsoft version of Windows (Windows 2000 and later)
Cygwin on the Microsoft version of Windows
MinGW-w64/MSYS2 on the Microsoft version of Windows
[Gnuplot](http://www.gnuplot.info/) a command-line driven plotting engine that runs on all
major operating systems (Windows, GNU/Linux, OSX, etc.).\
Gnuplot provides a large array of styles to produce different plots including plots popular in mathematics, statistics, or even financial analysis. It can also produce various plot styles for three dimensional data including surface and contour plots.
It is capable of plotting user defined functions or specific data and can even generate
data through various facilities if needed.
Upvotes: 2 [selected_answer] |
2018/03/20 | 791 | 2,686 | <issue_start>username_0: I've followed [this guide](http://jonisalonen.com/2012/calling-c-from-java-is-easy/) to access two C native methods, but when I call
```
System.loadLibrary("SensorReader");
```
I get
```
Exception in thread "main" java.lang.UnsatisfiedLinkError: no SensorReader in java.library.path
```
I've followed the guide explaining I have to export the path to have it working temporarily or put the .so library in ld paths. I've even checked for java properties and got this:
```
java.library.path = .
/usr/java/packages/lib/arm
/lib
/usr/lib
```
but even if I put a copy of SensorReader.so in any of those directories (the first one doesn't even exist) nothing changes.
Here is the SensorReader.c code I made the library with:
```
#include
#include
#include
#include
#include
#include
#include "HTU21D.h"
#include "SensorController.h"
JNIEXPORT jdouble JNICALL Java\_SensorController\_getCurrentTemperature
(JNIEnv \*env, jobject obj) {
wiringPiSetup();
int fd = wiringPiI2CSetup(HTU21D\_I2C\_ADDR);
double temperature;
getTemperature(fd, &temperature);
return temperature;
}
JNIEXPORT jdouble JNICALL Java\_SensorController\_getCurrentHumidity
(JNIEnv \*env, jobject obj) {
wiringPiSetup();
int fd = wiringPiI2CSetup(HTU21D\_I2C\_ADDR);
double humidity;
getHumidity(fd, &humidity);
return humidity;
}
```
Executing
```
$ gcc -fPIC -c SensorReader.c -I $JAVA_HOME/include -I $JAVA_HOME/include/Linux
$ gcc SensorReader.o -shared -o SensorReader.so -Wl,-soname,SensorReader
```
returns no errors and the SensorReader.so file is created, I just get the problem when I try to run Java.
I'm not sure but I think the .so library is called on execution and not on compilation, but just in case I've tried both to just execute and compile then execute the code directly on the target Raspberry device and nothing changed.<issue_comment>username_1: Just a long shot: I have had similar problems trying to load a 64-bit compiled native library with a 32-bit java virtual machine. You should make sure that both are 64-bit (or 32-bit if it fits better your needs).
In any other case, I would have a second look at the library paths.
Upvotes: 0 <issue_comment>username_2: So apparently the wrong thing was the missing "lib" before "SensorReader.so" file name.
Changing
```
$ gcc SensorReader.o -shared -o SensorReader.so -Wl,-soname,SensorReader
```
with
```
$ gcc SensorReader.o -shared -o libSensorReader.so -Wl,-soname,SensorReader
```
or maybe just renaming the .so file, then moving it to /lib and executing
```
# ldconfig
```
solved the problem and now Java actually finds the library.
Upvotes: 2 [selected_answer] |
2018/03/20 | 921 | 3,813 | <issue_start>username_0: I have a data class in Kotlin hat is using the `@Parcelize` annotation for easy parcelization. Thing is I now want to pass a function to this class and I do not really know how to make the function not be considered during parceling.
This is my data class:
```
@Parcelize
data class GearCategoryViewModel(
val title: String,
val imageUrl: String,
val categoryId: Int,
val comingSoon: Boolean,
@IgnoredOnParcel val onClick: (gearCategoryViewModel: GearCategoryViewModel) -> Unit
) : DataBindingAdapter.LayoutViewModel(R.layout.gear_category_item), Parcelable
```
I tried using `@IgnoredOnParcel` and `@Transient` without success.
This is the compile error I get:
>
> Error:(20, 39) Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'
>
>
>
And this `@RawValue` annotation does not work either.<issue_comment>username_1: I know this isn't exactly a real answer but I would do it like this. Replace your function with class like this:
```
open class OnClick() : Parcelable {
companion object {
@JvmStatic
fun fromLambda(func: (GearCategoryViewModel) -> Unit) = object : OnClick() {
override fun invoke(param: GearCategoryViewModel) = func(param)
}
@JvmField
val CREATOR = object : Parcelable.Creator {
override fun createFromParcel(parcel: Parcel) = OnClick(parcel)
override fun newArray(size: Int) = arrayOfNulls(size)
}
}
constructor(parcel: Parcel) : this()
open operator fun invoke(param: GearCategoryViewModel) {
throw UnsupportedOperationException("This method needs to be implemented")
}
override fun writeToParcel(parcel: Parcel, flags: Int) = Unit
override fun describeContents() = 0
}
```
And use it like this:
```
val onClick = OnClick.fromLambda { vm -> /* do something*/ }
onClick(viewModel);
```
Upvotes: 0 <issue_comment>username_2: Just cast lambda to serializable, and then create object from
```
@Parcelize
data class GearCategoryViewModel(
val title: String,
val imageUrl: String,
val categoryId: Int,
val comingSoon: Boolean,
@IgnoredOnParcel val onClick: Serializable
) : DataBindingAdapter.LayoutViewModel(R.layout.gear_category_item), Parcelable {
fun onClicked() = onClick as (gearCategoryViewModel: GearCategoryViewModel) -> Unit
companion object {
fun create(
title: String,
imageUrl: String,
categoryId: Int,
comingSoon: Boolean,
onClick: (gearCategoryViewModel: GearCategoryViewModel) -> Unit
): GearCategoryViewModel = GearCategoryViewModel(
title,
imageUrl,
categoryId,
comingSoon,
onClick as Serializable
)
}
}
```
Upvotes: 3 <issue_comment>username_3: The premise of the question doesn't really make sense.
You can't deserialise this object if you don't serialise all of its properties.
You seem to want `onClick` to be `null` if this is deserialised, but even if that was possible, it'd throw a NPE because this property is not marked nullable.
Consider changing your architecture so you only serialise simple objects (POJOs or data classes) and not Functions.
Upvotes: 0 <issue_comment>username_4: ```
@Parcelize
data class GearCategoryViewModel(
val title: String,
val imageUrl: String,
val categoryId: Int,
val comingSoon: Boolean,
val onClick: @RawValue (gearCategoryViewModel: GearCategoryViewModel) -> Unit
) : DataBindingAdapter.LayoutViewModel(R.layout.gear_category_item), Parcelable
```
Use @RawValue with the onClick parameter.
Upvotes: 2 |
2018/03/20 | 885 | 3,679 | <issue_start>username_0: I did my best to solve the problem and I hope someone would be able to help me finding a solution.
I delcared the following layout for my activity:
```
xml version="1.0" encoding="utf-8"?
```
The related java code is the following:
```
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
TextView textView;
TextView laltitude;
TextView longitude;
Bundle bundle;
Double lal;
Double longt;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView=(TextView)findViewById(R.id.textView6);
editText = (EditText) findViewById(R.id.editText1);
laltitude =(TextView)findViewById(R.id.textView2);
longitude =(TextView)findViewById(R.id.textView3);
bundle = getIntent().getExtras();
lal = bundle.getDouble("laltitude");
longt = bundle.getDouble("longitude");
laltitude.setText("laltitude : " + lal.toString());
longitude.setText("longitude : " + longt.toString());
//hhhhhhhhhhhhhhhhh going back to main activity
// CancelButton.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
// }
// });
//hhhhhhhhhhhhhhh
// AddButton.setOnClickListener({});
// if (editText.getText() == null)
// textView.setVisibility(View.VISIBLE);
// else
// textView.setVisibility(View.INVISIBLE);
// });
}
public void buttonClickFunction(View view) {
Toast.makeText(getApplicationContext(),editText.getText().toString(),Toast.LENGTH_LONG);
if (editText.getText().toString() == "")
textView.setVisibility(View.VISIBLE);
else
textView.setVisibility(View.INVISIBLE);
}
public void Cancelonbuttonclickfunc(View view) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
}
}
```
The problem is that only one button seems to work (cancelbutton) but the
but the add button does not seem work.
I did declare the button and use the `findViewById` method but no luck so far.<issue_comment>username_1: In your button click method you're comparing strings using the `==` operator which tests for reference equality and not value equality. This is why your `textView`'s visibility never get set to VISIBLE. To check for value equality you should use `equals` method instead, like this:
```
public void buttonClickFunction(View view) {
Toast.makeText(getApplicationContext(),editText.getText().toString(),Toast.LENGTH_LONG).show();
if (editText.getText().toString().equals(""))
textView.setVisibility(View.VISIBLE);
else
textView.setVisibility(View.INVISIBLE);
}
```
Note that you also forgot to put `.show()` at the end of your Toast.
Upvotes: 2 <issue_comment>username_2: Try this
```
mBtnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String text= edittext.getText().toString().trim();
Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show();
if (text.length() <= 0) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.INVISIBLE);
}
}
});
```
Upvotes: 0 |
2018/03/20 | 824 | 2,507 | <issue_start>username_0: In SQL server (2016), I want to convert 2 rows into 1 row with fields of both rows.
I have this example:
```
IF OBJECT_ID('tempdb.dbo.#MyTable') IS not NULL DROP TABLE #MyTable
CREATE TABLE #MyTable (
Direction varchar(1),
DateKey int,
ID varchar(8),
[Sessions] int
)
insert into #MyTable values('S', 20180301, 'ID123456', 46)
insert into #MyTable values('R', 20180301, 'ID123456', 99)
select * from #MyTable
```
Output:
```
Direction DateKey ID Sessions
S 20180301 ID123456 46
R 20180301 ID123456 99
```
The output I want is:
```
DateKey ID S_Sessions R_Sessions
20180301 ID123456 46 99
```
So I tried this query but it won't work:
```
select DateKey,ID,
case Direction
when 'S' then [Sessions] as S_Sessions -- Incorrect syntax near the keyword 'as'.
else [Sessions] as R_Sessions
end
from #MyTable
```
Maybe I have to create an extra table, insert rows where direction='S' and then update the records with data where direction='R' but I wonder if there is a better way to do this.<issue_comment>username_1: use `PIVOT`
```
select *
from #MyTable
pivot
(
max(Sessions)
for Direction in ([S], [R])
) p
```
Upvotes: 2 <issue_comment>username_2: `CASE` in SQL is an expression that returns a single value. It cannot be used to control execution flow like in procedural languages.
You can use *conditional aggregation* for this:
```
select DateKey, ID,
max(case Direction when 'S' then [Sessions] end) as S_Sessions,
max(case Direction when 'R' then [Sessions] end) as R_Sessions
from #MyTable
group by DateKey, ID
```
[**Demo here**](http://rextester.com/LRE25831)
Upvotes: 1 [selected_answer]<issue_comment>username_3: assuming that your table contains the "pairs" S and R you can also use a self join
```
SELECT s.DateKey , s.ID , s.Sessions S_Sessions , r.Sessions R_Sessions
FROM #MyTable S
JOIN #MyTable R
ON s.ID = r.ID
AND s.DateKey = r.DateKey
WHERE S.Direction = 'S'
AND r.Direction = 'R'
```
Upvotes: 1 <issue_comment>username_4: Try It ... It works for me . more variable more case and more left join table.
```
select a.DateKey,a.ID,
(case a.Direction
when 'S' then a.Sessions
end) as S_Sessions,
(case b.Direction
when 'R' then b.Sessions
end) as R_Sessions
from mytable as a CROSS JOIN mytable as b ON a.ID=b.ID LIMIT 2,1
```
Upvotes: 0 |
2018/03/20 | 544 | 1,791 | <issue_start>username_0: I am trying to use Bind Variable for Informix Procedure.
Can someone guide me how to use for the below procedure?
CREATE PROCEDURE neura\_omega\_stg.grn\_payment\_mode\_update(vv\_material\_document\_id Varchar(20),vv\_payment\_mode Varchar(10))
UPDATE goods\_receive\_header\_tbl SET payment\_mode=vv\_payment\_mode WHERE
material\_document\_id=vv\_material\_document\_id;
END PROCEDURE;<issue_comment>username_1: use `PIVOT`
```
select *
from #MyTable
pivot
(
max(Sessions)
for Direction in ([S], [R])
) p
```
Upvotes: 2 <issue_comment>username_2: `CASE` in SQL is an expression that returns a single value. It cannot be used to control execution flow like in procedural languages.
You can use *conditional aggregation* for this:
```
select DateKey, ID,
max(case Direction when 'S' then [Sessions] end) as S_Sessions,
max(case Direction when 'R' then [Sessions] end) as R_Sessions
from #MyTable
group by DateKey, ID
```
[**Demo here**](http://rextester.com/LRE25831)
Upvotes: 1 [selected_answer]<issue_comment>username_3: assuming that your table contains the "pairs" S and R you can also use a self join
```
SELECT s.DateKey , s.ID , s.Sessions S_Sessions , r.Sessions R_Sessions
FROM #MyTable S
JOIN #MyTable R
ON s.ID = r.ID
AND s.DateKey = r.DateKey
WHERE S.Direction = 'S'
AND r.Direction = 'R'
```
Upvotes: 1 <issue_comment>username_4: Try It ... It works for me . more variable more case and more left join table.
```
select a.DateKey,a.ID,
(case a.Direction
when 'S' then a.Sessions
end) as S_Sessions,
(case b.Direction
when 'R' then b.Sessions
end) as R_Sessions
from mytable as a CROSS JOIN mytable as b ON a.ID=b.ID LIMIT 2,1
```
Upvotes: 0 |
2018/03/20 | 619 | 2,471 | <issue_start>username_0: I am new to JQuery/JavaScript and need a jump start for below case:
Notifications (alert messages) can be useful for new users but annoying to experienced users. So I want to give my users the option to show or not show these messages depending on user setting.
In order not having to build the same condition (derived from the user setting) around every single alert, I would like to write a function that
* can be called with jquery in the script section of all my views
* evaluates the condition and takes the passed-in text and sends/does not send an alert message depending on the condition
I know how to build the condition around the alert, but fail to make it globally accessible:
```
var isConfirmActiv = "@UserPrincipal.ConfirmActiv";
var myMessage ="Bla bla";
if (isConfirmActiv.toLowerCase() === "true") {
alert(myMessage);
}
```
I would like to use it in the script section of the view:
```
(var isConfirmActiv = "@UserPrincipal.ConfirmActiv";) ... somewhere?
myAlert("Bla bla", isConfirmActiv);
```
And in a script-file:
```
function myAlert(myMessage, isConfirmActiv){
if (isConfirmActiv.toLowerCase() === "true") {
alert(myMessage);
}
}
```<issue_comment>username_1: You must define this var in the global scope (outside a function):
<https://www.w3schools.com/js/js_scope.asp>
For example:
```
var isConfirmActiv = "@UserPrincipal.ConfirmActiv";
function myAlert(string myMessage){
if (isConfirmActiv.toLowerCase() === "true") {
return alert(myMessage);
}
}
```
Upvotes: 2 <issue_comment>username_2: You can create javascript file and name it Utility for example.
place your function and the global variable isConfirmActiv inside that file and link the js file to all views or to the master layout.
```
var isConfirmActiv;
function myAlert(myMessage, isConfirmActiv){
if (isConfirmActiv.toLowerCase() === "true") {
alert(myMessage);
}
}
- set directly the global defined isConfirmActiv value in every View in the script section (Note: don't redefine it, its already defined globally in javascript file)
isConfirmActiv = "@UserPrincipal.ConfirmActiv";
- Now you can call the function from anywhere in your project.
function myAlert(myMessage, isConfirmActiv){
if (isConfirmActiv.toLowerCase() === "true") {
alert(myMessage);
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 405 | 1,643 | <issue_start>username_0: Using the SQL api you can specify the partition key in the SQL statement e.g. `SELECT * FROM c WHERE c.MyPartitionKey = 'KeyValue'` or using `FeedOptions.PartitionKey`.
Are they equivalent or will one way have a lower RU cost?
I have tried both ways and can't see a difference but the data set is quite small and this may change as the data grows over time.<issue_comment>username_1: You must define this var in the global scope (outside a function):
<https://www.w3schools.com/js/js_scope.asp>
For example:
```
var isConfirmActiv = "@UserPrincipal.ConfirmActiv";
function myAlert(string myMessage){
if (isConfirmActiv.toLowerCase() === "true") {
return alert(myMessage);
}
}
```
Upvotes: 2 <issue_comment>username_2: You can create javascript file and name it Utility for example.
place your function and the global variable isConfirmActiv inside that file and link the js file to all views or to the master layout.
```
var isConfirmActiv;
function myAlert(myMessage, isConfirmActiv){
if (isConfirmActiv.toLowerCase() === "true") {
alert(myMessage);
}
}
- set directly the global defined isConfirmActiv value in every View in the script section (Note: don't redefine it, its already defined globally in javascript file)
isConfirmActiv = "@UserPrincipal.ConfirmActiv";
- Now you can call the function from anywhere in your project.
function myAlert(myMessage, isConfirmActiv){
if (isConfirmActiv.toLowerCase() === "true") {
alert(myMessage);
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 306 | 1,060 | <issue_start>username_0: I'm trying to insert a variable inside one SQL query using `"+uid+"` but the variable does not seem to be taken into account:
```
import datetime
import sqlite3 as lite
import sys
con = lite.connect('user.db')
uid = raw_input("UID?: ")
time = datetime.datetime.now()
with con:
cur = con.cursor()
cur.execute("SELECT Name FROM Users WHERE Id = "+uid+";")
rows = cur.fetchall()
for row in rows:
print row
print time
```<issue_comment>username_1: Do not use string manipulation on SQL. It can result in sql-injections.
Change
```
cur.execute("SELECT Name FROM Users WHERE Id = "+uid+";")
```
to (using `prepared statements`)
```
cur.execute("SELECT Name FROM Users WHERE Id=?;", (uid,))
```
Upvotes: 2 <issue_comment>username_2: ```
cur.execute("SELECT Name FROM Users where %s=?" % (Id), (uid,))
```
also check out this answer
[Python sqlite3 string variable in execute](https://stackoverflow.com/questions/13880786/python-sqlite3-string-variable-in-execute)
Upvotes: 1 |
2018/03/20 | 584 | 1,999 | <issue_start>username_0: I am trying to run the Example CorDapp (<https://github.com/corda/cordapp-example>) on Corda 3. When I try to run the `./gradlew deployNodes` step, I get the following error:
```
Execution failed for task ':java-source:deployNodes'.
> Node in Notary exited with 1 when generating its node-info - see logs in [REDACTED]/cordapp-example/java-source/build/nodes/Notary/logs
* Try:
Run with --info and --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':java-source:deployNodes'.
at ...
Caused by: java.lang.IllegalStateException: Node in Notary exited with 1 when generating its node-info - see logs in [REDACTED]/cordapp-example/java-source/build/nodes/Notary/logs
at net.corda.nodeapi.internal.network.NetworkBootstrapper$gatherNodeInfoFiles$future$1.invoke(NetworkBootstrapper.kt:136)
at net.corda.nodeapi.internal.network.NetworkBootstrapper$gatherNodeInfoFiles$future$1.invoke(NetworkBootstrapper.kt:44)
at net.corda.core.internal.concurrent.ValueOrException$DefaultImpls.capture(CordaFutureImpl.kt:107)
at net.corda.core.internal.concurrent.OpenFuture$DefaultImpls.capture(CordaFutureImpl.kt
at net.corda.core.internal.concurrent.CordaFutureImpl.capture(CordaFutureImpl.kt:119)
at net.corda.core.internal.concurrent.CordaFutureImplKt$fork$$inlined$also$lambda$1.run(CordaFutureImpl.kt:22)
```
Why is the network failing to be created?<issue_comment>username_1: I encountered this when old builds with old names were present in the cordapp. Looking at the logs at "/cordapp-example/java-source/build/nodes/Notary/logs/" will reveal which old node is causing problems.
Running `./gradlew clean deployNode` clears the issue.
Upvotes: 0 <issue_comment>username_2: This can also be caused by having the wrong Java version. Ensure your Java version is in-line with the requirements here: <https://docs.corda.net/getting-set-up.html#software-requirements>.
Upvotes: 1 |
2018/03/20 | 535 | 2,188 | <issue_start>username_0: I want to delete the Firebase database child with this follow code when I click the first item in a list in an app, but I can't. What's wrong?
```
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String remCal = dataSnapshot.toString();
mCalendarioDatabaseReference.child(remCal).removeValue();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```<issue_comment>username_1: Firebase Queries return a list of possible locations where the query might be satisfied, you'd need to iterate through your dataSnapshot to access those locations. Moreover, this :
```
String remCal = dataSnapshot.toString();
```
is not going to print the String value of this snapshot. If you want to get the string value of a dataSnapshot it should be:
```
String remCal = dataSnapshot.getValue(String.class);
```
If you want to get the reference of a datasnapshot just use getRef(), you don't have to access the original reference.
```
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
child.getRef().setValue(null); //deleting the value at this location. You can also use removeValue()
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```
Upvotes: 1 <issue_comment>username_2: I solve the problem with this code:
```
Query removerCalendario = mCalendarioDatabaseReference.limitToFirst(1);
removerCalendario.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}
```
Upvotes: 0 <issue_comment>username_3: You can do `mCalendarioDatabaseReference.child(remCal).setValue(null);`
Upvotes: 0 |
2018/03/20 | 347 | 1,209 | <issue_start>username_0: I have made a form in which I want to apply a different style to a particular Select Box in that form.
```
select#complaintSource
{
@import url("http://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css");
@import url("http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css");
}
@if(select)
{
}
@endif
1
2
```
I want to apply the Style to this particular Select Box . At the moment it is applying to all of them.<issue_comment>username_1: Is there any reason that the OP here can't just do:
```
select#complaintSource {
/\*enter Bootstrap [select] code only here, such as:\*/
display: block;
width: 100px; /\*and so on \*/
/\*enter your custom select code here\*/
color: green;
}
```
Where 'enter code here' would have 1) the relevant lines from Bootstrap, since it's only for select, and 2) the custom styles for it, placed inside as CSS.
Upvotes: 1 <issue_comment>username_2: There is no method that We Can Include Style Sheet to only select box in View. If you have applied the Style Sheet then you have to change CSS or Style your page accordingly. That's the only way.
Upvotes: 1 [selected_answer] |
2018/03/20 | 1,191 | 4,511 | <issue_start>username_0: I have this rather intricate `try` `except` block:
```
try:
self.sorting = sys.argv[1]
try:
test_sorting_var = int(self.sorting)
if test_sorting_var < 1:
print "Sorting column number not valid."
raise ValueError
else:
self.sorting = test_sorting_var
except ValueError:
print "There's a problem with the sorting value provided"
print "Either the column doesn't exists or the column number is invalid"
print "Please try a different sorting value or omit it."
sys.exit(1)
except:
if self.sorting not in self.output_table.column_headers:
print "Sorting column name not valid."
raise ValueError
except:
pass
```
Basically I'm checking:
1. If there's a `sys.argv[1]`
2. If so, try it as `int`, and see if it's less than 1
3. If `int` fails, test it as string
In both 2+3, if the tests don't succeed, I'm raising a `ValueError` that should be caught in the `except ValueError` block and it does as expected:
```
Sorting column number not valid.
There's a problem with the sorting value provided
Either the column doesn't exists or the column number is invalid
Please try a different sorting value or omit it.
```
BUT! The `sys.exit(1)` is not invoked and the program just continues.
How can I fix it and even make it more readable?<issue_comment>username_1: In the last two lines you catch *any* exception:
```
except:
pass
```
This includes the exception `SystemExit`, which is raised by `sys.exit`.
To fix this, only catch exceptions deriving from `Exception`, [which
`SystemExit` does not](https://docs.python.org/3/library/exceptions.html#exception-hierarchy):
```
except Exception:
pass
```
---
In general, it's (almost) never a good idea to do a bare except, always catch `Exception`, or if possible, something more specific.
Upvotes: 4 [selected_answer]<issue_comment>username_2: The builtint `sys.exit()` raises a `SystemExit`-Exception. As you are catching any type of exception when you don't define the Exception to catch (`except:` without an Exception Type) the SystemExit gets also caught. Ultimately the function will run until the last line where you wrote `pass`.
Best thing to do is to always catch specific Exceptions and never ever catch all Exceptions with an `except:`.
Furthermore you should put the check if `self.sorting` is not in `self.output_table.column_headers` outside the try catch where you check for a valid self.sorting.
Upvotes: 2 <issue_comment>username_3: From the [documentation for `sys.exit`](https://docs.python.org/3/library/sys.html#sys.exit):
>
> Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
>
>
>
This means that the outer try except loop is catching the `SystemExit` exception and causing it to pass. You can add this exception to the outer block and call it again.
Upvotes: 1 <issue_comment>username_4: I think I would do something like this:
```
import sys
def MyClass(object):
def method(self, argv, ...):
# ...
if len(argv) < 2:
raise RuntimeError("Usage: {} ".format(argv[0]))
sorting = argv[1]
try:
self.sorting = int(sorting)
except ValueError:
try:
self.sorting = self.output\_table.column\_headers.index(sorting)
except ValueError:
raise ValueError("Invalid sorting column '{}'.".format(sorting))
# ...
try:
# ...
obj.method(sys.argv, ...)
except Exception as e:
sys.exit(e.message)
```
* It's okay to [ask for forgiveness instead of permission](https://www.jefftk.com/p/exceptions-in-programming-asking-forgiveness-instead-of-permission) when it makes things easier (for example to parse a number), but if you need to make sure if `sys.argv` has enough elements just check it, it will make the program flow clearer.
* Avoid using `sys.exit` within regular code, try to use it only in the outermost levels. For the most part, it is generally better to let exceptions bubble up and catch them at top level or let them crash the program if necessary.
* Do make use of exception parameters to store error information, you can decide at a later point whether to print the error, log it, show it in a popup, ...
* Instead of using `sys.argv` directly from within a class, you can pass it as an argument to the method/constructor, it will make the code easier to test and more flexible towards the future.
Upvotes: 1 |
2018/03/20 | 564 | 2,376 | <issue_start>username_0: I am working on an android application that have a web-view. The problem comes when I want to check whether Internet is available before displaying default message.
I have studied these links [Link1](https://stackoverflow.com/questions/38038301/how-to-check-internet-connection-in-android-webview-and-show-no-internet-image-n)and [link2](https://stackoverflow.com/questions/29294907/check-whether-connected-to-the-internet-or-not-before-loading-webview). I am confused how to do this.
Here is my code
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Web= findViewById(R.id.webview);
Web.getSettings().setJavaScriptEnabled(true);
Web.loadUrl("http://yourconsenthomebuilders.com/app/clients");
}
```<issue_comment>username_1: Use this method to check internet connection
```
public class ConnectionDetector {
public ConnectionDetector() {
}
public Boolean check_internet(Context context) {
if (context != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
}
return false;
}
}
```
**After this you can create object and check internet connection like this**
Fragment
```
ConnectionDetector connectionDetector = new ConnectionDetector();
connectionDetector.check_internet(getContext())
```
Activity
```
ConnectionDetector connectionDetector = new ConnectionDetector();
connectionDetector.check_internet(this)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: After setContentView()
add this logic
```
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable() && info.isConnected())
{
//network connected
//show web view logic here
}else{
//network not connected
//show alerts to users
}
```
Upvotes: 1 |
2018/03/20 | 473 | 1,538 | <issue_start>username_0: I am stuck with 'join' command in UNIX.
Requirement :
Trying to compare two files with similar meta data by embedding sort inside a join command.
Execution :
The below command works smooth in command line :
```
join -v 2 <(sort file1) <(sort file2) >difference.file
```
However when we embede this inside a shell script as given below throws a syntax error:
Script Name : join.sh
Script Content:
```
#!/bin/bash
join -v 2 <(sort file1) <(sort file2) >difference.file
#EndOfScript
```
Error message :
```
./join.sh: line 1: syntax error near unexpected token `('
./join.sh: line 1: `join -v 2 <(sort file1) <(sort file2) >difference.file'
```
Similar query was posed for `comm` and `sort` commands but this doesnt help for `join`
[Bash script using COMM and SORT issues syntax error near unexpected token](https://stackoverflow.com/questions/36391675/bash-script-using-comm-and-sort-issues-syntax-error-near-unexpected-token)<issue_comment>username_1: I am giving you an alternate option. You can try with this:-
```
sort file1 > file1.dat
sort file2 > file2.dat
join -v 2 file1.dat file2.dat > difference.file
rm -rf file1.dat file2.dat
```
Upvotes: 0 <issue_comment>username_2: You are probably running the script with
```
sh join.sh
```
This invokes the `/bin/sh` executable, that is not compatible with bash specific syntax (the process substitution in this example).
Run the script with
```
./join.sh
```
or
```
bash join.sh
```
and it should work as expected.
Upvotes: 2 |
2018/03/20 | 251 | 960 | <issue_start>username_0: Long story short in my app the user receives an email notification which has hyperlink to open a certain record for a given id number. It looks something like this:
```
https://myappserver.com/?aid=12343551
```
The question I have is once the user opens the record is it possible to change the URL through ionic? I would like to change the url after opening and remove the parameter so it looks like this `https://myappserver.com/`
I can retrieve the URL through this.platform.url() but I don’t know how to change it.<issue_comment>username_1: You can use `Location` from `@angular/common`. Then you can use it like:
`this.location.replaceState('/')`. Here is the [reference](https://angular.io/api/common/Location#replaceState).
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could use the history function of the window object
```
window.history.pushState('', '', '/');
```
Which don't rely on Angular.
Upvotes: 0 |
2018/03/20 | 804 | 2,462 | <issue_start>username_0: Can you please help me out to write the Laravel Raw Query for below Mysql query.
```
SELECT
SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS `business_email_template_10_open`,
SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`
FROM dummy_email_track d
join recommend_email_send_by_cron r on d.user_id = r.user_id
join user_form_submission u on r.user_id = u.id'
where d.business_id = $businessId
```<issue_comment>username_1: This should give you a headstart!
<https://laravel.com/docs/5.6/database#running-queries>
```
$results = DB::select('select * from users where id = :id', ['id' => 1]);
```
Make sure you give right id to your where clause. So in you case it would something like this:
```
(where d.business_id = :businessId, ['businessId' => 1])
```
Goodluck!
Upvotes: 0 <issue_comment>username_2: If you can't use stored procedure, ignore my answer.
I think you can't use Laravel QueryBuilder cause something reason(I have a similar situation). How about using SP(stored procedure)?
Mysql SP
```
CREATE DEFINER=`your_mysql_id`@`%` PROCEDURE `get_usage_business_email_template`()
__SP:BEGIN
BEGIN
SELECT
SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS `business_email_template_10_open`,
SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`
FROM dummy_email_track d
join recommend_email_send_by_cron r on d.user_id = r.user_id
join user_form_submission u on r.user_id = u.id'
WHERE d.business_id = $businessId
END;
END
```
And, Laravel call this SP like below
```
$result = DB::select('CALL get_usage_business_email_template()');
```
I hope you will save your time becasue my answer...
Upvotes: 1 <issue_comment>username_3: Please try this :
```
$data = DB::table('dummy_email_track as d')
->select('d.*','r.*','u.*')
->selectRaw('SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS business_email_template_10_open')
->selectRaw('SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`')
->leftJoin('recommend_email_send_by_cron as r','d.user_id', '=', 'r.user_id')
->leftJoin('user_form_submission as u', 'r.user_id', '=', 'u.id')
->where('d.business_id','=', $businessId)
->get();
```
Upvotes: 0 |
2018/03/20 | 134 | 536 | <issue_start>username_0: I have a table body which is declared as animation block.
In some particular scenarios I want remove the transition to the table body. Is there any way to do that.<issue_comment>username_1: You can use template with if-else condition:
```
<>
<>
```
Upvotes: 1 <issue_comment>username_2: ### HTML
```
Hello
```
Specify the condition in the name attribute, when condition is true (or equal any value) run the "name" argument, in another case leave it empty and the transition will not work
Upvotes: 3 |
2018/03/20 | 311 | 881 | <issue_start>username_0: I have two lists of integers. I want to make all possible combinations of elements in list-1 with elements with list-2. For Example:
```
List-1 List-2
1 5
2 6
```
I need another list of all possible combinations like:
```
element-1 element-2
1 5
1 6
2 5
2 6
```
How to do that in python?<issue_comment>username_1: You are looking for [`itertools.product()`](https://docs.python.org/3/library/itertools.html#itertools.product):
```
>>> import itertools
>>> list(itertools.product([1, 2], [5, 6]))
[(1, 5), (1, 6), (2, 5), (2, 6)]
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can try itertools :
```
list_1=[1,2]
list_2=[5,6]
import itertools
print([i for i in itertools.product(list_1,list_2)])
```
output:
```
[(1, 5), (1, 6), (2, 5), (2, 6)]
```
Upvotes: 0 |
2018/03/20 | 1,372 | 3,927 | <issue_start>username_0: This code run the huge data but with all Arabic words written in reverse:
```
from bidi.algorithm import get_display
import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
os.chdir("C:")
f = open('example.txt', 'r', encoding = 'utf-8')
data = arabic_reshaper.reshape(f.read())
WordCloud = WordCloud(font_path='arial',background_color='white', mode='RGB',width=2000,height=1000).generate(data)
plt.title("wordcloud")
plt.imshow(WordCloud)
plt.axis("off")
plt.show()
```
This is my data:
```
أحمد
خالد
سلمان
سليمان
عبدالله
عبدالرحمن
عبدالرحمن
خالد
صالح
```
Finally this what I get:
[](https://i.stack.imgur.com/5vZqk.png)
Can someone help me to solve it?<issue_comment>username_1: First you need to import the arabic\_resharper package then use get\_display function and pass it to the wordcloud as the following:
```
from bidi.algorithm import get_display
import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import arabic_reshaper # this was missing in your code
# os.chdir("C:")
f = open('example.txt', 'r', encoding='utf-8')
data = arabic_reshaper.reshape(f.read())
data = get_display(data) # add this line
WordCloud = WordCloud(font_path='arial', background_color='white',
mode='RGB', width=2000, height=1000).generate(data)
plt.title("wordcloud")
plt.imshow(WordCloud)
plt.axis("off")
plt.show()
```
Upvotes: 2 <issue_comment>username_2: Update
======
Ok. Just created a tiny Arabic wrapper ([`ar_wordcloud`](https://github.com/iamaziz/ar_wordcloud)) to do this. I hope it helps.
`$ pip install ar_wordcloud`
```py
from ar_wordcloud import ArabicWordCloud
awc = ArabicWordCloud(background_color="white")
t = 'أهلاً وسهلا، اللغة العربية جميلة'
wc = awc.from_text(t)
```
[](https://i.stack.imgur.com/VgD2R.png)
---
Or, here is another example without the wrapper:
```py
from collections import Counter
from wordcloud import WordCloud # pip install wordcloud
import matplotlib.pyplot as plt
# -- Arabic text dependencies
from arabic_reshaper import reshape # pip install arabic-reshaper
from bidi.algorithm import get_display # pip install python-bidi
rtl = lambda w: get_display(reshape(f'{w}'))
COUNTS = Counter("السلام عليكم ورحمة الله و بركاته السلام كلمة جميلة".split())
counts = {rtl(k):v for k, v in COUNTS.most_common(10)}
font_file = './NotoNaskhArabic-Regular.ttf' # download from: https://www.google.com/get/noto
wordcloud = WordCloud(font_path=font_file).generate_from_frequencies(counts)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
```
The result:
[](https://i.stack.imgur.com/sBk7w.png)
Also, there is a PR discussion on this here: <https://github.com/amueller/word_cloud/pull/315>
Upvotes: 1 <issue_comment>username_3: Here is a Good example on how you can generate Arabic wordCloud.
```
import arabic_reshaper
from bidi.algorithm import get_display
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
wordcloud = WordCloud(font_path='NotoNaskhArabic-Regular.ttf').generate(bidi_text)
wordcloud.to_file("worCloud.png")
```
Here is a link on how you can do it on : [Google colab](https://colab.research.google.com/drive/1OmP1TOqXq8gCPNxlLCaKGWHNJ_q3dHRu?usp=sharing)
Upvotes: 1 <issue_comment>username_4: here is the solution , converting an Arabic string to wordcloud using arworldcloud library
```
pip install ar_wordcloud
from ar_wordcloud import ArabicWordCloud
awc = ArabicWordCloud(font='NotoSansArabic-ExtraBold.ttf')
t = f"عيدفطر2020 سعيد، كل عام وانتم بخير"
awc.from_text(t).to_image()
```
reference: [for more details visit][1]
[1]: https://pypi.org/project/ar\_wordcloud/
Upvotes: 0 |
2018/03/20 | 2,907 | 11,077 | <issue_start>username_0: About two months ago we started using Rollbar to notify us of various errors in our Web App. Ever since then we have been getting the occasional error:
`ResizeObserver loop limit exceeded`
The thing that confuses me about this is that we are not using `ResizeObserver` and I have investigated the only plugin which I thought could possibly be the culprit, namely:
[Aurelia Resize](https://www.npmjs.com/package/aurelia-resize)
But it doesn't appear to be using `ResizeObserver` either.
What is also confusing is that these error messages have been occuring since January but `ResizeObserver` support has only recently been added to Chrome 65.
The browser versions that have been giving us this error are:
* Chrome: 63.0.3239 (ResizeObserver loop limit exceeded)
* Chrome: 64.0.3282 (ResizeObserver loop limit exceeded)
* Edge: 14.14393 (SecurityError)
* Edge: 15.15063 (SecurityError)
So I was wondering if this could possibly be a browser bug? Or perhaps an error that actually has nothing to do with `ResizeObserver`?<issue_comment>username_1: You can safely ignore this error.
One of the specification authors wrote in a comment to your question but it is not an answer and it is not clear in the comment that the answer is really the most important one in this thread, and the one that made me comfortable to ignore it in our Sentry logs.
>
> This error means that ResizeObserver was not able to deliver all observations within a single animation frame. It is benign (your site will not break). – [<NAME>](https://github.com/WICG/ResizeObserver/commits?author=atotic) Apr 15 at 3:14
>
>
>
There are also some [related issues](https://github.com/WICG/ResizeObserver/issues/38) to this in the specification repository.
Upvotes: 10 [selected_answer]<issue_comment>username_2: It's an old question but it still might be helpful to someone. You can avoid this error by wrapping the callback in `requestAnimationFrame`.
For example:
```js
const resizeObserver = new ResizeObserver(entries => {
// We wrap it in requestAnimationFrame to avoid this error - ResizeObserver loop limit exceeded
window.requestAnimationFrame(() => {
if (!Array.isArray(entries) || !entries.length) {
return;
}
// your code
});
});
```
Upvotes: 7 <issue_comment>username_3: We had this same issue. We found that a chrome extension was the culprit. Specifically, the loom chrome extension was causing the error (or some interaction of our code with loom extension). When we disabled the extension, our app worked.
I would recommend disabling certain extensions/addons to see if one of them might be contributing to the error.
Upvotes: 4 <issue_comment>username_4: If you're using Cypress and this issue bumps in, you can safely ignore it in Cypress with the following code in support/index.js or commands.ts
```js
const resizeObserverLoopErrRe = /^[^(ResizeObserver loop limit exceeded)]/
Cypress.on('uncaught:exception', (err) => {
/* returning false here prevents Cypress from failing the test */
if (resizeObserverLoopErrRe.test(err.message)) {
return false
}
})
```
You can follow the discussion about it [here](https://github.com/quasarframework/quasar/issues/2233).
As Cypress maintainer themselves proposed this solution, so I believe it'd be safe to do so.
Upvotes: 6 <issue_comment>username_5: add debounce like
new ResizeObserver(\_.debounce(entries => {}, 200);
fixed this error for me
Upvotes: 3 <issue_comment>username_6: For Mocha users:
The snippet below overrides the window.onerror hook mocha installs and turns the errors into a warning.
<https://github.com/mochajs/mocha/blob/667e9a21c10649185e92b319006cea5eb8d61f31/browser-entry.js#L74>
```js
// ignore ResizeObserver loop limit exceeded
// this is ok in several scenarios according to
// https://github.com/WICG/resize-observer/issues/38
before(() => {
// called before any tests are run
const e = window.onerror;
window.onerror = function(err) {
if(err === 'ResizeObserver loop limit exceeded') {
console.warn('Ignored: ResizeObserver loop limit exceeded');
return false;
} else {
return e(...arguments);
}
}
});
```
not sure there is a better way..
Upvotes: 3 <issue_comment>username_7: <https://github1s.com/chromium/chromium/blob/master/third_party/blink/renderer/core/resize_observer/resize_observer_controller.cc#L44-L45>
<https://github1s.com/chromium/chromium/blob/master/third_party/blink/renderer/core/frame/local_frame_view.cc#L2211-L2212>
After looking at the source code, it seems in my case the issue surfaced when the NotifyResizeObservers function was called, and there were no registered observers.
The GatherObservations function will return a min\_depth of 4096, in case there are no observers, and in that case, we will get the "ResizeObserver loop limit exceeded" error.
The way I resolved it is to have an observer living throughout the lifecycle of the page.
Upvotes: 1 <issue_comment>username_8: In my case, the issue "ResizeObserver - loop limit exceeded" was triggered because of `window.addEventListener("resize"` and React's `React.useState`.
In details, I was working on the hook called `useWindowResize` where the use case was like this `const [windowWidth, windowHeight] = useWindowResize();`.
The code reacts on the *windowWidth/windowHeight* change via the *useEffect*.
```
React.useEffect(() => {
ViewportService.dynamicDimensionControlledBy(
"height",
{ windowWidth, windowHeight },
widgetModalRef.current,
{ bottom: chartTitleHeight },
false,
({ h }) => setWidgetHeight(h),
);
}, [windowWidth, windowHeight, widgetModalRef, chartTitleHeight]);
```
So any browser window resize caused that issue.
I've found that many similar issues caused because of the connection *old-javascript-world* (DOM manipulation, browser's events) and the *new-javascript-world* (React) may be solved by the `setTimeout`, but I would to avoid it and call it anti-pattern when possible.
So my fix is to wrap the setter method into the *setTimeout* function.
```
React.useEffect(() => {
ViewportService.dynamicDimensionControlledBy(
"height",
{ windowWidth, windowHeight },
widgetModalRef.current,
{ bottom: chartTitleHeight },
false,
({ h }) => setTimeout(() => setWidgetHeight(h), 0),
);
}, [windowWidth, windowHeight, widgetModalRef, chartTitleHeight]);
```
Upvotes: 2 <issue_comment>username_9: The error might be worth investigating. It can indicate a problem in your code that can be fixed.
In our case an observed resize of an element triggered a change on the page, which caused a resize of the first element again, which again triggered a change on the page, which again caused a resize of the first element, … You know how this ends.
Essentially we created an infinite loop that could not be fitted into a single animation frame, obviously. We broke it by holding up the change on the page using `setTimeout()` (although this is not perfect since it may cause some flickering to the users).
So every time `ResizeObserver loop limit exceeded` emerges in our Sentry now, we look at it as a useful hint and try to find the cause of the problem.
Upvotes: 3 <issue_comment>username_10: One line solution for Cypress. Edit the file support/commands.js with:
```js
Cypress.on(
'uncaught:exception',
(err) => !err.message.includes('ResizeObserver loop limit exceeded')
);
```
Upvotes: 2 <issue_comment>username_11: Managed to solve this in React for our error logger setup.
The Observer error propagates to the `window.onerror` error handler, so by storing the original `window.onerror` in a ref, you can then replace it with a custom method that doesn't throw for this particular error. Other errors are allowed to propagate as normal.
Make sure you reconnect the original `onerror` in the `useEffect` cleanup.
```
const defaultOnErrorFn = useRef(window.onerror);
useEffect(() => {
window.onerror = (...args) => {
if (args[0] === 'ResizeObserver loop limit exceeded') {
return true;
} else {
defaultOnErrorFn.current && defaultOnErrorFn.current(...args);
}
};
return () => {
window.onerror = defaultOnErrorFn.current;
};
}, []);
```
Upvotes: 0 <issue_comment>username_12: I had this issue with cypress tests not being able to run.
I found that instead of handling the exception the proper way was to edit the tsconfig.json in a way to target the new es6 version like so:
```js
{
"extends": "../tsconfig.json",
"compilerOptions": {
"baseUrl": "../node_modules",
"target": "es5", --> old
"target": "es6", --> new
"types": ["cypress", "@testing-library/cypress"],
"sourceMap": true
},
"include": [
"**/*.ts"
]
}
```
Upvotes: 0 <issue_comment>username_13: In my case, I was only interested in changes to an element's width. But changing the element's height during a ResizeObserver event caused a "ResizeObserver loop limit exceeded" error.
To suppress the error, I stopped observing prior to changing the element's size, and started observing again after rendering was complete. Essentially:
```
const observer = new ResizeObserver(function (entries) {
observer.unobserve(element);
// ...manipulate the element...
setTimeout(function () {
observer.observe(element);
}, 0);
});
```
The complete solution is here: <https://gist.github.com/username_13/b026fdd168c8af8cd8ac5cb914e7b3cc>.
Upvotes: 0 <issue_comment>username_14: In Cypress/Jest/Mocha, you can avoid this error with a polyfill:
```
npm install resize-observer-polyfill --save-dev
```
Add this to the test:
```
global.ResizeObserver = require('resize-observer-polyfill');
```
Upvotes: 0 <issue_comment>username_15: Reactjs
Fix Error: ResizeObserver loop limit exceeded
```
useEffect(() => {
window.addEventListener('error', e => {enter code here
if (e.message === 'ResizeObserver loop limit exceeded' || e.message === 'Script error.') {
const resizeObserverErrDiv = document.getElementById(
'webpack-dev-server-client-overlay-div'
)
const resizeObserverErr = document.getElementById(
'webpack-dev-server-client-overlay'
)
if (resizeObserverErr) {
resizeObserverErr.setAttribute('style', 'display: none');
}
if (resizeObserverErrDiv) {
resizeObserverErrDiv.setAttribute('style', 'display: none');
}
}
})
}, [])
```
Upvotes: 1 <issue_comment>username_16: We also had that issue with [Monaco Editor](https://github.com/microsoft/monaco-editor) because it is using `ResizeObserver` internally.
To fix it, we patched the original API by doing:
```js
class CalmResizeObserver extends ResizeObserver {
constructor(callback: ResizeObserverCallback) {
super((entries, observer) => {
requestAnimationFrame(() => {
callback(entries, observer);
});
});
}
}
win.ResizeObserver = CalmResizeObserver;
```
Upvotes: 2 |
2018/03/20 | 2,753 | 10,497 | <issue_start>username_0: ```
newfile = open("Student Data.txt","w")
with open("Student Data.txt") as a_file:
data = a_file.readlines()
data[1] = username + " " + password + "\n"
with open("Student Data.txt", "w") as a_file:
a_file.writelines(data)
input()
```
i have created username and password with a input statement and and a int input for the age. If anyone can help me write this to a .txt file i would help me massively.<issue_comment>username_1: You can safely ignore this error.
One of the specification authors wrote in a comment to your question but it is not an answer and it is not clear in the comment that the answer is really the most important one in this thread, and the one that made me comfortable to ignore it in our Sentry logs.
>
> This error means that ResizeObserver was not able to deliver all observations within a single animation frame. It is benign (your site will not break). – [<NAME>](https://github.com/WICG/ResizeObserver/commits?author=atotic) Apr 15 at 3:14
>
>
>
There are also some [related issues](https://github.com/WICG/ResizeObserver/issues/38) to this in the specification repository.
Upvotes: 10 [selected_answer]<issue_comment>username_2: It's an old question but it still might be helpful to someone. You can avoid this error by wrapping the callback in `requestAnimationFrame`.
For example:
```js
const resizeObserver = new ResizeObserver(entries => {
// We wrap it in requestAnimationFrame to avoid this error - ResizeObserver loop limit exceeded
window.requestAnimationFrame(() => {
if (!Array.isArray(entries) || !entries.length) {
return;
}
// your code
});
});
```
Upvotes: 7 <issue_comment>username_3: We had this same issue. We found that a chrome extension was the culprit. Specifically, the loom chrome extension was causing the error (or some interaction of our code with loom extension). When we disabled the extension, our app worked.
I would recommend disabling certain extensions/addons to see if one of them might be contributing to the error.
Upvotes: 4 <issue_comment>username_4: If you're using Cypress and this issue bumps in, you can safely ignore it in Cypress with the following code in support/index.js or commands.ts
```js
const resizeObserverLoopErrRe = /^[^(ResizeObserver loop limit exceeded)]/
Cypress.on('uncaught:exception', (err) => {
/* returning false here prevents Cypress from failing the test */
if (resizeObserverLoopErrRe.test(err.message)) {
return false
}
})
```
You can follow the discussion about it [here](https://github.com/quasarframework/quasar/issues/2233).
As Cypress maintainer themselves proposed this solution, so I believe it'd be safe to do so.
Upvotes: 6 <issue_comment>username_5: add debounce like
new ResizeObserver(\_.debounce(entries => {}, 200);
fixed this error for me
Upvotes: 3 <issue_comment>username_6: For Mocha users:
The snippet below overrides the window.onerror hook mocha installs and turns the errors into a warning.
<https://github.com/mochajs/mocha/blob/667e9a21c10649185e92b319006cea5eb8d61f31/browser-entry.js#L74>
```js
// ignore ResizeObserver loop limit exceeded
// this is ok in several scenarios according to
// https://github.com/WICG/resize-observer/issues/38
before(() => {
// called before any tests are run
const e = window.onerror;
window.onerror = function(err) {
if(err === 'ResizeObserver loop limit exceeded') {
console.warn('Ignored: ResizeObserver loop limit exceeded');
return false;
} else {
return e(...arguments);
}
}
});
```
not sure there is a better way..
Upvotes: 3 <issue_comment>username_7: <https://github1s.com/chromium/chromium/blob/master/third_party/blink/renderer/core/resize_observer/resize_observer_controller.cc#L44-L45>
<https://github1s.com/chromium/chromium/blob/master/third_party/blink/renderer/core/frame/local_frame_view.cc#L2211-L2212>
After looking at the source code, it seems in my case the issue surfaced when the NotifyResizeObservers function was called, and there were no registered observers.
The GatherObservations function will return a min\_depth of 4096, in case there are no observers, and in that case, we will get the "ResizeObserver loop limit exceeded" error.
The way I resolved it is to have an observer living throughout the lifecycle of the page.
Upvotes: 1 <issue_comment>username_8: In my case, the issue "ResizeObserver - loop limit exceeded" was triggered because of `window.addEventListener("resize"` and React's `React.useState`.
In details, I was working on the hook called `useWindowResize` where the use case was like this `const [windowWidth, windowHeight] = useWindowResize();`.
The code reacts on the *windowWidth/windowHeight* change via the *useEffect*.
```
React.useEffect(() => {
ViewportService.dynamicDimensionControlledBy(
"height",
{ windowWidth, windowHeight },
widgetModalRef.current,
{ bottom: chartTitleHeight },
false,
({ h }) => setWidgetHeight(h),
);
}, [windowWidth, windowHeight, widgetModalRef, chartTitleHeight]);
```
So any browser window resize caused that issue.
I've found that many similar issues caused because of the connection *old-javascript-world* (DOM manipulation, browser's events) and the *new-javascript-world* (React) may be solved by the `setTimeout`, but I would to avoid it and call it anti-pattern when possible.
So my fix is to wrap the setter method into the *setTimeout* function.
```
React.useEffect(() => {
ViewportService.dynamicDimensionControlledBy(
"height",
{ windowWidth, windowHeight },
widgetModalRef.current,
{ bottom: chartTitleHeight },
false,
({ h }) => setTimeout(() => setWidgetHeight(h), 0),
);
}, [windowWidth, windowHeight, widgetModalRef, chartTitleHeight]);
```
Upvotes: 2 <issue_comment>username_9: The error might be worth investigating. It can indicate a problem in your code that can be fixed.
In our case an observed resize of an element triggered a change on the page, which caused a resize of the first element again, which again triggered a change on the page, which again caused a resize of the first element, … You know how this ends.
Essentially we created an infinite loop that could not be fitted into a single animation frame, obviously. We broke it by holding up the change on the page using `setTimeout()` (although this is not perfect since it may cause some flickering to the users).
So every time `ResizeObserver loop limit exceeded` emerges in our Sentry now, we look at it as a useful hint and try to find the cause of the problem.
Upvotes: 3 <issue_comment>username_10: One line solution for Cypress. Edit the file support/commands.js with:
```js
Cypress.on(
'uncaught:exception',
(err) => !err.message.includes('ResizeObserver loop limit exceeded')
);
```
Upvotes: 2 <issue_comment>username_11: Managed to solve this in React for our error logger setup.
The Observer error propagates to the `window.onerror` error handler, so by storing the original `window.onerror` in a ref, you can then replace it with a custom method that doesn't throw for this particular error. Other errors are allowed to propagate as normal.
Make sure you reconnect the original `onerror` in the `useEffect` cleanup.
```
const defaultOnErrorFn = useRef(window.onerror);
useEffect(() => {
window.onerror = (...args) => {
if (args[0] === 'ResizeObserver loop limit exceeded') {
return true;
} else {
defaultOnErrorFn.current && defaultOnErrorFn.current(...args);
}
};
return () => {
window.onerror = defaultOnErrorFn.current;
};
}, []);
```
Upvotes: 0 <issue_comment>username_12: I had this issue with cypress tests not being able to run.
I found that instead of handling the exception the proper way was to edit the tsconfig.json in a way to target the new es6 version like so:
```js
{
"extends": "../tsconfig.json",
"compilerOptions": {
"baseUrl": "../node_modules",
"target": "es5", --> old
"target": "es6", --> new
"types": ["cypress", "@testing-library/cypress"],
"sourceMap": true
},
"include": [
"**/*.ts"
]
}
```
Upvotes: 0 <issue_comment>username_13: In my case, I was only interested in changes to an element's width. But changing the element's height during a ResizeObserver event caused a "ResizeObserver loop limit exceeded" error.
To suppress the error, I stopped observing prior to changing the element's size, and started observing again after rendering was complete. Essentially:
```
const observer = new ResizeObserver(function (entries) {
observer.unobserve(element);
// ...manipulate the element...
setTimeout(function () {
observer.observe(element);
}, 0);
});
```
The complete solution is here: <https://gist.github.com/username_13/b026fdd168c8af8cd8ac5cb914e7b3cc>.
Upvotes: 0 <issue_comment>username_14: In Cypress/Jest/Mocha, you can avoid this error with a polyfill:
```
npm install resize-observer-polyfill --save-dev
```
Add this to the test:
```
global.ResizeObserver = require('resize-observer-polyfill');
```
Upvotes: 0 <issue_comment>username_15: Reactjs
Fix Error: ResizeObserver loop limit exceeded
```
useEffect(() => {
window.addEventListener('error', e => {enter code here
if (e.message === 'ResizeObserver loop limit exceeded' || e.message === 'Script error.') {
const resizeObserverErrDiv = document.getElementById(
'webpack-dev-server-client-overlay-div'
)
const resizeObserverErr = document.getElementById(
'webpack-dev-server-client-overlay'
)
if (resizeObserverErr) {
resizeObserverErr.setAttribute('style', 'display: none');
}
if (resizeObserverErrDiv) {
resizeObserverErrDiv.setAttribute('style', 'display: none');
}
}
})
}, [])
```
Upvotes: 1 <issue_comment>username_16: We also had that issue with [Monaco Editor](https://github.com/microsoft/monaco-editor) because it is using `ResizeObserver` internally.
To fix it, we patched the original API by doing:
```js
class CalmResizeObserver extends ResizeObserver {
constructor(callback: ResizeObserverCallback) {
super((entries, observer) => {
requestAnimationFrame(() => {
callback(entries, observer);
});
});
}
}
win.ResizeObserver = CalmResizeObserver;
```
Upvotes: 2 |
2018/03/20 | 1,592 | 5,189 | <issue_start>username_0: I am using the python-pptx library for pptx manipulation. I want to add a bullet list in the pptx document.
I am using the following snippet to add list item:
```
p = text_frame.add_paragraph()
run = p.add_run()
p.level = 0
run.text = "First"
```
But it does not display bullet points; please guide.<issue_comment>username_1: Try this:
```
p = text_frame.add_paragraph()
p.level = 0
p.text = "First"
```
Or if the text\_frame already has a paragraph:
```
p = text_frame.paragraphs[0]
p.level = 0
p.text = "First"
```
Upvotes: 0 <issue_comment>username_2: It is currently not possible to access the bullet property using python-pptx, but I want to share a workaround that has served me well.
This requires the use of a pptx template, in which we exploit the fact that the levels in a slide layout can be customized individually.
For instance, in the slide layout you could set level 0 to be normal text, level 1 to be bullets, and level 2 to be numbers or any other list style you want. You can then modify font size, indentation (using the ruler at the top), and any other property of each level to get the look you want.
For my use-case, I just set levels 1 and 2 to have the same indentation and size as level 0, making it possible to create bullet lists and numbered lists by simply setting the level to the corresponding value.
This is how my slide layout looks in the template file:
[slide layout example](https://i.stack.imgur.com/vAiHX.png)
And this is how I set the corresponding list style in the code:
```
p.level = 0 # Regular text
p.level = 1 # Bullet
p.level = 2 # Numbers
```
In theory, you should be able to set it up exactly the way you want, even with indented sub-lists and so on. The only limitation I am aware of is that there seems to be a maximum of 8 levels that can be customized in the slide layout.
Upvotes: 2 <issue_comment>username_3: My solution:
```
from pptx.oxml.xmlchemy import OxmlElement
def SubElement(parent, tagname, **kwargs):
element = OxmlElement(tagname)
element.attrib.update(kwargs)
parent.append(element)
return element
def makeParaBulletPointed(para):
"""Bullets are set to Arial,
actual text can be a different font"""
pPr = para._p.get_or_add_pPr()
## Set marL and indent attributes
pPr.set('marL','171450')
pPr.set('indent','171450')
## Add buFont
_ = SubElement(parent=pPr,
tagname="a:buFont",
typeface="Arial",
panose="020B0604020202020204",
pitchFamily="34",
charset="0"
)
## Add buChar
_ = SubElement(parent=pPr,
tagname='a:buChar',
char="•")
```
Upvotes: 1 <issue_comment>username_4: This question is still up to date on May 27, 2021.
Following up on @username_3's answer I would like to add a little more detail as well as my turn on the problem.
I created a new package with the following code:
```py
from pptx.oxml.xmlchemy import OxmlElement
def getBulletInfo(paragraph, run=None):
"""Returns the attributes of the given OxmlElement
as well as its runs font-size.
\*param: paragraph\* pptx \_paragraph object
\*param: run\* [optional] specific \_run object
"""
pPr = paragraph.\_p.get\_or\_add\_pPr()
if run is None:
run = paragraph.runs[0]
p\_info = {
"marL": pPr.attrib['marL'],
"indent": pPr.attrib['indent'],
"level": paragraph.level,
"fontName": run.font.name,
"fontSize": run.font.size,
}
return p\_info
def SubElement(parent, tagname, \*\*kwargs):
"""Helper for Paragraph bullet Point
"""
element = OxmlElement(tagname)
element.attrib.update(kwargs)
parent.append(element)
return element
def pBullet(
paragraph, # paragraph object
font, # fontName of that needs to be applied to bullet
marL='864000',
indent='-322920',
size='350000' # fontSize (in )
):
"""Bullets are set to Arial,
actual text can be a different font
"""
pPr = paragraph.\_p.get\_or\_add\_pPr()
# Set marL and indent attributes
# Indent is the space between the bullet and the text.
pPr.set('marL', marL)
pPr.set('indent', indent)
# Add buFont
\_ = SubElement(parent=pPr,
tagname="a:buSzPct",
val="350000"
)
\_ = SubElement(parent=pPr,
tagname="a:buFont",
typeface=font,
# panose="020B0604020202020204",
# pitchFamily="34",
# charset="0"
)
# Add buChar
\_ = SubElement(parent=pPr,
tagname='a:buChar',
char="•"
)
```
The reason I did this is because I was frustrated that the bullet character was not of the same size as the original and the text was stuck to the bullet.
`getBulletInfo()` allows me to retrieve information from an existing paragraph.
I use this information to populate the element's attributes (so that it is identical to the template).
Anyways the main add-on is the creation of a sub-element (documentation [here](https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.drawing.bulletsizepercentage?view=openxml-2.8.1) and [here](http://www.officeopenxml.com/drwSp-text-paraProps-numbering.php)). This is a size percentage that can go from 25% to 350% (100000 = 100%).
Upvotes: 1 |
2018/03/20 | 887 | 3,470 | <issue_start>username_0: In most modern programming languages, programmers don't need to *close* the `stdin`,`stdout`,`stderr`. Does it mean that the operating system will handle the close of the `stdin`, `stdout`, `stderr` in general?
Or for instance in `java`, the `jvm` will close the `stdin`, `stdout`, `stderr` when the running Java program `exit`?
There might be exceptions like some old programmers mentioned, so hereby I narrow down the language spectrum to Java, C, C++ only<issue_comment>username_1: Almost all programs run under a C run-time, so upon normal termination the rules of the C `exit()` function should apply. Per **7.22.4.4 The `exit` function** of [the C Standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf):
>
> **Description**
>
>
> The `exit` function causes normal program termination to occur. No
> functions registered by the `at_quick_exit` function are called. If a program calls the `exit` function more than once, or calls
> the `quick_exit` function in addition to the `exit` function, the
> behavior is undefined.
>
>
> First, all functions registered by the `atexit` function are called,
> in the reverse order of their registration, except that a function
> is called after any previously registered functions that had
> already been called at the time it was registered. If, during the
> call to any such function, a call to the `longjmp` function is made
> that would terminate the call to the registered function, the behavior
> is undefined.
>
>
> Next, all open streams with unwritten buffered data are
> flushed, all open streams are closed, and all files created by the
> `tmpfile` function are removed.
>
>
> Finally, control is returned to the host environment. If the
> value of `status` is zero or `EXIT_SUCCESS`, an
> implementation-defined form of the status
> *successful termination* is returned. If the value of `status` is `EXIT_FAILURE`, an implementation-defined form of the status
> *unsuccessful termination* is returned. Otherwise the status returned is implementation-defined.
>
>
>
For any process that's not running under a standards-compliant C runtime, what happens upon process termination would be implementation-defined.
Upvotes: 2 <issue_comment>username_2: Your question is highly system specific. First of all, these terms have multiple meanings. Let's take the specific examples of eunuchs-variants. There, each process is a copy of parent process. It is normal for shells to set up file numbers 0, 1, and 2 set up for the child process when it runs.
These "files" are referred to as stdin, stdout, and stderr.
C programers have two layers of libraries. In eunuchs variants, you can access the system services like read or write that operate on a file idea. In addition, the standard C library has function layered upon these (e.g. fread and fwrite) that do buffer. It also defines symbols stdin, stout, and stderr which that reference structures the serve as arguments for the f\_\_\_\_\_ file function. Somewhere, embedded in these structures is the file number.
So, just in eunuchs-land, your question has two answers depending if you are referring to stdio et al. as file numbers or as symbols created by the c library?
If you are referring to the library symbols, the library has to be set up to handle program exit to flush the buffer.
If you are referring to the file numbers, that has to be handled by the operating system.
Upvotes: 0 |
2018/03/20 | 1,195 | 4,151 | <issue_start>username_0: I am using two controllers. When changes happen in one controllers it should get changed immediately in the other controller. I am using the $broadcast event to achive this.
My code:
My First controller
```
app.controller('configurationCtrl', function($scope, $http,Notification,$rootScope,$cookies) {
$scope.awssubmit=function(){
$scope.page_loader=true
$http.post("/insert_config_details",$scope.userdata).then(function(List){
if(List){
$scope.page_loader=false;
$cookies.put("bucket",$scope.userdata.bucket_name)
$scope.$broadcast('eventEmitedName', 'Some data');
Notification.success(' **AWS Configuration details updated successfully.**');
}
else{
$scope.page_loader=false;
Notification.error(' **Error!!! Please try again later.**');
}
$scope.awssave = false;
$scope.awstext=true;
})
}
});
```
My Second Controller:
```
app.controller('SidemenuController', function($scope, $http,$location,BucketService)
{
$scope.$on('eventEmitedName', function (event, data) {
console.log("Called"); //I am not getting this
value
console.log(data); // 'Some data' // I am not getting this
value
});
});
```
aws\_submit() is called from my view and everything seems to work fine. But in SidemenuController I am not getting any data. Is there any mistake in my code?
Update:
My view :
```
#### AWS S3 Configurations
<% if(valid\_role[1]) { %>
<% } %>
#### AWS S3 Configurations
Test
Submit
Cancel
\*Enter your AWS access Key, S3 Bucket name configured in your AWS Environment. Which is used to store your document in the
cloud.
AWS access key \*
AWS Secret Key \*
AWS Region Code \*
AWS Bucket Name \*
```<issue_comment>username_1: If you want to call one controller event into another there are four methods available:
* `$rootScope.$broadcast()` if your controller are not in a parent / child relation.
* If your second controller (event fired here) is a parent you can use `$scope.$broadcast();`
* If your second controller (event fired here) is a child you can use `$scope.$emit();`
* The best way to solve this would be to **use a service** -> [Example of using a service to share data between controllers](https://stackoverflow.com/questions/49148694/angularjs-emit-method-sending-duplicate-data/49149266#49149266).
**Note:** You need to destroy `$rootScope.$on()` listeners manually avoid stacking events. This [Difference between $rootScope.$on vs $scope.$on](https://stackoverflow.com/questions/41632318/difference-between-rootscope-on-vs-scope-on/43638652#43638652) and this [Do you need to unbind $scope.$on in $scope $destroy event?](https://stackoverflow.com/questions/42247286/do-you-need-to-unbind-scope-on-in-scope-destroy-event/42247423#42247423) will help you understand the basics of using events.
### View
```
broadcast
{{ test }}
```
### AngularJS application
```
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $rootScope) {
$scope.broadcast = function() {
$rootScope.$broadcast('test', 'testit');
}
});
myApp.controller('MySecondCtrl', function($scope, $rootScope) {
var registerScope = $rootScope.$on('test', function(test, args) {
console.log(args);
$scope.test = args;
});
// clean up, destroy event when controller get destroyed.
$scope.$on('$destroy', registerScope);
});
```
**> [demo fiddle](http://jsfiddle.net/393k25t5/)**
Upvotes: 1 <issue_comment>username_2: If you want to send data from one controller to another controller using $`brodcast` than use `$rootscope.$broadcast`
```
$rootScope.$broadcast('eventEmitedName', 'Some data');
```
Second Controller
```
app.controller('SidemenuController', function($scope, $http,$location,BucketService) {
$scope.$on('eventEmitedName', function (event, data) {
console.log("Called");
console.log(data); // 'Some data'
$scope.bucket = data;
});
});
```
>
> Note: Do not use `$rootscope.$on` as listener because $rootscope
> listener are not destroyed . Instead it will create listeners stack
>
>
>
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,387 | 4,925 | <issue_start>username_0: I have a template txt file. This txt file is to be written as 10 new files but each with some characters changed according to a list of arbitrary values:
```
with open('template.txt') as template_file:
template = template_file.readlines()
for i in range(10):
with open('output_%s.txt' % i, 'w') as new_file:
new_file.writelines(template_file)
```
The length of the list is the same as the number of new files (10).
I am trying to replace part of the 2nd line of each new file with the value in my list.
So for example, I want line 2, positions [5:16] in each new file replaced with the respective value in the list..
File 0 will have element 0 of the list
File 1 will have element 1 of the list
etc..
I tried using the `replace()` method:
```
list = [element0, element1, etc...element9]
for i in template_file:
i.replace(template_file[2][5:16], list_element)
```
But it will only replace all the files with the first list element... It wont loop over.
Any help appreciated<issue_comment>username_1: Looks like you need
```
list = [element0, element1, etc...element9]
for i in list:
template_file = template_file.replace(template_file[2][5:16], i)
```
Upvotes: 0 <issue_comment>username_2: There are a couple of problems I can find which prevent your code from working:
* You should write `template` out, which is a list of lines, not `template_file`, which is a file object
* In Python, strings are immutable, meaning they cannot be changed. The `replace` function does not change the string, it returns a new copy of the string. Furthermore, `replace` will replace a substring with a new text, regardless of where that substring is. If you want to replace at a specific index, I suggest to slice the string yourself. For example:
```
line2 = '0123456789ABCDEFG'
element = '-ho-ho-ho-'
line2 = line2[:5] + element + line2[16:]
# line2 now is '01234-ho-ho-ho-G'
```
* Please do not use `list` as a variable name. It is a type, which can be used to construct a new list as such:
```
empty = list() # ==> []
letters = list('abc') # ==> ['a', 'b', 'c']
```
* The expression `template_file[2][5:16]` is incorrect: First, it should be `template`, not `template_file`. Second, the second line should be `template[1]`, not `template[2]` since Python list are zero based
* The `list_element` variable is not declared in your code
Solution 1
==========
That being said, I find that it is easier to structure your template file as a real template with placeholders. I'll talk about that later. If you still insist to replace index 5-16 of line 2 with something, here is a solution I tested and it works:
```
with open('template.txt') as template_file:
template = template_file.readlines()
elements = ['ABC', 'DEF', 'GHI', 'JKL']
for i, element in enumerate(elements):
with open('output_%02d.txt' % i, 'w') as out_file:
line2 = template[1]
line2 = line2[:5] + element + line2[16:]
for line_number, line in enumerate(template, 1):
if line_number == 2:
line = line2
out_file.write(line)
```
Notes
* The code writes out all lines, but with special replacement applies to line 2
* The code is clunky, nested deeply
* I don't like having to hard code the index numbers (5, 16) because if the template changes, I have to change the code as well
Solution 2
==========
If you have control of the template file, I suggest to use the `string.Template` class to make search and replace easier. Since I don't know what your template file looks like, I am going to make up my own template file:
```
line #1
This is my ${token} to be replaced
line #3
line #4
```
Note that I intent to replace `${token}` with one of the elements in the code. Now on to the code:
```
import string
with open('template.txt') as template_file:
template = string.Template(template_file.read())
elements = ['ABC', 'DEF', 'GHI', 'JKL']
for i, element in enumerate(elements):
with open('output_%02d.txt' % i, 'w') as out_file:
out_file.write(template.substitute(token=element))
```
Notes
* I read the whole file in at once with `template_file.read()`. This could be a problem if the template file is large, but previous solution als ran into the same performance issue as this one
* I use the `string.Template` class to make search/replace easier
* Search and replace is done by `substitute(token=element)` which said: replace all the `$token` or `${token}` instances in the `template` with `element`.
* The code is much cleaner and dare I say, easier to read.
Solution 3
==========
If the template file is too large to fit in memory at once, you can modify the first solution to read it line-by-line instead of reading all lines in at once. I am not going to present that solution here, just a asuggestion.
Upvotes: 1 |
2018/03/20 | 1,324 | 4,748 | <issue_start>username_0: I am trying to create an AbstractClass using both abc.ABCMeta and QObject as parents and cannot seems to make it work.
Here is the Base class init. I have Pyqt5 and python 2.7
```
pyqtWrapperType = type(QObject)
class ParamsHandler(abc.ABCMeta, pyqtWrapperType):
def __init__(self, device_model, read_only=False):
super(ParamsHandler, self).__init__()
self.cmd_to_get_data = None
self.device_model = device_model
class ConfigParamsHandler(ParamsHandler):
def __init__(self, device_model):
super(ConfigParamsHandler, self).__init__(device_model)
self.cmd_to_get_data = Commands.CONFIG_PARAMS
```
I get a TypeError('**new**() takes exactly 4 arguments (2 given)',) I also have Pycharm suggesting that I use cls instead of self
If I supply 4 arguments, it asks for a string as the first argument.<issue_comment>username_1: Looks like you need
```
list = [element0, element1, etc...element9]
for i in list:
template_file = template_file.replace(template_file[2][5:16], i)
```
Upvotes: 0 <issue_comment>username_2: There are a couple of problems I can find which prevent your code from working:
* You should write `template` out, which is a list of lines, not `template_file`, which is a file object
* In Python, strings are immutable, meaning they cannot be changed. The `replace` function does not change the string, it returns a new copy of the string. Furthermore, `replace` will replace a substring with a new text, regardless of where that substring is. If you want to replace at a specific index, I suggest to slice the string yourself. For example:
```
line2 = '0123456789ABCDEFG'
element = '-ho-ho-ho-'
line2 = line2[:5] + element + line2[16:]
# line2 now is '01234-ho-ho-ho-G'
```
* Please do not use `list` as a variable name. It is a type, which can be used to construct a new list as such:
```
empty = list() # ==> []
letters = list('abc') # ==> ['a', 'b', 'c']
```
* The expression `template_file[2][5:16]` is incorrect: First, it should be `template`, not `template_file`. Second, the second line should be `template[1]`, not `template[2]` since Python list are zero based
* The `list_element` variable is not declared in your code
Solution 1
==========
That being said, I find that it is easier to structure your template file as a real template with placeholders. I'll talk about that later. If you still insist to replace index 5-16 of line 2 with something, here is a solution I tested and it works:
```
with open('template.txt') as template_file:
template = template_file.readlines()
elements = ['ABC', 'DEF', 'GHI', 'JKL']
for i, element in enumerate(elements):
with open('output_%02d.txt' % i, 'w') as out_file:
line2 = template[1]
line2 = line2[:5] + element + line2[16:]
for line_number, line in enumerate(template, 1):
if line_number == 2:
line = line2
out_file.write(line)
```
Notes
* The code writes out all lines, but with special replacement applies to line 2
* The code is clunky, nested deeply
* I don't like having to hard code the index numbers (5, 16) because if the template changes, I have to change the code as well
Solution 2
==========
If you have control of the template file, I suggest to use the `string.Template` class to make search and replace easier. Since I don't know what your template file looks like, I am going to make up my own template file:
```
line #1
This is my ${token} to be replaced
line #3
line #4
```
Note that I intent to replace `${token}` with one of the elements in the code. Now on to the code:
```
import string
with open('template.txt') as template_file:
template = string.Template(template_file.read())
elements = ['ABC', 'DEF', 'GHI', 'JKL']
for i, element in enumerate(elements):
with open('output_%02d.txt' % i, 'w') as out_file:
out_file.write(template.substitute(token=element))
```
Notes
* I read the whole file in at once with `template_file.read()`. This could be a problem if the template file is large, but previous solution als ran into the same performance issue as this one
* I use the `string.Template` class to make search/replace easier
* Search and replace is done by `substitute(token=element)` which said: replace all the `$token` or `${token}` instances in the `template` with `element`.
* The code is much cleaner and dare I say, easier to read.
Solution 3
==========
If the template file is too large to fit in memory at once, you can modify the first solution to read it line-by-line instead of reading all lines in at once. I am not going to present that solution here, just a asuggestion.
Upvotes: 1 |
2018/03/20 | 919 | 3,665 | <issue_start>username_0: I have a superclass and two subclasses that extend it. I'd like to initialize a variable called radius which can be set freely in subclass A, but is always the same for subclass B. I could initialize the variable every time I create an object B, but I was wondering if it's possible to make the variable final and static in subclass B, while still being able to implement a getter in my superclass. I might implement more subclasses which have a radius that's either final or variable. If not I'm wondering what would be the most elegant solution for my problem. Here is some sample code which works, but isn't very great.
```
abstract class SuperClass {
public double getRadius() {
return this.radius;
}
protected double radius;
}
class A extends SuperClass{
public void setRadius(double radius) { // Would like to put this setter in SuperClass for future subclasses.
this.radius = radius;
}
}
class B extends SuperClass{
public B() {
radius = 0.2; //Want to make this static and final only for this subclass.
}
}
```<issue_comment>username_1: >
> Making a variable final and static in one subclass, while keeping it
> variable in others in Java
>
>
>
Technically, you cannot do it.
A field is either a static field or an instance field, not both.
As alternative, override `getRadius()` in the `B` class where you want to provide a different value :
```
@Override
public double getRadius() {
return 0.2;
}
```
And to make this constant respected, you should also override the setter in this `B` class:
```
@Override
public void setRadius(double radius) {
throw new UnsupportedOperationException();
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Why dont you try this:
Make the Variable private in the superclass.
Have a getter and setter method in the superclass.
Override the setter method in the subclass so that is is not possible to change the variable.
Like that:
```
abstract class SuperClass {
private double radius;
public double getRadius() {
return this.radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
class A extends SuperClass{
}
class B extends SuperClass{
public B() {
super.setRadius(0.2d);
}
@Override
public void setRadius(double radius) {
throw new UnsupportedOperationException("My Info Text");
}
}
```
Upvotes: 1 <issue_comment>username_3: Another approach would be to have the base class **in its own package**, with a protected setter:
```
package sandbox.radius.base;
public class Radius {
private double radius;
public double getRadius() {
return radius;
}
protected void setRadius(double radius) {
this.radius = radius;
}
}
```
Then implementations in a **different package**, exposes the setter only where appropriate, delegating to super:
```
package sandbox.radius;
import sandbox.radius.base.Radius;
public class FixedRadius extends Radius {
public FixedRadius() {
setRadius(0.2);
}
}
```
and
```
package sandbox.radius;
import sandbox.radius.base.Radius;
public class MutableRadius extends Radius {
public void setRadius(double radius) {
super.setRadius(radius);
}
}
```
So the API is cleaner:
```
public class RadiusApp {
public static void main(String[] args) {
FixedRadius fr = new FixedRadius();
fr.getRadius();
// fr.setRadius(1.0); //compile error
MutableRadius mr = new MutableRadius();
mr.getRadius();
mr.setRadius(1.0);
}
}
```
Upvotes: 1 |
2018/03/20 | 1,377 | 4,934 | <issue_start>username_0: I'm having issues trying to remove elements/objects from an array in elasticsearch.
This is the mapping for the index:
```
{
"example1": {
"mappings": {
"doc": {
"properties": {
"locations": {
"type": "geo_point"
},
"postDate": {
"type": "date"
},
"status": {
"type": "long"
},
"user": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
```
And this is an example document.
```
{
"_index": "example1",
"_type": "doc",
"_id": "8036",
"_score": 1,
"_source": {
"user": "kimchy8036",
"postDate": "2009-11-15T13:12:00",
"locations": [
[
72.79887719999999,
21.193036000000003
],
[
-1.8262150000000001,
51.178881999999994
]
]
}
}
```
Using the query below, I can add multiple locations.
```
POST /example1/_update_by_query
{
"query": {
"match": {
"_id": "3"
}
},
"script": {
"lang": "painless",
"inline": "ctx._source.locations.add(params.newsupp)",
"params": {
"newsupp": [
-74.00,
41.12121
]
}
}
}
```
But I'm not able to remove array objects from locations. I have tried the query below but it's not working.
```
POST example1/doc/3/_update
{
"script": {
"lang": "painless",
"inline": "ctx._source.locations.remove(params.tag)",
"params": {
"tag": [
-74.00,
41.12121
]
}
}
}
```
Kindly let me know where i am doing wrong here. I am using elastic version 5.5.2<issue_comment>username_1: Unlike `add()`, `remove()` takes **the index of the element** and remove it.
Your `ctx._source.locations` in painless is an `ArrayList`. It has `List`'s [`remove()`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#remove-int-) method:
>
> E remove(int index)
>
>
> Removes the element at the specified position in this list (optional operation). ...
>
>
>
See [Painless API - List](https://www.elastic.co/guide/en/elasticsearch/painless/6.3/painless-api-reference.html#painless-api-reference-List) for other methods.
See [this answer](https://stackoverflow.com/questions/45980054/how-to-remove-arraylist-value-in-elastic-search-using-curl) for example code.
Upvotes: 2 <issue_comment>username_2: In painless scripts, `Array.remove()` method removes by index, not by value.
Here's a working example that removes array elements by value in Elasticsearch script:
```
POST objects/_update_by_query
{
"query": {
... // use regular ES query to remove only in relevant documents
},
"script": {
"source": """
if (ctx._source[params.array_attribute] != null) {
for (int i=ctx._source[params.array_attribute].length-1; i>=0; i--) {
if (ctx._source[params.array_attribute][i] == params.value_to_remove) {
ctx._source[params.array_attribute].remove(i);
}
}
}
""",
"params": {
"array_attribute": "",
"value\_to\_remove": "",
}
}
}
```
You might want to simplify script, if your script shall only remove values from one specific array attribute. For example, removing `"green"` from document's `.color_list` array:
```
_doc/001 = {
"color_list": ["red", "blue", "green"]
}
```
Script to remove `"green"`:
```
POST objects/_update_by_query
{
"query": {
... // use regular ES query to remove only in relevant documents
},
"script": {
"source": """
for (int i=ctx._source.color_list.length-1; i>=0; i--) {
if (ctx._source.color_list[i] == params.color_to_remove) {
ctx._source.color_list.remove(i);
}
}
""",
"params": {
"color_to_remove": "green"
}
}
}
```
Upvotes: 3 <issue_comment>username_3: ```
"script" : {
"lang":"painless",
"inline":"ctx._source.locations.remove(params.tag)",
"params":{
"tag":indexToRemove
}
}
```
If with `ctx._source.locations.add(elt)` You add the element, with `ctx._source.locations.remove(indexToRemove)`, you remove by the index of element in the array.
Upvotes: 0 |
2018/03/20 | 1,282 | 4,016 | <issue_start>username_0: Let's say I have 2 tables where both has column called `Brand`. The value is comma delimited so for example if one of the table has
```
ACER,ASUS,HP
AMD,NVIDIA,SONY
```
as value. Then the other table has
```
HP,GIGABYTE
MICROSOFT
SAMSUNG,PHILIPS
```
as values.
I want to compare these table to get all matched record, in my example `ACER,ASUS,HP` and `HP,GIGABYTE` match because both has `HP`. Right now I'm using loop to achieve this, I'm wondering if it's possible to do this in a single query syntax.<issue_comment>username_1: Had the same problem with comparing "," delimited strings
you can use "XML" to do that and compare the outputs and return the same/different value:
```
declare @TestInput nvarchar(255)
, @TestInput2 nvarchar(255)
set @TestInput = 'ACER,ASUS,HP'
set @TestInput2 = 'HP,GIGABYTE'
;WITH FirstStringSplit(S1) AS
(
SELECT CAST('' + REPLACE(@TestInput,',','') + '' AS XML)
)
,SecondStringSplit(S2) AS
(
SELECT CAST('' + REPLACE(@TestInput2,',','') + '' AS XML)
)
SELECT STUFF(
(
SELECT ',' + part1.value('.','nvarchar(max)')
FROM FirstStringSplit
CROSS APPLY S1.nodes('/x') AS A(part1)
WHERE part1.value('.','nvarchar(max)') IN(SELECT B.part2.value('.','nvarchar(max)')
FROM SecondStringSplit
CROSS APPLY S2.nodes('/x') AS B(part2)
)
FOR XML PATH('')
),1,1,'') as [Same Value]
```
Edit:
Changed 'Stuff' to 'XML'
Upvotes: 0 <issue_comment>username_2: You are correct in wanting to step away from the loop.
Since you are on 2012, String\_Split() is off the table. However, there are any number of split/parse TVF functions in-the-wild.
**Example 1 - without a TVF**
```
Declare @T1 table (Brand varchar(50))
Insert Into @T1 values
('ACER,ASUS,HP'),
('AMD,NVIDIA,SONY')
Declare @T2 table (Brand varchar(50))
Insert Into @T2 values
('HP,GIGABYTE'),
('MICROSOFT'),
('SAMSUNG,PHILIPS')
Select Distinct
T1_Brand = A.Brand
,T2_Brand = B.Brand
From (
Select Brand,B.*
From @T1
Cross Apply (
Select RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('' + replace(Brand,',','')+'' as xml)) as A
Cross Apply x.nodes('x') AS B(i)
) B
) A
Join (
Select Brand,B.*
From @T2
Cross Apply (
Select RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('' + replace(Brand,',','')+'' as xml)) as A
Cross Apply x.nodes('x') AS B(i)
) B
) B
on A.RetVal=B.RetVal
```
**Example 2 - with a TVF**
```
Select Distinct
T1_Brand = A.Brand
,T2_Brand = B.Brand
From (
Select Brand,B.*
From @T1
Cross Apply [dbo].[tvf-Str-Parse](Brand,',') B
) A
Join (
Select Brand,B.*
From @T2
Cross Apply [dbo].[tvf-Str-Parse](Brand,',') B
) B
on A.RetVal=B.RetVal
```
**Both Would Return**
```
T1_Brand T2_Brand
ACER,ASUS,HP HP,GIGABYTE
```
**The UDF if interested**
```
CREATE FUNCTION [dbo].[tvf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [\*] For XML Path('')),'§§Split§§','')+'' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[tvf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[tvf-Str-Parse]('username_2 was here',' ')
--Select * from [dbo].[tvf-Str-Parse]('this,is,,for,< & >',',')
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 478 | 1,698 | <issue_start>username_0: Hi I have a spreadsheet similar to below
[](https://i.stack.imgur.com/eJeP4.png)
Where when I click on a cell (red cell), I want to return the row and column number to another cell for use in an indirect lookup (blue cell)
Ideally I want to only update the cell value if it's within a set range or at least limit it only to that worksheet for error handling.
Hope that's clear... not an easy thing to google. My experiments with
```
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
MsgBox ActiveCell.Row
End Sub
```
Have returned nothing, not even a message box even though macros run fine. Any ideas?<issue_comment>username_1: Based on your example. Make sure your code is in the appropriate sheet module, not a standard module and make sure Application.EnableEvents=True (your existing code should have done something).
```
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
If Intersect(Target(1), Range("C4:H9")) Is Nothing Then Exit Sub
Range("J3").Value = Cells(Target(1).Row, 2) & "," & Cells(3, Target(1).Column)
End Sub
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Use this in the worksheet's private code sheet.
```
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target.Cells(1), Range("C4:H9")) Is Nothing Then
Range("C4:H9").Interior.Pattern = xlNone
Cells(3, "J") = Join(Array(Cells(Target.Cells(1).Row, "B"), _
Cells(3, Target.Cells(1).Column)), Chr(44))
Target.Cells(1).Interior.ColorIndex = 3
End If
End Sub
```
Upvotes: 2 |
2018/03/20 | 608 | 2,483 | <issue_start>username_0: I have a page in my application that is an interactive chart with a bunch of settings (filters, time ranges, etc). I'd like to store them in-app state because some of the settings may be used by other components on another page, but right now if I click on any other tab and come back to the previous tab then the page shows the initial state(chart is gone, filtered data gone, date range showing the default value, dropdowns shows default ass well). And the state is also showing `null`.<issue_comment>username_1: You some library for state management. The most popular one that's used with React is redux.
<https://redux.js.org/introduction>
Upvotes: -1 [selected_answer]<issue_comment>username_2: Anything in your component state is dynamic; i.e., it is temporary. If you refresh the window, the old state is lost. A similar thing happens when you open a fresh tab—you get the state declared in your constructor. You can use any of the following if you want the state data in another tab:
1. Simply using redux won't solve your problem as redux store is also related to a specific browser tab. If you would like to persist your redux state across a browser refresh, it's best to do this using redux middleware. Check out the [redux-persist](https://www.npmjs.com/package/redux-persist), [redux-storage](https://www.npmjs.com/package/redux-storage) middleware.
2. If you are using `react-router` you can simply pass required state through the link when you open a fresh tab. Here's an example:
```js
```
3. Simply store the data in `localStorage` and access `localStorage` in other tabs.
Upvotes: 4 <issue_comment>username_3: If you are looking to use a variable across the entire application you can also use **localStorage**
```
localStorage.setItem('move', this.state.move);
```
also don't forget to unset it when you are done!
```
localStorage.removeItem('move');
```
Upvotes: 2 <issue_comment>username_4: I think you should implement react-redux into your app.
React-redux is a state management tool that manage the state of your application at a centralized location and you access data from store at anytime from anywhere.
React-redux:
<https://redux.js.org/basics/usage-with-react>
Upvotes: -1 <issue_comment>username_5: The straight forward solution to this is [redux-state-sync](https://github.com/AOHUA/redux-state-sync#readme). It will just work and the store will be updated on all tabs and even windows on the browser.
Upvotes: 1 |
2018/03/20 | 1,804 | 4,672 | <issue_start>username_0: I have following sample table where I need to have sum of columns values where VA1 and Val2 are same , need to sum cvalue and seelct the ID where cValue is max
```
+---------------------------+
¦ ID ¦ Val1 ¦ Val2 ¦ CValue ¦
¦----+------+------+--------¦
¦ 1 ¦ 1 ¦ 1 ¦ 1 ¦
¦----+------+------+--------¦
¦ 2 ¦ 1 ¦ 1 ¦ 9 ¦
¦----+------+------+--------¦
¦ 3 ¦ 1 ¦ 1 ¦ 1 ¦
¦----+------+------+--------¦
¦ 4 ¦ 5 ¦ 3 ¦ 2 ¦
¦----+------+------+--------¦
¦ 5 ¦ 5 ¦ 3 ¦ 8 ¦
¦----+------+------+--------¦
¦ 6 ¦ 7 ¦ 5 ¦ 8 ¦
¦----+------+------+--------¦
¦ 7 ¦ 8 ¦ 9 ¦ 4 ¦
+---------------------------+
```
for above raw data below is the required output:
```
+---------------------------+
¦ ID ¦ Val1 ¦ Val2 ¦ CValue ¦
¦----+------+------+--------¦
¦ 2 ¦ 1 ¦ 1 ¦ 11 ¦
¦----+------+------+--------¦
¦ 4 ¦ 5 ¦ 3 ¦ 10 ¦
¦----+------+------+--------¦
¦ 6 ¦ 7 ¦ 8 ¦ 8 ¦
¦----+------+------+--------¦
¦ 7 ¦ 8 ¦ 9 ¦ 4 ¦
+---------------------------+
```
Can someone help to provide the right query to achieve this.
Thanks<issue_comment>username_1: ```
SELECT Val1, Val2, SUM(CValue) AS sum
FROM table
GROUP BY Val1, Val2
ORDER BY sum DESC
```
You can't select the ID without having some kind of aggregation strategy for it (there's no method by which it can be implicitly grouped).
Upvotes: 0 <issue_comment>username_2: I'd suggest something like this:
```
SQL> with test (id, val1, val2, cvalue) as
2 (select 1, 1, 1, 1 from dual union
3 select 2, 1, 1, 9 from dual union
4 select 3, 1, 1, 1 from dual union
5 select 4, 5, 3, 2 from dual union
6 select 5, 5, 3, 8 from dual union
7 select 6, 7, 5, 8 from dual union
8 select 7, 8, 9, 4 from dual
9 ),
10 inter as
11 (select id, val1, val2,
12 sum(cvalue) over (partition by val1, val2) cvalue,
13 row_number() over (partition by val1, val2 order by cvalue desc) rn
14 From test t
15 )
16 select id, val1, val2, cvalue
17 from inter
18 where rn = 1
19 order by id;
ID VAL1 VAL2 CVALUE
---------- ---------- ---------- ----------
2 1 1 11
5 5 3 10
6 7 5 8
7 8 9 4
SQL>
```
Note, though, the difference in IDs: you have ID = 4, while I have ID = 5 instead. Why? Because you said that you want to "select the ID where cValue is max". For VAL1 = 5 and VAL2 = 3 (rows with IDs 4 and 5), max cValue is 8, and it belongs to ID = 5.
Also, row for ID = 6 whould be 6-7-5-8, not 6-7-8-8.
Upvotes: 0 <issue_comment>username_3: Try This, using `KEEP..DENSE_RANK`
[SQL Fiddle](http://sqlfiddle.com/#!4/c82f51/5)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE yourtable
(ID int, Val1 int, Val2 int, CValue int)
;
INSERT ALL
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (1, 1, 1, 1)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (2, 1, 1, 9)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (3, 1, 1, 1)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (4, 5, 3, 2)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (5, 5, 3, 8)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (6, 7, 5, 8)
INTO yourtable (ID, Val1, Val2, CValue)
VALUES (7, 8, 9, 4)
SELECT * FROM dual
;
```
**Query 1**:
```
SELECT MAX(ID) KEEP (
DENSE_RANK FIRST ORDER BY cvalue DESC
) as ID
,Val1
,Val2
,SUM(CValue) AS CValue
FROM yourtable
GROUP BY Val1
,Val2
```
**[Results](http://sqlfiddle.com/#!4/c82f51/5/0)**:
```
| ID | VAL1 | VAL2 | CVALUE |
|----|------|------|--------|
| 2 | 1 | 1 | 11 |
| 5 | 5 | 3 | 10 |
| 6 | 7 | 5 | 8 |
| 7 | 8 | 9 | 4 |
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: If you select distinct values from your table and then sum the cvalue whcih is linked to them, that should do the trick?
```
select distinct [val1], [val2] ,sum([cvalue]) from [table] group by [val1], [val2]
```
Upvotes: 0 <issue_comment>username_5: ```
SELECT t2.id,t1.Val1,t1.Val2, SUM(t1. CValue ) AS sum
FROM table1 t1
INNER JOIN
(SELECT id,Val1,Val2 FROM Table1
WHERE cvalue IN (SELECT MAX(cvalue) FROM table1 GROUP BY Val1,Val2)) t2
ON t1.Val1 =t2.Val1 AND t1.Val2 =t2.Val2
GROUP BY t1.Val1,t1.Val2,t2.id
ORDER BY sum DESC
```
Output
```
ID VAL1 VAL2 SUM
2 1 1 11
5 5 3 10
6 7 5 8
7 8 9 4
```
Upvotes: 1 |
2018/03/20 | 396 | 1,298 | <issue_start>username_0: I am using Qt 5.4.0 and created a QTableWidget. The table has several rows and columns.
In my application I want to search a string in that table and if that string exists, I want to know the row number.
I could not find any such api in qt 5.4.0 documentation.
Does anyone has understanding of such api or similar to what I am looking for.
Thanks in advance !<issue_comment>username_1: You can use [findItems method](http://doc.qt.io/qt-5/qtablewidget.html#findItems):
```
QString searchtext = "text";
QList items = ui->tableWidget->findItems(searchtext, Qt::MatchExactly);
for(int i=0; irow();
//...
}
```
Notice that you can pass an extra argument to `findItems`, to set one or more [match flags](http://doc.qt.io/qt-5/qt.html#MatchFlag-enum).
Upvotes: 1 <issue_comment>username_2: You can use the [`match()`](http://doc.qt.io/qt-5/qabstractitemmodel.html#match) method of the model:
```
for (int col=0; colcolumnCount(); col++){
// return a list of all matching results
QModelIndexList results = tableWidget->model()->match(
tableWidget->model()->index(0, col),
Qt::DisplayRole,
"yourstring",
-1,
Qt::MatchContains
);
// for each result, print the line number
for (QModelIndex idx : results)
qDebug() << idx.row();
}
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,963 | 6,084 | <issue_start>username_0: I'm creating toggle buttons that need some specific functions:
1) Show content on the first click (this works)
2) Hide content when you click on a different button (this works)
3) Hide content on the second click (this doesn't work)
Right now, if you click the same button twice it first slidesUp (because if you do click a different button, the previous content needs to be closed). Once it's up it then slidesDown, making it very jumpy.
Is there a way to make all 3 functions work??
Removing the " $(".assortiment").slideUp();" line fixes this jumpy problem, but that also stops function 2 from working...
```js
function assortiment(e){
var assortimentid = e.id + "__js";
if ($("#" + assortimentid).display = "block"){
$(".assortiment").slideUp();
$("#" + assortimentid).slideToggle();
} else if ($("#" + assortimentid).display = "none"){
$("#" + assortimentid).slideToggle();
}
}
```
```css
.assortiment {
display: none;
}
.btn {
border: 1px solid black;
border-radius: 10px;
padding: 10px;
width: 100px;
margin: 5px;
background-color: lightblue;
}
.btn:hover {
cursor: pointer
}
```
```html
Section 1
Section 2
Section 3
SOME CONTENT 1
Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
SOME CONTENT 2
Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
SOME CONTENT 3
Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
```<issue_comment>username_1: You are missing the `.stop()` method which stops the currently-running animation on the matched element or in other words, prevents repetition:
```js
function assortiment(e){
var assortimentid = e.id + "__js";
if ($("#" + assortimentid).display = "block"){
$(".assortiment").stop().slideUp();
$("#" + assortimentid).stop().slideToggle();
} else if ($("#" + assortimentid).display = "none"){
$("#" + assortimentid).stop().slideToggle();
}
}
```
```css
* {margin: 0; box-sizing: border-box} /* addition; more "fluent" */
.assortiment {
display: none;
}
.btn {
border: 1px solid black;
border-radius: 10px;
padding: 10px;
width: 100px;
margin: 5px;
background-color: lightblue;
}
.btn:hover {
cursor: pointer
}
```
```html
Section 1
Section 2
Section 3
SOME CONTENT 1
SOME CONTENT 2
SOME CONTENT 3
```
Upvotes: 1 <issue_comment>username_2: Try this
```
function assortiment(e){
var assortimentid = e.id + "__js";
if ($("#" + assortimentid).display == "block"){
$(".assortiment").hide();
$("#" + assortimentid).slideToggle();
} else if ($("#" + assortimentid).display == "none"){
$("#" + assortimentid).slideToggle();
}
```
Upvotes: 0 <issue_comment>username_3: Update your JS function defination to :
```
function assortiment(e){
var assortimentid = e.id + "__js";
$(".assortiment").not("#" + assortimentid).slideUp();
$("#" + assortimentid).slideToggle();
}
```
**Full Snippet:** and [jsFiddle](https://jsfiddle.net/m127msuc/8/)
```js
function assortiment(e){
var assortimentid = e.id + "__js";
$(".assortiment").not("#" + assortimentid).slideUp();
$("#" + assortimentid).slideToggle();
}
```
```css
.assortiment {
display: none;
}
.btn {
border: 1px solid black;
border-radius: 10px;
padding: 10px;
width: 100px;
margin: 5px;
background-color: lightblue;
}
.btn:hover {
cursor: pointer
}
```
```html
Section 1
Section 2
Section 3
SOME CONTENT 1
Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
SOME CONTENT 2
Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
SOME CONTENT 3
Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
```
Upvotes: 0 <issue_comment>username_4: Well try to avoid inline javascript..Write a separate function for `.btn` click to toggle display...use `slideToggle()` jQuery to toggle the same element...and `slideUp()` with `not()` to hide other elements
Also use `===` for comparison in condition,...`=` is used to assigned a value...
Also the `element.display = "none"` is not a valid statement, it should be like `element.css("display") === "none"`
```js
$(".btn").on("click", function() {
var item = "#" + $(this).attr("id") + "__js"
$(".assortiment").not(item).stop().slideUp();
$(item).stop().slideToggle();
})
```
```css
.assortiment {
display: none;
}
.btn {
border: 1px solid black;
border-radius: 10px;
padding: 10px;
width: 100px;
margin: 5px;
background-color: lightblue;
}
.btn:hover {
cursor: pointer
}
p {
margin: 0;
}
```
```html
Section 1
Section 2
Section 3
SOME CONTENT 1
SOME CONTENT 2
SOME CONTENT 3
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 771 | 2,943 | <issue_start>username_0: Which HOC will wrap the other. Does the order of wrapping with multiple HOCs matter in react or not? I have created multiple HOCs **withSocket**, **withLoadingBar** etc etc. Should I be worry about deep ugly nesting, Will it make an impact on performance of component?<issue_comment>username_1: React is all about composition and in the majority of cases it shouldn't be a performance problem at all. Don't worry about it until you actually perceive a performance issue. Nesting HOC's is also fine. The only thing you need to take into consideration is when one of the HOC's consumes props injected by another HOC. This is e.g. the case when you need `react-router` url params in your `mapStateToProps` to select an object by `id`. Then you need to apply first the `connect()` HOC and only then the `withRouter()` HOC to access the `match` object in the `ownProps` of the wrapped component.
Upvotes: 1 <issue_comment>username_2: >
> Does the order of wrapping with multiple HOCs matter in react or not?
>
>
>
The order in which you wrap the HOCs matters because of the props that are passed on from one HOC to its child component. Consider the following example
```
const mapStateToProps(state, props) {
console.log(props.match);
return {
match: props.match
}
}
```
**First case:**
```
withRouter(connect(mapStateToProps)(App));
```
In this case since the `withRouter` wraps the `connect`, the props provided by `withRouter ie history, match etc` **will be** available in `mapStateToProps` used by connect.
Think of an HOC like
```
const MyComponent = connect(mapStateToProps)(App);
export default withRouter(MyComponent);
```
where `withRouter` could be implement like
```
const withRouter = (Comp) => {
return class Something extends React.Component {
render() {
return
}
}
..
}
```
and so in this case, the `Comp` i.e `MyComponent` which is wrapped with `withRouter` receives the match props, which in the above case is the component being wrapped by `connect`
**Second case:**
```
connect(mapStateToProps)(withRouter(App));
```
In this case since the connect wraps the withRouter, the props provided by `withRouter` ie `history, match etc` **will not be** available in `mapStateToProps` used by `connect` if they are not provided by the parent.
>
> Should I be worry about deep ugly nesting?
>
>
>
you should only worry about it if the props provided by one HOC is being used by another. Say if you use passed down props from HOC directly inside the base component, you won't need to worry about the order
>
> Will it make an impact on performance of component?
>
>
>
The order of using HOC doesn't affect a components performance
Check the below codesandbox for an example
[](https://codesandbox.io/s/2vo8oknk6r)
Upvotes: 6 [selected_answer] |
2018/03/20 | 654 | 2,241 | <issue_start>username_0: I am trying to import a csv with a date in the following format:
`2018/01/25`
the date format in mysql is in Int and I want to remove the slashes in the current date format.
I need to get the date looking like this:
```
20180125
```
I need to work only on the first column and not the rest of the csv.
here is the code for reading the csv.
```
while(reader.readLine()!= null)
{
String read = reader.readLine();//bufferedreader string variable
String [] rawRow = read.split(",");
String lastEntry = rawRow[rawRow.length-1];// this contains MemberNo/branchNo
String [] properLastEntry = lastEntry.split("/");//this contains MemberNo,BranchNo
//memory that contains rawRow nd properLastEntry in a single array
String [] oneRow = new String[rawRow.length+1];
System.arraycopy(rawRow, 0, oneRow, 0,rawRow.length-1);
System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - properLastEntry.length,properLastEntry.length);
System.out.println(Arrays.toString(oneRow));
rs2.add(oneRow);
}
```<issue_comment>username_1: ```
/**
*
* @author CHIRAG
*
*/
public class DateConverter {
public static void main(String... args) {
String date = "2018/01/25";
System.out.println(date + " converted to -> " + convertDate(date));
}
public static String convertDate(String date) {
return date.replaceAll("/|-", ""); // it will remove all occurrences of '/' or '-'
}
}
```
The output of this code snip is:
```
2018/01/25 converted to -> 20180125
```
Only you have to pass `date string` to the method `convertDate(String date)`
Happy Coding :)
Upvotes: -1 <issue_comment>username_2: Why wouldn't it come from the database in a `java.sql.Date` object?
Well, if you're reading it as a string, just do this:
```
String convert(String dateIn) {
String year = dateIn.subString(0,4);
String month = dateIn.subString(5,7);
String day = dateIn.subString(8);
return year + month + day;
}
```
Of course it's still a very bad idea to read the date as a String from the database, because the format is not guaranteed to be the same on every server. Could be one on your test server and another on the production.
Upvotes: 0 |
2018/03/20 | 651 | 2,081 | <issue_start>username_0: I am builing a multi-step form.
Here is part of it:
```
Radio button 1-1
Radio button 1-2
Radio button 2-1
Radio button 2-2
Checkbox 1
Checkbox 2
Other
```
And here is my JS :
```
$("[data-show]").change(function(){
if($(this).is(":checked")) {
$($(this).data('show')).show();
} else {
$($(this).data('show')).hide();
}
});
```
What's the problem:
With checkbox it works fine. Showing and hiding on checking/unchecking the checkbox.
With radio buttons it works fine on the show, but it's not hiding on changing from current group of radio buttons.
Here is [JSFiddle](https://jsfiddle.net/v9kgugrc/18/)
EDIT 1:
What I need with radio button groups:
If I check radio-button with
```
name="radio_group_1" data-show="#id-of-textarea"
```
a textarea with
```
id="id-of-textarea"
```
shows up. If after this I check another radio-button from the same group
```
name="radio_group_1" NO DATA-ATTRIBUTE HERE
```
the textarea hides.<issue_comment>username_1: You have some errors in your code.Use this script.
```
$("[type='radio']").change(function(){
$("[type='radio']").each(function(){
if($(this).is(":checked")) {
$($(this).data('show')).show();
} else {
$($(this).data('show')).hide();
}
});
});
```
Fiddle: <https://codepen.io/smitraval27/pen/XEpGNR>
In your code you have not given [data-show] to every radio button. Plus on change of radio you have to use each to find out the changes of each and every radio.
Upvotes: 0 <issue_comment>username_2: The jQuery logic is wrong. **Working:** <https://jsfiddle.net/vutpcu0g/5>
You should check the change event on all radios, not just the `data-show` ones. Then, select the nearest sibling radio to toggle the data-show element.
```
$("[type=radio],[type=checkbox]").change(function(){
if($(this).is(":checked") && $(this).data("show")) {
$($(this).data('show')).show();
} else {
var sib= $(this).parents('.form-group').find('[data-show]');
$(sib.data("show")).hide();
}
});
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 927 | 2,772 | <issue_start>username_0: I want to use mingw to compile my C language project.
I found the command of `make all` succeeded, however `make clean` failed. There are only two files in my test project: `test.c` and `Makefile.mak`.
`test.c`:
```
#include
int main()
{
printf("Hello world\n");
while (1);
return 0;
}
```
`Makefile.mak`:
```
all: test.o
gcc test.o -o test.exe
test.o: test.c
gcc -c test.c
clean:
@echo "clean project"
-rm test *.o
@echo "clean completed"
.PHONY: clean
```
When I ran `make all -f Makefile.mak`, it succeeded and generated the expected `test.exe`, and I also can run the executable. However, when I run `make clean -f Makefile.mak`, it failed, the error is:
```
"clean project"
rm test *.o
process_begin: CreateProcess(NULL, rm test *.o, ...) failed.
make (e=2):
Makefile.mak:8: recipe for target 'clean' failed
make: [clean] Error 2 (ignored)
"clean completed"
```
[](https://i.stack.imgur.com/PgKa5.jpg)
Why?
**EDIT:**
The following link enlightened me:
[MinGW makefile with or without MSYS (del vs rm)](https://stackoverflow.com/questions/19928965/mingw-makefile-with-or-without-msys-del-vs-rm)
1. I added the workaround code mentioned in the above link in my `makefile`:
```
ifeq ($(OS),Windows_NT)
RM = del /Q /F
CP = copy /Y
ifdef ComSpec
SHELL := $(ComSpec)
endif
ifdef COMSPEC
SHELL := $(COMSPEC)
endif
else
RM = rm -rf
CP = cp -f
endif
all: test.o
gcc test.o -o test.exe
test.o: test.c
gcc -c test.c
clean:
@echo "clean project"
-$(RM) test.exe *.o
@echo "clean completed"
.PHONY: clean
```
It works:
```
"clean project"
del /Q /F test.exe *.o
"clean completed"
```
2. This reminds me that it may be because current environment doesn't support `rm` command, so I add my `msys` install path into environment path, then it works:
```
clean project
rm test.exe *.o
clean completed
```<issue_comment>username_1: You're trying to remove a file called "test" but no such file exists. As a result, the `rm` command fails.
You want to delete "test.exe", as that is the name of your output file. Also, you should use the `-f` option to `rm`, as that will 1) do a forced remove, and 2) won't fail if the file doesn't exist:
```
clean:
@echo "clean project"
-rm -f test.exe *.o
@echo "clean completed"
```
Upvotes: 0 <issue_comment>username_2: Try this one:
['make clean' not working](https://stackoverflow.com/questions/47735464/make-clean-not-working)
Clean in MinGW by default will run -rm command. But this command is not supported by window. Window use del.
So you need to edit makefile with notepad++, change
```
clean:
-rm -fR $(BUILD_DIR)
```
To
```
clean:
-del -fR $(BUILD_DIR)
```
Upvotes: 2 |
2018/03/20 | 983 | 3,577 | <issue_start>username_0: I'm looping through an array and showing the images:
```
<% @attachments.each do |attachment| %>
<%= image_tag(attachment.image.url(: thumb))%>
<%= link_to "Remove", remove_item_attachment_path(attachment),
data: { confirm: "Are you sure" },
:method => :delete %>
```
and this is what I have in the controller in order to find the attachments of the specific item:
```
@attachments = Attachment.where(item_id: @item.id)
```
The image column inside the attachments table is a `string`
I would like the loop to skip and not show a specific image I have stored inside the db, but show all the other images!
I have tried using the `break if` or `next if` condition but without any luck:
```
<% @attachments.each do |attachment| %>
<% next if attachment.image == "no-image.jpg" %>
<%= image_tag(attachment.image.url(:thumb))%>
<%= link_to "Remove", remove_item_attachment_path(attachment),
data: { confirm: "Are you sure" },
:method => :delete %>
```
or
```
<% @attachments.each do |attachment| %>
<% break if attachment.image == "no-image.jpg" %>
<%= image_tag(attachment.image.url(:thumb))%>
<%= link_to "Remove", remove_item_attachment_path(attachment),
data: { confirm: "Are you sure" },
:method => :delete %>
```
Any ideas on how I can implement this?
**Update 1**
this is what I'm getting in the console from `attachment.image`
`#, @mounted\_as=:image, @storage=#>, @file=#, @versions={:thumb=>#, @mounted\_as=:image, @parent\_version=#, @storage=#>, @file=#, @versions={}>, :mini=>#, @mounted\_as=:image, @parent\_version=#, @storage=#>, @file=#, @versions={}>}>`<issue_comment>username_1: Just use the "reject" method.
```
<% @attachments.reject { |attachment| attachment.image == "no-image.jpg" }.each do |attachment| -%>
...
<% end -%>
```
edit:
Per comments below and above, the original poster is using Carrierwave to store files. Because of this, "attachment.image" is a Carrierwave uploader object.
```
<% @attachments.reject { |attachment| attachment.image.identifier == "no-image.jpg" }.each do |attachment| -%>
...
<% end -%>
```
Upvotes: 2 <issue_comment>username_2: If you used paperclip you have default method to find file name **original\_filename**
```
<% @attachments.each do |attachments| %>
<% if attachment.image.original_filename != "no-image.jpg" %>
<%= image_tag(attachments.image.url(:thumb))%>
<%= link_to "Remove", remove_item_attachment_path(attachments),
data: { confirm: "Are you sure" },
:method => :delete %>
<% end %>
```
Upvotes: 2 <issue_comment>username_3: Ok I go it to work with a combination of username_1 and prasanthrubyist answers
`<% @attachments.reject { |attachment| attachment.image.file.identifier != "no-image.jpg" }.each do |attachment| -%>`
Upvotes: 0 <issue_comment>username_4: You can also probably do this in the database via your original query. It's often best to try to keep this sort of logic out of the views.
```
@attachments = Attachment.where(item_id: @item.id).where.not(image: 'no-image.jpg')
```
Or if the database value is `nil`:
```
@attachments = Attachment.where(item_id: @item.id).where.not(image: nil)
```
I'd probably add it as a scope on the model so instead you can do something like:
```
@attachments = @item.attachments.with_image
```
Upvotes: 0 |
2018/03/20 | 552 | 1,988 | <issue_start>username_0: I use the video as a background. The background works well everywhere except the iPhone. I deleted the audio track, but it does not help. How can I play video on iPhone?
**PHP CODE**
```
```<issue_comment>username_1: Just use the "reject" method.
```
<% @attachments.reject { |attachment| attachment.image == "no-image.jpg" }.each do |attachment| -%>
...
<% end -%>
```
edit:
Per comments below and above, the original poster is using Carrierwave to store files. Because of this, "attachment.image" is a Carrierwave uploader object.
```
<% @attachments.reject { |attachment| attachment.image.identifier == "no-image.jpg" }.each do |attachment| -%>
...
<% end -%>
```
Upvotes: 2 <issue_comment>username_2: If you used paperclip you have default method to find file name **original\_filename**
```
<% @attachments.each do |attachments| %>
<% if attachment.image.original_filename != "no-image.jpg" %>
<%= image_tag(attachments.image.url(:thumb))%>
<%= link_to "Remove", remove_item_attachment_path(attachments),
data: { confirm: "Are you sure" },
:method => :delete %>
<% end %>
```
Upvotes: 2 <issue_comment>username_3: Ok I go it to work with a combination of username_1 and prasanthrubyist answers
`<% @attachments.reject { |attachment| attachment.image.file.identifier != "no-image.jpg" }.each do |attachment| -%>`
Upvotes: 0 <issue_comment>username_4: You can also probably do this in the database via your original query. It's often best to try to keep this sort of logic out of the views.
```
@attachments = Attachment.where(item_id: @item.id).where.not(image: 'no-image.jpg')
```
Or if the database value is `nil`:
```
@attachments = Attachment.where(item_id: @item.id).where.not(image: nil)
```
I'd probably add it as a scope on the model so instead you can do something like:
```
@attachments = @item.attachments.with_image
```
Upvotes: 0 |
2018/03/20 | 648 | 2,241 | <issue_start>username_0: I am new to xpaths in selenium and trying to click on Next> image/button in the code below. I have tried following two xpaths but its not working and giving no element not found error.
```
By.xpath("//div[@class='pzbtn-mid']/img[contains(text(), \"Next >\")]"))
By.xpath("//div[@class='pzbtn-mid']/img[contains(text(), 'Next >')]"))
```
What am i doing wrong here?
```
==$0

"Next >"

```<issue_comment>username_1: Just use the "reject" method.
```
<% @attachments.reject { |attachment| attachment.image == "no-image.jpg" }.each do |attachment| -%>
...
<% end -%>
```
edit:
Per comments below and above, the original poster is using Carrierwave to store files. Because of this, "attachment.image" is a Carrierwave uploader object.
```
<% @attachments.reject { |attachment| attachment.image.identifier == "no-image.jpg" }.each do |attachment| -%>
...
<% end -%>
```
Upvotes: 2 <issue_comment>username_2: If you used paperclip you have default method to find file name **original\_filename**
```
<% @attachments.each do |attachments| %>
<% if attachment.image.original_filename != "no-image.jpg" %>
<%= image_tag(attachments.image.url(:thumb))%>
<%= link_to "Remove", remove_item_attachment_path(attachments),
data: { confirm: "Are you sure" },
:method => :delete %>
<% end %>
```
Upvotes: 2 <issue_comment>username_3: Ok I go it to work with a combination of username_1 and prasanthrubyist answers
`<% @attachments.reject { |attachment| attachment.image.file.identifier != "no-image.jpg" }.each do |attachment| -%>`
Upvotes: 0 <issue_comment>username_4: You can also probably do this in the database via your original query. It's often best to try to keep this sort of logic out of the views.
```
@attachments = Attachment.where(item_id: @item.id).where.not(image: 'no-image.jpg')
```
Or if the database value is `nil`:
```
@attachments = Attachment.where(item_id: @item.id).where.not(image: nil)
```
I'd probably add it as a scope on the model so instead you can do something like:
```
@attachments = @item.attachments.with_image
```
Upvotes: 0 |
2018/03/20 | 637 | 1,830 | <issue_start>username_0: I'm trying to add to an array based on a condition.
Can someone clarify why the if statement isn't working as I intend it to?
```
all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]
new_staff = []
def person_finder(staff):
for x in staff:
if x == "Reuben" or "Harry" or "Jonathan":
new_staff.append(x)
else:
continue
return new_staff
selected = person_finder(all_staff)
def the_men(people):
for x in people:
print(x + " is a man")
the_men(selected)
```
This returns:
Judith is a man<issue_comment>username_1: replace
```
if x == "Reuben" or "Harry" or "Jonathan":
```
with
```
if x == "Reuben" or x == "Harry" or x == "Jonathan":
```
Upvotes: 2 <issue_comment>username_2: Change this line :
```
if x == "Reuben" or "Harry" or "Jonathan":
```
to
```
if x == "Reuben" or x=="Harry" or x=="Jonathan":
```
Working code:
```
all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]
new_staff = []
def person_finder(staff):
for x in staff:
if x == "Reuben" or x=="Harry" or x=="Jonathan":
new_staff.append(x)
else:
continue
return new_staff
selected = person_finder(all_staff)
def the_men(people):
for x in people:
print(x + " is a man")
the_men(selected)
```
output:
```
Harry is a man
Jonathan is a man
Reuben is a man
```
Upvotes: 1 <issue_comment>username_3: ```
all_staff = ["Judith", "Harry", "Jonathan", "Reuben"]
def person_finder(staff):
new_staff = []
for x in staff:
if x in ["Reuben", "Harry", "Jonathan"]:
new_staff.append(x)
else:
continue
return new_staff
selected = person_finder(all_staff)
def the_men(people):
for x in people:
print(x + " is a man")
the_men(selected)
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 1,517 | 6,318 | <issue_start>username_0: Here is an example of the usage of `volatile` keyword.
```
public class Test3{
public static volatile boolean stop = false;// if volatile is not set, the loop will not stop
public static void main(String[] args) throws InterruptedException{
Thread thread = new Thread(){
public void run() {
int i=0;
while(!stop){
i++;
// add this line
// System.out.println(i);
// or this block
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
};
thread.start();
Thread.sleep(2000);
stop = true;
}
}
```
It's easy to understand that if `volatile` is set, JVM should load the updated value from memory while checking its value, then the while loop can stop as expected. But question is, should not the static variable change at the same time? There may be some delay but eventually, this change should be detected. no? I've tested that if we add some print code or sleep code, this change can be detected? Can someone teach me why it likes that? Maybe it's about the JMM.<issue_comment>username_1: >
> It's easy to understand that if volatile is set, JVM should load the
> updated value from memory while checking its value, then the while
> loop can stop as expected.
>
>
>
[`volatile`](https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html) is some kind of `rule` or `mechanism`, not about concrete implemention above. It is used to build [`happends-before`](https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html) relationship between threads:
>
> Using volatile variables reduces the risk of memory consistency
> errors, because any write to a volatile variable establishes a
> happens-before relationship with subsequent reads of that same
> variable. **This means that changes to a volatile variable are always
> visible to other threads. What's more, it also means that when a
> thread reads a volatile variable, it sees not just the latest change
> to the volatile, but also the side effects of the code that led up the
> change**.
>
>
>
---
Without `volatile` or other synchronization, the update to static variable **could** be seen to other threads with some delay, and **could not** be seen forever because [memory barriar](https://en.wikipedia.org/wiki/Memory_barrier). **It is uncertain**. Even you add some print code or sleep code, and find it works, it does not mean it can still work in other enviroment or other moment.
---
However, if you add the print code in both the `while loop` and the `main` thread:
```
while(!stop){
i++;
System.out.println(i);
}
```
and
```
stop = true;
System.out.println("some");
```
JMM can gurantee that the `stop = true` will be detected in the loop(at least on oracle jdk 8u161), this is because `System.out.println` is [`synchronized`](https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html), which also can build a `happens-before` relationship between involved threads, see the source code:
```
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
```
Upvotes: 2 <issue_comment>username_2: Time, in the sense of wall-clock time, has no meaning for the memory visibility. What matters is the *synchronization order* between synchronization actions. Reading and writing a non-`volatile` field is not a synchronization action, so in the absence of any other synchronization action, there is no ordering between them.
So even if the main thread completed a year ago, so the write must have been done from the main thread’s perspective, the subthread may continue to run, running forever; the write has not happened from its perspective. It also doesn’t know that the main thread has terminated. Note that performing an action capable of detecting that the other thread has terminated, is a synchronization action that may establish an order.
But since the actual program behavior also depends on the JIT compiler and optimizer, some code changes may have an impact, even if it is not guaranteed.
E.g. inserting `sleep` does not imply any memory visibility:
[JLS §17.3. Sleep and Yield](https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.3):
>
> It is important to note that neither `Thread.sleep` nor `Thread.yield` have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to `Thread.sleep` or `Thread.yield`, nor does the compiler have to reload values cached in registers after a call to `Thread.sleep` or `Thread.yield`.
>
>
>
But it may stop the optimizer from considering the loop to be a hotspot that needs optimizations.
When you insert a `System.out.println` statement, the internal synchronization of the `PrintStream` may have an impact on the overall memory visibility, though this effect also isn’t guaranteed, as the main thread does not synchronize on that `PrintStream`.
By the way there isn’t even a guaranty that preemptive thread switching ever happens between threads of the same priority. Hence, it would be a valid execution, if a JVM tries to complete your subthread after `start()` has been called, before giving the CPU back to the main thread.
In that execution scenario, with no `sleep` in the loop, the subthread would never give up the CPU, so `stop` would never be set to `true`, even if declared `volatile`. That would be another reason to avoid polling loops, though there might be no real life execution environment without preemptive thread switching anymore. Most of today’s execution environments even have multiple CPUs so not giving up a CPU won’t prevent other threads from executing.
Still, to be formally correct, you should enforce an ordering between a write to the `stop` variable and the reading of the variable, like declaring the variable `volatile` and insert an action that may cause the thread to release the CPU eventually, when `quit` is still `false`.
Upvotes: 3 [selected_answer] |
2018/03/20 | 567 | 1,890 | <issue_start>username_0: I'm trying to scale an image with css transition upon clicking some text.
The checkmark image should animate out and in each time the link is clicked. In iPhone Chrome however the checkmark doesn't animate - simply jumps from one state to the other, seemingly ignoring the css {transition: transform 200ms}.
It seems to work everywhere except iPhone Chrome browser - I've gone through everything as best as I can but it's totally stumped me!
Codepen link: <https://codepen.io/anon/pen/oqBJzr>
**CSS:**
```
.checkmark {
width: 35px;
-webkit-transition: transform 200ms;
transition: all 200ms;
}
.checkmark.scale {
-webkit-transform: scale(3);
transform: scale(3);
}
```
**JavaScript:**
```
function checkMarkAnim() {
$('.checkmark').toggleClass('scale');
}
```
Any pointers on what has gone wrong would really help.
Thank you in advance
Update:
=======
The suggestion to add `-webkit-transition: -webkit-transform 200ms;` does not seem to have resolved the problem (although I initially thought it had).<issue_comment>username_1: Please also add/keep `-webkit-transition: transform 200ms;`. So in the end you should have:
```css
.checkmark {
width: 35px;
-webkit-transition: transform 200ms;
-webkit-transition: -webkit-transform 200ms
transition: all 200ms;
}
.checkmark.scale {
-webkit-transform: scale(3);
transform: scale(3);
}
```
See it here working with mobile chrome (iOS): <https://codepen.io/miikaeru/pen/aMXYEb>
Upvotes: 2 [selected_answer]<issue_comment>username_2: After a few days of searching what actually worked for me is **just Chrome restart**.
Upvotes: 6 <issue_comment>username_3: This is caused by a known issue in iOS.
For more information, see: <https://bugs.webkit.org/show_bug.cgi?id=228333>
and <https://bugs.chromium.org/p/chromium/issues/detail?id=1231712>
Upvotes: 2 |
2018/03/20 | 395 | 1,343 | <issue_start>username_0: I want to put online image on tab bar item.
Is this possible in iOS?
[](https://i.stack.imgur.com/3jfZX.png)<issue_comment>username_1: This is possible in iOS via `UITabBarItem`
You need to select UITabBarItem constructor for your business and **set the image**
```
UITabBarItem(title: String?, image: UIImage?, selectedImage: UIImage?)
UITabBarItem(title: String?, image: UIImage?, tag: Int)
```
Upvotes: 0 <issue_comment>username_2: You can use **WebImage** and load it by using **SDWebImage**.
<https://github.com/rs/SDWebImage>
So once it load and you get the object of `UIImage` inside its method you can check UIImage object should not be nil If not nil then set that `UIImage` to your tabbar Item Image.
```
imageView.sd_setImageWithURL(NSURL(string: urlString), completed: {
(image, error, cacheType, url) in
// Change tabbar item image here....
tabHome.image=image?.withRenderingMode(.alwaysOriginal) // deselect image
tabHome.selectedImage = image?.withRenderingMode(.alwaysOriginal) // select image
})
```
Reference: [how to set image in a tab bar item in swift?](https://stackoverflow.com/questions/39715932/how-to-set-image-in-a-tab-bar-item-in-swift/39716048)
Upvotes: 2 |
2018/03/20 | 564 | 1,949 | <issue_start>username_0: I know that the question is confusing. Let me explain.
I am coding a Scrabble Trainer in Python3. You get a set of 7 letters(which can repeat) and you have to make as many words as possible just from those letters. I want the user to get an error if they use a letter which is not in that set. How can I do this?
```
a = random.choice("abcdefghijklmnopqrstuvwxyz")
b = random.choice("abcdefghijklmnopqrstuvwxyz")
c = random.choice("abcdefghijklmnopqrstuvwxyz")
d = random.choice("abcdefghijklmnopqrstuvwxyz")
e = random.choice("abcdefghijklmnopqrstuvwxyz")
f = random.choice("abcdefghijklmnopqrstuvwxyz")
g = random.choice("abcdefghijklmnopqrstuvwxyz")
print ("Your letters are...")
print (a)
print (b)
print (c)
print (d)
print (e)
print (f)
print (g)
```
Where to go from here?!<issue_comment>username_1: This is possible in iOS via `UITabBarItem`
You need to select UITabBarItem constructor for your business and **set the image**
```
UITabBarItem(title: String?, image: UIImage?, selectedImage: UIImage?)
UITabBarItem(title: String?, image: UIImage?, tag: Int)
```
Upvotes: 0 <issue_comment>username_2: You can use **WebImage** and load it by using **SDWebImage**.
<https://github.com/rs/SDWebImage>
So once it load and you get the object of `UIImage` inside its method you can check UIImage object should not be nil If not nil then set that `UIImage` to your tabbar Item Image.
```
imageView.sd_setImageWithURL(NSURL(string: urlString), completed: {
(image, error, cacheType, url) in
// Change tabbar item image here....
tabHome.image=image?.withRenderingMode(.alwaysOriginal) // deselect image
tabHome.selectedImage = image?.withRenderingMode(.alwaysOriginal) // select image
})
```
Reference: [how to set image in a tab bar item in swift?](https://stackoverflow.com/questions/39715932/how-to-set-image-in-a-tab-bar-item-in-swift/39716048)
Upvotes: 2 |
2018/03/20 | 989 | 3,270 | <issue_start>username_0: I have a (non-admin) account on one GCP project.
When I start the Dataproc cluster, GCP spins up 3 VMs. When I try to access one of the VM via **SSH (in browser)** I get the following error:
[](https://i.stack.imgur.com/nXGdz.png)
I tried to add recommended permissions, but I cannot add the **iam.serviceAccounts.actAs** permission.
[](https://i.stack.imgur.com/QOmwh.png)
Any idea how to solve this? I read through the GCP documentation, but I just cannot find the solution for this. I have the following roles associated with my account:
[](https://i.stack.imgur.com/HUW9A.png)<issue_comment>username_1: I believe the latest documentation on Compute Engine SSH access is here: <https://cloud.google.com/compute/docs/instances/managing-instance-access>
It seems that you have to enable OS Login on the specific instance(s) you want to SSH into.
Upvotes: 0 <issue_comment>username_2: In the end, we managed to solve it by granting users the *Editor* permission on *Compute Engine default service account*. Not sure it is the right way but it seems to work.
[](https://i.stack.imgur.com/oMuqS.png)
Upvotes: 2 <issue_comment>username_3: If from console you want to click the "SSH" button next to an instance but face this issue, you can grant the `Service Account User` role instead of `Editor`, and it should resolve this.
If you're using OS Login, you may need the `Compute OS Login` role as well, but SA user should work.
If you're using IAP, you may need the `IAP-secured Tunnel User` role (or `roles/iap.tunnelResourceAccessor` in CLI)
Before:
[](https://i.stack.imgur.com/ekSce.png)
After adding `Service Account User` role:
[](https://i.stack.imgur.com/GsPmg.png)
If you want to access remotely, use a bastion and Cloud IAP tunnel. [Here is an example setup/teardown](https://gist.github.com/mikesparr/c420a2d827e79a496c39f03b08b56de5) (NAT and router optional if you want to configure your bastion or install packages)
Upvotes: 3 <issue_comment>username_4: Adding an ID under a role for a specific instance somehow did not work for us
[](https://i.stack.imgur.com/XuvFY.png)
However, when the same ID was assigned the same role under IAM, it worked
[](https://i.stack.imgur.com/9m2or.png)
Upvotes: 0 <issue_comment>username_5: Official docs: <https://cloud.google.com/compute/docs/instances/access-overview>
For **OS Login** <https://cloud.google.com/compute/docs/oslogin/set-up-oslogin> :
* `roles/compute.osLogin`, which doesn't grant administrator permissions
* `roles/compute.osAdminLogin`, which grants administrator permissions
If you use **IAP** additionally you have to add: `roles/iap.tunnelResourceAccessor`, see <https://cloud.google.com/iap/docs/managing-access>
Upvotes: 0 |
2018/03/20 | 495 | 1,994 | <issue_start>username_0: Let say we have:
```
std::vector segments;
...
Segment\* dd = new Segment;
segments.emplace\_back(dd);
Owner\* owner = getOwner();
owner->setSegmentPointer(&(segments.back());
```
This will not work because of [Iterator invalidation rules](https://stackoverflow.com/questions/6438086/iterator-invalidation-rules).
Any subsequent element addition to the vector `segments` will render invalid the pointers stored in `owner`. How to circumvent this problem keeping the access time of `std::vector<>`? (Assuming that we can't use `vector.resize` in advance). Is to use `std::map<>` the only solution?
Thanks in advance<issue_comment>username_1: If you need random access but you need the container to grow without invalidating pointers/references/iterators to the elements then you can use a [`std::deque`](http://en.cppreference.com/w/cpp/container/deque). This will let you grow/shrink from the front or back. If you insert/erase from the middle though that can still invalidate iterators.
Upvotes: 1 <issue_comment>username_2: >
> Each owner can use that pointer to access other elements in the vector.
>
>
>
Apart from being a horrible idea, you could realise it with a `std::list`, though:
First, every owner instance gets an iterator to the list, not a pointer to a segment. `std::list` has the advantage of not invalidating iterators on insertion/deletion, unless you delete the element an iterator points to.
Via this iterator, you can find the other elements in the list. One problem remains, though: you need to detect safely the begin and end of the list. So you need sentinel values at begin and end, which could be e. g. null pointers, if these do not occur in the list.
One important note: If you need to remove a segment from the list, although an owner still has an iterator to it, you need to find a way to inform the owner about iterator invalidation. There are no means available to get this done automatically!
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,022 | 4,341 | <issue_start>username_0: I can call other apps' Activities without problem, including sending them some data and receiving some data back. But I am sending and receiving some sensitive information that could arguably be misused if in the wrong hands. My question is, is this data safe when traveling between appications?
For example, I call an Activity like this:
```
Intent intent = new Intent("com.my.package.MY_REQUEST_ACTION");
intent.setClassName("com.other.package", "com.other.package.UserActionActivity");
signerIntent.putExtra("INTENT_PASSWORD", "<PASSWORD>");
signerIntent.putExtra("INTENT_COMMAND", "COMMAND_DO_SOMETHING");
signerIntent.setType("text/plain");
startActivityForResult(intent, 0);
```
And return something in UserActionActivity:
```
Intent result = new Intent("com.other.package.INTENT_RESULT_DESCRIPTION");
result.putExtra("INTENT_RETURN_RESULT", "...");
result.putExtra("INTENT_RETURN_RESULT2", "...");
setResult(Activity.RESULT_OK, result);
finish();
```
And so on. But how secure are these *extra* strings? Do I have to worry about them being accessible to other applications (other than the two involved), either intentionally or through some kind of "hack"? Do I need something like public key encryption?
And is the situation different on rooted systems (i.e. an app with root privileges can, without too much effort, read inter-app communication)?<issue_comment>username_1: >
> Do I have to worry about them being accessible to other applications (other than the two involved), either intentionally or through some kind of "hack"?
>
>
>
Let's assume for the moment that neither app has been modified by an attacker.
If so, then in principle, the communications that you have established should be private on non-rooted device. In practice, there have been bugs with activity `Intent` extras, though none that I know of recently. Of your IPC options, activities are probably the worst choice from a security standpoint, as they have other impacts (e.g., appear in the overview/recent-tasks screen) that increase the likelihood that there is some bug that we have overlooked.
In your code, though, both sides assume that the other app has not been modified. In particular:
* Unless you have some security that is not shown, any app on the device can run the code in your first snippet and try to trick the app to return the response in the second snippet.
* The code in your first snippet assumes that `com.other.package` has not been modified by an attacker.
There are ways to help defend against this (e.g., custom `signature` permissions, checking the signature at runtime).
Also, bear in mind that an attacker can find `"1234"` without much difficulty.
With regards to the comments advising encryption, given the protocol that you are describing, encryption seems like an unlikely solution. If you have to provide a secret (`INTENT_PASSWORD`) *in the IPC protocol*, then there is no shared secret that both apps would have to use for encryption purposes, and I'm not quite certain what public-key infrastructure you would use to offer public-key encryption here.
>
> And is the situation different on rooted systems (i.e. an app with root privileges can, without too much effort, read inter-app communication)?
>
>
>
Absolutely. On a rooted device, all bets are off. That is not tied specifically to IPC, though.
Upvotes: 2 [selected_answer]<issue_comment>username_2: short answer: it is not safe but it needs some effort for the attacker.
long answer:
the transfer can be intercepted by a man in the middle attack:
on unrooted phones:
if you send data to `intent.setClassName("com.other.package", "com.other.package.UserActionActivity");` somone can uninstall the original "com.other.package" and install his own "com.other.package" with the same activity that receives the unencrypted data.
For example an attacker can disassemble the original software, add code (that does something with the secret data) and reassemble the code to a new apk (with a different certificate)
On rooted devices: I donot know but i assume it is possible that the "exposed framework" is capable to intercept and redefine android os calls.
Upvotes: 0 |
2018/03/20 | 797 | 2,679 | <issue_start>username_0: I want to display a custom text next to my plot's y-axis, as in this minimal example:
```
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.text(-0.05, 0.5, '$x$')
plt.show()
```
The horizontal alignment `0.05` is something I figure out by trial and error.
Unfortunately, `0.05` is only right for exactly one size of the plot window.
For the default window size, the text is where I want it:
[](https://i.stack.imgur.com/R6Evpm.jpg)
But once I enlarge the plot window, my text gets lost in no-man's-land:
[](https://i.stack.imgur.com/017z0m.jpg)
I tried `ax.text(-ax.yaxis.get_tick_padding, 0.5, '$x$')`, but padding appears to be measured in different units.
How can I make sure my text has the same distance from the y-axis for every window size?<issue_comment>username_1: You may use `ax.annotate` instead of `ax.text` as it allows a little bit more freedom. Specifically it allows to annotate a point in some coordinate system with the text being offsetted to that location in different coordinates.
The following would create an annotation at position `(0, 0.5)` in the coordinate system given by the `yaxis_transform`, i.e `(axes coordinates, data coordinates)`. The text itself is then offsetted by `-5` points from this location.
```
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.annotate('$x$', xy=(0, 0.5), xycoords=ax.get_yaxis_transform(),
xytext=(-5,0), textcoords="offset points", ha="right", va="center")
plt.show()
```
[](https://i.stack.imgur.com/CER8D.png)
Note that `-5` is also just an estimate and you may again want to find the best value yourself. However, having done so, this will stay the same as long as the padding and fontsize of the labels do not change.
Upvotes: 3 [selected_answer]<issue_comment>username_2: When tick lengths or padding have been changed, you can find out the exact offset by querying one of the ticks.
The ticks have a "pad" (between label and tick mark) and a "padding" (length of the tick mark), both measured in "points".
In the default setting, both are `3.5`, giving a padding of `7`.
```py
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
tick = ax.yaxis.get_major_ticks()[-1]
padding = tick.get_pad() + tick.get_tick_padding()
ax.annotate('$half$', xy=(0, 0.5), xycoords=ax.get_yaxis_transform(),
xytext=(-padding,0), textcoords="offset points", ha="right", va="center")
plt.show()
```
Upvotes: 1 |
2018/03/20 | 640 | 2,245 | <issue_start>username_0: I need to generate a server stub code in eclipse using with swagger-codegen-plugin (for maven) . can you please help how to do it ? and what configuration needed for that( in pom.xml).<issue_comment>username_1: I found this answer. You just need to change pom.xml like below.
pom.xml.
```
UTF-8
UTF-8
1.8
2.2.1
${project.basedir}/src/main/resources/Api.yaml
${project.build.directory}/generated-sources
main/java
org.springframework.boot
spring-boot-maven-plugin
io.swagger
swagger-codegen-maven-plugin
${version.swagger.codegen}
${yaml.file}
${generated-sources-java-path}
${generated-sources-path}
generate-swagger-spring
generate-sources
generate
spring
${project.groupId}.swagger.model
${project.groupId}.swagger.api
${project.groupId}.swagger.invoker
org.codehaus.mojo
build-helper-maven-plugin
add-generated-source
initialize
add-source
${generated-sources-path}/${generated-sources-java-path}
org.eclipse.m2e
lifecycle-mapping
1.0.0
io.swagger
swagger-codegen-maven-plugin
[${version.swagger.codegen},)
generate
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Sample configuration for `swagger-codegen-maven-plugin` is available at <https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen-maven-plugin>
List of possible languages is available here: <https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages>
Upvotes: 2 <issue_comment>username_3: ```
io.swagger
swagger-codegen-maven-plugin
2.3.1
contract-service
generate
${basedir}/src/main/resources/swagger/rest-data-exchange-format.yaml
contract-service
${basedir}/target/generated-sources
spring
ru.payhub.rest.v1.model
ru.payhub.rest.v1.api
false
src/main/java
true
spring-boot
${generator.datelibrary}
ru.payhub.config
true
```
Official parametrs description [here](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen-maven-plugin)
Swagger syntax specification [here](https://swagger.io/specification/)
On this example maven plugin, used swagger data-model file (yaml) generate model classes for use it in the controllers.
Upvotes: 3 |
2018/03/20 | 463 | 1,618 | <issue_start>username_0: ```
public void mystery7(String sWord){
int nL=sWord.length();
if (nL>=3) {
mystery7(sWord.substring(0,nL/3));
System.out.println(sWord.substring(0,nL/3));
mystery7(sWord.substring(0,nL/3));
}
}
```
I am having trouble with recursion. I have to find the input of mystery7("abcdefgjijkl") but I don't understand what happens when the first line in the "if" segment. If anyone can help, please do.<issue_comment>username_1: The condition `if (nL>=3)` means that the recursive calls are only executed as long as the length of the input `String` is at least 3.
* The recursive method calls itself with the first third of the input String `sWord.substring(0,nL/3)`.
* Then it prints that first third of the String.
* Finally it calls itself again with the first third of the input String.
For the input "abcdefgjijkl", whose length is 12, mystery7("abcdefgjijkl") results in the following calls:
```
mystery7("abcdefgjijkl")
mystery7("abcd");
mystery7("a"); // does nothing
System.out.println("a");
mystery7("a"); // does nothing
System.out.println("abcd");
mystery7("abcd");
mystery7("a"); // does nothing
System.out.println("a");
mystery7("a"); // does nothing
```
Therefore the output is
```
a
abcd
a
```
Upvotes: 1 <issue_comment>username_2: The first recursion function will execute recursively if the condition satisfies and once the recursion is over and while backtracking the `System.out.println(xxx)` will come to play and the recursion kicks off again with that string.
Upvotes: 0 |
2018/03/20 | 572 | 2,196 | <issue_start>username_0: I have used Animation() method to make my view with the animation of scaling and Rotation. With the Rotation based on the Y axis, the default height and width of my view has been changed. It looks like the parallelogram.
rotation of rectangle along y-axis transformed to a parallelogram.
```
myview.Animate().RotationY(rotationangle)
.X(xposition)
.SetDuration(mduration)
.WithLayer()
.SetInterpolator(interpolate).Start();
```
My requirement:
I just want the rotation of my view no need to change its projection. How to restrict the rotation of rectangle along y-axis transformed to a parallelogram.
For more reference, please check the attached sample
now view be like,
[Image](https://i.stack.imgur.com/xdG9u.png)
Please share your idea.
Thanks in Advance.
Note: while using PivotX and PivotY, there is no parallelogram shape. But I don't know the exact usage of that.
Regards,
<NAME><issue_comment>username_1: The condition `if (nL>=3)` means that the recursive calls are only executed as long as the length of the input `String` is at least 3.
* The recursive method calls itself with the first third of the input String `sWord.substring(0,nL/3)`.
* Then it prints that first third of the String.
* Finally it calls itself again with the first third of the input String.
For the input "abcdefgjijkl", whose length is 12, mystery7("abcdefgjijkl") results in the following calls:
```
mystery7("abcdefgjijkl")
mystery7("abcd");
mystery7("a"); // does nothing
System.out.println("a");
mystery7("a"); // does nothing
System.out.println("abcd");
mystery7("abcd");
mystery7("a"); // does nothing
System.out.println("a");
mystery7("a"); // does nothing
```
Therefore the output is
```
a
abcd
a
```
Upvotes: 1 <issue_comment>username_2: The first recursion function will execute recursively if the condition satisfies and once the recursion is over and while backtracking the `System.out.println(xxx)` will come to play and the recursion kicks off again with that string.
Upvotes: 0 |
2018/03/20 | 774 | 2,731 | <issue_start>username_0: I am trying to run the code using python(scrapy) but there is no output.
I am also tyring to login to a webpage, let me know if there are any errors
The code i am using is this:
```
class MySpider(Spider):
def init(self, login, password):
link = "http://freeerisa.benefitspro.com"
self.login = login
self.password = <PASSWORD>
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.loginToFreeErissa()
self.loginToFreeErissa()
def loginToFreeErissa(self):
login_data = urllib.urlencode({
'MainContent_mainContent_txtEmail' : self.login,
'MainContent_mainContent_txtPassword' : self.password,
})
response = self.opener.open(link + "/login.aspx", login_data)
return ''.join(response.readlines())
def after_login(self, response):
if "Error while logging in" in response.body:
self.logger.error("Login failed!")
else:
url = [link + "/5500/plandetails.aspx?Ein=042088633",
link + "/5500/plandetails.aspx?Ein=046394579"]
for u in url:
g_data =soup.find_all("span")
for item in g_data:
return item.text
```
I tried calling the function and this is the error I received:
```
Traceback (most recent call last):
File "", line 1, in
File "C:\ProgramData\Anaconda3\lib\site-packages\scrapy\spiders\_init\_.py",line 30,
in init raise ValueError("%s must have a name" % type(self).\_\_name\_\_)
ValueError: MySpider must have a name
```<issue_comment>username_1: There is no output because you don't call anything.
In other worlds, you defined what is **MySpider** but you didn't used it.
Here's [a link](https://docs.python.org/2/tutorial/classes.html) that could help you
Upvotes: 0 <issue_comment>username_2: The error message could not be plainer: **The spider must have a name**. There is no name in the code you have posted. This is *basic* to creating a spider in Scrapy. Also, your Python spacing is terrible, you need an editor with Pylint or something that will tell you about PEP8.
Upvotes: -1 <issue_comment>username_3: Change your code to
```
class MySpider(Spider):
name = 'myspider'
def init(self, login, password):
link = "http://freeerisa.benefitspro.com"
```
and run your spider by
```
scrapy crawl myspider
```
for [**more information**](https://doc.scrapy.org/en/latest/topics/practices.html)
Upvotes: 0 |
2018/03/20 | 613 | 2,299 | <issue_start>username_0: Thought that it will be an easy, but appears to be complicated (for me). Could someone, please, help to find correct solution for following:
Have 200 tests inside one package **selenium.tests.postTip** which looks like this one below:
```
package selenium.tests.postTip;
import java.util.List;
import selenium.BaseTest;
import selenium.DriverBase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class PostBadmintonOddEven extends DriverBase {
@Test
public void main() throws Exception {
WebDriver driver = BaseTest.login();
Thread.sleep(2000);
List allSports = driver.findElements(By.xpath("//ul[@class='be-sportpicker\_\_list']//div[@class='be-sport-thumb\_\_title be-typo-be']"));
driver.findElement(By.xpath("/html/body/be-root/main//be-scroller//be-sportpicker//ul[@class='be-sportpicker\_\_list']/li/a[contains(@href,\"/badminton\")]")).click();
Thread.sleep(2000);
BaseTest.betTypeOddEvenFullEvent(driver);
}
}
```
Since that I have to run those tests as a single test (which already works perfectly) and as a Suite, my question is:
How can I achieve to create (I tried with one **xml** file without any success) TestNG suite with all tests in it. Tried to run all of them, but only first can run, rest of them not. What am I doing wrong?
*Note: BaseTest method which I am calling on last line, doing data check and finish when loop (for loop) finishes.*
I tried with following in above test without success to start second test (aomost same as shown above):
```
@AfterTest
driver.quit();
```
Thank you in advance.<issue_comment>username_1: Instead of @AfterTest method, you can check with @AfterMethod
If that's not solve,
What do you use to get all tests, in TestNG ? @DataProvider with dynamic Array or Excel !
Upvotes: 0 <issue_comment>username_2: What you are doing wrong is naming your test class and methods incorrectly. Rename your test class so that it should have ***Test*** label either in *prefix* or *suffix*. Also you have annotated main method with @Test annotation. Main method is defacto entry point from where JVM starts. Use custom names for methods , that describes the test method.
Upvotes: 2 [selected_answer] |
2018/03/20 | 2,122 | 6,242 | <issue_start>username_0: I have a script receiving a JSON from PHP. I have to parse the data. Unfortunately I'm not able to parse the JSON into an object and get the different arrays. I tried to validate the JSON but I cant find an error there either.
Code:
```
$.ajax({
type: "POST",
dataType: "html",
url: "/sqldblink.php",
data: data,
success: function(data) {
var recdata=data;
console.log("Received data from listregistered:");
console.log("Server reports:" + recdata);
ListRegisteredResults(recdata);
},
error: function () {
console.log("Failed to list!");
}
});
function ListRegisteredResults(recdata) {
console.log(typeof recdata);
var data = JSON.parse(recdata);
console.log(data);
console.log(typeof data);
console.log(data.Address.length);
}
```
The output:
```
Server reports:"{\"Address\":[\"Home\",\"\",\"Home,\nHoover House 85\",\"\",\"Home\",\"\",\"\",\"\",\"\",\"\"],\"BloodGroup\":[\"o+\",\"\",\"B+\",\"B+\",\"AB+\",\"o+\",\"o-\",\"\",\"\",\"\"],\"Occupation\":[\"Vendor\",\"\",\"Carpenter\",\"Playing\",\"Nurse\",\"IT professional\",\"Engineer\",\"Doctor\",\"\",\"\"],\"Alternate\":[\"0\",\"0\",\"925\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"Email\":[\"<EMAIL>\",\"\",\"<EMAIL>\",\"\",\"\",\"\",\"<EMAIL>\",\"\",\"\",\"\"],\"Mobile\":[\"90000006\",\"90000005\",\"90000005\",\"34344444\",\"902w0w05\",\"90002005\",\"900020w5\",\"90000005\",\"90002105\",\"90000005\"],\"Marital\":[\"Married\",\"Married\",\"Married\",\"Unmarried\",\"Unmarried\",\"Married\",\"Married\",\"Married\",\"Married\",\"Married\"],\"Gender\":[\"1\",\"2\",\"\",\"1\",\"1\",\"2\",\"2\",\"1\",\"1\",\"1\"],\"Age\":[\"28\",\"65\",\"35\",\"2\",\"25\",\"34\",\"31\",\"28\",\"60\",\"58\"],\"Name\":[\"<NAME>\",\"<NAME>\",\"<NAME>\",\"<NAME>\",\"<NAME>\",\"<NAME>\",\"<NAME>\",\"<NAME>\",\"Dr Kim\",\"St<NAME>wig\"],\"HospitalID\":[\"3\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"16\"]}"
string
{"Address":["Home","","Home,\nHoover House 85","","Home","","","","",""],"BloodGroup":["o+","","B+","B+","AB+","o+","o-","","",""],"Occupation":["Vendor","","Carpenter","Playing","Nurse","IT professional","Engineer","Doctor","",""],"Alternate":["0","0","925","0","0","0","0","0","0","0"],"Email":["<EMAIL>","","<EMAIL>","","","","<EMAIL>","","",""],"Mobile":["90000006","90000005","90000005","34344444","902w0w05","90002005","900020w5","90000005","90002105","90000005"],"Marital":["Married","Married","Married","Unmarried","Unmarried","Married","Married","Married","Married","Married"],"Gender":["1","2","","1","1","2","2","1","1","1"],"Age":["28","65","35","2","25","34","31","28","60","58"],"Name":["<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"],"HospitalID":["3","5","6","7","8","9","10","11","12","16"]}
string
userjs/main.js:347 Uncaught TypeError: Cannot read property 'length' of undefined
at ListRegisteredResults (userjs/main.js:347)
at Object.success (userjs/main.js:295)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest. (jquery-3.2.1.min.js:4)
```
After I parse the string into JSON, why is it still being reported as being a string?<issue_comment>username_1: Remove `dataType: "html"` as well as any `JSON.parse()` from your code and it'll work. jQuery automatically parses the data if you don't set wrong dataTypes, or `json`
```
$.ajax({
type: "POST",
url: "/sqldblink.php",
data: data,
success: function(data) {
var recdata=data;
console.log("Received data from listregistered:");
console.log("Server reports:" + recdata);
ListRegisteredResults(recdata);
},
error: function () {
console.log("Failed to list!");
}
});
function ListRegisteredResults(recdata) {
console.log(typeof recdata);
var data = recdata;
console.log(data);
console.log(typeof data);
console.log(data.Address.length);
}
```
Upvotes: 2 <issue_comment>username_2: You JSON was invalid. `\n` at position `28` was breaking it, you need to escape it.
`"Address":["Home","","Home,\nHoover House 85"`
Should be
`"Address":["Home","","Home,\\nHoover House 85"`
If you want to keep that `\n`.
```js
let jsonString = `{"Address":["Home","","Home,\\nHoover House 85","","Home","","","","",""],"BloodGroup":["o+","","B+","B+","AB+","o+","o-","","",""],"Occupation":["Vendor","","Carpenter","Playing","Nurse","IT professional","Engineer","Doctor","",""],"Alternate":["0","0","925","0","0","0","0","0","0","0"],"Email":["<EMAIL>","","<EMAIL>","","","","<EMAIL>","","",""],"Mobile":["90000006","90000005","90000005","34344444","902w0w05","90002005","900020w5","90000005","90002105","90000005"],"Marital":["Married","Married","Married","Unmarried","Unmarried","Married","Married","Married","Married","Married"],"Gender":["1","2","","1","1","2","2","1","1","1"],"Age":["28","65","35","2","25","34","31","28","60","58"],"Name":["<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"],"HospitalID":["3","5","6","7","8","9","10","11","12","16"]}`;
let json = JSON.parse(jsonString);
console.log(json.Address);
```
Upvotes: 2 <issue_comment>username_3: This is happening only because of `dataType: "html"`, that you are sending with your post request. SO the response you are getting with '\' so `JSON.parse()` can't handle them.
Remove `dataType` from post request and then try, then you'll get correct response and your required result.
Code:
```
$.ajax({
type: "POST",
url: "/sqldblink.php",
data: data,
success: function(data) {
var recdata=data;
console.log("Received data from listregistered:");
console.log("Server reports:" + recdata);
ListRegisteredResults(recdata);
},
error: function () {
console.log("Failed to list!");
}
});
function ListRegisteredResults(recdata) {
console.log(typeof recdata);
var data = JSON.parse(recdata);
console.log(data);
console.log(typeof data);
console.log(data.Address.length);
}
```
Upvotes: 0 |
2018/03/20 | 1,163 | 3,525 | <issue_start>username_0: This is the `SP_ARCHIVE` table
[](https://i.stack.imgur.com/JaeUm.png)
This is the `Account` table
[](https://i.stack.imgur.com/YQQO7.png)
This is the `Proponent` table
[](https://i.stack.imgur.com/Y3EKf.png)
What the query should output is `sp_archive.SP_ID`, `sp_archive.SP_Title`, `sp_archive.SP_Type`, `Account.Account_FirstName`, `Account.MiddleName`, and `Account.LastName`.
The `name` should be different column<issue_comment>username_1: Remove `dataType: "html"` as well as any `JSON.parse()` from your code and it'll work. jQuery automatically parses the data if you don't set wrong dataTypes, or `json`
```
$.ajax({
type: "POST",
url: "/sqldblink.php",
data: data,
success: function(data) {
var recdata=data;
console.log("Received data from listregistered:");
console.log("Server reports:" + recdata);
ListRegisteredResults(recdata);
},
error: function () {
console.log("Failed to list!");
}
});
function ListRegisteredResults(recdata) {
console.log(typeof recdata);
var data = recdata;
console.log(data);
console.log(typeof data);
console.log(data.Address.length);
}
```
Upvotes: 2 <issue_comment>username_2: You JSON was invalid. `\n` at position `28` was breaking it, you need to escape it.
`"Address":["Home","","Home,\nHoover House 85"`
Should be
`"Address":["Home","","Home,\\nHoover House 85"`
If you want to keep that `\n`.
```js
let jsonString = `{"Address":["Home","","Home,\\nHoover House 85","","Home","","","","",""],"BloodGroup":["o+","","B+","B+","AB+","o+","o-","","",""],"Occupation":["Vendor","","Carpenter","Playing","Nurse","IT professional","Engineer","Doctor","",""],"Alternate":["0","0","925","0","0","0","0","0","0","0"],"Email":["<EMAIL>","","<EMAIL>","","","","<EMAIL>","","",""],"Mobile":["90000006","90000005","90000005","34344444","902w0w05","90002005","900020w5","90000005","90002105","90000005"],"Marital":["Married","Married","Married","Unmarried","Unmarried","Married","Married","Married","Married","Married"],"Gender":["1","2","","1","1","2","2","1","1","1"],"Age":["28","65","35","2","25","34","31","28","60","58"],"Name":["<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>"],"HospitalID":["3","5","6","7","8","9","10","11","12","16"]}`;
let json = JSON.parse(jsonString);
console.log(json.Address);
```
Upvotes: 2 <issue_comment>username_3: This is happening only because of `dataType: "html"`, that you are sending with your post request. SO the response you are getting with '\' so `JSON.parse()` can't handle them.
Remove `dataType` from post request and then try, then you'll get correct response and your required result.
Code:
```
$.ajax({
type: "POST",
url: "/sqldblink.php",
data: data,
success: function(data) {
var recdata=data;
console.log("Received data from listregistered:");
console.log("Server reports:" + recdata);
ListRegisteredResults(recdata);
},
error: function () {
console.log("Failed to list!");
}
});
function ListRegisteredResults(recdata) {
console.log(typeof recdata);
var data = JSON.parse(recdata);
console.log(data);
console.log(typeof data);
console.log(data.Address.length);
}
```
Upvotes: 0 |
2018/03/20 | 339 | 925 | <issue_start>username_0: I need to add same values on array and then to see it as one string.
```
char txt[33] = "";
for (int i=0; i<4; i++)
{
txt[i]="A";
}
LCDPutStr(txt,25);
```
I get `4` characters but they are strange symbols. I need to take `"AAAA"`.<issue_comment>username_1: If LCDPutStr expects a string (as its name suggests), then you need to null terminate your string:
```
char txt[33]="";
for (int i=0;i<4;i++)
{
txt[i]='A';
}
txt[4] = '\0';
LCDPutStr(txt,25);
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: 1) use `'A'`, single quote, in stead of the double quote;
2) terminate the string with a `'\0'`: `text[i]= '\0';`
Summary:
```
char txt[33] = "";
int i;
for (i=0; i<4; i++)
{
txt[i]='A';
}
txt[i]='\0';
LCDPutStr(txt,25);
```
(I moved `int i` to before the loop so it is available afer the loop to put the terminator there.)
Upvotes: 2 |
2018/03/20 | 809 | 2,994 | <issue_start>username_0: I am making a simple CRUD function in my Xamarin.Forms app, but I can't understand how to delete from the list.
**My question** is this, how do I delete the selected item in the TextCell? As of now since I am using `var delete = _saveData[0];` I'm obviously deleting the first item. My guess is that I have to get the Id and pass it to the `OnDelete` but I have no idea how.
Maybe there is a much better approach to this? It doesn't have to be a TextCell as long as I can present the data as
```
Name
Status
```
and then be able to e.g longpress on the cell and choose to delete it.
**My xaml page:**
*StatusPage.xaml*
```
```
**The relevant parts of the code-behind:**
*StatusPage.xaml.cs*
```
namespace MyCRUDApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class StatusPage : ContentPage
{
private SQLiteAsyncConnection _connection;
private ObservableCollection \_saveData;
public StatusPage()
{
InitializeComponent ();
\_connection = DependencyService.Get().GetConnection();
}
protected override async void OnAppearing()
{
base.OnAppearing();
await \_connection.CreateTableAsync();
var abc = await \_connection.Table().ToListAsync();
\_saveData = new ObservableCollection(abc);
mylistview.ItemsSource = \_saveData;
}
void OnAdd(object sender, EventArgs e)
{
var SaveData = new SaveData { Name = Name.Text, Status = Status.Text };
\_connection.InsertAsync(SaveData);
\_saveData.Add(SaveData);
}
void OnDelete(object sender, EventArgs e)
{
var delete = \_saveData[0];
\_connection.DeleteAsync(delete);
\_saveData.Remove(delete);
}
}
}
```
**My SaveData class**
*SaveData.cs*
```
namespace MyCRUDApp.Models
{
public class SaveData
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(255)]
public string Name { get; set; }
[MaxLength(255)]
public string Status { get; set; }
}
}
```<issue_comment>username_1: First, add a public property to store the currently selected item to your code:
```
public SaveData SelectedSaveData{get; set;} // Add appropriate handling, e.g. INotifyPropertyChanged
```
Then bind this to the `SelectedItem` property of the `ListView`, remove the `Tapped` binding on your `TextCell` and bind to `ItemSelected` on the `ListView` instead.
```
```
Now `SelectedSaveData` will always hold the one that was selected in the `ListView` and can be used in your methods, e.g.
```
void OnDelete(object sender, EventArgs e)
{
_connection.DeleteAsync(SelectedSaveData);
_saveData.Remove(SelectedSaveData);
}
```
Upvotes: 1 <issue_comment>username_2: One way to trigger the event
add event ItemTapped to the listView
```
```
event implementation looks like
```
public void OnItemTapped ( object o, ItemTappedEventArgs e ) {
var item = e.Item as Object;
//here you can call the delete function
}
```
Upvotes: 1 [selected_answer] |
2018/03/20 | 796 | 2,509 | <issue_start>username_0: For python `dict`, I could use `iteritems()` to loop through key and value at the same time. But I cannot find such functionality for NumPy array. I have to manually track `idx` like this:
```
idx = 0
for j in theta:
some_function(idx,j,theta)
idx += 1
```
Is there a better way to do this?<issue_comment>username_1: There are a few alternatives. The below assumes you are iterating over a 1d NumPy array.
### Iterate with [`range`](https://docs.python.org/3/library/functions.html#func-range)
```
for j in range(theta.shape[0]): # or range(len(theta))
some_function(j, theta[j], theta)
```
Note this is [the only](https://github.com/numba/numba/issues/3111) of the 3 solutions which will work with [`numba`](http://numba.pydata.org/). This is noteworthy since iterating over a NumPy array explicitly is usually only efficient when combined with `numba` or another means of pre-compilation.
### Iterate with [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate)
```
for idx, j in enumerate(theta):
some_function(idx, j, theta)
```
The most efficient of the 3 solutions for 1d arrays. See benchmarking below.
### Iterate with [`np.ndenumerate`](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.ndenumerate.html)
```
for idx, j in np.ndenumerate(theta):
some_function(idx[0], j, theta)
```
Notice the additional indexing step in `idx[0]`. This is necessary since the index (like `shape`) of a 1d NumPy array is given as a singleton tuple. For a 1d array, `np.ndenumerate` is inefficient; its benefits only show for multi-dimensional arrays.
### Performance benchmarking
```
# Python 3.7, NumPy 1.14.3
np.random.seed(0)
arr = np.random.random(10**6)
def enumerater(arr):
for index, value in enumerate(arr):
index, value
pass
def ranger(arr):
for index in range(len(arr)):
index, arr[index]
pass
def ndenumerater(arr):
for index, value in np.ndenumerate(arr):
index[0], value
pass
%timeit enumerater(arr) # 131 ms
%timeit ranger(arr) # 171 ms
%timeit ndenumerater(arr) # 579 ms
```
Upvotes: 7 [selected_answer]<issue_comment>username_2: You can use `numpy.ndenumerate` for example
```
import numpy as np
test_array = np.arange(2, 3, 0.1)
for index, value in np.ndenumerate(test_array):
print(index[0], value)
```
For more information refer to <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html>
Upvotes: 3 |
2018/03/20 | 513 | 1,768 | <issue_start>username_0: The following code is from `export_stockinfo_xls` in Odoo 10. I want to know what mean `context.get('active_ids', [])` and what is the returned value. Why do we use `[]` in that expression?
```
@api.multi
def export_xls(self):
context = self._context
datas = {'ids': context.get('active_ids', [])} # what mean this and what return
datas['model'] = 'product.product'
datas['form'] = self.read()[0]
for field in datas['form'].keys():
if isinstance(datas['form'][field], tuple):
datas['form'][field] = datas['form'][field][0]
if context.get('xls_export'):
return {
'type': 'ir.actions.report.xml',
'report_name': 'export_stockinfo_xls.stock_report_xls.xlsx',
'datas': datas,
'name': 'Current Stock'
}
```<issue_comment>username_1: the method `dict.get` is used to fetch a value from a dictionary. It has an additional parameter that returns a default value from a dict.
**dict.get Demo:**
```
dictionary = {"message": "Hello, World!"}
print(dictionary.get("message", ""))
print(dictionary.get("message_1111", "No Value")) #Note: "message_1111" not in dictionary.
```
**Output:**
```
Hello, World!
No Value
```
**[MoreInfo](https://www.programiz.com/python-programming/methods/dictionary/get)**
*In your case.*
```
context.get('active_ids', [])
```
if `'active_ids'` is not in context returns an empty list.
Upvotes: 2 <issue_comment>username_2: If you are in a tree view `context.get('active_ids', [])` returns a list of checked elements ids. If you are in a form view it returns the id of the item that you see on the screen.
If there is no element id it returns an empty list ([]).
I hope this help you.
Upvotes: 2 |
2018/03/20 | 714 | 2,533 | <issue_start>username_0: So. I've got a list Property that groups values with identical names;
```
List> MyList { get; set; }
```
It's initially populated from a database by means of an `IQueryable<>`.
But say I wanted to add a new item to this list using code, how would I go about that? Since IGrouping is an interface, I can't exactly new it up like;
```
IGrouping newGroup = new IGrouping();
MyList.Add(newGroup);
```
That doesn't work. I'd like to know, 'what does?' How do I get a new item in there?
Many thanks.
**EDIT:**
A little perspective:
Imagine having two or more cities. These cities have a few respective streets with matching names. `IGrouping<,>` ensures that the street name appears only once in the List. Therefore the data-bound `Combobox` doesn't repeat any values (typically because the end user won't know to what city the street belongs to).
My view has two `Combobox`es. One for street, the other for city. Should a street be selected, the viewmodel will select the corresponding city, unless the street group contains more that one street within it. At that point, the user will be prompted to manually select which city the street resides in.
I figured that `IGrouping<,>` would suit this purpose seeing as it's the default return type when using the GroupBy() extension method. Still open to suggestions though.<issue_comment>username_1: Either use a `GroupBy` call on an `IEnumerable` that produces what you want, or implement `IGrouping` as per [this answer to a question about that particular approach](https://stackoverflow.com/a/8508212/400547).
Upvotes: 0 <issue_comment>username_2: Use this method to create IGrouping value:
```
IGrouping GetIGrouping(string key,MyItemDTO item)
{
return new[] {item}.GroupBy(val => key).First();
}
```
or if you want several items in group:
```
IGrouping GetIGrouping(string key,IEnumerable items)
{
return items.GroupBy(val => key).First();
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: I think You really do not needed `IGrouping` in your Property , What rather you need is a collection like `Dictionary` , `List` etc.
Still if you want it then here's how you should add items with IGrouping
```
var t = new List();
foreach (var item in t.GroupBy(x => x.A))
{
A.MyList.Add(item);
}
```
---
```
public static class A
{
public static List> MyList { get; set; }
}
```
---
```
public class Test
{
public string A { get; set; }
public int B { get; set; }
}
```
Hope that helps !!
Upvotes: 0 |
2018/03/20 | 282 | 938 | <issue_start>username_0: Does the regular expression `X•(Y*+Z)` accept the word `X`?
I would say it does, as `Y=ε` should fulfill the disjunction, but I'm not sure.<issue_comment>username_1: This answer is assuming that your regex could also be represented as `X.(Y*|Z)` in addition to your original of `X•(Y*|Z)` -- if that is not correct, please explain what `•` is supposed to do or represent.
`X•(Y*|Z)` necessitates that `X` be present before `Y*` or `Z` can match, but will not include `X` in the match's specific capture-group results, only the matching line. If you wanted to include `X`, you might re-write it as `(X)•(Y*|Z)` and extract `X` from capture group 1, and your disjunction match in capture group 2.
Upvotes: 1 <issue_comment>username_2: Yes, matching 0 times still counts as success.
Or, looking at it from the other direction, your regex generates
```
X
XY
XZ
XYY
XYYY
XYYYY
...
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 692 | 2,997 | <issue_start>username_0: So I'm writing a chat application and I need to store each users chat log locally. I'm using Room to do this.
User class:
```
@PrimaryKey
@NonNull
private String userid;
private String name;;
@TypeConverters(Object_Converter.class)
private ArrayList messages = new ArrayList<>();
```
The issue I'm having is updating the List of messages.
I'm currently using the default @Update method:
```
@Update
void updateUser(User user);
```
So basically every time a message is received by my listener, it will request the user by Id, then get the list of messages and then add to it, and finally call updateUser.
My question is how detrimental to performance is this method since I assume updateUser just overwrites the entire list of messages with a new one? Messages can be recieved every few moments so is their a better way to store and update a user chat history?<issue_comment>username_1: You are right. All messages will be overwritten by update. It would be best to store messages in its own table with a foreign key to sending and receiving user. Basically your message would look like this:
```
@Entity(tableName = "message", foreignKeys = {
@ForeignKey(
entity = User.class,
parentColumns = "userid",
childColumns = "senderId",
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
),
@ForeignKey(
entity = User.class,
parentColumns = "userid",
childColumns = "receiverId",
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
}, indices = {
@Index("senderId"),
@Index("receiverId")
})
public class Message {
@PrimaryKey(autoGenerate = true)
public long id;
public String senderId;
public String receiverId;
public String content;
// ... other stuff
}
```
And then you would just insert and delete messages when needed. When you want to retrieve messages you could just retrieve it with `userid` or you could join tables and create another model class which would contain user and list of sent and receieved messages.
It's never a good idea to store a list as a column because it indicated that a new table is needed. For more information read about [database normal form](https://www.studytonight.com/dbms/database-normalization.php).
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is more about the design of the database, rather than the implementation.
I'd go about this issue like this:
You can create a new database entity for the Messages and use a foreign key to connect the two entities. That would be one-to-many relationship where each user can have more messages. Then, you would simply insert each new message in the second table and get the list of messages with a query, i.e:
```
"SELECT message FROM messages WHERE userid = :id"
```
or something similar. The main point is, you need to change your database structure.
Upvotes: 0 |
2018/03/20 | 957 | 3,093 | <issue_start>username_0: I'm new to HTML/CSS and I want quite simple thing - 2 column layout, where the right column gets the width according to its content (text) and left column takes the rest of the space.
I was able to do that using `floats` - basically the right `div` was floated to the right and the left `div` was using some `overflow: auto` magic to get the remaining area:
```css
body, html {
margin: 0;
height: 100%;
}
.ellipsize {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.right {
float: right;
width: auto;
background-color: orange;
height: 100%;
}
.left {
background-color: black;
width: auto;
overflow: auto;
height: 100%;
color: white;
}
```
```html
HELLO WORLD!!!
Lorizzle ipsum shiznit black amizzle, fo shizzle adipiscing tellivizzle. Nullizzle sapien velizzle, volutpat, suscipit bow wow wow, gravida i'm in the shizzle, stuff. We gonna chung i saw beyonces tizzles and my pizzle went crizzle tortizzle. Gangster erizzle. Brizzle izzle dolizzle my shizz turpizzle tempizzle fo shizzle. Maurizzle fo shizzle nibh shizzlin dizzle gangsta. Own yo' izzle yo mamma. Yo the bizzle rhoncus away. In black habitasse platea black. Phat dapibizzle. Curabitur tellizzle urna, pretizzle eu, mattizzle pot, break yo neck, yall vitae, nunc. Mammasay mammasa mamma oo sa suscipizzle. Shizznit sempizzle fizzle shiz yo.
```
However, I have recently read a lot of posts about how `floats` are *wrong, old-style, should not be used* and so on, and everybody says to use `display: inline-block` instead.
**Question:** is it possible to reach the same effect with `inline-block` or without `floats`?<issue_comment>username_1: >
> However, I have recently read a lot of posts about how floats are wrong, old-style, should not be used and so on
>
>
>
If you're looking for a more modern solution using flexboxes is one of them. Here's how you could achive your desired effect by wrapping your content in a wrapper with a `display:flex`.
```css
.wrapper{
display:flex;
flex-direction:row-reverse;
}
.right{
background-color:pink;
}
.left{
background-color:lightgreen
}
```
```html
HELLO WORLD!!!
Lorizzle ipsum shiznit black amizzle, fo shizzle adipiscing tellivizzle. Nullizzle sapien velizzle, volutpat, suscipit bow wow wow, gravida i'm in the shizzle, stuff. We gonna chung i saw beyonces tizzles and my pizzle went crizzle tortizzle. Gangster erizzle. Brizzle izzle dolizzle my shizz turpizzle tempizzle fo shizzle. Maurizzle fo shizzle nibh shizzlin dizzle gangsta. Own yo' izzle yo mamma. Yo the bizzle rhoncus away. In black habitasse platea black. Phat dapibizzle. Curabitur tellizzle urna, pretizzle eu, mattizzle pot, break yo neck, yall vitae, nunc. Mammasay mammasa mamma oo sa suscipizzle. Shizznit sempizzle fizzle shiz yo.
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: use display:flex . It will work perfectly and If you want this to be responsive use flex-wrap: wrap.
```
.ellipsize {
display: flex;
flex-wrap: wrap
}
```
Upvotes: 1 |
2018/03/20 | 466 | 1,798 | <issue_start>username_0: I'd like to create a custom sequence of elements. When iterating over it, the length of the sequence is ignored. Here is a minimal code example:
```
class Test():
def __init__(self):
pass
def __len__(self):
return 5
def __getitem__(self, idx):
return idx
t = Test()
for i, x in enumerate(t):
print(i, x)
```
I'd expect to have only `0 0` to `4 4` printed out. In reality, the loop behaves as with an infinitely long sequence and goes on and on and on. `len(t)` returns `5` as expected.
What am I missing?<issue_comment>username_1: Python expects `__getitem__()` to raise an `IndexError` when indexes outside of the possible range are requested, as noted in [the docs](https://docs.python.org/3/reference/datamodel.html#object.__getitem__):
>
> **Note** `for` loops expect that an `IndexError` will be raised for illegal indexes to allow proper detection of the end of the sequence.
>
>
>
The advantage to this is that you don't *have* to implement `__len__()` which means your index-based iterable can be lazy, meaning unknown lengths or infinite lengths are possible.
This mirrors the way [iterator objects](https://docs.python.org/3/glossary.html#term-iterator) and for loops work in Python - they continue to ask for values until an exception is reached (`StopIteration` for iterators), which makes the implementation easier - `iter()` just wraps with a loop incrementing the index until it hits the exception.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to check yourself, if the key is out of bounds. `__len__` is only used for two purposes. To be able to call len(obj) and it will be used, if no `__bool__` method exists to determine, if the object evaluates to true in conditions.
Upvotes: 0 |
2018/03/20 | 676 | 2,368 | <issue_start>username_0: I'm using the GraphQL Spring-boot library to build a GraphQL API
<https://github.com/graphql-java/graphql-spring-boot>
I have a schema
```
type Car {
id: ID!
model: String
brand: String
}
type Query {
allCars: [Car]!
}
```
And my query is implemented in a Query class in my Spring Boot project
```
@Component
public class Query implements GraphQLQueryResolver {
public List allCars() {}
}
```
My question is:
How do I use filters and sorting when returning lists:
```
allCars(first:3){id model}
allCars(filter: {....}){}
```
I guess this is something that has to be implemented in the Java method, but i'm unsure how to inject the filters etc. in the method.<issue_comment>username_1: My guess is that you would create your own filter input type, for example:
```graphql
type Query {
allCars(filter: CarsFilter!): [Car]
}
input CarsFilter {
color: String!
brand: String!
}
```
After that, you can write a Java implementation of `CarsFilter`, for example:
```java
public class CarsFilter {
private String color;
private String brand;
// Getters + Setters
}
```
Now you can write your resolver using the `CarsFilter` class:
```
public List allCars(CarsFilter filter) {
// Filter by using JPA specifications, custom queries, ...
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: GraphQL allows for the client to specify exactly what data is desired but it doesn't has any inbuilt way of filtering and sorting the data. You will have write code for that yourself. Regarding injecting the filters, one possible way of doing it can be following:
```
type Query {
allCars(filter: String, range: String, sort: String): [Car]!
}
```
For above Query, sample request would be like:
```
{
allCars(filter: "{brand: 'Abc'}", range: "[0, 100]", sort: "[id, ASC]") { # Fetch first 100 cars of brand 'Abc' sorted by id
id
model
brand
}
}
```
Then your getAllCars method would be like following:
```
public List getAllCars(String filter, String range, String sort) {
// Implement parser and filter by using JPA specifications
}
```
To see a sample implementation of parser and its conversion it to JPA specifications, please refer to following project: <https://github.com/jaskaransingh156/spring-boot-graphql-with-custom-rql>
Upvotes: 0 |
2018/03/20 | 9,659 | 23,219 | <issue_start>username_0: I am very much new to AES encryption and decryption. In my app, I have to decrypt the data which I get from the server. The data I receive is encrypted using the CryptoJS library. The decryption works pretty much fine. But while posting the data to the server, I have to again encrypt the data and send it to the server, which is not giving proper encryption. I have followed [This Stack overflow answer](https://stackoverflow.com/questions/41432896/cryptojs-aes-encryption-and-java-aes-decryption) for decryption which is working fine. I will post my decryption code below. Please help.
For decryption:
```
public static String Decrypt(String Encrpyt , String Key ) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
byte[] cipherData = Base64.decode(Encrpyt, Base64.DEFAULT);
byte[] saltData = Arrays.copyOfRange(cipherData, 8, 16);
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
final byte[][] keyAndIV = GenerateKeyAndIV(32, 16, 1, saltData, Key.getBytes(StandardCharsets.UTF_8), md5);
SecretKeySpec key = new SecretKeySpec(keyAndIV[0], "AES");
IvParameterSpec iv = new IvParameterSpec(keyAndIV[1]);
byte[] encrypted = Arrays.copyOfRange(cipherData, 16, cipherData.length);
Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decryptedData = aesCBC.doFinal(encrypted);
String decryptedText = new String(decryptedData, StandardCharsets.UTF_8);
System.out.println(decryptedText);
return decryptedText;
}
public static byte[][] GenerateKeyAndIV(int keyLength, int ivLength, int iterations, byte[] salt, byte[] password, MessageDigest md) {
int digestLength = md.getDigestLength();
int requiredLength = (keyLength + ivLength + digestLength - 1) / digestLength * digestLength;
byte[] generatedData = new byte[requiredLength];
int generatedLength = 0;
try {
md.reset();
// Repeat process until sufficient data has been generated
while (generatedLength < keyLength + ivLength) {
// Digest data (last digest if available, password data, salt if available)
if (generatedLength > 0)
md.update(generatedData, generatedLength - digestLength, digestLength);
md.update(password);
if (salt != null)
md.update(salt, 0, 8);
try {
md.digest(generatedData, generatedLength, digestLength);
} catch (DigestException e) {
e.printStackTrace();
}
// additional rounds
for (int i = 1; i < iterations; i++) {
md.update(generatedData, generatedLength, digestLength);
md.digest(generatedData, generatedLength, digestLength);
}
generatedLength += digestLength;
}
// Copy key and IV into separate byte arrays
byte[][] result = new byte[2][];
result[0] = Arrays.copyOfRange(generatedData, 0, keyLength);
if (ivLength > 0)
result[1] = Arrays.copyOfRange(generatedData, keyLength, keyLength + ivLength);
return result;
} catch (DigestException e) {
throw new RuntimeException(e);
} finally {
// Clean out temporary data
Arrays.fill(generatedData, (byte)0);
}
}
```<issue_comment>username_1: Please find the below snippet. Add it in a .js file named aes.js. Create a Raw folder inside res folder. Inside the Raw folder add the aes.js file.
You can see in the javascript code, there are 2 methods called encryption() and decryption() which we will be using in our code.
```js
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by <NAME>. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
var CryptoJS=CryptoJS||function(u,p){var d={},l=d.lib={},s=function(){},t=l.Base={extend:function(a){s.prototype=this;var c=new s;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
r=l.WordArray=t.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=p?c:4*a.length},toString:function(a){return(a||v).stringify(this)},concat:function(a){var c=this.words,e=a.words,j=this.sigBytes;a=a.sigBytes;this.clamp();if(j%4)for(var k=0;k>>2]|=(e[k>>>2]>>>24-8\*(k%4)&255)<<24-8\*((j+k)%4);else if(65535>>2]=e[k>>>2];else c.push.apply(c,e);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
32-8\*(c%4);a.length=u.ceil(c/4)},clone:function(){var a=t.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],e=0;e>>2]>>>24-8\*(j%4)&255;e.push((k>>>4).toString(16));e.push((k&15).toString(16))}return e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j>>3]|=parseInt(a.substr(j,
2),16)<<24-4\*(j%8);return new r.init(e,c/2)}},b=w.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var e=[],j=0;j>>2]>>>24-8\*(j%4)&255));return e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j>>2]|=(a.charCodeAt(j)&255)<<24-8\*(j%4);return new r.init(e,c)}},x=w.Utf8={stringify:function(a){try{return decodeURIComponent(escape(b.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return b.parse(unescape(encodeURIComponent(a)))}},
q=l.BufferedBlockAlgorithm=t.extend({reset:function(){this.\_data=new r.init;this.\_nDataBytes=0},\_append:function(a){"string"==typeof a&&(a=x.parse(a));this.\_data.concat(a);this.\_nDataBytes+=a.sigBytes},\_process:function(a){var c=this.\_data,e=c.words,j=c.sigBytes,k=this.blockSize,b=j/(4\*k),b=a?u.ceil(b):u.max((b|0)-this.\_minBufferSize,0);a=b\*k;j=u.min(4\*a,j);if(a){for(var q=0;q>>2]>>>24-8\*(r%4)&255)<<16|(l[r+1>>>2]>>>24-8\*((r+1)%4)&255)<<8|l[r+2>>>2]>>>24-8\*((r+2)%4)&255,v=0;4>v&&r+0.75\*v>>6\*(3-v)&63));if(l=t.charAt(64))for(;d.length%4;)d.push(l);return d.join("")},parse:function(d){var l=d.length,s=this.\_map,t=s.charAt(64);t&&(t=d.indexOf(t),-1!=t&&(l=t));for(var t=[],r=0,w=0;w<
l;w++)if(w%4){var v=s.indexOf(d.charAt(w-1))<<2\*(w%4),b=s.indexOf(d.charAt(w))>>>6-2\*(w%4);t[r>>>2]|=(v|b)<<24-8\*(r%4);r++}return p.create(t,r)},\_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
(function(u){function p(b,n,a,c,e,j,k){b=b+(n&a|~n&c)+e+k;return(b<>>32-j)+n}function d(b,n,a,c,e,j,k){b=b+(n&c|a&~c)+e+k;return(b<>>32-j)+n}function l(b,n,a,c,e,j,k){b=b+(n^a^c)+e+k;return(b<>>32-j)+n}function s(b,n,a,c,e,j,k){b=b+(a^(n|~c))+e+k;return(b<>>32-j)+n}for(var t=CryptoJS,r=t.lib,w=r.WordArray,v=r.Hasher,r=t.algo,b=[],x=0;64>x;x++)b[x]=4294967296\*u.abs(u.sin(x+1))|0;r=r.MD5=v.extend({\_doReset:function(){this.\_hash=new w.init([1732584193,4023233417,2562383102,271733878])},
\_doProcessBlock:function(q,n){for(var a=0;16>a;a++){var c=n+a,e=q[c];q[c]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360}var a=this.\_hash.words,c=q[n+0],e=q[n+1],j=q[n+2],k=q[n+3],z=q[n+4],r=q[n+5],t=q[n+6],w=q[n+7],v=q[n+8],A=q[n+9],B=q[n+10],C=q[n+11],u=q[n+12],D=q[n+13],E=q[n+14],x=q[n+15],f=a[0],m=a[1],g=a[2],h=a[3],f=p(f,m,g,h,c,7,b[0]),h=p(h,f,m,g,e,12,b[1]),g=p(g,h,f,m,j,17,b[2]),m=p(m,g,h,f,k,22,b[3]),f=p(f,m,g,h,z,7,b[4]),h=p(h,f,m,g,r,12,b[5]),g=p(g,h,f,m,t,17,b[6]),m=p(m,g,h,f,w,22,b[7]),
f=p(f,m,g,h,v,7,b[8]),h=p(h,f,m,g,A,12,b[9]),g=p(g,h,f,m,B,17,b[10]),m=p(m,g,h,f,C,22,b[11]),f=p(f,m,g,h,u,7,b[12]),h=p(h,f,m,g,D,12,b[13]),g=p(g,h,f,m,E,17,b[14]),m=p(m,g,h,f,x,22,b[15]),f=d(f,m,g,h,e,5,b[16]),h=d(h,f,m,g,t,9,b[17]),g=d(g,h,f,m,C,14,b[18]),m=d(m,g,h,f,c,20,b[19]),f=d(f,m,g,h,r,5,b[20]),h=d(h,f,m,g,B,9,b[21]),g=d(g,h,f,m,x,14,b[22]),m=d(m,g,h,f,z,20,b[23]),f=d(f,m,g,h,A,5,b[24]),h=d(h,f,m,g,E,9,b[25]),g=d(g,h,f,m,k,14,b[26]),m=d(m,g,h,f,v,20,b[27]),f=d(f,m,g,h,D,5,b[28]),h=d(h,f,
m,g,j,9,b[29]),g=d(g,h,f,m,w,14,b[30]),m=d(m,g,h,f,u,20,b[31]),f=l(f,m,g,h,r,4,b[32]),h=l(h,f,m,g,v,11,b[33]),g=l(g,h,f,m,C,16,b[34]),m=l(m,g,h,f,E,23,b[35]),f=l(f,m,g,h,e,4,b[36]),h=l(h,f,m,g,z,11,b[37]),g=l(g,h,f,m,w,16,b[38]),m=l(m,g,h,f,B,23,b[39]),f=l(f,m,g,h,D,4,b[40]),h=l(h,f,m,g,c,11,b[41]),g=l(g,h,f,m,k,16,b[42]),m=l(m,g,h,f,t,23,b[43]),f=l(f,m,g,h,A,4,b[44]),h=l(h,f,m,g,u,11,b[45]),g=l(g,h,f,m,x,16,b[46]),m=l(m,g,h,f,j,23,b[47]),f=s(f,m,g,h,c,6,b[48]),h=s(h,f,m,g,w,10,b[49]),g=s(g,h,f,m,
E,15,b[50]),m=s(m,g,h,f,r,21,b[51]),f=s(f,m,g,h,u,6,b[52]),h=s(h,f,m,g,k,10,b[53]),g=s(g,h,f,m,B,15,b[54]),m=s(m,g,h,f,e,21,b[55]),f=s(f,m,g,h,v,6,b[56]),h=s(h,f,m,g,x,10,b[57]),g=s(g,h,f,m,t,15,b[58]),m=s(m,g,h,f,D,21,b[59]),f=s(f,m,g,h,z,6,b[60]),h=s(h,f,m,g,C,10,b[61]),g=s(g,h,f,m,j,15,b[62]),m=s(m,g,h,f,A,21,b[63]);a[0]=a[0]+f|0;a[1]=a[1]+m|0;a[2]=a[2]+g|0;a[3]=a[3]+h|0},\_doFinalize:function(){var b=this.\_data,n=b.words,a=8\*this.\_nDataBytes,c=8\*b.sigBytes;n[c>>>5]|=128<<24-c%32;var e=u.floor(a/
4294967296);n[(c+64>>>9<<4)+15]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360;n[(c+64>>>9<<4)+14]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360;b.sigBytes=4\*(n.length+1);this.\_process();b=this.\_hash;n=b.words;for(a=0;4>a;a++)c=n[a],n[a]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return b},clone:function(){var b=v.clone.call(this);b.\_hash=this.\_hash.clone();return b}});t.MD5=v.\_createHelper(r);t.HmacMD5=v.\_createHmacHelper(r)})(Math);
(function(){var u=CryptoJS,p=u.lib,d=p.Base,l=p.WordArray,p=u.algo,s=p.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:p.MD5,iterations:1}),init:function(d){this.cfg=this.cfg.extend(d)},compute:function(d,r){for(var p=this.cfg,s=p.hasher.create(),b=l.create(),u=b.words,q=p.keySize,p=p.iterations;u.length>>2]&255}};d.BlockCipher=v.extend({cfg:v.cfg.extend({mode:b,padding:q}),reset:function(){v.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this.\_xformMode==this.\_ENC\_XFORM\_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this.\_minBufferSize=1;this.\_mode=c.call(a,
this,b&&b.words)},\_doProcessBlock:function(a,b){this.\_mode.processBlock(a,b)},\_doFinalize:function(){var a=this.cfg.padding;if(this.\_xformMode==this.\_ENC\_XFORM\_MODE){a.pad(this.\_data,this.blockSize);var b=this.\_process(!0)}else b=this.\_process(!0),a.unpad(b);return b},blockSize:4});var n=d.CipherParams=l.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),b=(p.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt;return(a?s.create([1398893684,
1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=s.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return n.create({ciphertext:a,salt:c})}},a=d.SerializableCipher=l.extend({cfg:l.extend({format:b}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var l=a.createEncryptor(c,d);b=l.finalize(b);l=l.cfg;return n.create({ciphertext:b,key:c,iv:l.iv,algorithm:a,mode:l.mode,padding:l.padding,blockSize:a.blockSize,formatter:d.format})},
decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this.\_parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},\_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),p=(p.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=s.random(8));a=w.create({keySize:b+c}).compute(a,d);c=s.create(a.words.slice(b),4\*c);a.sigBytes=4\*b;return n.create({key:a,iv:c,salt:d})}},c=d.PasswordBasedCipher=a.extend({cfg:a.cfg.extend({kdf:p}),encrypt:function(b,c,d,l){l=this.cfg.extend(l);d=l.kdf.execute(d,
b.keySize,b.ivSize);l.iv=d.iv;b=a.encrypt.call(this,b,c,d.key,l);b.mixIn(d);return b},decrypt:function(b,c,d,l){l=this.cfg.extend(l);c=this.\_parse(c,l.format);d=l.kdf.execute(d,b.keySize,b.ivSize,c.salt);l.iv=d.iv;return a.decrypt.call(this,b,c,d.key,l)}})}();
(function(){for(var u=CryptoJS,p=u.lib.BlockCipher,d=u.algo,l=[],s=[],t=[],r=[],w=[],v=[],b=[],x=[],q=[],n=[],a=[],c=0;256>c;c++)a[c]=128>c?c<<1:c<<1^283;for(var e=0,j=0,c=0;256>c;c++){var k=j^j<<1^j<<2^j<<3^j<<4,k=k>>>8^k&255^99;l[e]=k;s[k]=e;var z=a[e],F=a[z],G=a[F],y=257\*a[k]^16843008\*k;t[e]=y<<24|y>>>8;r[e]=y<<16|y>>>16;w[e]=y<<8|y>>>24;v[e]=y;y=16843009\*G^65537\*F^257\*z^16843008\*e;b[k]=y<<24|y>>>8;x[k]=y<<16|y>>>16;q[k]=y<<8|y>>>24;n[k]=y;e?(e=z^a[a[a[G^z]]],j^=a[a[j]]):e=j=1}var H=[0,1,2,4,8,
16,32,64,128,27,54],d=d.AES=p.extend({\_doReset:function(){for(var a=this.\_key,c=a.words,d=a.sigBytes/4,a=4\*((this.\_nRounds=d+6)+1),e=this.\_keySchedule=[],j=0;j>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255]):(k=k<<8|k>>>24,k=l[k>>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255],k^=H[j/d|0]<<24);e[j]=e[j-d]^k}c=this.\_invKeySchedule=[];for(d=0;dd||4>=j?k:b[l[k>>>24]]^x[l[k>>>16&255]]^q[l[k>>>
8&255]]^n[l[k&255]]},encryptBlock:function(a,b){this.\_doCryptBlock(a,b,this.\_keySchedule,t,r,w,v,l)},decryptBlock:function(a,c){var d=a[c+1];a[c+1]=a[c+3];a[c+3]=d;this.\_doCryptBlock(a,c,this.\_invKeySchedule,b,x,q,n,s);d=a[c+1];a[c+1]=a[c+3];a[c+3]=d},\_doCryptBlock:function(a,b,c,d,e,j,l,f){for(var m=this.\_nRounds,g=a[b]^c[0],h=a[b+1]^c[1],k=a[b+2]^c[2],n=a[b+3]^c[3],p=4,r=1;r>>24]^e[h>>>16&255]^j[k>>>8&255]^l[n&255]^c[p++],s=d[h>>>24]^e[k>>>16&255]^j[n>>>8&255]^l[g&255]^c[p++],t=
d[k>>>24]^e[n>>>16&255]^j[g>>>8&255]^l[h&255]^c[p++],n=d[n>>>24]^e[g>>>16&255]^j[h>>>8&255]^l[k&255]^c[p++],g=q,h=s,k=t;q=(f[g>>>24]<<24|f[h>>>16&255]<<16|f[k>>>8&255]<<8|f[n&255])^c[p++];s=(f[h>>>24]<<24|f[k>>>16&255]<<16|f[n>>>8&255]<<8|f[g&255])^c[p++];t=(f[k>>>24]<<24|f[n>>>16&255]<<16|f[g>>>8&255]<<8|f[h&255])^c[p++];n=(f[n>>>24]<<24|f[g>>>16&255]<<16|f[h>>>8&255]<<8|f[k&255])^c[p++];a[b]=q;a[b+1]=s;a[b+2]=t;a[b+3]=n},keySize:8});u.AES=p.\_createHelper(d)})();
function encryption(PlainText,key){
var encrypt = CryptoJS.AES.encrypt(PlainText,key);
return(encrypt);
}
function decryption(EncrpytData,key){
var decrypted =CryptoJS.AES.decrypt(EncrpytData,key).toString(CryptoJS.enc.Utf8);
return(decrypted);
}
```
After adding the .js file, add the [Rhino library](https://github.com/mozilla/rhino) to your project for interpreting the javascript code in android. Once, you have added rhino, add the following code in a util class for all encryption and decryption. Call the encryption() and decryption() methods for your purpose.
AesUtil:
```
public class AESUtil{
Context context;
InputStream inputStream;
org.mozilla.javascript.Context rhino;
Scriptable scope;
public AESUtil(Context context)
{
this.context = context;
}
public void set_values()
{
inputStream = context.getResources().openRawResource(
context.getResources().getIdentifier("aes",
"raw", context.getPackageName()));
String data = convertStreamToString(inputStream);
Log.d("animesh_data", data);
rhino = org.mozilla.javascript.Context.enter();
// Turn off optimization to make Rhino Android compatible
rhino.setOptimizationLevel(-1);
scope = rhino.initStandardObjects();
rhino.evaluateString(scope, data, "JavaScript", 0, null);
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public String encrypt( String data, String key)
{
set_values();
Object obj = scope.get("encryption", scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
Object[] params = new Object[]{data, key};
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = org.mozilla.javascript.Context.toString(jsResult);
return result;
}
return null;
}
public String decrypt( String data, String key)
{
set_values();
Object obj = scope.get("decryption", scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
Object[] params = new Object[]{data, key};
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = org.mozilla.javascript.Context.toString(jsResult);
return result;
}
return null;
}
```
}
Upvotes: 2 <issue_comment>username_2: This library working fine for all platforms.
<https://github.com/skavinvarnan/Cross-Platform-AES>
***For android encryption***
**Step 1 : Use this util class ->** [link](https://github.com/skavinvarnan/Cross-Platform-AES/blob/master/Android/CryptLib.java)
**Step 2: Encrypt & decrypt using this code**
```
try {
String plainText = "this is my plain text";
String key = "simplekey";
String iv = "1234123412341234";
CryptLib cryptLib = new CryptLib();
String encryptedString = cryptLib.encryptSimple(plainText, key, iv);
System.out.println("encryptedString " + encryptedString);
String decryptedString = cryptLib.decryptSimple(encryptedString, key, iv);
System.out.println("decryptedString " + decryptedString);
} catch (Exception e) {
e.printStackTrace();
}
```
***Java Script code***
```
var plainText = "this is my plain text";
var key = "simplekey";
var iv = "1234123412341234";
var cryptoLib = require('cryptlib');
shaKey = cryptoLib.getHashSha256(key, 32); // This line is not needed on Android or iOS. Its already built into CryptLib.m and CryptLib.java
var encryptedString = cryptoLib.encrypt(plainText, shaKey, iv);
console.log('encryptedString %s', encryptedString);
var decryptedString = cryptoLib.decrypt(encryptedString, shaKey, iv);
console.log('decryptedString %s', decryptedString);
```
***For iOS users use this sample***
<https://github.com/skavinvarnan/Cross-Platform-AES/tree/master/iOS>
All platforms produce same following output
>
> **encryptedString:** rKzNsa7Qzk9TExJ6aHg49tGDiritTUJ08RMPm48S0o4=
>
>
> **decryptedString:** this is my plain text
>
>
>
Upvotes: 2 <issue_comment>username_3: Finally i have found a solution from [this gist](https://gist.github.com/thackerronak/554c985c3001b16810af5fc0eb5c358f)
This is the case when **the default config is used**
I have ported the code to Kotlin for android
```kotlin
import android.util.Base64
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.math.min
/**
* Conforming with CryptoJS AES method
*/
// see https://gist.github.com/thackerronak/554c985c3001b16810af5fc0eb5c358f
@Suppress("unused", "FunctionName")
object CryptoAES {
private const val KEY_SIZE = 256
private const val IV_SIZE = 128
private const val HASH_CIPHER = "AES/CBC/PKCS7Padding"
private const val AES = "AES"
private const val KDF_DIGEST = "MD5"
// Seriously crypto-js, what's wrong with you?
private const val APPEND = "Salted__"
/**
* Encrypt
* @param password <PASSWORD>
* @param plainText plain string
*/
fun encrypt(password: String, plainText: String): String {
val saltBytes = generateSalt(8)
val key = ByteArray(KEY_SIZE / 8)
val iv = ByteArray(IV_SIZE / 8)
EvpKDF(password.toByteArray(), KEY_SIZE, IV_SIZE, saltBytes, key, iv)
val keyS = SecretKeySpec(key, AES)
val cipher = Cipher.getInstance(HASH_CIPHER)
val ivSpec = IvParameterSpec(iv)
cipher.init(Cipher.ENCRYPT_MODE, keyS, ivSpec)
val cipherText = cipher.doFinal(plainText.toByteArray())
// Thanks kientux for this: https://gist.github.com/kientux/bb48259c6f2133e628ad
// Create CryptoJS-like encrypted!
val sBytes = APPEND.toByteArray()
val b = ByteArray(sBytes.size + saltBytes.size + cipherText.size)
System.arraycopy(sBytes, 0, b, 0, sBytes.size)
System.arraycopy(saltBytes, 0, b, sBytes.size, saltBytes.size)
System.arraycopy(cipherText, 0, b, sBytes.size + saltBytes.size, cipherText.size)
val bEncode = Base64.encode(b, Base64.NO_WRAP)
return String(bEncode)
}
/**
* Decrypt
* Thanks <NAME>. for this: http://stackoverflow.com/a/29152379/4405051
* @param password <PASSWORD>
* @param cipherText encrypted string
*/
fun decrypt(password: String, cipherText: String): String {
val ctBytes = Base64.decode(cipherText.toByteArray(), Base64.NO_WRAP)
val saltBytes = Arrays.copyOfRange(ctBytes, 8, 16)
val cipherTextBytes = Arrays.copyOfRange(ctBytes, 16, ctBytes.size)
val key = ByteArray(KEY_SIZE / 8)
val iv = ByteArray(IV_SIZE / 8)
EvpKDF(password.toByteArray(), KEY_SIZE, IV_SIZE, saltBytes, key, iv)
val cipher = Cipher.getInstance(HASH_CIPHER)
val keyS = SecretKeySpec(key, AES)
cipher.init(Cipher.DECRYPT_MODE, keyS, IvParameterSpec(iv))
val plainText = cipher.doFinal(cipherTextBytes)
return String(plainText)
}
private fun EvpKDF(
password: ByteArray,
keySize: Int,
ivSize: Int,
salt: ByteArray,
resultKey: ByteArray,
resultIv: ByteArray
): ByteArray {
return EvpKDF(password, keySize, ivSize, salt, 1, KDF_DIGEST, resultKey, resultIv)
}
private fun EvpKDF(
password: ByteArray,
keySize: Int,
ivSize: Int,
salt: ByteArray,
iterations: Int,
hashAlgorithm: String,
resultKey: ByteArray,
resultIv: ByteArray
): ByteArray {
val keySize = keySize / 32
val ivSize = ivSize / 32
val targetKeySize = keySize + ivSize
val derivedBytes = ByteArray(targetKeySize * 4)
var numberOfDerivedWords = 0
var block: ByteArray? = null
val hash = MessageDigest.getInstance(hashAlgorithm)
while (numberOfDerivedWords < targetKeySize) {
if (block != null) {
hash.update(block)
}
hash.update(password)
block = hash.digest(salt)
hash.reset()
// Iterations
for (i in 1 until iterations) {
block = hash.digest(block!!)
hash.reset()
}
System.arraycopy(
block!!, 0, derivedBytes, numberOfDerivedWords * 4,
min(block.size, (targetKeySize - numberOfDerivedWords) * 4)
)
numberOfDerivedWords += block.size / 4
}
System.arraycopy(derivedBytes, 0, resultKey, 0, keySize * 4)
System.arraycopy(derivedBytes, keySize * 4, resultIv, 0, ivSize * 4)
return derivedBytes // key + iv
}
private fun generateSalt(length: Int): ByteArray {
return ByteArray(length).apply {
SecureRandom().nextBytes(this)
}
}
}
```
Upvotes: 2 |
2018/03/20 | 1,064 | 3,767 | <issue_start>username_0: I am unable to convert an rdd with `zipWithIndex` to a dataframe.
I have read from a file and I need to skip the first 3 records and then limit the records to row number 10. For this, I used `rdd.zipwithindex`.
But afterwards, when I try to save the 7 records , I am not able to do so.
```
val df = spark.read.format("com.databricks.spark.csv")
.option("delimiter", delimValue)
.option("header", "false")
.load("/user/ashwin/data1/datafile.txt")
val df1 = df.rdd.zipWithIndex()
.filter(x => { x._2 > 3&& x._2 <= 10;})
.map(f => Row(f._1))
val skipValue = 3
val limitValue = 10
val delimValue = ","
df1.foreach(f2=> print(f2.toString))
[[113,3Bapi,Ghosh,86589579]][[114,4Bapi,Ghosh,86589579]]
[[115,5Bapi,Ghosh,86589579]][[116,6Bapi,Ghosh,86589579]]
[[117,7Bapi,Ghosh,86589579]][[118,8Bapi,Ghosh,86589579]]
[[119,9Bapi,Ghosh,86589579]]
scala> val df = spark.read.format("com.databricks.spark.csv").option("delimiter", delimValue).option("header", "true").load("/user/bigframe/ashwin/data1/datafile.txt")
df: org.apache.spark.sql.DataFrame = [empid: string, fname: string ... 2 more fields]
scala> val df1 = df.rdd.zipWithIndex().filter(x => { x._2 > skipValue && x._2 <= limitValue;}).map(f => Row(f._1))
df1: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[885] at map at :38
scala> import spark.implicits.\_
import spark.implicits.\_
```
scala> df1.
```
++ count flatMap groupBy mapPartitionsWithIndex reduce takeAsync union
aggregate countApprox fold id max repartition takeOrdered unpersist
cache countApproxDistinct foreach intersection min sample takeSample zip
cartesian countAsync foreachAsync isCheckpointed name saveAsObjectFile toDebugString zipPartitions
checkpoint countByValue foreachPartition isEmpty partitioner saveAsTextFile toJavaRDD zipWithIndex
coalesce countByValueApprox foreachPartitionAsync iterator partitions setName toLocalIterator zipWithUniqueId
collect dependencies getCheckpointFile keyBy persist sortBy toString
collectAsync distinct getNumPartitions localCheckpoint pipe sparkContext top
compute filter getStorageLevel map preferredLocations subtract treeAggregate
context first glom mapPartitions randomSplit take treeReduce
scala> df1.toDF
:44: error: value toDF is not a member of org.apache.spark.rdd.RDD[org.apache.spark.sql.Row]
df1.toDF
^
```<issue_comment>username_1: This is probably of type `RDD[Row]` right now. have you tried using the `toDF` function? You'll have to `import spark.implicits._` as well.
Upvotes: 0 <issue_comment>username_2: You get `RDD[ROW]` once you change `dataframe` to `rdd`, So to convert back to the `dataframe` you need to create dataframe by `sqlContext.createDataframe()`
Schema is also required to create the `dataframe`, In this case you can use the schema that was generated before in `df`
```
val df1 = df.rdd.zipWithIndex()
.filter(x => { x._2 > 3&& x._2 <= 10})
.map(_._1)
val result = spark.sqlContext.createDataFrame(df1, df.schema)
```
Hope this helps!
Upvotes: 3 [selected_answer] |
2018/03/20 | 460 | 1,483 | <issue_start>username_0: I'm using DOSBox MASM to learn Assembly Language. However, I want to give input along with debug. That is, I want to execute my program line by line and also give input as soon as
```
INT 21H
```
comes. I'm debugging in
```
afdebug test.exe
```
But as soon as it sees
```
MOV AH,01H
INT 21H
```
The debug just skips after INT 21H and doesn't prompt any screen to take input.
Here is the program in case:
```
.MODEL SMALL
.STACK 64
.DATA
MSG DB "ENTER A CHARACTER:$"
ORG 0030H
LOL DB ?
.CODE
MOV AX,@DATA
MOV DS,AX
LEA DX,MSG
MOV AH,09H
INT 21H
MOV AH,01H
INT 21H
MOV LOL,AL
MOV AH,4CH
INT 21H
END
```<issue_comment>username_1: This is probably of type `RDD[Row]` right now. have you tried using the `toDF` function? You'll have to `import spark.implicits._` as well.
Upvotes: 0 <issue_comment>username_2: You get `RDD[ROW]` once you change `dataframe` to `rdd`, So to convert back to the `dataframe` you need to create dataframe by `sqlContext.createDataframe()`
Schema is also required to create the `dataframe`, In this case you can use the schema that was generated before in `df`
```
val df1 = df.rdd.zipWithIndex()
.filter(x => { x._2 > 3&& x._2 <= 10})
.map(_._1)
val result = spark.sqlContext.createDataFrame(df1, df.schema)
```
Hope this helps!
Upvotes: 3 [selected_answer] |
2018/03/20 | 965 | 3,628 | <issue_start>username_0: Using Go's [default HTTP client](https://golang.org/pkg/net/http/), I am unable to directly determine the IP address of the server that processed the request. For instance, when requesting `example.com`, what is the IP address that `example.com` resolved to at the time of the request?
```
import "net/http"
resp, err := http.Get("http://example.com/")
```
The `resp` object contains the `resp.RemoteAddr` property, but as detailed below it is not utilized during client operations.
```
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
```
Is there a straightforward way to accomplish this? My initial thought would be to:
1. Initiate a DNS lookup to remote domain
2. Create new `http` transport using returned A/AAAA records
3. Make the request
4. Set the `RemoteAddr` property on the response object
Is there a better way?
---
UPDATED - to use @flimzy's suggestion. This method stores the remote IP:PORT into the `request.RemoteAddr` property. I've also added support for multiple redirects so that each subsequent request has its `RemoteAddr` populated.
```
request, _ := http.NewRequest("GET", "http://www.google.com", nil)
client := &http.Client{
Transport:&http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := net.Dial(network, addr)
request.RemoteAddr = conn.RemoteAddr().String()
return conn, err
},
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
request = req
return nil
},
}
resp, _ := client.Do(request)
```<issue_comment>username_1: As far as I can tell, the only way to accomplish this with the standard library is with a custom [http.Transport](https://golang.org/pkg/net/http/#Transport) that records the remote IP address, for example in the `DialContext` function.
```
client := &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
conn, err := d.DialContext(ctx, network, addr)
fmt.Printf("Remote IP: %s\n", conn.RemoteAddr())
return conn, err
},
},
}
resp, _ := client.Get("http://www.google.com")
```
Tying the connection IP to the response is left as an exercise for the reader.
Upvotes: 4 [selected_answer]<issue_comment>username_2: you also can build a request with trace:
```
request = request.WithContext(httptrace.WithClientTrace(request.Context(), &httptrace.ClientTrace{
GotConn: func(connInfo httptrace.GotConnInfo) {
fmt.Printf("target ip:%+v\n", connInfo.Conn.RemoteAddr().String())
},
}))
response, _:= client.Do(request)
```
Upvotes: 2 <issue_comment>username_3: httptrace form <https://golang.org/pkg/net/http/httptrace/>
```
req, err := http.NewRequest(method, url, strings.NewReader(body))
trace := &httptrace.ClientTrace{
GotConn: func(connInfo httptrace.GotConnInfo) {
fmt.Printf("Got Conn: %+v\n", connInfo)
},
DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
fmt.Printf("DNS Info: %+v\n", dnsInfo)
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
```
Upvotes: 0 |
2018/03/20 | 461 | 1,605 | <issue_start>username_0: I have a SpringBoot app and an interface that extends from `CrudRepository`
```
@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
List findMine(Pageable pageable);
```
I would like to know if it is possible to get the total number of pages from the object `Pageable`<issue_comment>username_1: You can use the `Page` Interface which returns the total elements.
>
> long - `getTotalElements()`
>
>
> Returns the total amount of elements.
>
>
>
You can find more in the docs:
[Page](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Page.html) and
[PageImpl](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageImpl.html).
In your example it should work like that:
```
@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
Page findMine(Pageable pageable);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You should extend your repository from `PagingAndSortingRepository` instead of `CrudRepository`. Then the method query should be:
```
@Query("select cps from HotelPriceSummary cps where cps.price > 5 and cps.profilePercentage >= 70 ")
Page findMine(Pageable pageable);
```
After that, you can use the query from a service (or whatever you want) and then `getTotalPages()` in the response. Example:
```
int page = 0, pageSize = 10;
Page response = myRepo.findMine(PageRequest.of(page, pageSize));
int numberOfPages = response.getTotalPages();
```
Upvotes: 2 |
2018/03/20 | 393 | 1,564 | <issue_start>username_0: What is the most appropriate way to test if a variable is undefined in JavaScript?
```
$.ajax({
type: method,
url: url,
success: function (data) {
if (form != null || form != undefined){
data = $(form).serialize();
}
var json = JSON.parse(data),
list = $(table).html(),
compileTemplate = Handlebars.compile(list),
result = compileTemplate(json),
content = doc.getElementById(element);
content.innerHTML = result;
},
dataType: "text"
});
```
I'm looking for a more beautiful way for this check.<issue_comment>username_1: First check if it is undefined before checking the value so it does not throw an error. Also it needs an AND (&&) not an OR (||).
The official way to do that is to check type.
Change the 'if' statement to say this:
```
if (typeof(form) !== "undefined" && form != null) {
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could simply test `form != null` which will be true if `form` is neither `null` ***or*** `undefined`.
```
$.ajax({
type: method,
url: url,
success: function (data) {
if (form != null){
data = $(form).serialize();
}
var json = JSON.parse(data),
list = $(table).html(),
compileTemplate = Handlebars.compile(list),
result = compileTemplate(json),
content = doc.getElementById(element);
content.innerHTML = result;
},
dataType: "text"
});
```
Upvotes: 0 |
2018/03/20 | 548 | 2,091 | <issue_start>username_0: I have main method:
```
Future main() async {
final securityService = new SecurityService(new BrowserClient());
await securityService.getObject();
bootstrapStatic(
AppComponent,
[
provide(SecurityService,
useFactory: () => securityService, deps: []),
provide(BrowserClient,
useFactory: () => new BrowserClient(), deps: []),
routerProvidersHash
],
ng.initReflector as Function);
}
```
I want to rewrite it to use `bootstrapFactory`. How to do that? What should I rewrite in components with `providers: const [MyService]`?<issue_comment>username_1: So, I wrote this:
```
// ignore: uri_has_not_been_generated
import 'package:budget/app_component.template.dart' as ng_app;
...
// ignore: uri_has_not_been_generated
import 'main.template.dart' as ng;
@GenerateInjector(const [
const ClassProvider(BrowserClient),
const FactoryProvider(SecurityService, getSecurityService),
routerProvidersHash
])
final InjectorFactory appInjector = ng.appInjector$Injector;
SecurityService \_securityService;
SecurityService getSecurityService() => \_securityService;
Future main() async {
\_securityService = new SecurityService(new BrowserClient());
await \_securityService.getObject();
runApp(
ng\_app.AppComponentNgFactory as ComponentFactory,
createInjector: appInjector);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: It can also be done like this:
```
Client _browserClient;
Client getBrowserClient() => _browserClient;
SecurityService _securityService;
SecurityService getSecurityService() => _securityService;
Future main() async {
\_browserClient = new BrowserClient();
\_securityService = new SecurityService(\_browserClient);
await \_securityService.getObject();
bootstrapStatic(
AppComponent,
[
const FactoryProvider(Client, getBrowserClient),
const FactoryProvider(SecurityService, getSecurityService),
],
ng.initReflector);
}
```
**Edit:** The above method applies till AngularDart 5.0.0-alpha+9. From 5.0.0-alpha+10 version, `runApp` function is strongly recommended instead of `bootstrapStatic`
Upvotes: 0 |
2018/03/20 | 2,173 | 6,830 | <issue_start>username_0: I currently have a project going on and I was wondering how to make a counter that increases as clicked. All the buttons would have different values (such as 2) and once clicked, the counter would increase. I currently have all the buttons set up but I'm not sure how to add value to them and have a counter increase according to the amount that button is worth. I also wanted to know how I could store that value on the web cache. If anyone could help, I'd be really thankful. Here is the current code I have.
```css
body{
background-color: #162428;
}
.button {
background-color: #4CAF50;
color: white;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 60px;
margin: 200px 100px;
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
cursor: pointer;
width: 250;
height: 200;
}
.click1 {border-radius: 8px}
.click1 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click1:hover {
background-color: #070d0f;
color: white;
}
.click2 {border-radius: 8px}
.click2 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click2:hover {
background-color: #070d0f;
color: white;
}
.click3 {border-radius: 8px}
.click3 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click3:hover {
background-color: #070d0f;
color: white;
}
.click5 {border-radius: 8px}
.click5 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click5:hover {
background-color: #070d0f;
color: white;
}
.click10 {border-radius: 8px}
.click10 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click10:hover {
background-color: #070d0f;
color: white;
}
footer {
color: grey;
font-size: 65px;
}
```
```html
Button of Magnificance
+1
+2
+3
+5
+10
```
Thank you for any help!<issue_comment>username_1: Here is a piece of code making what you want. I commented the JS part so that you can understand it but dont hesitate to ask if you still have questions.
```
Button of Magnificance
body{
background-color: #162428;
}
.button {
background-color: #4CAF50;
color: white;
padding: 32px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 60px;
margin: 100px 100px;
-webkit-transition-duration: 0.4s; /\* Safari \*/
transition-duration: 0.4s;
cursor: pointer;
width: 250;
height: 200;
}
.click1 {border-radius: 8px}
.click1 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click1:hover {
background-color: #070d0f;
color: white;
}
.click2 {border-radius: 8px}
.click2 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click2:hover {
background-color: #070d0f;
color: white;
}
.click3 {border-radius: 8px}
.click3 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click3:hover {
background-color: #070d0f;
color: white;
}
.click5 {border-radius: 8px}
.click5 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click5:hover {
background-color: #070d0f;
color: white;
}
.click10 {border-radius: 8px}
.click10 {
background-color: grey;
color: #070d0f;
border: 2px solid #070d0f;
}
.click10:hover {
background-color: #070d0f;
color: white;
}
+1
+2
+3
+5
+10
count : 0
===========
// start script when DOM is ready
$(document).ready(function(){
// initialize a counter to 0
var count = 0;
// do something when an element with "button" class is clicked
$('.button').on('click', function(){
// get the button value
var value = $(this).data('value');
// update the count with new value
count += value;
// print the new value count on the element with "count" class
$('.count').html(count);
});
});
footer {
color: grey;
font-size: 65px;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can write a JS like this
```
var count=0;
function updateValue(val){
count = count + val;
}
```
and in every button you have created, you may add an onclick to call this function, as follows:
```
+1
+2
```
**To store the value** in cache you may use **localStorage**.
You can read about them here:
<https://www.w3schools.com/html/html5_webstorage.asp>
Upvotes: 0 <issue_comment>username_3: Notes
-----
This answer is using the [ES6 syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla). Be sure to be confortable with this one before going any further.
Explainations
-------------
You can achieve what you want by using a class on your button to identify buttons that must be incremented buttons.
Using a `getElementsByClassName()` will help you retrieve only buttons that match the class you gave in your HTML.
Then, you need to iterate through your buttons. I use the newer spread operator to transform your `HTMLCollection` into an `Array`. You can then use the `forEach` method to operate a set of instructions (set the HTML content and add a listener) for each one of the buttons.
Using the [Web Storage API](https://developer.mozilla.org/fr/docs/Web/API/Web_Storage_API) and some application logic will ensure that data are kept from reloading the page.
Code
----
HTML:
```
```
Javascript:
```
'use strict';
// all the .button-counter from the DOM
const buttonsCounter = document.getElementsByClassName('button-counter');
// sets the content of the button to what value is currently set for data-counter
const buttonCounterSetText = button => button.innerHTML = `Click me (${button.dataset.count || 0})`;
// handles click event on the button
const buttonCounterClickHandler = ({currentTarget}) => {
// increases the current value for data-count, or sets it to 0
currentTarget.dataset.count = (parseInt(currentTarget.dataset.count) || 0) + 1;
// see above
buttonCounterSetText(event.currentTarget);
};
// initialize the buttons content and add listeners for click events
const buttonCounterInitialization = button => {
buttonCounterSetText(button);
button.addEventListener('click', buttonCounterClickHandler);
};
// initialize all buttons found with class .button-counter
[...buttonsCounter].forEach(buttonCounterInitialization);
```
Demo
----
[Codepen](https://codepen.io/anon/pen/BrpEEm?editors=0010).
Upvotes: 0 |
2018/03/20 | 254 | 910 | <issue_start>username_0: I'm using VSCode, and have TSLint plugin installed. Apart from this I also have `eslint` configured for my app. However, for one line, I'm trying to disable `eslint` with the below code.
```
if (!Intl) {
// eslint-disable-next-line global-require no-global-assign
Intl = require('intl')
}
```
However, when I run my linter it still shows an error. What am I doing wrong?<issue_comment>username_1: Usually with vs code, you can just put your cursor on the offending line and type `Ctrl + .` and the ide will add the appropriate rule.
the syntax you are looking for is `// tslint:disable-next-line:max-line-length`
Upvotes: 2 <issue_comment>username_2: Turn out that when specifying multiple rules a `,` is required in between the rules.
```
if (!Intl) {
// eslint-disable-next-line global-require, no-global-assign
Intl = require('intl')
}
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,138 | 4,059 | <issue_start>username_0: I have added a share functionality in my app to share data like name, price,quantity and description. This is how I have achieved it...
```
let prodObj = newProdDetails[indexPath.row]
let name = prodObj.name
let price = prodObj.mrp
let qty = prodObj.quantity
let description = prodObj.descriptions
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [name, price, qty, description], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
```
when I have shared like this in whatsapp, what the receiver gets is just something like Box,6,500 (if the name is box, quantity is 6 & price 500).
But when I am sending, I want the receiving party to get something like
```
Name: Box
Quantity: 6
Price: 500
```
instead of mere Box,6,500
How can I achieve this...?<issue_comment>username_1: Send string for activity item like this `"Name: \(name)"`
```
let prodObj = newProdDetails[indexPath.row]
if let name = prodObj.name,
let price = prodObj.mrp,
let qty = prodObj.quantity,
let description = prodObj.descriptions {
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: ["Name: \(name)", "Price: \(price)", "Quantity: \(qty)", "Description: \(description)"], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
```
Upvotes: 2 <issue_comment>username_2: **You can try like this**:
```
let prodObj = newProdDetails[indexPath.row]
let name = prodObj.name
let price = prodObj.mrp
let qty = prodObj.quantity
let description = prodObj.descriptions
let finalString:String = "Name:" + name + "\n" + "Quantity:" + qty + "\n" + "Price:" + price
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [finalString], applicationActivities: nil)
```
**Result:**
```
Name: Box
Quantity: 6
Price: 500
```
**TESTED 100 % working**
Upvotes: 0 <issue_comment>username_3: you can do like this.
```
let share : String = "Name: \(name) \nQuantity: \(qty) \nPrice: \(price)"
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: [share], applicationActivities: nil)
```
Upvotes: 0 <issue_comment>username_2: just run the code:
```
let name = "javed"
let price = 700
let qty = 77
let finalString:String = "Name:" + name + "\n" + "Quantity:" + String(qty) + "\n" + "Price:" + String(price)
print(finalString)
```
**Result:**
[](https://i.stack.imgur.com/8B3fm.png)
**or you have already string value then:**
[](https://i.stack.imgur.com/cEh7X.png)
Upvotes: 1 <issue_comment>username_4: Whats happening is instead of passing individual attributes like name price qty you create an array of string or dictionary using (key-value pair so you know which value is associate for which key) out of it and then pass the whole array, you can also check if a value exists, then only add it to the final array (based on your requirement)
```
let prodObj = newProdDetails[indexPath.row]
let name = prodObj.name ?? "" //this means if name is nil it will set empty string
let price = prodObj.mrp ?? 0
let qty = prodObj.quantity ?? 0
let description = prodObj.descriptions ?? ""
//create array from the data you get you can create a string like below
let finalArrayString = ["Name: \(name)", "Price: \(price)", "Quantity: \(qty)", "Description: \(description)"]
//or create an array of the dictionary for using it late
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: finalArrayString , applicationActivities: nil)
```
Also, check if your prodObj is nil or not before using it, You can either return if its nill (base on your requirement)
Also understand why before just copy-pasting code from StackOverflow, as it will save your time later,
Upvotes: 0 |
2018/03/20 | 206 | 750 | <issue_start>username_0: Using pip in a console window under windows 7 I can barely see the text of the errormessages.
[](https://i.stack.imgur.com/l5QYr.jpg)
Is there any chance to tell pip to use another color? This dark red on top of black is a bad choice.
My workaround currently is to copy the text into an editor and read it there but this is not a nice solution.<issue_comment>username_1: Just to turn the background color intor white with an easy right click solves this problem for me. Thanks, that was quick.
Upvotes: -1 <issue_comment>username_2: There is a "--no-color" command line option:
<https://pip.pypa.io/en/stable/reference/pip/#general-options>
Upvotes: 3 |
2018/03/20 | 389 | 1,206 | <issue_start>username_0: I have a problem to generate the token, use the command you passed in tutorial
```
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer access-token" \
-d '{"foo": "bar"}' \
"https://.cloudfunctions.net/get"
```
When enter in my link /get return " No authorization token found." IT necessary i inform token?
<https://github.com/tnguyen14/functions-datastore/><issue_comment>username_1: Is your access token, access-token?
A proper jwt format is something like this.
<KEY>
Upvotes: 1 <issue_comment>username_2: Your http request using `curl` looks ok. But I doubt that `access-token` is a valid token. Normally there's some form of `/login` route you need to *obtain* the token, which later on should be provided using the `Authorization: Bearer $TOKEN`.
Upvotes: 0 <issue_comment>username_3: You can get help from <https://jwt.io/> where you can specify your `payload` and pass the secret under `VERIFY SIGNATURE` to get a valid `jwt` token. Then you can use this in your `curl` requests.
Upvotes: 0 |
2018/03/20 | 622 | 2,133 | <issue_start>username_0: I need to create a statement that can be run to rename a partition only if specific partition name exists and if not then continue on to execute other code.
```
basic command = ALTER TABLE TEST RENAME PARTITION P1 TO P2:
```
I have looked at the following but have not come up with a solution
* [Using IF ELSE in Oracle](https://stackoverflow.com/questions/14386881/using-if-else-in-oracle)
* <https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/controlstructures.htm><issue_comment>username_1: One option is to enclose ALTER TABLE into its own BEGIN-END block, with appropriate exception handling section. Mine is kind of *stupid* (WHEN OTHERS, eh?); feel free to rewrite it to be meaningful - it is just to show *how* to do it.
So: if ALTER TABLE fails, it'll raise some error; it'll be captured, handled, and code will continue its execution.
```
begin
begin
execute immediate 'alter table test rename partition p1 to p2';
exception
when others then
-- ignore errors
null;
end;
-- continue to execute other code
...
end;
```
Upvotes: 0 <issue_comment>username_2: I depends on your requirements but a basic procedure would be this one:
```
DECLARE
PARTITION_DOES_NOT_EXIST EXCEPTION;
PRAGMA EXCEPTION_INIT(PARTITION_DOES_NOT_EXIST, -2149);
BEGIN
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE TEST RENAME PARTITION P1 TO P2';
EXCEPTION
WHEN PARTITION_DOES_NOT_EXIST THEN NULL;
END;
... ohter commands
END;
```
Upvotes: 2 <issue_comment>username_3: You could check whether the partition exists within the table USER\_TAB\_PARTITIONS:
```
DECLARE
v_p1_exists AS NUMBER;
v_p2_exists AS NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_p1_exists
FROM user_tab_partitions
WHERE table_name = 'TEST'
AND partition_name = 'P1';
SELECT COUNT(*)
INTO v_p2_exists
FROM user_tab_partitions
WHERE table_name = 'TEST'
AND partition_name = 'P2';
IF (v_p1_exists <> 0) AND (v_p2_exists = 0) THEN
EXECUTE IMMEDIATE 'ALTER TABLE TEST RENAME PARTITION P1 TO P2';
END;
END;
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 442 | 1,857 | <issue_start>username_0: As my browser was crashing I was not able to create a pull request from GitHub UI, I was trying to create a pull request from git console but didn't found any way to create a pull request.
I have also searched for the same over the net but most of the tutorials suggested to create a pull request from UIs only. I just want to be able to handle the pull request like creation, rejection, approved and merging without the browser. Please suggest.<issue_comment>username_1: git add -p
then
git commit -m "message"
then
git push origin "your\_branch"
the pull request will be created in github
Upvotes: -1 <issue_comment>username_2: `git` and `github` are separate products. `github` is a service that happens to use `git`, but it is not part of git, its UI is not a git interface, and git does not have any special support for github functionality.
There is a little potential confusion here, because there are "pull requests" - an integrated feature of github having to do with branch workflow - and there is `git request-pull`, a seemingly lesser-known feature of git which creates a text message you could send to another repository maintainer to request that they pull changes from your repository.
Naming confusion aside, the "pull request" you want is a feature of github, not git; and so git itself (including git console and any git UI tool) have no command for this. You have to use a github-supplied interface, and AFAIK that means the web UI.
Upvotes: 2 <issue_comment>username_3: To open a pull request from the command line, you can install the `hub` set of command-line tools that [GitHub supports](https://github.com/github/hub). This will allow you to create a pull request from a repository with:
```
hub pull-request
```
I'm not aware of any similar tools for managing pull requests, though.
Upvotes: 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.