text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Broken/missing handler after reinstall my site recently got deleted by a possible hack. I uploaded backed up folders and the db but now my views are not showing. everything else works. i can't think of anything that changed, just uploaded a backup from a few days ago.
the fields are showing this in admin/build/views/edit/nameofview
Broken/missing handler: node_data_field_guru_photo > field_guru_photo_fid
Broken/missing handler: node > title
Broken/missing handler: views > nothing
Broken/missing handler: node_revisions > body
Broken/missing handler: node_data_field_guru_link > field_guru_link_url
I tried clearing cache
I rearanged the fields in views and updated them and got this error
Display "Defaults" uses fields but there are none defined for it or all are excluded.
A: Normally just clearing Drupal's cache would fix this but if not go into the 'Manage Fields' screen for the content type to which node_data_field_guru_photo, node_data_field_guru_link etc. are attached, make a temporary change (e.g. to the order of the fields) and save. That should force a refresh of the field cache and you should be on your way.
A: Just rearrange the order of you content type fields and then save it. In my case broken or missing handler was showing for Class content type. rearranging the content type fields solved my problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7812706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there any way to add markers above overlay in google maps react? I am trying to add overlay above the map and place the marker above the overlay. but I am not able to do so. how I can do it? and I am using the google-maps-react library as a dependency.
<div>
<Map
key={active}
google={google}
containerStyle={containerStyle}
zoom={5}
disableDefaultUI
initialCenter={{
lat: markers[0].position.lat,
lng: markers[0].position.lng,
}}
>
<div className="absolute top-0 bottom-0 right-0 left-0 bg-gray-400 pointer-events-none" />
<Marker
title="The marker`s title will appear as a tooltip."
name="SOMA"
position={{ lat: 37.778519, lng: -122.40564 }}
/>
</Map>
</div>
the view right now
A: You can do this by using the GroundOverlay object of Google Maps JavaScript API. But you need to get the current map object used in your google-maps-react code and you will use this to setMap the overlay into this map ref.
See the sample code and code snippet below:
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
const mapStyles = {
width: '100%',
height: '100%',
};
const imageBounds = {
north: 40.773941,
south: 40.712216,
east: -74.12544,
west: -74.22655,
};
class MapWithOverlay extends Component {
mapRef = (ref) => {
let historicalOverlay = new google.maps.GroundOverlay(
'https://storage.googleapis.com/geo-devrel-public-buckets/newark_nj_1922-661x516.jpeg',
imageBounds
);
historicalOverlay.setMap(ref.map);
};
render() {
return (
<>
<div>
<Map
ref={(ref) => {
this.mapRef(ref);
}}
google={this.props.google}
zoom={12}
style={mapStyles}
initialCenter={{ lat: 40.74, lng: -74.18 }}
>
<Marker position={{ lat: 40.74, lng: -74.18 }} />
</Map>
</div>
</>
);
}
}
export default GoogleApiWrapper({
apiKey: 'YOUR_KEY',
})(MapWithOverlay);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70182745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed I am getting below error while creating a spring maven rest webservice project. I am new with springboot, could someone help me with this. The error is:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.example.spring.backend.model.Employee.firstName; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : com.example.spring.backend.model.Employee.firstName] with root cause
I created a database using MySQL Workbench and defined a table in it to store employee details. Here is my code:
EmployeeController.java
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
super();
this.employeeService = employeeService;
}
// build create employee REST API
@PostMapping()
public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee){
return new ResponseEntity<Employee>(employeeService.saveEmployee(employee), HttpStatus.CREATED);
}
}
Employee.java
@Data
@Entity
@Table(name="employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
}
EmployeeRepository.java
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
EmployeeService.java
public interface EmployeeService {
Employee saveEmployee(Employee employee);
}
EmployeeServiceImpl.java
@Service
public class EmployeeServiceImpl implements EmployeeService{
private EmployeeRepository employeeRepository;
public EmployeeServiceImpl(EmployeeRepository employeeRepository) {
super();
this.employeeRepository = employeeRepository;
}
@Override
public Employee saveEmployee(Employee employee) {
return employeeRepository.save(employee);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/employee_management_system?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hibernate properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# create, create-drop
spring.jpa.hibernate.ddl-auto=update
While sending a post request using postman, I am getting Internal Server Error 500.
**Input**
{
"firstName": "abc",
"lastName": "abc",
"email": "abc@gmail.com"
}
**Result:**
{
"timestamp": "2022-10-26T09:48:51.322+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/employees"
}
I am taking reference from a youtube video but in the video, the code works but not in my case.
Please advise what is wrong in my code. Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74206520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why python doesn't read the environment variable and can't run a windows command line? I am trying to run the appium server from my python 3.7 code.
So I use this simple line of code:
os.system("start /B start cmd.exe @cmd /k appium")
I see the command windows pop up and give the error "appium' is not recognized as an internal or external command, operable program or batch file".
But I checked my environment variable and they are fine. I can even run appium from command by hand from same folder. Please check the screenshot as a prove:
So what I am doing wrong? Doesn't anyone can help me please?
A: After some investigation, this is the command which fix my issue:
proc = subprocess.Popen('npm install -g appium',shell=True,stdin=None, stdout=True, stderr=None, close_fds=True)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61132372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not able to save data to aws dynamodb in batchSave I am not able to save list of objects in dynamodb by using mapper.batchSave() but I am able to save it single object at a time. I am not seeing any exception also in the logs, an idea why this is happening? Please help me to resolve this issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65650213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Expandable ListView with custom adapter I am trying to implement a ExpandableListView in Android by implementing a custom adapter but I am not getting any output on the screen.
The main xml layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is an expandable listview"
/>
<ExpandableListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
The group layout file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/tvPlayerName"
android:textSize="14px"
android:textStyle="normal"
android:layout_width="150px"
android:layout_height="wrap_content"
/>
The child layout file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/tvPlayerName"
android:textSize="14px"
android:textStyle="normal"
android:layout_width="150px"
android:layout_height="wrap_content"
/>
</LinearLayout>
AND lastly, the activity class file is:
public class ExpandableListViewTest extends ExpandableListActivity {
String groupElements[] = {"India","Austrailia","England","South Africa"};
String childElements[][] = {
{"Sachin Tendulkar","Raina","Dhoni","Yuvraj"},
{"Ponting","Adam Gilchrist","Michael Clarke"},
{"Andrew Strauss","Kevin Peterson","Nasir Hussain"},
{"Grame Smith","AB de Villiers","Jacques Kallis"}
};
int width;
ExpandableListView expList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Setup our adapter
MyExpandableAdapter mAdapter = new MyExpandableAdapter(this);
setListAdapter(mAdapter);
}
public class MyExpandableAdapter extends BaseExpandableListAdapter
{
private Context myContext;
public MyExpandableAdapter(Context context)
{
this.myContext= context;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childElements[groupPosition][childPosition];
}
@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.child, parent,false);
}
TextView tvPlayerName =
(TextView)convertView.findViewById(R.id.tvPlayerName);
tvPlayerName.setText(childElements[groupPosition][childPosition]);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childElements[groupPosition].length;
}
@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.group,parent,false);
}
TextView tvGroupName = (TextView)convertView.findViewById(R.id.groupName);
//tvGroupName.setText(groupElements[groupPosition]);
tvGroupName.setText("Group Row");
return convertView;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
}
}
All seems straighhtforward enough but after running the app, the screen stays blank.Any help/ideal is appreciated.
A: Your code looks incomplete. You've just got placeholders in the methods getGroup, getGroupId and getGroupCount. They should reference your groupElements array.
The fact that getGroupCount currently returns zero would be enough for the ExpandableListView to not display anything.
A: You probably should set the return value of getGroupCount() to groupElements.length.
The 0 currently returned indicates that you don't have any groups, so there is nothing to show.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10584915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting out of memory error while using threads for Image loading in Android. This is my code to take a photo from gallery or camera. I've implemented a background thread to get the task done and then using SmartImageView to set the image using the url. My error is Out of Memory Allocation.:
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity.this);
builder.setMessage("Select") .setCancelable(false).setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
startActivityForResult(gallIntent, 10);
}
})
.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
}
});
AlertDialog alert = builder.create();
alert.show();
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(activity.this, "Uploading",
"Please wait...", true);
//new ImageUploadTask().execute();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, final Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == Activity.RESULT_OK) {
Thread t = new Thread()
{
public void run(){
Uri imageUri = data.getData();
Bitmap b;
try {
b = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
String timestamp = Long.toString(System.currentTimeMillis());
MediaStore.Images.Media.insertImage(getContentResolver(), b, timestamp, timestamp);
HttpResponse httpResponse;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
int f = 0;
String ba1=Base64.encodeToString(ba, f);
try {
OAuth oAuth = new OAuth(activity.this);
HttpPost httpPost = new HttpPost("url");
httpPost.setEntity(new ByteArrayEntity(ba));
HttpClient httpClient= new DefaultHttpClient();
httpResponse = httpClient.execute(httpPost);
int responseCode = httpResponse.getStatusLine().getStatusCode();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}};
t.start();
imgView.setImageUrl(obj.ImageUrl);
}
A: this
String ba1=Base64.encodeToString(ba, f);
is very heavy. I recommend using a http://developer.android.com/reference/android/util/Base64OutputStream.html instead, write to a file, then use an InputStream in the HttpEntity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9767794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to send number of images to server using JSON Array in objective c I'm facing a problem in sending Images to the server . I'm trying to save the list of Images in the base64 encryption format string into each object of array and I have to send the array to the server , but when I try to send multiple images , this thing does not work and only one or no image are uploaded to the server and sometimes all image are uploaded . Can anyone tell me how can I achieve this using AFNetworking or any any other approach?
A: Try this:
-(void)uploadPhoto{
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://server.url"]];
NSData *imgData = UIImageJPEGRepresentation(self.avatarView.image, 0.5);
NSDictionary *params = @{@"username": self.username, @"password" : self.password};
AFHTTPRequestOperation *operation = [manager POST:@"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imgData name:paramNameForImage fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[operation start];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37700036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write a python list to a specific row in a csv file? I have a csv file which has 2 rows of data. I have a python list to be written to the next immediate row in the csv file ie row number 3 without altering the contents of the first two rows.
I wrote a code but it is always writing to the first row. Below is my code. Kindly suggest where to specify the row number in the code.
import sys,csv
with open("C:\pavan\pav.csv",'w',newline='') as wr:
lst=[9,10,11,12]
writer = csv.writer(wr, delimiter = ',')
writer.writerows([lst])
A: Just open the csv file in append mode. This will solve your problem.
Use:
with open("pav.csv",'a',newline='') as wr:
A: You need to open the file in append mode so that it will write to the end of the file:
with open("C:\pavan\pav.csv",'a',newline='') as wr:
This will open the file in write mode, and append to the end of the file if it exists.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44164135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: sqlserver format date time I am not familar with sql server why i have the following error
Conversion failed when converting date and/or time from character string.
...
values (1, 'P' + char(10) + 'd' + char(10) + 'inst',
CONVERT(VARCHAR(24),'18-01-2016 11:29:27',113))
the code for 13 is = dd mon yyyy hh:mi:ss:mmm (24h) is it possible wrong code ?
I checked this answer also didnt work
values (1, 'P' + char(10) + 'd' + char(10) + 'inst',
format('18-01-2016 11:29:27','MM/dd/yyyy HH:mm:ss'))
A: First of all the target type of CONVERT should be DATETIME...
The format code you've tried expects the month as word (mon != mm)
SELECT CONVERT(DATETIME,'18 jan 2016 11:29:27',113);
You might use one of these:
SELECT CONVERT(DATETIME,'18-01-2016 11:29:27',103)
SELECT CONVERT(DATETIME,'18-01-2016 11:29:27',104)
A: I believe its inserting as varchar, u can use this script
SELECT CONVERT(varchar(24),'18-01-2016 11:29:27',120)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44650265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: FastLED library not working when iterating through the LEDS backwards Im having issues where my code running up the w2812b strip is working fine but when I run down the strip I get an error.
This is the error
/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c:1443 (xQueueGenericReceive)- assert failed! abort() was called at PC 0x40087f1d on core 1
I have tried looking it up and changing how I iterate through but nothing has worked so far. I have figured out that it breaks on the first run through in for loop within the ledDown function when I call the showStrip function.
The code is being uploaded to a esp32 but I'm pretty sure that doesn't have anything to do with it.
Any help would be amazing.
Here is my code. I currently just have the LedDown function commented out.
#include "FastLED.h"
#define NUM_LEDS 100
#define LEDPIN 26
CRGB leds[NUM_LEDS];
void setup()
{
// Debug console
Serial.begin(9600);
FastLED.addLeds<WS2812B, LEDPIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
}
void showStrip() {
FastLED.show();
}
void setPixel(int Pixel, byte red, byte green, byte blue) {
// FastLED
leds[Pixel].r = red;
leds[Pixel].g = green;
leds[Pixel].b = blue;
}
void setAll(byte red, byte green, byte blue) {
for(int i = 0; i < NUM_LEDS; i++ ) {
setPixel(i, red, green, blue);
}
showStrip();
}
void loop() {
LedUp();
//LedDown();
}
void LedDown() {
for(int i = NUM_LEDS; i > 1; i--){
Serial.println(i);
setAll(0,0,0);
delay(100);
if(i < 33){
setPixel(i,0,0xff,0);
}else if(i < 63){
setPixel(i,0xff,0,0);
}else{
setPixel(i,0,0,0xff);
}
showStrip();
}
}
void LedUp() {
for(int i = 0; i < NUM_LEDS; i++){
setAll(0,0,0);
delay(20);
if(i < 30){
setPixel(i,0,0xff,0);
}else if(i < 60){
setPixel(i,0xff,0,0);
}else{
setPixel(i,0,0,0xff);
}
showStrip();
}
}
A: for(int i = NUM_LEDS; i > 1; i--)
You need to start from NUM_LEDS - 1 and go to zero:
for(int i = NUM_LEDS - 1; i >= 0; i--)
Because NUM_LEDS itself is out of range.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63313357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Fit as many views as posiible without overlapping I want to fit as many textViews( Each of them is clicable and leads to some action, so it cannot be just a signle textview populated with text) from my set as possible in layout.
To achieve that, I used following gridview layout
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/blue"
android:gravity="left"
android:verticalSpacing="10dip"
android:horizontalSpacing="10dip"
android:visibility="gone"
android:numColumns="auto_fit"
android:padding="16dip"
/>
And I get result like on image. It looks like 3 colums of items.
What I want to achive - all those textviews should look like i have single textview with long text.
E.g
A: Maybe FlowLayout is what you're looking for.
It wraps content to the next line if there is no space in the current line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25407446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sorting an array and keep the index in MATLAB I have an array called A, it has 2 Rows and 56 columns ( as shown in the attached image)
the first row represents the values while the second row represents the index for each value.
I want to sort the first row but keep the index for each value (I tried to use Sort function but it doesnt keep the index of each value in the second row).
for example, let's suppose I have this matrix
input
x=[9 2 4 3 ;3 1 8 2 ]
i want the output looks like this
y=[2 3 4 9; 1 2 8 3 ];
A: You can use indices of sorted elements
[S,I]=sort(x(1,:));
result = [S;x(2,I)]
The first row is sorted and indices of the sorted elements is used to order the second row.
result
2 3 4 9
1 2 8 3
A: There are a couple of ways to achieve this:
[y1,I] = sort(x(1,:))
y2 = x(2,I)
y = [ y1 ; y2 ]
This basically sort the first row of your data, and save the sorting index in I, and then use those index to get the 'sorted' second row, and then just join them
or
y = sortrows(x')'
The ' operator transposes the matrix, which allows you to use sortrows and then use it again to reshape your output matrix.
A: You can get the indices directly from sorting the first row. These can be used as an argument in x itself:
x=[9 2 4 3 ;3 1 8 2 ];
%get the indices of the first row:
[~,indices] = sort(x(1,:))
%return x in the order "indices" for each row:
y = [x(1,indices);x(2,indices)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42526075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: routes on error functionality not working in web2py i am trying to present a custom error to the end user , but these custom routes are not working and i am still being shown default ticker number, since exposing ticker numbers pose security issues, what am i missing? need help in this thanks in advance ,
Also i have these routes in routes.py in project level directory adjacent to web2py.py
routes_onerror = [
('gms/404', '/gms/static/404.html'),
('gms/500', '/gms/static/500.html'),
('gms/408', '/gms/static/404.html'),
('gms/400', '/gms/static/404.html'),
('super/*', '/super/static/404.html'),
(r'*/*', r'/gms/static/404.html'),
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71761661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I make a set of numbers increase every second and for each increment, print the current set on a new line? I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;
20220215155
20220215156
20220215157 etc...
I tried adding the n tag buh it returned an error.
var i = 20220215155
function increment() {
i+, + </n>;
document.getElementById('test').innerHTML = i
}
('increment()', 1000);
Please I really need help as I have been trying to get this for so long.
A: Your code is not valid JS
Here is something that does work - I am using setInterval here
var i = 20220215155
function increment() {
i++; // increment
document.getElementById('test').innerHTML += i + "<br/>"; // add it with a breakline
}
setInterval(increment, 1000);
<div id="test"></div>
You can use a template literal for the string too
`${i}<br/>`
A: You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.
// Cache the element
const test = document.querySelector('#test');
let n = 20220215155;
// `increment` accepts `n` as an argument
function increment(n) {
// Add a new HTML string to the element
test.innerHTML += `${n}</br>`;
// Call the function again with an new `n`
setTimeout(increment, 1000, ++n);
}
increment(n);
<div id="test"></div>
Additional documentation
*
*Template/string literals
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71104409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R lubridate: Apply helper to dataframe I have a dataframe of times looking like this:
library(lubridate)
times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"),
exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")),
row.names = c(NA, 3L), class = "data.frame")
I want to convert the times in more convenient date-time objects, which I will do with the hms() helper function from the lubridate package.
Running hms() on one column of my dataframe works like a charm:
hms(times[,1])
[1] "17H 19M 4S" "17H 28M 53S" "17H 38M 44S"
Great, surely I can just apply() on my whole dataframe then.
apply(times, 2, hms)
Which gives a weird dataframe with some integers, definitely not what I am expecting.
What is the right way to convert all of my times dataframe with the hms() function?
A: Instead of apply, can use lapply as apply converts to matrix and it wouln't hold the attributes created by hms
library(lubridate)
times[] <- lapply(times, hms)
str(times)
#'data.frame': 3 obs. of 2 variables:
# $ exp1:Formal class 'Period' [package "lubridate"] with 6 slots
# .. ..@ .Data : num 4 53 44
# .. ..@ year : num 0 0 0
# .. ..@ month : num 0 0 0
# .. ..@ day : num 0 0 0
# .. ..@ hour : num 17 17 17
# .. ..@ minute: num 19 28 38
# $ exp2:Formal class 'Period' [package "lubridate"] with 6 slots
# .. ..@ .Data : num 4 53 45
# .. ..@ year : num 0 0 0
# .. ..@ month : num 0 0 0
# .. ..@ day : num 0 0 0
# .. ..@ hour : num 17 17 17
# .. ..@ minute: num 22 31 41
With the devel version of dplyr, we can use mutate with across
library(dplyr)
times %>%
mutate(across(everything(), hms))
A: library(dplyr)
library(lubridate)
times %>% mutate_all(hms)
#OR
mutate_all(times, hms)
# exp1 exp2
#1 17H 19M 4S 17H 22M 4S
#2 17H 28M 53S 17H 31M 53S
#3 17H 38M 44S 17H 41M 45S
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60306237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rails with rmagick and simple test I want just play with rmagick on rails 4 but get:
undefined method `annotate' for #<Array:0xbe4434>
controller:
class ImgController < ApplicationController
include Magick
def index
img = Magick::Image.read('public/images/bg.png')
txt = Draw.new
img.annotate(txt, 0,0,90,15, "hello word"){
txt.gravity = Magick::SouthWestGravity
txt.pointsize = 30
txt.fill = '#084B8A'
txt.font_weight = Magick::BoldWeight
}
img.write('bg_1.png')
send_data bg_1.to_blob, disposition: 'inline',
type: 'image/png'
end
end
gemfile
gem 'rmagick', require: 'RMagick'
from irb rmagick worked fine with:
1. require 'RMagick'
2. include Magick
3.
4. cat = ImageList.new("Cheetah.jpg")
5. cat.display
6. exit
A: Magick::Image#read returns an array of images, because this method may be used for reading animated gifs. Simply call .first on the result:
img = Magick::Image.read('public/images/bg.png').first
Another problem is that you should call annotate on instance of Draw, passing img as first parameter:
Magick::Draw.new.annotate(img, 0, 0, 90, 15, 'hello world') do
# set options here
self.gravity = Magick::SouthEastGravity
# …
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20440707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how get value from html combo box in asp.net code behind I'm unable to get the selected value from combo box in asp.net. I'm using the HTML combo box in server side coding by adding id and runat="server" and using bootstrap property. How to get the value of a combo box in a button click
<div class="form-group">
<label class="col-xs-3 control-label">Size</label>
<div class="col-xs-5 selectContainer">
<select class="form-control" name="size" runat="server" id="Combobox">
<option value="">Choose a size</option>
<option value="s">Small (S)</option>
<option value="m">Medium (M)</option>
<option value="l">Large (L)</option>
<option value="xl">Extra large (XL)</option>
</select>
</div>
</div>
code behind
string value = Combobox.Items.ToString();
A: ASP.NET is so called server side code, whilst HTML is client side code. This means there is no direct connection between HTML and ASP.NET, besides the fact that ASP.NET generates the HTML and sends it back to te client.
In order to be able to get the value from the select box, you should either use an AJAX request to post the value to the server as soon as the selection changes, or force the user to post a form.
Since you appear to be creating a size selection, I think using the AJAX-method should be the best way.
A: In codebehind a html-select with runat=server is a HtmlSelect and Items returns a ListItemCollection.
You can use the SelectedIndex:
string selectedItemValue = null;
string selectedItemText = null;
if(Combobox.SelectedIndex >= 0)
{
ListItem selectedItem = Combobox.Items[Combobox.SelectedIndex];
selectedItemValue = selectedItem.Value;
selectedItemText = selectedItem.Text;
}
or use the HtmlSelect.Value property which does the same:
string selectedItemValue = Combobox.Value; // String.Empty if no item selected
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34308232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: I have a problem with this question: building a function called findFirstWordWithMostRepeatedChars Problem statement :
Write a function that finds Max Repeat count In Word. Looks like there is a problem with loops
// Skeleton
// FUNCTION DEFINITION(S)
function findMaxRepeatCountInWord(word) {
// Break up individual word into individual letters.
word = word.split('');
// Count the instances of each letter
let objOfLetters = {};
for (let i = 0; word.length; i++) {
//if word[i] is not exist in objOfLetters
if (objOfLetters[word[i]] === undefined) {
//creat an an prop with key set to word at i and value set to 1
objOfLetters[word[i]] = 1;
//otherwize
} else {
//add 1 to its value
objOfLetters[word[i]]++;
}
}
// getting all the valuse that are the counts of letters
let counts = Object.values(objOfLetters);
let max = counts[0];
for (let k = 1; k < counts.length; k++) {
if (counts[k] > max) {
max = counts[k];
}
}
return max;
}
// ASSERTION FUNCTION(S) TO BE USED
function assertEqual(actual, expected, testName) {
if (actual === expected) {
console.log('passed');
} else {
console.log('FAILED [' + testName + '] Expected ' + expected + ', but got ' + actual);
}
}
var input_1 = 'passed';
var actual_1 = findMaxRepeatCountInWord(input_1);
var expected_1 = 2;
assertEqual(actual_1, expected_1, 'it shows that how many times a characters repeated');
Can someone help me on this ?
A: Might be the for loop end condition. You have this:
for (let i = 0; word.length; i++) {
Instead of this:
for (let i = 0; i < word.length; i++) {
A: function find_max_repeat_count_in_word(word) {
const chars = word && word.split('').filter(char => (char || '').trim()) || [];
let counterMap = {};
let max = 0;
// max value can be tracked along side building the counter map
chars.forEach(char => {
counterMap = {...counterMap, [char]: (counterMap[char] || 0) + 1 };
if (counterMap[char] > max) {
max = counterMap[char];
}
});
return max;
}
Considerations
It doesn't take into consideration whitespaces
Since expected is just max, it doesn't matter if two or more characters have same count
Illustration
function find_max_repeat_count_in_word(word) {
const chars = word && word.split('').filter(char => (char || '').trim()) || [];
let counterMap = {};
let max = 0;
// max value can be tracked along side building the counter map
chars.forEach(char => {
counterMap = {...counterMap, [char]: (counterMap[char] || 0) + 1 };
if (counterMap[char] > max) {
max = counterMap[char];
}
});
return max;
}
console.log('[Input]', undefined, '[Output]', find_max_repeat_count_in_word(undefined));
console.log('[Input]', null, '[Output]', find_max_repeat_count_in_word(null));
console.log('[Input]', '\'\'', '[Output]', find_max_repeat_count_in_word(''));
console.log('[Input]', '\'undefined\'', '[Output]', find_max_repeat_count_in_word('undefined'));
console.log('[Input]', 'Hello', '[Output]', find_max_repeat_count_in_word('Hello'));
console.log('[Input]', 'passive', '[Output]', find_max_repeat_count_in_word('passive'));
console.log('[Input]', 'possessive postman', '[Output]', find_max_repeat_count_in_word('possessive postman'));
console.log('[Input]', 'Do something with previous code, it seems to be running in infinite loop', '[Output]', find_max_repeat_count_in_word('Do something with previous code, it seems to be running in infinite loop'));
WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET
A: The exit condition of the for loop is not written correctly.
You can correct by writing : for(let i = 0; i < word.length; i++)
otherwise the word.length condition will always be true.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71323970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: MPAndroidChart LineChart: Using dates instead of Strings for X-axis MPAndroidChart LineChart by default accepts Strings for X-axis. Is there a way to set the Date as a datatype for the X-axis?
The problem with just converting Date into strings is that the graph can be skewed depending on the data points. For example, if I have one data entry on January and 10 entries in June, by default the graph is just split into 11 and plot accordingly.
I want a "Your weight over time" graph, where X-Axis represents time. User weights in at random times, so some dates will have entry and some dates will not.
A: I found a thread on the project's gitHub ( https://github.com/PhilJay/MPAndroidChart/issues/12
).
Apparently, this feature is not yet implemented.
Update
Doing a bit of search, I found this alternative library:
https://github.com/lecho/hellocharts-android
It supports values for x-axis.
UPDATE
Since 2016, this feature has been included in MPAndroid. See https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/main/java/com/xxmassdeveloper/mpchartexample/LineChartTime.java for an exapmle in the docs.
A: You can make new array with full dates and fill empty positions with previous values.
For example:
you making an array may[31] for each day of may, initializate it with zeroes, and then do something like this:
may[1] = values[1];
for (int i = 2; i <= may.size(); ++i) {
if (may[i] == 0)
may[i] = may[i-1];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32292466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: two page layouts into one view I would like some advice on this matter. I have a view page that will display a number of users. One view is to display users in a grid (gallery like) of their images. Second view is to display the same users but by their name in a list layout. I will have a toggle button on the page to switch between the two. What is the best way to go about it? Having two separate view pages or have a partial view of some sort?
Update Code after suggestion below
<div data-bind="template: {name:'grid-template'}"></div>
<div data-bind="template: {name:'list-template'}"></div>
<script style="float:left" type="text/html" id ="grid-template">
<section " style="width:100%; float:left">
<section id="users" data-bind="foreach: Users">
<div id="nameImage">
<figure id="content">
<img width="158" height="158" alt="Gravatar" data-bind="attr:{src: GravatarUrl}"/>
<figcaption>
<a title="Email" id="emailIcon" class="icon-envelope icon-white" data-bind="attr:{'href':'mailto:' + Email()}"></a>
<a title="Profile" id="profileIcon" class="icon-user icon-white"></a>
</figcaption>
</figure>
<p data-bind="text:Name"></p>
</div>
</section>
</section>
</script>
<script style="float:left" type="text/html" id="list-template">
<div data-bind="foreach: Users">
<div style="width:60%; float:left; margin:10px; height:58px">
<img style="float:left; margin-right:5px" width="58" height="58" alt="Gravatar" data-bind="attr:{src: GravatarUrl}"/>
<p style="height:58px; float:left; vertical-align:central" data-bind="text:Name"></p>
<a style="float:right" title="Profile" class="icon-user icon-black"></a>
<a style="float:right" title="Email" class="icon-envelope icon-black" data-bind="attr:{'href':'mailto:' + Email()}"></a>
</div>
</div>
</script>
Knockout Script File
$.views.User.UserViewModel = function (data) {
var self = this;
self.Name = ko.observable(data.Name);
self.Email = ko.observable(data.Email);
self.ContentRole = ko.observable(data.ContentRole);
self.MD5Email = ko.observable(data.MD5Email);
self.GravatarUrl = ko.computed(function () {
return 'http://www.gravatar.com/avatar/' + self.MD5Email() + '?s=300&d=identicon&r=G';
});
self.renderMode = ko.observable('grid');
self.displayTemplate = ko.computed(function () {
return self.renderMode() + '-layout-template';
});
};
A: Personally, I like having clean isolated small little Partial Views especially if it is going to be regular HTTP POST.
However, based on the assumptions I am making below, I think I can suggest a better implementation design.
My Assumption
You have
*
*Index.cshtml Parent view to display a list Users.
*JSON object array containing your list of Users
*Based on what I see, you are using KnockoutJS.
Read the KnockoutJS Template Binding especially the "Note 5: Dynamically choosing which template is used" part.
It kind of makes it easier to do what you are doing if you are using KnockoutJS or something similar.
You simply have toggle between the two rendering templates.
<script type="text/html" id="gallery-layout-template"> ... </script>
<script type="text/html" id="listing-layout-template"> ... </script>
<div id="divOutputContainer"
data-bind="template: { name: displayTemplate, foreach: users }"></div>
<script type="text/javascript">
$(document).ready(function() {
// I am just writing out a dummy User array here.
// Render out your User Array JSON encoded using JSON.NET.
var myUsers = [
{ "id" : 1, "name": "User 1" },
{ "id" : 2, "name": "User 2" }
];
// here is your KnockoutJS View Model "class"
function MyKoViewModel(users) {
var self = this;
self.users = ko.observableArray(users);
// Toggle this renderMode observable's value
// between 'listing' and 'gallery' via your Toggle button click event handler
self.renderMode = ko.observable( 'gallery' );
self.displayTemplate = function(user) {
// this will return 'gallery-layout-template' or 'listing-layout-template'
return self.renderMode() + '-layout-template';
}
}
ko.applyBindings( new MyKoViewModel( myUsers ) );
});
</script>
So with that technique, you don't need to make an AJAX call every time to refresh the view with a different rendering template.
You have all your data that you want to display as a client-side JavaScript KnockoutJS view model.
Then, just switch the client-side rendering template using KnockoutJS.
Must more efficient :-)
NOTE
I have a feeling, you might have to use the ko.computed() for the MyKoViewModel's displayTemplate() function like this.
self.displayTemplate = ko.computed(function() {
return self.renderMode() + '-layout-template';
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15892233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Templated Intermediate Array for Given Type I have a library that contains a function:
// Gets [bytes] number of *bytes* and fills rx_buff
void getData(uint8_t* rx_buff, uint16_t bytes);
I also have a library that I am writing an interface for, the structure is rather simple (protected IP, all names are imaginary):
[libGetData] <-> libMyLib <-> [libDoStuff]
I cannot modify libGetData, nor can I change libDoStuff.
libDoStuff has a number of functions that look like:
bool isDataGood8(uint8_t input);
bool isDataGood16(uint16_t input);
bool isDataGood32(uint32_t input);
bool isDataGood64(uint64_t input);
I just want a clean way to implement an intermediate function between getData() and all types of isDataGoodXX().
template <typename T>
T getValue()
{
// Create intermediate array for getData
uint8_t temp_array[sizeof(T)];
// Fill temp_array
getData(&temp_array, sizeof(T));
// Create value type to hold byte-array
T return_val;
// Copy array data into integer type
std::memcpy(&return_val, temp_array, sizeof(T));
return return_val;
}
Is this template a valid solution?
A: Yes, this code is almost correct, with a slight exception. Your call to getData should look like:
getData(temp_array, sizeof(T));
You should not be passing the address of array into your getValue function. Other than that, it is good, and it doesn't suffer from quite common strict aliasing violation.
You are also avoiding any issues of alignment, and the code is as optimal as can be give the API.
A: A problem I see is that because you are only templating the returned value, you will need to explicitly specify the type to use your template method, i.e.
auto val = getValue<uint32_t>();
isDataGood(val); // Should be!
Without using auto, this is prone to mismatch errors, not all of which will be reported:
uint32_t val = getValue<uint16_t>();
isDataGood(val); // perhaps not!
It depends how heavy-handed you want to be to protect against this, but one way is to make the returned value a parameter, which allows template type deduction:
uint32_t val;
getValue(val);
isDataGood(val); // Must be!
Another is to not use raw integers, but always a struct containing the value as a member of the right size. You can't trivially switch between structs like you can between integer sizes.
Another is to have getValue return a wrapper that for a given type knows how to cast to it, and for other types, fails to cast at compile time:
struct FailIntBase
{
operator uint8_t()const = delete;
operator uint16_t()const = delete;
operator uint32_t()const = delete;
operator uint64_t()const = delete;
// etc
};
template <class Castable> struct SafeInt: FailIntBase
{
Castable val;
SafeInt(Castable val): val(val) {}
operator Castable()const
{ return val; }
};
template <typename T>
SafeInt<T> getValue() { //...
// Testing:
auto X = getValue<uint16_t>();
uint16_t Y = getValue<uint16_t>();
uint32_t Z = getValue<uint16_t>(); //error: use of deleted function 'FailIntBase::operator uint32_t() const'
If you need to cover more types including signed types, you can get away with a much smaller implementation of FailIntBase if you can live with the less informative error message:
conversion from 'SafeInt<short unsigned int>' to 'uint32_t' {aka 'unsigned int'} is ambiguous
note: candidate: 'SafeInt<Castable>::operator Castable() const [with Castable = short unsigned int]'
note: candidate: 'FailIntBase::operator uint64_t() const' <deleted>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51845296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Meteor: Variable in Variable I want to update an array with the help of a variable, thats my sourcecode:
var y = Flags.findOne({_id: "flagsone"});
// This one works, but I need the other one
// Books.update({_id:book}, {$set: {"score20130901.5": 222}});
Books.update({_id:book}, {$set: {"score20130901.[y.flag1]": 222}});
Have somebody an idea, how I can variables put together?
A: var y = Flags.findOne({_id: "flagsone"});
var props = {};
props["score20130901." + y.flag1] = 222;
Books.update({_id:book}, {$set: props});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18430976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Condition 'listenerReg != null' is always 'true' when trying to detach/close Firestore snapshot (Android) Context: It is my first project in Android and I fill I am asking some silly question but I can't find any direction on it (certainly I am messing up some previous knowledge of Angular/Srping with Android/Kotlin)
Goal: Android App will get a Firestore customtoken from certain backend microservice and then start to listen a document. So far so good. I read about good practices of how close/detach the listen and I believe I have successfully done this by passing Android activity as first argument to snapshot. So far also so good. But in my case, I have to close/detach the snapshot listen either after 10 minutes or after a especific value from document is received. Now I really got stuck.
I tried the simplest first step as imagined and I am getting the naive warnning form this topic. So my straght question is: why it is complaining as ALWAYS TRUE condition? A complementaty comment from someone expert on Android would be how to close/detach the snapshot after 10 minutes and if I receive a specific value from the listened document. Please accept the idea that either one of these two conditions needs to stops listen and still keep in same MainActivity.kt.
Here is the code with warning when trying to check during onStop cycle phase
package com.mycomp.appfirestore
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.FirebaseFirestore
import com.mycomp.appfirestore.data.service.Endpoint
import com.mycomp.appfirestore.data.service.NetworkUtils
import com.mycomp.appfirestore.model.Transfer
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
lateinit var auth: FirebaseAuth
lateinit var listenerReg : FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnTransfer = findViewById(R.id.btnTransfer) as Button
val textViewTransfer = findViewById(R.id.textViewTransfer) as TextView
btnTransfer.setOnClickListener {
getToken()
}
}
fun getToken() {
val retrofitClient = NetworkUtils
.getRetrofitInstance("http://192.168.15.13:8080/")
val endpoint = retrofitClient.create(Endpoint::class.java)
...
callback.enqueue(object : Callback<Transfer> {
override fun onFailure(call: Call<Transfer>, t: Throwable) {
Toast.makeText(baseContext, t.message, Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<Transfer>, response: Response<Transfer>) {
listenStatus()
}
})
}
fun listenStatus() {
val TAG = "ListenStatus"
auth = FirebaseAuth.getInstance()
// to make simple for this question let's say the backend returned a valid customtoken used here
auth.signInWithCustomToken("eyJ **** gXsQ")
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d(TAG, "*** signInWithCustomToken:success")
startSnapshot()
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCustomToken:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
}
}
}
fun startSnapshot() {
val TAG = "StartSnapshot"
//Try to pass this(activity context) as first parameter.It will automatically handle acivity life cycle.
// Example if you are calling this listener in onCreate() and passing this as a first parameter then
// it will remove this listener in onDestroy() method of activity.
listenerReg = FirebaseFirestore.getInstance()
listenerReg.collection("transfer")
.document("sDme6IRIi4ezfeyfrU7y")
.addSnapshotListener(
this,
EventListener<DocumentSnapshot?> { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@EventListener
}
if (snapshot != null && snapshot.exists()) {
textViewTransfer.text = snapshot.data!!["status"].toString()
//Log.d(TAG, snapshot.data!!["status"].toString())
} else {
Log.d(TAG, "Current data: null")
}
})
}
//here I get the warnning mentioned in my question topic
fun stopSnapshot() {
if (listenerReg != null) {
listenerReg.remove()
}
}
}
I am aware that since I added the activity as first argument of snapshot soon the activity is left it will detached automatically the listen. But I have two more condition to stop listen:
1 - after 10 minutes
2 - if I get a specific returned value
So as imaginary solution I would try more or less
...
EventListener<DocumentSnapshot?> { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@EventListener
}
if (snapshot != null && snapshot.exists()) {
textViewTransfer.text = snapshot.data!!["status"].toString()
**** imagined solution ****
if (snapshot.data!!["status"].toString() == "FINISH"){
stopSnapshot()
}
//Log.d(TAG, snapshot.data!!["status"].toString())
} else {
Log.d(TAG, "Current data: null")
}
})
...
**** imagined solution ***
listenerReg.timeout(10000, stopSnapshot())
A: To answer your questions:
Why it is complaining as ALWAYS TRUE condition?
Your FirebaseFirestore object is initialized as lateinit var listenerReg : FirebaseFirestore, which means you've marked your listenerReg variable as non-null and to be initialized later. lateinit is used to mark the variable as not yet initialized, but basically promising that it will be initialized when first referenced in code. Kotlin will throw an error at runtime if trying to access this variable and it's not initialized.
If you want to make it nullable, you'd need to initialize it like this:
var listenerReg : FirebaseFirestore? = null
Then you could have your stop method looking something like this:
fun stopSnapshot() {
if (listenerReg != null) {
listenerReg.remove()
listenerReg.terminate()
listenerRef = null
}
}
But I have two more condition to stop listen:
1 - after 10 minutes
There are many ways to set certain timeouts on Android. The most straightforward way would be to post a handler that will invoke stopSnapshot() method, e.g.:
Handler().postDelayed({
//Do something after 10mins
stopSnapshot();
}, 1000 * 60 * 10)
2 - if I get a specific returned value
Just call stopSnapshot() when you receive this value.
Note: I assumed all the Firestore calls are correct. I don't have the API and this usage on top of my head. Hope my answer helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62140300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Typescript: detect the generic type of a function I am developing a web application that uses cookies. To read a cookie I would like to write a typescript function of this type:
let cookie1: number = getCookie<number>("fake_int_name");
let cookie2: boolean = getCookie<boolean>("fake_bool_name");
let cookie3: string = getCookie<string>("fake_string_name");
function getCookie<T>(name: string): T {
...
let cookie_value: string = "fake_cookie_value";
if(T is number)
return parseInt(cookie_value);
if(T is boolean)
return cookie_value == "true";
return cookie_value;
}
Is it possible to create a getCookie function able of behaving differently depending on the type T?
A: First of all, interfaces only exist at compile time, so it is not possible to have conditions on them in the code.
Conditional return types do exist, but only seem to be partially supported:
enum ResultType {
INT = 'int',
BOOL = 'bool',
STRING = 'string',
}
interface TypeMap {
int: number;
bool: boolean;
string: string;
}
function getCookie<K extends ResultType>(name: string, type: K): TypeMap[K] {
let cookieValue;
// ...
switch (type) {
case ResultType.INT:
return parseInt(cookieValue, 10) as any;
case ResultType.BOOL:
return (cookieValue === 'true') as any;
case ResultType.STRING:
return cookieValue as any;
}
}
// usage:
getCookie('foo', ResultType.INT); // compiler correctly assumes number as return type
getCookie('foo', ResultType.BOOL); // compiler correctly assumes boolean as return type
You can see here that the return type is casted to any. The compiler does not properly infer this type. The issue addressing this is https://github.com/microsoft/TypeScript/issues/24929, but it seems to be closed without a fix.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65918542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to Compute Difference Between Two fields in MongoDB Good evening. I have a project in MongoDB and i keep getting an error while trying to run my last querie. The dataset i have is about wines. What i want to do is to print the wines that match the Red wine category and that are at least 20 years old (i have a start date-the date that they were put in their barrels- and an end date, which is the date they were bottled). Note:i want all these fields to be printed at the end and be printed according to their rating.
let me give an example of the data:
{ _id: ObjectId("638f389d8830abb3f19aaf51"),
tconst: 'tt0040030',
wineType: 'Red',
Brand: '#brand',
startYear: 1990,
endYear: 2002
rating:6.6}
When i am using the $match function for my three criteria all is working just fine but i haven't figured out how to subtract the two date fields so i can find the wines that are at least 20 years old and print the results properly.
A: Query
*
*you need to refer to a field to compute the difference so you need $expr and aggregate operators
*the bellow keeps red wines, with years difference>=20, and then sorts by rating.
Playmongo
aggregate(
[{"$match":
{"$expr":
{"$and":
[{"$eq": ["$wineType", "Red"]},
{"$gte": [{"$subtract": ["$endYear", "$startYear"]}, 20]}]}}},
{"$sort": {"rating": -1}}])
A: In MongoDB, the $where query operator is used for comparing the fields or documents that satisfy the JavaScript expression. We can also pass a string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74752881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby/Rails: Correct way to implement to_csv that considers active record Been out of the game for a while, getting back into it..
So, with that I have Companies.
Companies have_many Users and Users belongs_to a Company.
It's super easy to do @company.users to get the list of users.. awesome.
More over you can do handy things like @company.users.where({foo}).limit({bar}).to_json to get a json list of users etc... Works great.
I'd like to do @company.users.to_csv or better yet @company.users.where({some query}).limit({somenumber}).to_csv but of course it errors there and says "did you mean to_s" or something of that nature..
I swear we used to be able to do .to_csv or at least do this using Serializers but damned if I can remember how.. Could someone point me in the right direction?
I can add a custom method to the model for .to_csv but that doesn't work when you're getting a bunch.. Thoughts? I feel like this should be trivial and I'm stumped.
A: You can define to_csv function on user model like this.
def self.to_csv(users, options = {})
header_columns = [
"Email",
"First Name",
"Last Name"
]
CSV.generate(options) do |csv|
csv << header_columns
users.each do |user|
row = [
user.email,
user.first_name,
user.last_name
]
csv << row
end
end
end
And call it like this.
User.to_csv(@company.users)
A: require "csv" dont forget to include the module
@company.users.to_a.to_csv
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63184321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: expo firebase google signin gives: First argument "idToken" must be a valid string or a valid object or null https://docs.expo.io/versions/latest/sdk/google
I follow the integration guides on official website when I authenticate with google it gives me such a error
credential failed: First argument "idToken" must be a valid string or a valid object or null
_handleGoogleAuth = async () =>{
console.log(ENV.androidClientId)
const { type, token } = await Google.logInAsync({
androidClientId: ENV.androidClientId,
iosClientId:ENV.iosClientId,
behavior: Platform.OS === 'ios' ? 'web' : 'system'
})
console.log(type+'type')
if (type == 'success') {
const credential = firebase.auth.GoogleAuthProvider.credential(token)
console.log(credential.idToken)
firebase.auth().signInWithCredential(credential).catch((error) => {
console.log(error)
})
}
}
A: There's a known error with the expo-google-signin library where idToken and sometimes accessToken are returned as undefined.
It might stretch over to expo Google as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53897269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Ball-Box Collision Detection
var canvas,cxt,h,w,mousePos;
var player= {
x: 10,
y: 10,
height: 20,
width: 20,
color: 'black'
};
function init(){
canvas= document.querySelector('#style');
cxt= canvas.getContext('2d');
h= canvas.height;
w= canvas.width;
createBalls(10);
main();
}
function createBalls(c){
ball= [];
var i;
for(i=0;i<c;i++){
var k= {
x: h/2,
y: w/2,
color: colorGenerate(),
radius: 5+Math.round(30*Math.random()),
a: -5+Math.round(10*Math.random()),
b: -5+Math.round(10*Math.random())
}
ball.push(k);
}
}
function main(){
cxt.clearRect(0,0,h,w);
canvas.addEventListener('mousemove',function(evt){
mousePos= getMousePos(canvas,evt);
});
createPlayer();
draw(ball.length);
ballAlive();
move(ball.length);
movePlayer();
requestAnimationFrame(main);
}
function ballAlive(){
cxt.save();
cxt.font="30px Arial";
if(ball.length==0) cxt.fillText("You Win",20,20);
else cxt.fillText(ball.length,20,40);
cxt.restore();
}
function getMousePos(canvas,evt){
var rect= canvas.getBoundingClientRect();
return{
x: evt.clientX-rect.left,
y: evt.clientY-rect.top
}
}
function createPlayer(){
cxt.save();
cxt.translate(0,0);
cxt.fillStyle= player.color;
cxt.fillRect(player.x,player.y,player.height,player.width);
cxt.restore();
}
function movePlayer(){
if(mousePos !== undefined){
player.x= mousePos.x;
player.y= mousePos.y;
}
}
function draw(d){
var i;
for(i=0;i<d;i++){
cxt.save();
cxt.translate(0,0);
cxt.beginPath();
cxt.fillStyle= ball[i].color;
cxt.arc(ball[i].x,ball[i].y,ball[i].radius,0,2*Math.PI)
cxt.fill();
cxt.restore();
}
}
function move(m){
var i;
for(i=0;i<m;i++){
ball[i].x+= ball[i].a;
ball[i].y+= ball[i].b;
checkCollision(ball[i]);
checkCollisionPlayer(ball[i],i);
}
}
function checkCollision(n){
if(n.x+n.radius>w){
n.a= -n.a;
n.x= w-n.radius;
}
else if(n.x-n.radius<0){
n.a= -n.a;
n.x= n.radius;
}
if(n.y+n.radius>h){
n.b= -n.b;
n.y= h-n.radius;
}
else if(n.y-n.radius<0){
n.b= -n.b;
n.y= n.radius;
}
}
function checkCollisionPlayer(n,j){
if(overlap(n.x,n.y,n.radius,player.x,player.y,player.height,player.width)){
ball.splice(j,1);
}
}
function overlap(cx,cy,r,px,py,ph,pw){
var testX= cx;
var testY= cy;
// THESE LINES ARE FOR MOVING THE BALLS TOWARDS THE PLAYER
if(testX<px) testX=px;
if(testX>(px+pw)) testX=px+pw;
if(testY<py) testy=py;
if(testY>(py+ph)) testY=py+ph;
//DISTANCE FORMULA FOR CHECKING THE OVERLAPING BETWEEN THE BOX AND CIRCLE
return((cx-px)*(cx-px)+(cy-py)*(cy-py)<r*r);
}
function colorGenerate(){
var col= ['green','blue','pink','red','brown','yellow','black','orange','grey','golden'];
var i= Math.round((col.length-1)*Math.random()); //RETURN VALUES FROM 0 TO 9
return col[i];
}
#style{
border: 4px dotted green;
}
<!DOCTYPE html>
<html lang= 'en-us'>
<head>
<title>Feed The Monster</title>
</head>
<body onload= 'init();'>
<canvas id= 'style' height= '400' width= '400'>
Your browser does not support canvas...
</canvas>
</body>
</html>
I am getting error in my code as soon as the first collision takes place between the player(box) and the balls.
The only part which is giving error is the splice() function. If I comment the splice() function then code is not showing any error.
But if I use splice() function part in my code then it is showing error in the move function and I don't know why this is happening.
Please help me…
A: This appears to be to do with the loop inside your move function. You call it with the parameter m representing the lengh of the ball array - but the function checkCollisionPlayer which is called within that can remove a ball from the array if there is a collision. This means that the array is now shorter, so whenever you try to access a property on ball[m-1] later in the loop, as you will, you'll get this error.
I'm sure there are lots of different ways to fix this. The easiest I can think of (which I have successfully used myself in making a browser game) is to, instead of directly deleting the balls from the array upon collision, set a property on them to mark them as "deleted". Then add a "cleanup" function onto the end of the loop to filter the array into only those that are not marked as deleted. This ensures that every object you are looping over actually exists, while still changing the length dynamically to reflect the game state.
A:
var canvas,cxt,h,w,mousePos;
var player= {
x: 10,
y: 10,
height: 20,
width: 20,
color: 'black'
};
function init(){
canvas= document.querySelector('#style');
cxt= canvas.getContext('2d');
h= canvas.height;
w= canvas.width;
createBalls(10);
main();
}
function createBalls(c){
ball= [];
var i;
for(i=0;i<c;i++){
var k= {
x: h/2,
y: w/2,
color: colorGenerate(),
radius: 5+Math.round(30*Math.random()),
a: -5+Math.round(10*Math.random()),
b: -5+Math.round(10*Math.random())
}
ball.push(k);
}
}
function main(){
cxt.clearRect(0,0,h,w);
canvas.addEventListener('mousemove',function(evt){
mousePos= getMousePos(canvas,evt);
});
createPlayer();
draw(ball.length);
ballAlive();
move(ball);
movePlayer();
requestAnimationFrame(main);
}
function ballAlive(){
cxt.save();
cxt.font="30px Arial";
if(ball.length==0) cxt.fillText("You Win",20,20);
else cxt.fillText(ball.length,20,40);
cxt.restore();
}
function getMousePos(canvas,evt){
var rect= canvas.getBoundingClientRect();
return{
x: evt.clientX-rect.left,
y: evt.clientY-rect.top
}
}
function createPlayer(){
cxt.save();
cxt.translate(0,0);
cxt.fillStyle= player.color;
cxt.fillRect(player.x,player.y,player.height,player.width);
cxt.restore();
}
function movePlayer(){
if(mousePos !== undefined){
player.x= mousePos.x;
player.y= mousePos.y;
}
}
function draw(d){
var i;
for(i=0;i<d;i++){
cxt.save();
cxt.translate(0,0);
cxt.beginPath();
cxt.fillStyle= ball[i].color;
cxt.arc(ball[i].x,ball[i].y,ball[i].radius,0,2*Math.PI)
cxt.fill();
cxt.restore();
}
}
function move(m){
var i;
for(i=0;i<m.length;i++){
ball[i].x+= ball[i].a;
ball[i].y+= ball[i].b;
checkCollision(ball[i]);
checkCollisionPlayer(ball[i],i);
}
}
function checkCollision(n){
if(n.x+n.radius>w){
n.a= -n.a;
n.x= w-n.radius;
}
else if(n.x-n.radius<0){
n.a= -n.a;
n.x= n.radius;
}
if(n.y+n.radius>h){
n.b= -n.b;
n.y= h-n.radius;
}
else if(n.y-n.radius<0){
n.b= -n.b;
n.y= n.radius;
}
}
function checkCollisionPlayer(n,j){
if(overlap(n.x,n.y,n.radius,player.x,player.y,player.height,player.width)){
ball.splice(j,1);
}
}
function overlap(cx,cy,r,px,py,ph,pw){
var testX= cx;
var testY= cy;
// THESE LINES ARE FOR MOVING THE BALLS TOWARDS THE PLAYER
if(testX<px) testX=px;
if(testX>(px+pw)) testX=px+pw;
if(testY<py) testy=py;
if(testY>(py+ph)) testY=py+ph;
//DISTANCE FORMULA FOR CHECKING THE OVERLAPING BETWEEN THE BOX AND CIRCLE
return((cx-px)*(cx-px)+(cy-py)*(cy-py)<r*r);
}
function colorGenerate(){
var col= ['green','blue','pink','red','brown','yellow','black','orange','grey','golden'];
var i= Math.round((col.length-1)*Math.random()); //RETURN VALUES FROM 0 TO 9
return col[i];
}
#style{
border: 4px dotted green;
}
<!DOCTYPE html>
<html lang= 'en-us'>
<head>
<title>Feed The Monster</title>
</head>
<body onload= 'init();'>
<canvas id= 'style' height= '400' width= '400'>
Your browser does not support canvas...
</canvas>
</body>
</html>
If you pass the array as an argument in the move() function not the length of the array then your code will work perfectly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53062360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing values to a PowerShell script in a TeamCity metarunner I've got a metarunner defined like so:
<?xml version="1.0" encoding="UTF-8"?>
<meta-runner name="Fancy Pancy">
[...]
<build-runners>
<runner name="Fancy Pancy" type="jetbrains_powershell">
<parameters>
[...]
<param name="jetbrains_powershell_scriptArguments"><![CDATA-Optional:%SomeOptMetarunnerParam%
-Required:%SomeReqMetarunnerParam%]]></param>
<param name="jetbrains_powershell_script_code"><![CDATA[#Requires -Version 7
[CmdletBinding()]
param (
[string] $Optional,
[string] $Required
)
[...]
My problem is the following: if the user keeps the optional parameter empty, the PowerShell execution thinks that "-Required:%SomeReqMetarunnerParam" is the argument value for the "Optional" parameter and finally fails because a value for the "Required" parameter is missing. If the user does give a value for the optional parameter, everything works as intended.
I've worked around it by redefining the parameters as follows (note the quotes):
<param name="jetbrains_powershell_scriptArguments"><![CDATA-Optional:'%SomeOptMetarunnerParam%'
-Required:'%SomeReqMetarunnerParam%']]></param>
This works, however, the quotes become part of the value. So I have to trim them at the beginning of the PowerShell script which is clearly bad style and not clean code at all.
Is there a trick on how to overcome this problem?
A: I found a way to overcome my problem. I removed the scriptArguments XML, the CmdletBinding and the param declaration completely. Instead I simply access the variables at the beginning of the jetbrains_powershell_script_code XML:
$Optional = "%Optional%"
$Required = "%Required%"
The required check is done by TeamCity's validationMode property further up the XML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68271812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL/PHP and Tables - Making a Column with Text into URL I have a column in a DB that populates a list within a table of the top gaining athletes on my fantasy sports website, on the website I would like to be able to have "Jamal Charles" be a url and have it linked to the internal webpage for Jamaal that was already created. below the table I have the function that is calling the "companyname" - companyname is actually the athletes name.
How would I make the "companyname" a link to its own page in this table? Would i make another function that calls the url instead? Make another column that accepts urls and call that? I hear that sometimes the database will only echo the url text and not make it a link. Is any of the possible?
Please let me know if you need more code. Thanks in advance everyone!
Top Gaining Athletes Today
1. Jamaal Charles 0.54 %
2. Kyle Rudolph 0.50 %
3. A.J. Green 0.48 %
4. Michael Bush 0.48 %
5. Jared Cook 0.47 %
6. Christian Ponder 0.45 %
7. Alfred Morris 0.45 %
8. Nate Washington 0.44 %
9. Ryan Succop 0.44 %
10. DeMarco Murray 0.43 %
function getTopAthletes($connection){
$i=1;
$query = "SELECT b. companyname, (a.currentprice - a.open)/a.open as performance FROM jm_market a, jm_stocks b WHERE a.symbol = b.symbol AND active = 'Y' ORDER BY performance desc LIMIT 10";
$result=mysql_query($query,$connection) or die('Problem with obtaining top PLAYERS: ' . $query);
$output = "<table class='tab1 bborder' cellspacing='0'>";
$output.= "<th colspan='4'>Top Gaining Athletes Today</th>";
while($row=mysql_fetch_array($result)){
// Shorten really long names
if (strlen($row['companyname']) > 20) {
$short = split (' ', $row['companyname']);
$row['companyname'] = substr( $short[0],0,1 ) . ". ";
unset($short[0]);
foreach ($short as $n) {
$row['companyname'] .= $n . " ";
}
$row['companyname'] = rtrim($row['companyname']);
}
$output .="<tr ><td width='20px'><strong>" . $i.".</strong></td>";
$output .="<td ><strong>" . $row['companyname']."</strong></td>";
$output .="<td><strong>" . number_format(($row['performance']) * 100,2)." %</strong></td></tr>";
$i++;
}
$output .= "</table>";
return $output;
}
A: Try this
$output .="<td ><strong><a href='users.php?username=" . $row['companyname']."'>". $row['companyname']."</a></strong></td>";
That should give you
<a href='users.php?username=John'>John</a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12556022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find the Previous and Selected Value of a wxComboBox I'm coming from Qt trying to learn wxWidgets.
When a user selects an element from a wxComboBox I want to get the value that is being changed from and the value that is being changed to. I need to be able to change some other elements in my GUI in reaction to the previous and selected values.
In Qt I would have had to override the QComboBox and create my own signal. This example is a little overkill because the user cannot type into my combobox, nor can he add elements, but you get the idea: https://stackoverflow.com/a/3184619/2642059
Is there a way to accomplish this in wxWidgets? Or do I just have to maintain a variable holding the previous value and update that after each user selection?
A: Yes, you will need to remember the last selection yourself, wxWidgets doesn't do it for you (and neither does the native control).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28151528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Three table with value join query base value is first ,secound and third table i need to develop the query with join or any thing i can't make it
my concept is the first table have a usr id and usr type id
the second table have details of usr type and id and usr master details id
the third table have usr master details and id my question is how i select the value of those three table
Sample table is
user_details
usr_id Name us_ty_id
25 john 2
34 sam 3
24 rose 1
user_type
us_ty_id type usr_ma_id
1 dev 2
2 desi 1
3 test 2
user_master
usr_ma_id details
1 team1
2 team2
3 team3
my output like below
usr_id type details
34 test team3
the first table us_type_id find the type and usr_ma_id in second and find the details of selected id of usr_ma_id in second table and find the details
ple help me...
A: What about the simple:
SELECT *
FROM user_details d
INNER JOIN user_type t ON t.us_ty_id = d.us_ty_id
INNER JOIN user_master m ON m.usr_ma_id = t.usr_ma_id;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11342795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hibernate throwing StackOverflow Exception(Spring Boot) I'm working with SprinBoot/JPA in an integration via XML. I have to read an XML file and persist the data into my db.
Steps:
*
*I must verify if this XML is not recurrent if it does, I have to update this register.
*Each XML comes with a list of items, I have to verify if each child already exists, if it does I have to update, if not I have to create a new one.
*I have to verify if some child is not recurrent and if it not, I have to remove this item.
*I have to verify if the material, color and product are existent otherwise I have to create a new one for each case.
Generally, everything works fine. But I have some cases when I getting a StackOverflow Exception.
*
*It's not because it is recursive because 90% of the files are saved correctly and updated correctly.
*I tried to save separately the children, no success.
*It's always the same files that throw the exception.
*It's not the memory because I have success cases that the file is bigger than the ones who failed.
*I can save the success files multiple times and no error occurs but If I try to save just one problematic error and the exception occurs.
This is my class responsible for managing the loaded XML and persisting
@Override
public void createProductionSet(ClientOrder clientOrder) throws Exception {
try{
List<Long> recurrent = new ArrayList<>();
ProductionOrder order = orderService.findByCodeAndClientCode(clientOrder.getOp(), clientOrder.getClientCode());
boolean newProdOrder = order == null,
hasChildrenInfo = hasChildrenInfo(clientOrder);
if(newProdOrder)
order = new ProductionOrder(clientOrder.getOp(), clientOrder.getClientCode(), clientOrder.getObservation());
order.setItems(new ArrayList<>());
if(hasChildrenInfo)
manageCollectionChildrenValues(clientOrder, order, newProdOrder, recurrent);
else
manageCollection(clientOrder, order, newProdOrder,recurrent,
loadColor(clientOrder.getColorReference(), clientOrder.getColor()),
loadMaterial(clientOrder.getMaterialReference(), clientOrder.getMaterial()),
loadProduct(clientOrder.getProductReference(), clientOrder.getProduct(), clientOrder.getUnitOfMeasurement()));
if(!newProdOrder)
prodOrderItemService.deleteNotIn(recurrent, order.getId());
orderService.save(order);
} catch(StackOverflowError t) {
throw new Exception("Erro de StackOverflowError : "+clientOrder.toString());
}catch (Exception e){
log.warn("ERRO >> "+e.getMessage());
}
}
private void manageCollection(ClientOrder clientOrder, ProductionOrder order, boolean newProdOrder, List<Long> recurrent,
MaterialColor materialColor, Material material, Product product) {
for(ItemOrder item : clientOrder.getItems()) {
item.setColorObj(materialColor);
item.setMaterialObj(material);
item.setProductObj(product);
manageItem(item, order, newProdOrder, recurrent);
}
}
private void manageCollectionChildrenValues(ClientOrder clientOrder, ProductionOrder order, boolean newProdOrder, List<Long> recurrent) {
for(ItemOrder item : clientOrder.getItems()) {
item.setColorObj(loadColor(item.getColorReference(), item.getColor()));
item.setMaterialObj(loadMaterial(item.getMaterialReference(), item.getMaterial()));
item.setProductObj(loadProduct(item.getProductReference(), item.getProduct(), clientOrder.getUnitOfMeasurement()));
manageItem(item, order, newProdOrder, recurrent);
}
}
private void manageItem(ItemOrder item, ProductionOrder order, boolean newProdOrder, List<Long> recurrent) {
ProdOrderItem aux = null;
if(!newProdOrder)
aux = prodOrderItemService.findOneByProductionOrderAndSize(order.getId(), item.getSize());
if(aux != null) {
aux.update(item);
recurrent.add(aux.getId());
}else {
aux = new ProdOrderItem(item, order);
order.getItems().add(aux);
}
}
private boolean hasChildrenInfo(ClientOrder clientOrder) {
return clientOrder.getColorReference() == null
&& clientOrder.getProductReference() == null
&& clientOrder.getMaterialReference() == null;
}
private Product loadProduct(String reference, String description, String unitOfMeasurement) {
if(reference != null && !reference.isEmpty()) {
Product product = productService.findProductByReference(reference);
if (product != null)
return product;
return productService.save(new Product(description, reference, unitOfMeasurement));
}
return productService.loadFirstOrDefault();
}
private MaterialColor loadColor(String reference, String description) {
if(reference != null && !reference.isEmpty()) {
MaterialColor materialColor = colorService.findByReference(reference);
if (materialColor != null)
return materialColor;
return colorService.save(new MaterialColor(reference, description));
}
return colorService.loadFirstOrDefault();
}
private Material loadMaterial(String reference, String description) {
if(reference != null && !reference.isEmpty()) {
Material material = materialService.findByReference(reference);
if (material != null)
return material;
return materialService.save(new Material(description, reference, null));
}
return materialService.loadFirstOrDefault();
}
}
These are my models:
@Entity(name = "production_order")
public class ProductionOrder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
private Date updated;
@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean deleted;
@Column(nullable = false, length = 30)
private String code;
@Column(length = 30)
private String clientCode;
@Column(length = 200)
private String observation;
@OneToMany(fetch = FetchType.EAGER, mappedBy ="productionOrder", orphanRemoval = true, cascade = {CascadeType.ALL})
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<ProdOrderItem> items;
...
}
@Entity(name = "order_item")
public class ProdOrderItem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, length = 10)
private String size;
@Column(nullable = false)
private float quantity;
@Column(nullable = false)
private float weight;
@Column(nullable = false)
private float tolerance;
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
private Date updated;
@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean deleted;
@ManyToOne(optional = false)
@JoinColumn(name = "product_id")
private Product product;
@ManyToOne(optional = false)
@JoinColumn(name = "color_id")
private MaterialColor color;
@ManyToOne(optional = false)
private Material material;
@ManyToOne
@JoinColumn(name = "characteristic_id")
private Characteristic characteristic;
@ManyToOne(optional = false)
@JoinColumn(name="order_id")
private ProductionOrder productionOrder;
And this is the log:
java.lang.StackOverflowError
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:131)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
at com.sun.proxy.$Proxy106.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
at org.hibernate.type.EntityType.resolve(EntityType.java:431)
at org.hibernate.type.ComponentType.resolve(ComponentType.java:687)
at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:848)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:714)
at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
at org.hibernate.loader.Loader.doQuery(Loader.java:930)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
at org.hibernate.type.EntityType.resolve(EntityType.java:431)
at org.hibernate.type.ComponentType.resolve(ComponentType.java:687)
at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:848)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:714)
at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
at org.hibernate.loader.Loader.doQuery(Loader.java:930)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:306)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:60)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:50)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
at org.hibernate.internal.SessionImpl.internalLoad(SessionImpl.java:1022)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:639)
at org.hibernate.type.EntityType.resolve(EntityType.java:431)
at org.hibernate.type.ComponentType.resolve(ComponentType.java:687)
at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:848)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:714)
at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
at org.hibernate.loader.Loader.doQuery(Loader.java:930)
at
The complete log is here, together with 2 xml files
A: The reason can be in FetchType.EAGER try to remove it:
@Entity(name = "production_order")
public class ProductionOrder {
....
@OneToMany(mappedBy ="productionOrder", cascade = {CascadeType.ALL})
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private List<ProdOrderItem> items;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44530659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Encode Trie to a file to avoid rebuilding I've constructed a Trie with about 400,000 nodes from a dictionary having about 180,000 words. The problem is that the trie is taking too long to construct on my phone.
So I've decided to create the trie once and store it in some format to the disk, for fast recreation whenever needed. But I'm unable to come up with a good format to store it.
What would be the most efficient format to encode the trie, so that it can be reconstructed from the file as fast as possible?
A: If your Trie data structure implements serializable then writing to and from a file should be fairly straight forward. Java will take care of the file representation.
See this link.
A: Maybe good idea - to keep tried in the memory buffer in the position-independent code, and read it into memory by mmap(). This is mostly quick way to work with trie from "cold start".
Also, maybe you can keep data not in the tries, but in the hashtable. By this method, you can keep in the memory only "bucket index", which is very small. And, when compute hash - pread() bucket into memory from file, and search in loaded part.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19013331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP Use array results to complete MySQL query and add results to existing array I solved the problem with both the foreach loop stopping after the first iteration, as well as it not writing to the array by adding true to the json_decode. I was unaware that that changed it from object oriented to associated.
include '/var/www/html/api/apitoken.php';
include '/var/www/html/api/secrets.php';
$data = file_get_contents('/var/www/html/api/shOrders.json'); // put the contents of the file into a variable
$shOrders = json_decode($data, true);
$con = mysqli_connect("127.0.0.1",$user,$pass,"api") or die('Could not connect: ' . mysqli_error());
$a=0;
foreach($shOrders['varID'] AS $varID) {
$sql_statement= " SELECT invTrack AS invTrack, varID AS varID, varSKU AS varSku, revelSku AS revelSku, revelInvID AS revelInvID, p.prodID AS prodID, pr.ingredient AS ing, pr.main_product AS mainProduct, pr.product AS product, i.invID AS invC, pr.qty AS QTY
FROM shopifyProd sp
LEFT JOIN product p ON sp.revelSku = p.sku AND p.location = 1
LEFT JOIN prodRecipe pr ON p.prodID = pr.main_product
LEFT JOIN inventory i ON pr.product = i.prodID
WHERE varID =" . $varID . " ; ";
//connect to mysql db and process the statement
$result = mysqli_query($con,$sql_statement);
//var_dump($sql_statement . "<br><br>");
while($row = mysqli_fetch_assoc($result)) {
echo "varID: ";
print_r($row['varID']);
echo "<br>";
if($varID == $row['varID']) {
//set correct invID for product in revel
if (!$row['invC']) {
$revInvID = ( (int) $row['revelInvID']);
}else{
$revInvID = ( (int) $row['invC']);
}
//calculate qty to change in revel
if(!$row['QTY']) {
$changeQTY = $shOrders['soldQTY'][$a];
}else{
$changeQTY = ($row['QTY'] * $shOrders['soldQTY'][$a]);
}
echo $varID . " RESULTS! -- ";
print_r("varSku: " . $shOrders['varSku'][$a]);
echo ", ";
print_r("revelInvID: " . $row['revelInvID']);
echo ", ";
print_r("soldQTY: " . $shOrders['soldQTY'][$a]);
echo ", ";
print_r("ingredient: " . $row['ing']);
echo ", ";
print_r("Product: " . $row['product']);
echo ", ";
print_r("invC: " . $revInvID);
echo ", ";
print_r("changeQTY: " . $changeQTY);
echo "<br><br>";
$shOrders['revProdID'][$a] = ( (int) $row['product']);
$shOrders['revInvID'][$a] = ( (int) $revInvID);
$shOrders['changeQTY'][$a] = ( (float) $changeQTY);
if (!mysqli_query($con, $sql_statement)) {
print_r(mysqli_error_list($con));
echo "<br>";
mysqli_close($con);
}
}
}
$a++;
set_time_limit ( 30 );
}
echo "<pre>";
print_r($shOrders);
echo "</pre>";
A: var_dump out your query just before you run it, Are all the expected parameters there? Try running that in your local db tool (mysql workbench, phpmyadmin), does it do what you like?
var_dump out the variables at each step of the way and die (or alternatively use a debugger to step through the code 1 line at a time), to see what is happening.
It doesn't look like you've declared $varID above the query.
I think you need to move
foreach($shOrders->varID AS $varID) {
above the $sql_statement = ... line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48570193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to translate Japanese response page to English in Python Selenuim How to translate Japanese response page to English in Python Selenium. As i need to scrape a Japanese site, i could'nt even extract a single text from the site because all are in Japanese.
A: Google Chrome has a built in feature that lets you translate an entire page into your language. What you could do is set the language in the application to, say, English, go to the site in Chrome and auto translate back in to your language. However this could be tricky and may require something like https://chrome.google.com/webstore/detail/google-translate/aapbdbdomjkkjkaonfhkkikfgjllcleb?hl=en google chrome extension to fulfill your requirement. You can automate this utility using autoit.
To add an extension for chrome driver, please refer to those links:
Create .CRX file and Add extension to Chrome WebDriver
A possible workaround could be if you can utilize something like these custom configs. Those Python examples, should help :
Firefox:
import os
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference('intl.accept_languages', 'es')
driver = webdriver.Firefox(profile)
Chrome:
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option( "prefs", {'--lang': 'es'})
driver = webdriver.Chrome(chrome_options=chrome_options)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42361474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Array of Strings to Convert to Mixed Array I'm trying to convert an Array of Arrays consisting of Ruby Strings into an Array of Arrays consisting of Strings and Floats.
Here is my attempt:
array = [["My", "2"], ["Cute"], ["Dog", "4"]]
array.collect! do |x|
x.each do |y|
if y.gsub!(/\d+/){|s|s.to_f}
end
end
end
=> [["My", "2.0"], ["Cute"], ["Dog", "4.0"]]
I'm looking for this to rather return [["My", 2.0], ["Cute"], ["Dog", 4.0]] What did I do wrong?
A: What you did wrong is that you used gsub!. That takes a string and changes the string. It doesn't turn it into anything else, no matter what you do (even if you convert it to a float in the middle).
A simple way to achieve what you want is:
[["My", "2"], ["Cute"], ["Dog", "4"]].map{|s1, s2| [s1, *(s2.to_f if s2)]}
If you do not want to create the element array, but replace its contents, then:
[["My", "2"], ["Cute"], ["Dog", "4"]].each{|a| a[1] = a[1].to_f if a[1]}
If the numerical strings appear in random positions, then:
[["My", "2"], ["Cute"], ["Dog", "4"]]
.each{|a| a.each.with_index{|e, i| a[i] = a[i].to_f if a[i] and a[i] =~ /\d+/}}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14828546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: django-nonrel specify MongoDB BSON element name to model attributes In C# it is possible to use the MongoDB driver to define a custom BSONElement Name to each attribute in your data models, in order to shorten its stored name, such as
[BsonElement("c")]
public Boolean Current { get; set; }
Is there any way to accomplish this with a django-nonrel setup and a model defined like
class Test(models.Model):
Current = models.BooleanField()
so that the attribute "Current" will be stored as "c" and be referenced in code as "Current"?
Research did not work very well on this one.
A: Try setting the db_column option to BooleanField, or any field -- that should be the actual field name stored in MongoDB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11201533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem connecting to MS SQL server 2000 with Spring Boot I try connect to ms sql server 2000 and I can't understand what I'm doing wrong. Unfortunately, I can not use another server. Help me please.
server image
tree
Application.properties
spring.datasource.url=jdbc:sqlserver://DESKTOP-J1EE59P\\EGOR;databaseName=dekanat
spring.datasource.username=sa
spring.datasource.password=123
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.hibernate.ddl-auto = create-drop
Grandle file
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
//compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
//compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile("org.apache.commons:commons-dbcp2:2.1.1")
compile group: 'net.sourceforge.jtds', name: 'jtds', version: '1.2'
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-security')
compile group: 'com.google.code.gson', name: 'gson', version: '1.7.2'
compile('io.jsonwebtoken:jjwt:0.9.0')
testCompile('org.springframework.boot:spring-boot-starter-test')
compileOnly "org.projectlombok:lombok:1.16.16"
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.2.4'
compile group: 'org.modelmapper', name: 'modelmapper', version: '0.7.5'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter
// compile group: 'org.springframework.boot', name: 'spring-boot-starter', version: '2.0.0.RELEASE'
// https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
testCompile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.0.0.jre8'
// https://mvnrepository.com/artifact/net.sourceforge.jtds/jtds
compile group: 'net.sourceforge.jtds', name: 'jtds', version: '1.3.1'
// https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4
testCompile group: 'com.microsoft.sqlserver', name: 'sqljdbc4', version: '4.0.0'
Errors
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot load JDBC driver class 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
A: Make sure you have following dependency on your pom.
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52855806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CGImageMaskCreate: invalid mask bits/component: 16 I am updating an old objc project.
I noticed that creating an image mask doesn't work on iOS 11 & iPhone 7
I get "CGImageMaskCreate: invalid mask bits/component: 16. " warning.
If I decrease bits per component used to 8 (which seems to be maximum) it works but quality of gradient I draw is pretty bad.
Here is my code:
- (void)_background:(CGRect)rect
{
// context for drawing
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef backgroundimage = CGBitmapContextCreateImage(context);
CGContextClearRect(context, rect);
//CGContextDrawImage(context, rect, backgroundimage);
// save state
CGContextSaveGState(context);
// flip the context (right-sideup)
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//colors/components/locations
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat black[4] = {0.0,0.0,0.0,BACKGROUND_ALPHA};
CGFloat white[4] = {1.0,1.0,1.0,1.0};//clear
CGFloat components[8] = {
white[0],white[1],white[2],white[3],
black[0],black[1],black[2],black[3],
};
CGFloat colorLocations[2] = {0.25,0.5};
// draw spotlights
NSInteger spotlightCount = _positionArray.count;
for (int i=0; i<spotlightCount; ++i)
{
// center and radius of spotlight
CGPoint c = [[_positionArray objectAtIndex:i] CGPointValue];
CGFloat radius = [[_radiusArray objectAtIndex:i] floatValue];
CGContextSaveGState(context);
//add gradient
//create the gradient Ref
CGGradientRef gradientRef = CGGradientCreateWithColorComponents(colorspace, components, colorLocations, 2);
CGContextDrawRadialGradient(context, gradientRef, c, 0.0f, c, radius*2, 0);
CGGradientRelease(gradientRef);
CGContextRestoreGState(context);
}
CGColorSpaceRelease(colorspace);
CGContextRestoreGState(context);
//convert drawing to image for masking
CGImageRef maskImage = CGBitmapContextCreateImage(context);
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskImage),
CGImageGetHeight(maskImage),
CGImageGetBitsPerComponent(maskImage),
CGImageGetBitsPerPixel(maskImage),
CGImageGetBytesPerRow(maskImage),
CGImageGetDataProvider(maskImage), NULL, NO);
//
//------> CGImageMaskCreate: invalid mask bits/component: 16.
//
//mask the background image
CGImageRef masked = CGImageCreateWithMask(backgroundimage, mask);
CGImageRelease(backgroundimage);
//remove the spotlight gradient now that we have it as image
CGContextClearRect(context, rect);
//draw the transparent background with the mask
CGContextDrawImage(context, rect, masked);
CGImageRelease(maskImage);
CGImageRelease(mask);
CGImageRelease(masked);
}
Do you have an idea?
Thanks.
A: CGImageMaskCreate is documented as “Image masks must be 1, 2, 4, or 8 bits per component.”
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46409345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Excel return cell without duplicates I have a column that uses the LOOKUP function to pull a list of names from a separate sheet within the same workbook. The list of names is concatenated using an IF function - the list is in a single cell; names are separated by commas; and some names repeat.
Is there a function that can be applied or some other excel magic that can return this list of names without duplicates?
e.g. I have a table of company names in one column and account managers in another column - the LOOKUP function pulls the list of all account managers associated with that company into one cell with names separated by commas. For example, currently, the account managers shown for "Google" (A2) are "Bob, Joe, Bob, Tom, Bob" (B2), but I would like for it to only show "Bob, Joe, Tom".
EDIT:
Each row details a specific sale.
Column A: Company (a single company can appear multiple times)
Column B: Account Manager (a single name can be associated with multiple Companies)
Column C: concatenates Account Managers into single line using formula =IF(A2=A1,C1&", " & B2,B2)
Every time new data is added, the entire sheet is sorted A-Z by Company. The goal of the concatenation is to have ALL Account Managers associated with that particular company in one cell so that that cell can be referenced in the table mentioned above, which appears on a separate sheet in this workbook; however, if that AM has made multiple sales for the same company, the formula still adds it to the final list, which can result in a list of "Bob, Joe, Bob, Tom, Bob" when I want to see "Bob, Joe, Tom".
The formula I use in the table to reference this list of AMs for each company is =LOOKUP(A5,'7.1.16 data'!A:A,'7.1.16 data'!C:C)
A: Just add a SEARCH query in your IF statement:
=IF(A2=A1,IF(ISNUMBER(SEARCH(B2, C1)), C1, C1 &", " & B2),B2)
Regards
Cg
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38207807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cancelling Http connection in android I am using org.apache.http and I've this code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse resp = client.execute(get);
HttpEntity entity = resp.getEntity();
InputStream input = entity.getContent();
...
//Read the bytes from input stream
This is the code I am using to download files over Http, I want to cancel the connection(may be user chooses to) What is the graceful way to close the connection. I found 2 ways, Both cancels the download.
*
*Closing inputsteram, input.close(); which causes IOException.
*Aborting HttpGet object, get.abort() causes SocketException.
I have try catch, so no erros, but without throwing exception,
is there a way to cancel or abort the connection?
What is the right way to go about it ?
A: The proper way doing this is sending FIN value to the server side.
How ever in android you do not have the option to be involved in this level, so you can implement by your self using C, or use one of the methods you mention in your question.
A: Using HttpUriRequest#about is the right way in my opinion. This will cause immediate termination of the underlying connection and its eviction from the connection pool. Newer versions of HttpClient (4.2 and newer) intercept SocketExceptions caused by premature request termination by the user. The problem is that Google ships a fork of HttpClient based on an extremely outdated version (pre-beta1). If you are not able or willing to use a newer version of HttpClient your only option is to catch and discard SocketException in your code.
A: Use this
client.getConnectionManager().closeExpiredConnections();
client.getConnectionManager().shutdown();
Now you can decide where would you like to write these 2 lines in code.. It will close the connection using the DefaultHttpClient object that you created.
Let me know if this helps you.
A: Try to cancel the task when you want to interrupt the connection:
task.cancel(true);
This will cancel the task and the threads running in it.
Check this for reference:
public final boolean cancel (boolean mayInterruptIfRunning)
Since: API Level 3
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
Calling this method will result in onCancelled(Object) being invoked on the UI thread after doInBackground(Object[]) returns. Calling this method guarantees that onPostExecute(Object) is never invoked. After invoking this method, you should check the value returned by isCancelled() periodically from doInBackground(Object[]) to finish the task as early as possible.
Parameters
mayInterruptIfRunning true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
Returns
false if the task could not be cancelled, typically because it has already completed normally; true otherwise
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7291854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: jQuery Remote validation for multiple fields I have a form with two fields User ID and Email ID. I am trying to validate value of each field is already taken or not using same php file with jQuery remote validation.
But my confusion is how should be the remote file in my case (validate.php). How it can determine the fields.
My code looks like:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Validationt</title>
<script type="text/javascript">
$(document).ready(function(){
$("form").validate({
rules: {
userid: {
required: true,
remote: {
url: "validate.php",
type: "post",
}
}
emailid: {
required: true,
remote: {
url: "validate.php",
type: "post",
}
}
},
messages: {
userid: {
remote: jQuery.validator.format("userid {0} is already taken")
}
emailid: {
remote: jQuery.validator.format("emailid {0} is already taken")
}
}
});
});
</script
</head>
<body>
<form method="post" id="form" action="">
<input id="userid" name="userid" type="text" />
<input id="emailid" name="emailid" type="text" />
<input type="submit" name="submit" id="submit"/>
</form>
</body>
</html>
Any help ?
A: Like,
//validate.php
//get the post fields
$email_address = trim( $_POST["emailid"] );
//check if email exists against database, like
if( is_valid_from_db( $email_address ) ) {
return TRUE;
}
else {
return FALSE;
}
A: I am sure you have looked at the docs:
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
validate.php just needs to do what it says validate the fields.
This other question might be of some help:
jQuery Remote validation
A: I was also looking for an answer for this problem of validating multiple fields with remote method.
To determine each field separately, you don't have to define remote method for each field. Whereas you can define remote method for your 'emailid' field and you can send 'userid' alongside the emailid using data option as follows.
emailid: {
required: true,
remote: {
url: "validate.php",
type: "post",
data: {
userid: function() {
return $("#userid").val();
}
}
}
}
So you can have your js like this
<script type="text/javascript">
$(document).ready(function(){
$("form").validate({
rules: {
userid: {
required: true
}
emailid: {
required: true,
remote: {
url: "validate.php",
type: "post",
data: {
userid: function() {
return $("#userid").val();
}
}
}
}
},
messages: {
userid: {
remote: jQuery.validator.format("userid {0} is already taken")
}
emailid: {
remote: jQuery.validator.format("emailid {0} is already taken")
}
}
});
});
</script>
The above will post userid and emailid to your validate.php where you can follow DemoUser's answer. But make sure the returning values (true/false) are string values
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14354322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Phone Number Formatting Python Whenever i run my program is print the number 10 randomly and i don't know where its coming from. Anyone help me out?
def main():
phoneNumber=int(input("Enter a 10 digit unformatted telephone number in the format ##########: "))
tempNumber = []
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index=0
print(length)
if (length ==10):
print("The unformatted number is: ",phoneNumber)
else:
print("The telephone number was NOT entered in unformatted format ##########.")
for num in phoneNumber:
tempNumber.append(num)
tempNumber.insert(0,"(")
tempNumber.insert(4,")")
tempNumber.insert(8,"-")
phoneNumber = ''.join(tempNumber)
print("The formatted number is: ",phoneNumber)
main()
A: You are printing the length of the input given by user, so that's why 10 is printed out (see statement no. 6 inside main() function).
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index = 0
print(length) # <--- this statement is printing the length of the input
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41108685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: C# Date in CSV file I have to change a csv file with several dates in it. Every row starts with a date followed whith data.
11-nov-2015,data,data,data
10-nov-2015,data,data,data
9-nov-2015,data,data,data
With the following code I put the data in the right place (20141109 (yyyymmdd))
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
string[] parts = values[0].Split('-');
if (parts.Length == 3)
{
values[0] = String.Format("{0}-{1}-{2}", parts[2], parts[1], parts[0]);
lines1[i] = String.Join(",", values);
}
}
But two problems remain:
1) The month has to change from nov to 11
2) In the file I download the day for example 9-nov-2014 has to change to 09. for 8-nov-2014 to 08. So an extra 0.
How can this be solved in C#
A: Instead of making your own datetime format parser, you should use the one already available for you. DateTime.TryParseExact is your tool to convert a string in a date when you know the exact format.
Converting back the date, in the string format that you like, is another task easily solved by the override of ToString() specific for a datetime
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
DateTime dt;
if (DateTime.TryParseExact(values[0], "d-MMM-yyyy",
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None, out dt))
{
values[0] = dt.ToString("yyyyMMdd");
lines1[i] = String.Join(",", values);
}
}
A: I would parse the string into a date and then write it back using a custom date format. From this link we can write this code:
String pattern = "dd-MMM-yyyy";
DateTime dt;
if (DateTime.TryParseExact(values[0], pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt)) {
// dt is the parsed value
String sdt = dt.ToString("yyyyMMdd"); // <<--this is the string you want
} else {
// Invalid string, handle it as you see fit
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33986313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cassandra 2.2.11 add new map column from text column Let's say I have table with 2 columns
primary key: id - type varchar
and non-primary-key: data - type text
Data column consist only of json values for example like:
{
"name":"John",
"age":30
}
I know that i can not alter this column to map type but maybe i can add new map column with values from data column or maybe you have some other idea?
What can i do about it ? I want to get map column in this table with values from data
A: You might want to make use of the CQL COPY command to export all your data to a CSV file.
Then alter your table and create a new column of type map.
Convert the exported data to another file containing UPDATE statements where you only update the newly created column with values converted from JSON to a map. For conversion use a tool or language of your choice (be it bash, python, perl or whatever).
BTW be aware, that with map you specify what data type is your map's key and what data type is your map's value. So you will most probably be limited to use strings only if you want to be generic, i.e. a map<text, text>. Consider whether this is appropriate for your use case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49556740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Inconsistent outputs from Scala Spark and pyspark job I am converting my Scala code to pyspark like below, but got different counts for the final RDD.
My Scala code:
val scalaRDD = rowRDD.map {
row: Row =>
var rowList: ListBuffer[Row] = ListBuffer()
rowList.add(row)
(row.getString(1) + "_" + row.getString(6), rowList)
}.reduceByKey{ (list1,list2) =>
var rowList: ListBuffer[Row] = ListBuffer()
for (i <- 0 to list1.length -1) {
val row1 = list1.get(i);
var foundMatch = false;
breakable {
for (j <- 0 to list2.length -1) {
var row2 = list2.get(j);
val result = mergeRow(row1, row2)
if (result._1) {
list2.set(j, result._2)
foundMatch = true;
break;
}
} // for j loop
} // breakable for j
if(!foundMatch) {
rowList.add(row1);
}
}
list2.addAll(rowList);
list2
}.flatMap { t=> t._2 }
where
def mergeRow(row1:Row, row2:Row):(Boolean, Row)= {
var z:Array[String] = new Array[String](row1.length)
var hasDiff = false
for (k <- 1 to row1.length -2){
// k = 0 : ID, always different
// k = 43 : last field, which is not important
if (row1.getString(0) < row2.getString(0)) {
z(0) = row2.getString(0)
z(43) = row2.getString(43)
} else {
z(0) = row1.getString(0)
z(43) = row1.getString(43)
}
if (Option(row2.getString(k)).getOrElse("").isEmpty && !Option(row1.getString(k)).getOrElse("").isEmpty) {
z(k) = row1.getString(k)
hasDiff = true
} else if (!Option(row1.getString(k)).getOrElse("").isEmpty && !Option(row2.getString(k)).getOrElse("").isEmpty && row1.getString(k) != row2.getString(k)) {
return (false, null)
} else {
z(k) = row2.getString(k)
}
} // for k loop
if (hasDiff) {
(true, Row.fromSeq(z))
} else {
(true, row2)
}
}
I then tried to convert them to pyspark code as below:
pySparkRDD = rowRDD.map (
lambda row : singleRowList(row)
).reduceByKey(lambda list1,list2: mergeList(list1,list2)).flatMap(lambda x : x[1])
where I have:
def mergeRow(row1, row2):
z=[]
hasDiff = False
#for (k <- 1 to row1.length -2){
for k in xrange(1, len(row1) - 2):
# k = 0 : ID, always different
# k = 43 : last field, which is not important
if (row1[0] < row2[0]):
z[0] = row2[0]
z[43] = row2[43]
else:
z[0] = row1[0]
z[43] = row1[43]
if not(row2[k]) and row1[k]:
z[k] = row1[k].strip()
hasDiff = True
elif row1[k] and row2[k] and row1[k].strip() != row2[k].strip():
return (False, None)
else:
z[k] = row2[k].strip()
if hasDiff:
return (True, Row.fromSeq(z))
else:
return (True, row2)
and
def singleRowList(row):
myList=[]
myList.append(row)
return (row[1] + "_" + row[6], myList)
and
def mergeList(list1, list2):
rowList = []
for i in xrange(0, len(list1)-1):
row1 = list1[i]
foundMatch = False
for j in xrange(0, len(list2)-1):
row2 = list2[j]
resultBool, resultRow = mergeRow(row1, row2)
if resultBool:
list2[j] = resultRow
foundMatch = True
break
if foundMatch == False:
rowList.append(row1)
list2.extend(rowList)
return list2
BTW, rowRDD is converted from a data frame. i.e. rowRDD = myDF.rdd
However, I got different counts for scalaRDD and pySparkRDD. I checked the codes many times but couldn't figure out what I missed. Does anyone have any ideas? Thanks!
A: Consider this:
scala> (1 to 5).length
res1: Int = 5
and this:
>>> len(xrange(1, 5))
4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37473615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: GroupBy first result of lookup table in Entity Framework Core I'm trying to get the total Man Days worked by volunteers per section between a date range. There is an attendance table which includes the day and the member id to map to the member table. There is also a section table to list all the sections and a membertosection table as a member can be in more than one section.
I want to group by the first section a member is in and then have a count of all the attendance days for that section.
The following works perfectly where I'm grouping by a 1 to many field (Category) on the members table but I can't work out how to change this to the first section (If the member has a section)
var result = await _context.Attendance
.Where(p => p.Day >= firstDayOfLastQuarter && p.Day <= lastDayOfLastQuarter)
.GroupBy(p => p.Member.Category.Name)
.Select(p => new { key = p.Key, count = p.Count() })
.ToListAsync();
I'm looking for something like
var result = await _context.Attendance
.Where(p => p.Day >= firstDayOfLastQuarter && p.Day <= lastDayOfLastQuarter && p.Member.MemberToSection.Any(s => s.MemberId == p.MemberId))
.GroupBy(p => p.Member.MemberToSection.First().Section.Name)
.Select(p => new { key = p.Key, count = p.Count() })
.ToListAsync();
Update
T-Sql code that produces the desired result is
SELECT Count(*) as Total, Section.Name
FROM Attendance
LEFT JOIN Member on Attendance.Member_Id = Member.Id
OUTER APPLY (
SELECT TOP(1) sec.id, sec.Name
FROM MemberToSection m2s
LEFT JOIN Section sec ON m2s.Section_Id = sec.Id
WHERE m2s.Member_Id = Member.Id
) as Section
WHERE Attendance.Day >= '2016-10-01' AND Attendance.Day <= '2016-12-31'
GROUP BY Section.Name
The "something like" code returns the error
An unhandled exception occurred while processing the request.
ArgumentException: Property 'System.String Name' is not defined for type 'Microsoft.EntityFrameworkCore.Storage.ValueBuffer'
Classes
As requested here are the relevant classes
Attendance.cs
public partial class Attendance
{
public long Pk { get; set; }
public int MemberId { get; set; }
public DateTime Day { get; set; }
public virtual Member Member { get; set; }
}
Member.cs
public partial class Member
{
public Member()
{
MemberToSection = new HashSet<MemberToSection>();
}
public int Id { get; set; }
public int? CategoryId { get; set; }
public virtual ICollection<MemberToSection> MemberToSection { get; set; }
}
MemberToSection.cs
public partial class MemberToSection
{
public int SectionId { get; set; }
public int MemberId { get; set; }
public virtual Member Member { get; set; }
public virtual Section Section { get; set; }
}
Section.cs
public partial class Section
{
public Section()
{
MemberToSection = new HashSet<MemberToSection>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<MemberToSection> MemberToSection { get; set; }
}
A: The (currently combined) EF documentation starts with Compare EF Core & EF6.x section which contains the very "useful" topic Which One Is Right for You. Well, looks like EF Core is not for you (yet). The following applies to latest at this time EF Core v1.1.0.
First, GroupBy (even by simple primitive property) is always processed in memory.
Second, there are a lot of internal bugs causing exceptions when processing pretty valid LINQ queries like yours.
Third, after some trial and error, the following equivalent construct works for your case (at least does not generate exceptions):
.GroupBy(p => p.Member.MemberToSection.Select(m => m.Section.Name).FirstOrDefault())
(btw, irrelevant to the issue, the s => s.MemberId == p.MemberId condition inside the p.Member.MemberToSection.Any call is redundant because it is enforced by the relationship, so simple Any() would do the same.)
But now not only the GroupBy is performed in memory, but also the query is causing N + 1 SQL queries similar to EF Core nested Linq select results in N + 1 SQL queries. Congratulations :(
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41569461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use layers or invoke another lambda? I have a module that maintains a connection instance to a redis server:
const getClient = (() => {
let client;
return () => {
if (!client) client = clientFactory(); // lazy loading of the redis client
return client;
}
})();
And this module is intended to be deployed on AWS Lambda. As per best practices suggest, the redis client in the closure above shall never be destroyed manually in favour of context reuse, and will be automatically destroyed when the lambda invocation instance is killed.
Now the problem is: I have some other modules, which will also be deployed on lambda as separate lambda functions, and will need to utilize the redis client module. Should I set the redis module as a reusable layer, or should I deploy the module as yet another separate function, and directly invoke the function from the calling modules?
Concerns for using layer: the redis connection will be instantiated for every separate calling module, which is not good for context reuse.
Concerns for invoking another lambda function: network overhead.
As I understand invocation between two lambda functions, the caller will send an API request to the callee, producing extra network overhead. So will this matter more than poor context reusing?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54918307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to delete a specific cell in a csv file when the contents is said in an input in python elif addordelete = "delete":
whichdelete = input("What thing do you want to delete? ")
GameCharacter.csv
I want to know how to delete a specific cell in a csv file through a python input.
For example if the user in the python program says that they want to delete MP40 from the file, then it should delete. Can someone explain how to do this in simple terms as possible (I'm kind of a python noob. Code is appreciated.
A: You'll have to import the whole CSV into python, process it and saving it back to file.
Here's a simple snippet which opens the CSV, processes it asking what you want to delete, then saves it back again.
You can start from this code to get what you need.
import csv
try:
csvfile = open('testcsv.csv','rb')
table = [row for row in csv.reader(csvfile)] #further parameters such as delimiters on doc
whichdelete = whichdelete = input("What thing do you want to delete? ")
header = table.pop(0) #remove header and save it to header variable
res = [row for row in table if whichdelete not in row] #save result without the row you want to delete
csvfile.close()
except IOError:
print "File not found"
quit()
try:
resultFile = open('resultCSV.csv','wb+')
writer = csv.writer(resultFile)
writer.writerow(header)
for row in res:
writer.writerow(row)
resultFile.close()
except IOError:
print "Error creating result file"
quit()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44717609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OOP Javascript, get instance name I have an object and I write the instance:
var table1=new searchTable(someoptions)
Is there anyway to get "table1" programatically from inside the object?
A: No. Objects have no knowledge of what variables and properties (there can be multiple) they are assigned to.
A: There is absolutely no way of doing this.
When you do
LHS = RHS
RHS has no clue of what its result is going to be assigned to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15831415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: c# Model abstraction and generics, cast unknown generic like Java Basic Java way
class SomeModelController {
public void makeSomeRequest<T extends BaseJsonClass>(Type type, RequestCallback requestCallback) {
// Do request stuff.
requestCallback.success(Type.cast(sucessObject));
}
}
// Some code
ModelController.makeRequest<UserLoginResponse>(UserLoginResponse.class, new RequestCallback() {
public void success(UserLoginResponse sucessObject) {
// Object is now treated like response.
}
}
I'm aware that C# does not have a type erasor; so I can just use T (Generic as is?)
My C# class and where I'm struggling:
public class Response<T> {
private Action<T> success;
private Action<FailedReason> failed;
public Response(Action<T> success, Action<FailedReason> failed) {
this.success = success;
this.failed = failed;
}
public void Success<T>(T objectSuccess) {
// ?? How to convert success object to type?
success.Invoke(objectSuccess);
}
public void Failed(FailedReason failedReason) {
failed.Invoke(failedReason);
}
}
Edit 1
I'm getting the following complaint from the compiler:
I'm getting "Cannot implicitly convert T to T" when trying to compile.
A: You can simply call
public void Success(T objectSuccess) {
success(objectSuccess);
}
objectSuccess is of type T. That's exactly what Action<T> success expects as parameter. No conversion is required.
You can think of success as being a method declared like this:
void success(T arg)
{
}
And as Jorn Vernee says, remove <T> from Success<T>. You don't need a generic type parameter for this method, as it uses the generic type parameter of the class. If for some reason you need different generic type parameters for class and method, you must give them different names. But that's not the case here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38040485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to speedup the Chromium loading process under puppeteer, bypass the proxy check When using puppeteer, the Chromium page loading speed is sensibly slow than loading in a normal Chrome.
I can notice some text on the status bar about proxy, which is not seen in a normal Chrome.
Any way to speedup the puppeteer Chromium page laoding? It is a few seconds, but many times.
A: puppeteer Chromium do the proxy check by default, which is a waste of time if you do not use proxy.
Can disable it by
const browser = await puppeteer.launch({
headless: false,
args: ["--proxy-server='direct://'", '--proxy-bypass-list=*'],
});
then it will as fast as normal Chrome
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63893507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: enumerate days of week in t-sql Is anybody to know how to enumerate all week's days in T-SQL, so that we have in the ouput a string like: 'Sunday, Monday, Tuesday, ...'
A: WITH week (dn) AS
(
SELECT 1
UNION ALL
SELECT dn + 1
FROM week
WHERE dn < 7
)
SELECT DATENAME(dw, dn + 5)
FROM week
Replace dn + 5 with dn + 6 if your week starts from Monday.
If you need a single comma separated string instead of a set, use this:
WITH week (dn, dname) AS
(
SELECT 1, CAST(DATENAME(dw, 6) AS NVARCHAR(MAX))
UNION ALL
SELECT dn + 1, dname + ', ' + DATENAME(dw, dn + 6)
FROM week
WHERE dn < 7
)
SELECT dname
FROM week
WHERE dn = 7
A: A straight select that will work with any SET DATEFIRST setting
select
datename(dw, 6-@@datefirst) + ', ' +
datename(dw, 1+6-@@datefirst) + ', ' +
datename(dw, 2+6-@@datefirst) + ', ' +
datename(dw, 3+6-@@datefirst) + ', ' +
datename(dw, 4+6-@@datefirst) + ', ' +
datename(dw, 5+6-@@datefirst) + ', ' +
datename(dw, 6+6-@@datefirst)
If you don't care about region (Monday or Sunday as first day of week), then just
select
datename(dw, 0) + ', ' + datename(dw, 1) + ', ' +
datename(dw, 2) + ', ' + datename(dw, 3) + ', ' +
datename(dw, 4) + ', ' + datename(dw, 5) + ', ' +
datename(dw, 6) + ', '
It will perform much better than going through CTE and will also work in 2000 should you ever need it.
A: The fastest means is to statically define the comma separated list. I don't know if SET DATEFIRST affects only the database -- if it's the entire instance, I would really hesitate to use SET DATEFIRST.
Rather than using recursion, you can use the values from MASTER..SPT_VALUES, and a combination of the STUFF and FOR XML PATH functions (Caveat: SQL Server 2005+):
Week starting on Sunday:
SELECT STUFF((SELECT ', ' + x.wkday_name
FROM (SELECT DISTINCT DATENAME(dw, t.number) AS wkday_name,
t.number
FROM MASTER.dbo.SPT_VALUES t
WHERE t.number BETWEEN -1 AND 5) x
ORDER BY x.number
FOR XML PATH ('')), 1, 2, '')
Week starting on Monday:
SELECT STUFF((SELECT ', ' + x.wkday_name
FROM (SELECT DISTINCT DATENAME(dw, t.number) AS wkday_name,
t.number
FROM MASTER.dbo.SPT_VALUES t
WHERE t.number BETWEEN 0 AND 6) x
ORDER BY x.number
FOR XML PATH ('')), 1, 2, '')
Comparison:
The statically defined list won't return a query plan for me on SQL Server 2005. Quassnoi's recursion example on 2005 has a subtree cost of 0.0000072; SPT_VALUES has a subtree cost of 0.0158108. So the recursive approach is appears more efficient than SPT_VALUES -- possibly due to the very small size?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4804294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Docker - failed to compute cache key: not found - runs fine in Visual Studio I've generated a Dockerfile with Visual Studio. It runs in Visual Studio just fine and now I'm trying to build it from Windows itself (docker build ., and I tried many combinations). Yet I get the following error:
When I change copy to ./client.csproj it does continue and then I get:
What am I doing wrong? I changed Docker Linux to Windows, changed WSL, and restarted everything.
Dockerfile client
A: The following command was failing with failed to compute cache key: not found:
docker build -t tag-name:v1.5.1 - <Dockerfile
Upon changing the command to the following it got fixed:
docker build -t tag-name:v1.5.1 -f Dockerfile .
A: In my case I found that docker build is case sensitive in directory name, so I was writing /bin/release/net5.0/publish in the COPY instruction and failed with the same error, I've just changed to /bin/Release/net5.0/publish and it worked
A: Error : failed to compute cache key: "src" not found: not found
in my case , folder/file excluded in .dockerignore
*
*after resolving file from dockerignore able to create image.
A: In my case, I had something like this:
FROM mcr.microsoft.com/dotnet/aspnet:5.0
COPY bin/Release/net5.0/publish/ app/
WORKDIR /app
ENTRYPOINT ["dotnet", "MyApi.dll"]
And I finally realized that I had the bin folder in my .dockerignore file.
A: Check your .dockerignore file. Possible it ignores needed files for copy command and you get failed to compute cache key error.
.dockerignore may be configured to minimize the files sent to docker for performance and security:
*
!dist/
The first line * disallows all files. The second line !dist/ allows the dist folder
This can cause unexpected behavior:
FROM nginx:latest
# Fails because of * in .dockerignore
# failed to compute cache key: "/nginx.conf.spa" not found: not found
# Fix by adding `!nginx.conf.spa` to .dockerignore
COPY nginx.conf.spa /etc/nginx/nginx.conf
RUN mkdir /app
# Works because of !dist/ in .dockerignore
COPY dist/spa /app
Belts and suspenders.
A: I had the same issue, I set the Docker environment to Windows in when adding Docker support. Even running in Visual Studio threw error to that. I changed the environment to Linux as my Docker is running in the Windows Subsystem for Linux (WSL).
Then I moved back to the terminal to run the commands.
I was able to resolve this by moving to the Solutions folder (Root folder).
And I did docker build like this:
docker build -t containername/tag -f ProjectFolder/Dockerfile .
Then I did docker run:
docker run containername/tag
A: The way Visual Studio does it is a little bit odd.
Instead of launching docker build in the folder with the Dockerfile, it launches in the parent folder and specifies the Dockerfile with the -f option.
I was using the demo project (trying to create a minimal solution for another question) and struck the same situation.
Setup for my demo project is
\WorkerService2 ("solution" folder)
+- WorkerService2.sln
+- WorkserService2 ("project" folder)
+- DockerFile
+- WorkerService2.csproj
+- ... other program files
So I would expect to go
cd \Workerservice2\WorkerService2
docker build .
But I get your error message.
=> ERROR [build 3/7] COPY [WorkerService2/WorkerService2.csproj, WorkerService2/] 0.0s
------
> [build 3/7] COPY [WorkerService2/WorkerService2.csproj, WorkerService2/]:
------
failed to compute cache key: "/WorkerService2/WorkerService2.csproj" not found: not found
Instead, go to the parent directory, with the .sln file and use the docker -f option to specify the Dockerfile to use in the subfolder:
cd \Workerservice2
docker build -f WorkerService2\Dockerfile --force-rm -t worker2/try7 .
docker run -it worker2/try7
Edit (Thanks Mike Loux, tblev & Goku):
Note the final dot on the docker build command.
For docker the final part of the command is the location of the files that Docker will work with. Usually this is the folder with the Dockerfile in, but that's what's different about how VS does it. In this case the dockerfile is specified with the -f. Any paths (such as with the COPY instruction in the dockerfile) are relative to the location specified. The . means "current directory", which in my example is \WorkerService2.
I got to this stage by inspecting the output of the build process, with verbosity set to Detailed.
If you choose Tools / Options / Projects and Solutions / Build and Run you can adjust the build output verbosity, I made mine Detailed.
Edit #2 I think I've worked out why Visual Studio does it this way.
It allows the project references in the same solution to be copied in.
If it was set up to do docker build from the project folder, docker would not be able to COPY any of the other projects in the solution in. But the way this is set up, with current directory being the solution folder, you can copy referenced projects (subfolders) into your docker build process.
A: Asking for a directory that does not exist throws this error.
In my case, I tried
> [stage-1 7/14] COPY /.ssh/id_rsa.pub /.ssh/:
------
failed to compute cache key: "/.ssh/id_rsa.pub" not found: not found
I had forgotten to add the /.ssh folder to the project directory. In your case you should check whether /client is really a subfolder of your Dockerfile build context.
A: I had the same issue. In my case there was a wrong directory specified.
My Dockerfile was:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS publish
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o publish/web src/MyApp/MyApp.csproj
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish publish/web .
EXPOSE 80
CMD ASPNETCORE_URLS=http://*:$PORT dotnet MyApp.dll
Then I realised that in the second build stage I am trying to copy project files from directory publish/web:
COPY --from=publish publish/web .
But as I specified workdir /app in the first stage, my files are located in that directory in image filesystem, so changing path from publish/web to app/publish/web resolved my issue.
So my final working Dockerfile is:
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS publish
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o publish/web src/MyApp/MyApp.csproj
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=publish app/publish/web .
EXPOSE 80
CMD ASPNETCORE_URLS=http://*:$PORT dotnet MyApp.dll
A: In my case there was a sneaky trailing whitespace in the file name.
------
> [3/3] COPY init.sh ./:
------
failed to compute cache key: "/init.sh" not found: not found
So the file was actually called "init.sh " instead of "init.sh".
A: I had a similar issues: Apparently, docker roots the file system during build to the specified build directory for security reasons. As a result, COPY and ADD cannot refer to arbitrary locations on the host file system. Additionally, there are other issues with syntax peculiarities. What eventually worked was the following:
COPY ./script_file.sh /
RUN /script_file.sh
A: I had faced the same issue.
The reason was the name of the DLL file in the Docker file is case sensitive.
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY MyFirstMicroService.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:5.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "**MyFirstMicroService.dll**"]
This .dll name should match your .csproj file.
A: This also happens when you don't provide the proper path to your COPY command input. The most important clue I had is that WORKDIR command opens a folder for the container, not in the windows explorer (so it doesn't affect the path you need to specify for the COPY command).
A: In my Case,
i was doing mistake in '/' and ''. Let me explain
Open your dockerfile (it should be named as dockerfile only, not DockerFile or Dockerfile).
You may have something like this-
FROM mcr.microsoft.com/dotnet/runtime:5.0
COPY bin\Release\net5.0\publish .
ENTRYPOINT ["dotnet", "HelloDocker.dll"]
Replace COPY bin\Release\net5.0\publish . to COPY bin/Release/net5.0/publish .
A: in my case, it was a wrong Build with PATH configuration e.g. Docker build context
*
*Simple docker script
docker build .
where . is path to build context
*Gradle+Docker
docker {
dependsOn build
dependsOn dockerFilesCopy
name "${project.name}:${project.version}"
files "build" // path to build context
}
*Gradle+GitHub action
name: Docker build and push
on:
push:
branches: [ main ]
# ...
jobs:
build:
runs-on: ubuntu-latest
# ...
steps:
- name: Checkout
uses: actions/checkout@v2
# ...
- name: Build and export to Docker
uses: docker/build-push-action@v2
with:
# ...
file: src/main/docker/Dockerfile
context: ./build # path to build context
A: In my case, with Angular project, my project was in the folder called ex: My-Folder-Project and I was putting on Dockerfile COPY --from=publish app/dist/My-Folder-Project .
But of course the correct thing is put the "name" in your package.json like COPY --from=publish app/dist/name-in-package.json .
A: In my case I changed context, and path of Dockerfile within docker-compose.yml config:
services:
server:
# inheritance structru
extends:
file: ../../docker-compose.server.yml
# I recommend you to play with this paths
build:
context: ../../
dockerfile: ./apps/${APP_NAME}/Dockerfile
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66146088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "183"
}
|
Q: Is it possible to create Realm class without default values for parameters? I understand that this is not possible with Kotlin because Realm needs an empty constructor.
However, this creates an issue that we may accidentally create a RealmObject without setting all the required fields. Hence, the purpose of required fields is lost.
I was wondering if someone has found a way around this Realm limitation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61267725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to convert an audio file like mp3 to an mo3 file? I am trying to make a game and I need to convert an audio file like mp3, ogg or whatever to an mo3 file.
A: You can compress XM, S3M, IT and MOD files to MO3.
There is no way to convert MP3, WAV, OGG or FLAC to MO3, because the way of saving the audio is fundamentally different. It's like giving your computer a cd and asking it to write out the notes for all instruments, the lyrics and special effects.
Maybe this can help you, as somebody finds some hackings... http://www.un4seen.com/forum/?topic=1953.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41207912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: how to convert the numeric into indian currency format in oracle sql suppose i have column money say its value is eg:880856.00 i need a query to format this money column like this 8,80,856.00
A: You can use to_char to format characters.
So, for the format you have specified
to_char(money, '9,99,999.99' );
Would return 8,80,856.00
example
It should be noted that this is simply the length of the string provided in the first answer, and a longer second argument can be provided to properly format the number as desired.
So:
to_char(11111111111111.11, '9,99,999,99,9,99,999.99')
Would return 1,11,111,11,1,11,111.11
extra length example
This will also automatically adjust for the number of digits provided in the first argument, for instance:
to_char(5856.00, '9,99,999.99');
Would return 5,856.00
example 2
From the Oracle docs:
https://www.oradev.com/oracle_number_format.jsp
Here's an old stackoverflow post on the topic: oracle sql query to format number by comma
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70075779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I create different captions for each image using StaggeredGridView? Under each image I would like the caption/card to say something different.
How can I achieve this?
I saw someone add ['url', "Some text"], in their String to have the text overlay the image but I can't find it now and I couldn't get it to work either.
This is what I've managed to do...
class Water extends StatefulWidget {
const Water({Key key}) : super(key: key);
@override
_WaterState createState() => _WaterState();
}
class _WaterState extends State<Water> {
List<String> imageList = [
'https://i.pinimg.com/564x/bf/49/c6/bf49c6b37ab4be93bb77895ab777cee1.jpg',
'https://i.pinimg.com/564x/4e/4e/72/4e4e72a411e829ee47dd3e3c96450b1a.jpg',
];
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Expanded(
child: Text(
'Water',
style: TextStyle(
fontSize: 30,
color: Colors.blue),
)),
],
),
AnimatedContainer(
duration: Duration(milliseconds: 500),
width: Profile.width,
child: Expanded(
child: Container(
child: StaggeredGridView.countBuilder(
shrinkWrap: true,
primary: false,
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 12,
itemCount: imageList.length,
itemBuilder: (context, index) {
return Card(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero,
),
child: Column(
children: [
FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: imageList[index],
fit: BoxFit.cover),
Text(
'Some Text',
),
],
),
);
},
staggeredTileBuilder: (index) {
return StaggeredTile.fit(1);
A: define a model
class ImageItemModel{
String imagePath;
String title;
ImageItemModel(this.imagePath, this.title)
///other things you want.
}
and use it like below
List<ImageItemModel> list = [
ImageItemModel("Url0","title0"),
ImageItemModel("Url1","title1"),
ImageItemModel("Url2","title2"),
];
and you can access each item like this
print(list[1].title) /// prints title1
so this part of your code will changes like this
FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: list[index].imagePath,
fit: BoxFit.cover),
Text(
list[index].title,
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70465548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual Studio Code exit button position Does someone know why the Exit button is on the left where's the Menu Bar? Someone know how to fix this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73743946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Identify last group in a LOOP AT ... GROUP BY? I'm looking for the equivalent of the AT LAST statement within the LOOP AT ... GROUP BY statement.
I'm looping using group by, and for performance reasons, I execute a call method every few groups, when a certain amount of records has been accumulated into an internal table. But I would like to add an extra condition to run this call at the end of the loop, if I'm in the last group.
Below I wrote a piece of executable code simulating my problem, I would like to process my last material before exiting the loop.
constants: processing_size_threshold type i value 10.
types: begin of ty_material,
material_num type c length 3,
end of ty_material.
data: materials type standard table of ty_material,
materials_bom type standard table of ty_material.
materials = value #( for i = 1 then i + 1 while i <= 3
( material_num = conv #( i ) ) ).
loop at materials reference into data(material_grp) group by material_grp->material_num.
loop at group material_grp reference into data(material).
materials_bom = value #( base materials_bom (
lines of value #( for j = 1 then j + 1 while j <= 5
( material_num = |{ material->material_num }{ j }| ) ) ) ).
endloop.
"The 2nd condition of this IF is what I'm not able to figure out, I need material 3 BOM to be processed here
if lines( materials_bom ) >= processing_size_threshold. "or group_num = last_group.
"me->process_boms(materials_bom).
clear materials_bom.
endif.
endloop.
A: First: it is better to put real-world examples than just nonsensical tables filled with random numeric buzz like you did. You may just get the wrong answers that way.
If you want to process just the last group, you can use the GROUP INDEX for this:
SELECT matnr AS matno
FROM vbap UP TO 100 ROWS
INTO TABLE @DATA(materials)
ORDER BY matnr.
TYPES: ty_mats LIKE materials.
DATA: bom LIKE materials.
DATA(uniques) = lines( VALUE ty_mats( FOR GROUPS value OF <line> IN materials GROUP BY ( matno = <line>-matno ) WITHOUT MEMBERS ( value ) ) ).
LOOP AT materials REFERENCE INTO DATA(refmat) GROUP BY ( id = refmat->matno size = GROUP SIZE gi = GROUP INDEX ) ASCENDING REFERENCE INTO DATA(group_ref).
CHECK group_ref->*-gi = uniques.
bom = VALUE ty_mats( BASE bom FOR <mat> IN GROUP group_ref ( matno = <mat>-matno ) ).
me->process_boms( bom ). "<--here comes the drums
ENDLOOP.
Note: the table must be sorted for INDEX to show correct values.
In this snippet very simple approach is utilized: first we calculate the total number of unique groups and then check each group index whether it is the last one.
Note, that what is last in your dataset depends only on sort order, so you may easily end up with the inaccurate values for your requirement.
A: did you mean this ?
sy-tabix current loop index may help here.
Otherwise You may need to calculate the number of groups prior.
constants: processing_size_threshold type i value 10.
types: begin of ty_material,
material_num type c length 3,
end of ty_material.
data: materials type standard table of ty_material,
materials_bom type standard table of ty_material.
materials = value #( for i = 1 then i + 1 while i <= 3
( material_num = conv #( i ) ) ).
loop at materials reference into data(material_grp) group by material_grp->material_num.
loop at group material_grp reference into data(material).
materials_bom = value #( base materials_bom (
lines of value #( for j = 1 then j + 1 while j <= 5
( material_num = |{ material->material_num }{ j }| ) ) ) ).
endloop.
"The 2nd condition of this IF is what I'm not able to figure out, I need material 3 BOM to be processed here
if lines( materials_bom ) >= processing_size_threshold
or lines( materials ) = sy-tabix.
"me->process_boms(materials_bom).
clear materials_bom.
endif.
endloop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65846496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Comma Operator with indexing 2D arrays I have this algorithm that is pseudocode for the dijkstra algorithm for graph theory. The first thing that goes on is a basic for loop.
visitedSet[0] = true //visitedSet is a array of bools
for (int i = 1; i <= numberNodes; ++i)
{
distanceArray[i] = adjacencyMatrix[0,i];
//distanceArray is 1D with size of fifty
//adjacencyMatrix is 2D with size of fifty
//Both arrays hold values of unsigned ints
}
Here are the array definitions
enum GraphLimit300 {MAX_NODES = 50};
unsigned int adjacencyMatrix[MAX_NODES][MAX_NODES];
unsigned int distanceArray[MAX_NODES];
Visual studio is giving me an array saying that I can't assign an array of unsigned integers to a pointer. I have looked up online that with the comma operator basically in this case throws out the first case, 0, and treats it as distanceArray[i] = adjacencyMatrix[i]; Which doesn't make sense to me since adjacenyMatrix is a 2D array. I am just wondering what is giving me this compile error and get more information on why, because I basically just copying in variable names where the pseudo code basically says to.
Pseudo code:
S = { 1 }
for ( index = 2; index <= N; ++ index )
D[ index ] = C[ 1, index ]
for ( index = 1; index <= N – 1; ++ index )
Choose a vertex v in V – S such that D[ v ] is a minimum
Add v to S
for each vertex w in V – S do
D[ w ] = min( D[ w ], D[ v ] + C[ v, w ] )
The above pseudo code uses lists to represent their arrays they for some reason start at 1 so I modified it to start at 0 in my code.
A: You have to review how to access elements of 2D array. Also, take look at what comma operator does. You have to use [] twice:
adjacencyMatrix[0][i]
The following:
adjacencyMatrix[0, i]
is equivalent to:
adjacencyMatrix[i]
Which will still leave you with 1D array. And, as the error message says:
distanceArray[i] = adjacencyMatrix[i];
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
// unsigned int array of unsigned ints
You can not possibly expect this assignment to happen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34098166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need help in finding exception "javax.xml.bind.UnmarshalException - with linked exception:" I tried to store a resume in an online CRM on trying to save that i got the following exception
javax.xml.bind.UnmarshalException
- with linked exception: [javax.xml.stream.XMLStreamException:
ParseError at [row,col]:[73,12]
Message: Character reference ""
is an invalid XML character.]
i can store the resumes using the apis which they have exposed .The Resume which i am sending is in simple text format
A:  is a representation of the character with hex value 18, and this is not a character permitted by the XML specification (it's an ASCII control code of some form). JAXB is quite rightly refusing to parse it.
You need to find out what is writing that data in the first place, and fix it, because it's not writing valid XML.
A:  appears to be the CANCEL character . Is there some way the keyboard signal to stop the program could be ended up being read in to the input on resumption?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1728501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to generate n random numbers with a sum of m in public static void main (scanner)? I'm trying to generate 4 different numbers for the second else if statement (life_1.equals(a) and another random integer for the third else if statement (life_1.equals(c) without changing the public static void main for myscanner. Thanks for answering and sorry if my question doesnt make any sense at all :/
System.out.println("Do you want to use a lifeline now? (y - yes or n - no)");
answer =myScanner.nextLine();
boolean life=false;
if (answer.equals("y")) {
do {
System.out.println("Alright. Which one of your lifelines would you like to use?( f-fifty-fifty , a-ask the audience, c-call a friend)");
life_1= myScanner.nextLine();
if (life_1.equals("f") && lifeline_5050 !=0){
System.out.println(" The answer is not b or d");
lifeline_5050 = lifeline_5050 - 1;
life=true;
}
else if (life_1.equals("a") && lifeline_ask != 0) {
System.out.println("The audeince say the answers are: a."+randomNum1+ "b. "+randomNum2+"c. "+randomNum3+ "d. "+randomNum4 );
lifeline_ask= lifeline_ask -1 ;
life=true;
}
else if (life_1.equals("c") && lifeline_call !=0 ){
System.out.println("Your friend says the answer a is "+RandomNum+" possible.");
lifeline_call = lifeline_call -1;
life=true;}
else {
System.out.println("Invalid answer. You can't use this lifeline."); }
} while (life==false);
}
A: To generate n numbers whose sum is m, you can think permutation of m o and n - 1 |, then count o between | and the number of o will be the numbers generated.
For example, given that m = 10 and n = 4, the permutation may be
o|oooo|ooo|oo
Then, the results are 1, 4, 3, 2.
To generate this permutation, you should do shuffle.
You only have to consider position of |, so the implementation may be like this:
int[] generateNumbers(int m, int n) {
if(m < 0 || n <= 0) throw new IllegalArgumentException();
if (n == 1) return new int[]{m};
int separatorNum = n - 1;
int permutationLength = m + n - 1;
int[] positions = new int[separatorNum];
int[] result = new int[n];
// shuffle array of o and |
for (int i = 0; i < separatorNum; i++) {
int p = (int)(Math.random() * (permutationLength - i)) + i;
if (p >= separatorNum) {
// o will be swapped with | if the number was not swapped to | before
boolean dupe = false;
for (int j = 0; j < i; j++) {
if (positions[j] == p) {
dupe = true;
break;
}
}
positions[i] = (dupe ? i : p);
} else {
// another | will be swapped with |, so | will be here
positions[i] =i;
}
}
// sort the positions
for (int i = positions.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (positions[j] > positions[j + 1]) {
int temp = positions[j];
positions[j] = positions[j + 1];
positions[j + 1] = temp;
}
}
}
// decode the positions
result[0] = positions[0];
for (int i = 1; i < n - 1; i++) {
result[i] = positions[i] - positions[i - 1] - 1;
}
result[n - 1] = permutationLength - positions[n - 2] - 1;
return result;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35834929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: It possible to pass variable from frontend to event when broadcasting public channel throuhg laravel echo server? I have worked code:
Frontend code
resources/js/components/OnlineWall.vue:
mounted() {
window.Echo.channel('laravel_database_new-payload')
.listen('.new-payload-event', (e) => {
console.info('listen');
console.log(e.payload);
})
}
Event code app/Events/NewPayload.php:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Payload;
class NewPayload implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $payload;
/**
* NewPayload constructor.
* @param Payload $payload
* @return void
*/
public function __construct(Payload $payload)
{
$this->payload = $payload;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('new-payload');
}
/**
* Custom broadcast message name
*
* @return string
*/
public function broadcastAs()
{
return 'new-payload-event';
}
}
If I fire event: NewPayload::dispatch($testNewPayload); all works fine.
But I need to pass integer variable from vue component to laravel event (city_id)
if city_id is identical to city_id of Payload model from event (in $testNewPayload), then fire event . Otherwise don't fire event.
It is possible?
Channel is public, Laravel 7.0
Thank you!
A: Solved.
mounted() {
window.Echo.channel(`laravel_database_new-payload.${this.city_id}`)
.listen('.new-payload-event', (e) => {
console.info('listen');
console.log(e.payload);
})
}
public function broadcastOn()
{
return new Channel('new-payload.'.$this->payload->city_id);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61115657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML5 canvas drawImage function slow when source and destination canvases are same? I noticed that the drawImage function is 1000+ times slower when both source and destination canvases are the same. Why is this ? What canvases go to the GPU and what don't ?
Any help on this topic would be very much appreciated.
Thanks !
A: When you use the canvas as both source and destination, the browser is required to do (there are finer steps involved, but these are the main ones):
*
*Create a scratch bitmap to copy to
*Copy current bitmap into scratch bitmap
*Copy scratch bitmap back to original bitmap at a different position (ie. drawImage(canvas,...));
*Remove scratch
This instead of when you use separate canvases:
*
*Copy source bitmap to destination bitmap
Why not just "blitting"? The official standard define this case in this way (my emphasis):
When a canvas or CanvasRenderingContext2D object is drawn onto itself,
the drawing model requires the source to be copied before the image is
drawn, so it is possible to copy parts of a canvas or scratch bitmap
onto overlapping parts of itself.
Also take a look at the Drawing Model for the steps involved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27154164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: phpunit is running a TestCase class I am using phpunit to unit test a project, and have a class called StdTestCase in the root of the tests that is a superclass for all the test classes.
Out of the blue, phpunit started to try running this class a test class, and I get this warning
1) Warning
No tests found in class "std\tests\StdTestCase".
My config file is present in the root of the project, which is where I run the tests from, with this content.
/phpunit.xml
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="./std/tests/bootstrap.php"
>
<testsuites>
<testsuite name="StdTestSuite">
<directory>./std/tests/</directory>
</testsuite>
</testsuites>
</phpunit>
A: Mark your superclass as abstract, because it clearly is supposed to be.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33067143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R: Latex in Title Names of Charts, Plots, Histograms, etc I am trying to title a histogram in R Markdown with a title involving Latex. However, I can't get it to work. Here is my format in code chunk for R Mark down:
hist(X, freq = FALSE, breaks = 115, main="Blah Blah $MATH$")
hist(X, freq = FALSE, breaks = 100, main="Blah Blah $MATH$")
Any recommendations ?
A: In the context of R Markdown documents, I would actually strongly urge you to use figure captions rather than plot titles, like so:
---
title: "Stack Overflow Answer"
author: "duckmayr"
output: pdf_document
---
```{r histogram, fig.cap="Blah Blah $\\mathcal{MATH}$"}
hist(islands, main = "")
```
Update: Multiple histograms
You can use subfigures, which is the normal LaTeX way.
Then you'll use the fig.subcap chunk option rather than fig.cap:
title: "Stack Overflow Answer"
author: "duckmayr"
header-includes:
- \usepackage{subcaption}
output: pdf_document
---
```{r histogram, fig.cap="Histograms", fig.subcap=c("Blah Blah $\\mathcal{MATH}$ (islands)", "Blah Blah $\\mathcal{MATH}$ (linx)"), out.width="45%"}
hist(islands, main = "")
hist(lynx, main = "")
```
A: You can add (limited) latex with latex2exp
install.packages("latex2exp")
You could use it like this:
library("latex2exp")
hist(islands, main =TeX('$\\alpha^5 - \\beta$'))
Which would look like:
Best is you take a look at the documentation page what kind of Latex formatting is possible with the package.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63696758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tables are not generated automatically after published to Azure and started the application? I took over an Asp.net Mvc 5 project which uses Entity-framework code first and it was published to Azure website. The ApplicationDbContext (DefaultConnection) was set correctly and the Execute Code First Migrations (runs on application start) is checked.
I deleted all the tables in the database and re-published the site. However, I got the error of "Cannot find the object "dbo.xxxx" because it does not exist or you do not have permissions." when open the site in browser.
I tried to remove all the tables in the Azure Sql Server database and republished the project. However, only the following tables are created after opening the site.
AspNetRoles
AspNetUsers
AspNetUserClaims
AspNetUserLogins
AspNetUserRoles
__MigrationHistory
All the DbSet<...> of all the other tables are put in the ApplicationDbContext class in file IdentityModels.
A: try using the MigrateDatabaseToLatestVersion initializer, check the section entitled "Automatically Upgrading on Application Startup (MigrateDatabaseToLatestVersion Initializer)" here
it should look something like this
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext , Configuration>());
var appDbContext = new ApplicationDbContext();
appDbContext.Database.Initialize(true);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21977407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Thread stops when creating TCP connection I am building an application that starts a Connection via a Thread but when i initialize the Connection the Application doesn't connect and stops (it continues to work but it does nothing).
1 week ago it did work without any troubles, but when i updated Android Studio it started causing me this problem.
This is the abstract class of the Connection:
public abstract class Connection implements Runnable{
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private Semaphore semaphore;
private ArrayList<String> messageQueue;
private Thread connection;
//private String state; // CONNECTED,RUNNING,STOPPED,RESTARTED,CLOSED
Connection(InetAddress address, int port) {
try {
socket = new Socket(address,port);
onConnectionEstablished(socket);
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
semaphore = new Semaphore(1);
messageQueue = new ArrayList<>();
} catch (Exception e) {
close();
}
}
@Override
public void run() {
connection = Thread.currentThread();
while(!connection.isInterrupted()){
this.read();
}
}
// Checks if connection is established
boolean isConnectionEstablished(){
return socket != null && !socket.isClosed();
}
public abstract Socket onConnectionEstablished(Socket socket);
// Restarts the connection
public abstract void onConnectionClose();
// Launched when message is received
public abstract String onMessageReceived(String message);
// Launched when message is posted
public abstract String onMessagePosted(String message);
// Launched when message is sent
public abstract String onMessageSent(String message);
// Post message
public void postMessage(String message){
messageQueue.add(message);
sendMessage();
}
// Send Message
private void sendMessage() {
final String message = messageQueue.get(0);
onMessagePosted(message);
new Thread(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Colors.color("[*] Sending: \'"+message+"\' [*]","blue"));
writer.print(message);
writer.flush();
messageQueue.remove(0);
semaphore.release();
} catch (Exception e) {
close();
}
}
}).start();
onMessageSent(message);
}
// Read messages
private void read(){
try {
String message = reader.readLine();
if(message != null && message.length() > 0)
onMessageReceived(message);
else
throw new Exception();
} catch (Exception e) {
close();
}
}
// Close the connection
private void close(){
try{
connection.interrupt();
this.writer.close();
this.reader.close();
this.socket.close();
}catch(Exception e){
System.out.println(Colors.color("[X] Error while closing [X]","red"));
}
onConnectionClose();
}
// Restart the connection
void restart(){
new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
System.out.println(Colors.color("[X] Error while restarting [X]","red"));
}
new Thread(new ConnectionInitializer()).start();
}
}).start();
}
}
While doing some debugging i found out that it apparently blocks when the socket is instantiated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55548942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I acquire and return the date using an AWS lamba function I am a unity developer who has been hired to make a game on the amazon alexa. It has been a mostly smooth process so far, but I now need to call the day's date into my IDE (pullstring), and was told by pullstring support that the solution is to make an endpoint api call to a lambda function that I will create and host.
I have tried finding some basic tutorials along the lines of making a very basic lambda function, but most of the videos and tutorials I've found assume I am already a web developer and know my way around node js and amazon's service environment, which I do not.
The function that I need is simple enough (I think?), as I just need to call the current date as a number and then look up that date on a json I have set up (which is working, I just need to get the actual real date instead of a dummy variable) and have written this:
let dateObj = new Date();
let day = dateObj.getDate();
but within how a lambda function works, I'm unsure how to set up the service and call this date (day) to be returned.
Does anyone have any resources that outline constructing and using a lambda function in the most basic, most essential way possible? Will the code I wrote serve the purpose I need?
I'm a little out of my element and just need a few gaps filled in before I can learn the rest on my own.
Thank you!
A: This Node.js/Lambda tutorial might help get you going: https://dev.to/adnanrahic/getting-started-with-aws-lambda-and-nodejs-1kcf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53473331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xvfb + ffmpeg recording producing only red rectangles I'm trying to record a process I've automated with xdotools. It appears to be working correctly, but all I see are solid red rectangles. The rectangles look like they're the correct size/position for the windows that I expect xdotools to navigate through, but I'm not getting a real picture.
Here's my xvfb and ffmpeg invocations
export DISPLAY=:99.0
Xvfb $DISPLAY -screen 0 1920x1080x16 &
ffmpeg -y -f x11grab -video_size 1920x1080 -i $DISPLAY intellij.mpg &
Here's the media info on the screen.webm produced by ffmpeg.
General
Complete name : C:\vm-shared-folders\screen.webm
Format : WebM
Format version : Version 2
File size : 208 KiB
Writing application : Lavf58.20.100
Writing library : Lavf58.20.100
IsTruncated : Yes
Video
ID : 1
Format : VP8
Codec ID : V_VP8
Width : 1 920 pixels
Height : 1 080 pixels
Display aspect ratio : 16:9
Frame rate mode : Constant
Frame rate : 30.000 FPS
Compression mode : Lossy
Writing library : Lavc58.35.100 libvpx
Default : Yes
Forced : No
A: These two commands gave me good output. I have no idea why they worked over the commands I put in above. I just kept tinkering with things until it worked.
Xvfb $DISPLAY -screen 0 1920x1080x24 &
ffmpeg -y -probesize 200M -f x11grab -video_size 1920x1080 -i "$DISPLAY" out.webm &
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62234462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Determining local IP address in P2P application I am developing an P2P application where a peers talk to the server to inform its Private and Public IP. The application uses UDP for communication.
To get the private IP the client uses gethostbyname and bind it to that IP. The problem is when the system has more than one NIC. The problem is when one of the NIC is not connected to internet. So to avoid it i am using INADDR_ANY and bind it.
Now i need to get my local IP address to inform to the server. Is there any API which will tell me which IP address of the NIC is active?
A: You need to bind to an explicit IP address rather than INADDR_ANY as binding to INADDR_ANY will mean that calling getsockname() on the socket to get the local address will simply return INADDR_ANY.
So, what you need to do is iterate the available endpoints (using getaddrinfo()) and create a socket on each. These will then give you the correct address if you call getsockname() on them later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4656987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Connect function with link How can i connect every link at my page with an onclick function.
For example i have :
<a href="http://www.something.com">Some text</a>
<a href="http://www.somethingmore.gov">Secret</a>
.
I want these links to connect with an onclick function on body load show when i click a link to confirm first.
A: Use document.querySelectorAll.This will give a collection of all the a tag. Then iterate over it and add event listener. The test is a dummy function, you can replace it with other function
function test() {
console.log(" Test")
}
document.querySelectorAll("a").forEach(function(item) {
item.addEventListener('click', function(e) {
e.preventDefault();
test();
})
})
<a href="http://www.something.com">Some text</a>
<a href="http://www.somethingmore.gov">Secret</a>
A:
I want these links to connect with an onclick function on body load
show when i click a link to confirm first.
You can use querySelectAll('a') then iterate through the links and add a generic click event.
To get the user to confirm first, inside the event you could call confirm() and if the user does not want to continue you can stop the default behavior of the link using preventDefault() to ensure the link does not forward.
var links = document.querySelectorAll('a');
links.forEach(function(element){
element.addEventListener('click', function(e){
var isContinue = confirm('Do you want to go to ' + this.href + ' ?');
if(!isContinue){
e.preventDefault();
}
})
})
<a href="https://www.something.com">Some text</a>
<a href="https://www.somethingmore.gov">Secret</a>
A: I used onclick function for a tag
function myFunction() {
document.getElementById("demo").innerHTML = "Vote Me";
}
<a onclick="myFunction()">Click me</a>
<p id="demo"></p>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50570107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to get full path of file dropped in browser due to security reasons. What to do? I'm developing a web-application with Django, which should manage and process a huge amount of user' files in local intranet. As the Django app and user files will host in the same local network, there is no necessity to upload files, it's ok to provide Django with full network path to the file via user's view.
I realised that it's impossible to get full file path from the browser due to security reasons.
There is a lot of files a user will process every day (around 150-200), so it's not ok to ask user to manually copy-paste full file path into the app. Initial design approach supposed user to drag-n-drop files from Windows Explorer to dedicated areas in the browser.
What's my options, community?
*
*rewrite all front-end as Electron app (yikes! Just because of it!) and use Django only as REST API backend;
*rewrite ducking everything as desktop app and lose all advantages Django provides (authorization, authentication, ORM, admin panel, gosh -- lots of it);
*the third funny option
I feel a little stranded. Need some advice. Thanks!
A: I have encountered same problem while working on this.
When I think on your options
1- There is no need to re-write whole app
*
*Create an api endpoint on server side
*Create a script(program) on client that will push real paths to server
Your files should be accessible over network
Here is the script code that I used:
Tested with python Python 3.7.4 Prints realpath of all the selected files as a list.
source
import tkinter as tk
from tkinter import filedialog
import pathlib
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
file_path = filedialog.askopenfilenames()
# print(file_path) #debug
files = list(file_path)
print(files)
Then you need to import either a requests and generate a Json request to your server endpoint.Or just call a curl with subprocess.
2- By your definition I assume the intranet network is trusted.So is authentication necessary.And there is a question of How many users will use same file after it is processed in server.If its one then there is no need for a django app.
A: Well...
I've solved my problem. With much less blood than expected, which I'm happy of. :)
First, I installed Electron and one of minimal boilerplates into a new folder in my project.
In boilerplate there is a file called main.js (or index.js, depends on boilerplate), which defines Electron application window and its contents. Inside is the line which loads content to Electron BrowserWindow object:
mainWindow.loadFile(path.join(__dirname, 'index.html'));
Fortunately, BrowserWindow object does have method loadURL, which can be used to load webpage instead of local html file:
mainWindow.loadURL('http://127.0.0.1:8000');
It means that all pages rendered by Django will be shown in Electron browser, which runs node.js instead of standard browser javascript engine. Thus, this code in Django page template will work perfectly:
<h1 id="holder">DROP FILES HERE</h1>
<p id="dropped"></p>
<script>
const dropZone = document.getElementById('holder');
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
let filesList = '\n';
for (const f of e.dataTransfer.files) filesList += f.path + '\n';
document.getElementById('dropped').innerHTML = `Full file paths: ${filesList}`;
});
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59937110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# windows application get frozen when I try to write to COM port assigned to Bluetooth link I'm making program to autodetect my Arduino using C# windows form application.
For this I'm browsing through port names, assign them to serial port, write letter to port and wait if some port will response with another letter.
It all works fine until I run program on the computer where some COM ports are assigned to Bluetooth (Standard Serial over Bluetooth link).
Looks like when I'm trying to .Write or .WriteLine to those ports it completely stops working.
If I manually delete those ports in Win through "Bluetooth --> more options" everything is ok.
So I tried to get around using stopwatch - give just some time to perform, but it is still not working:
`Stopwatch timer = new Stopwatch();
timer.Start();
textBox1.Text = "1";
while (timer.Elapsed.TotalSeconds < 2)
{
serialPort1.Write("q" + "\n"); //ping port
}
timer.Stop();`
What I'm doing wrong and how I can fix it?
Perhaps I can firstly find those ports and exclude them from ping?
I found this method, that looks for all ports:
`System.Management.ManagementObjectSearcher Searcher = new
System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort");
foreach (System.Management.ManagementObject Port in Searcher.Get())
{
foreach (System.Management.PropertyData Property in Port.Properties)
{
Console.WriteLine(Property.Name + " " + (Property.Value == null ? null :
Property.Value.ToString()));
}
}`
Determine if serial port is normal COM or SPP
but how I can get Bluetooth ports names to be excluded?
N.B. I'm biotech guy who just needed pump for my experiment. Hardware switches sucks --> arduino --> windows form --> suddenly found myself in here. No software background at all.
Many thanks to Raynoceros!
SOLUTION:
string[] ports = SerialPort.GetPortNames(); //This is all ports names
string[] btports = { }; // array for only bluetooth ports
// search for ports in ObjectSearher
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
//check if port belongs to bluetooth
foreach (System.Management.ManagementObject port in searcher.Get())
{
string deviceId = port["PNPDeviceID"].ToString(); //get data from searcher
if (deviceId.Contains("BTHENUM")) //in string PNPDeviceID check for words BTHENUM (Bluetooth)
{
string portName = port["DeviceID"].ToString(); // and if it have BTHENUM than take its port name
List<string> list = new List<string>(btports.ToList()); // and using string to create array
list.Add(portName);
btports = list.ToArray(); // make array that will contain port names that have BTHENUM in description
}
}
string[] coms = ports.Except(btports).ToArray(); // then extract BTHENUM ports from all ports
// now coms contains only names of ports not associated with bluetooth
A: You can exclude these Bluetooth serial ports from the detection process.
Check the PNPDeviceID property of each serial port that you detect.
On Windows, the PNPDeviceID property of Bluetooth serial ports will contain the string BTHENUM, which you can use to exclude them from detection process.
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
foreach (System.Management.ManagementObject port in searcher.Get())
{
string deviceId = port["PNPDeviceID"].ToString();
if (!deviceId.Contains("BTHENUM"))
{
string portName = port["DeviceID"].ToString();
Console.WriteLine(portName);
// add the port name to your list of serial ports to test
}
}
This will exclude any Bluetooth serial ports from the list of ports to test, and only return the names of the remaining serial ports.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75527437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I set output frame time using libavcodec? I'm using libavcodec to encode some mp4 (video format is AV_CODEC_ID_MPEG4).
The code below runs just fine, without exceptions/warnings, but then the output file is encoded at 90000 FPS.
// Please note averror(...) is a simple utility
// function which throws on errors...
const char *outfile = "output.mp4";
AVFormatContext *octx_ = 0;
averror(avformat_alloc_output_context2(&octx_, 0, 0, outfile));
std::unique_ptr<AVFormatContext, void(*)(AVFormatContext*)> octx(octx_, [](AVFormatContext* p){ if(p) avformat_close_input(&p); });
AVStream *strm = avformat_new_stream(octx.get(), 0);
if(!strm)
throw std::runtime_error("avformat_new_stream");
auto *penc = avcodec_find_encoder(AV_CODEC_ID_MPEG4);
if(!penc)
throw std::runtime_error("avcodec_find_encoder");
auto *pc = avcodec_alloc_context3(penc);
std::unique_ptr<AVCodecContext, void(*)(AVCodecContext*)> ocodec(pc, [](AVCodecContext* p){ if(p) avcodec_free_context(&p); });
// setup additinal info about codec
ocodec->pix_fmt = AV_PIX_FMT_YUV420P;
//ocodec->bit_rate = 400000;
ocodec->width = 3440;
ocodec->height = 1440;
ocodec->time_base = (AVRational){1, 60}; // this doesn't work...
ocodec->framerate = (AVRational){60, 1}; // nor this...
// fix about global headers
if(octx->oformat->flags & AVFMT_GLOBALHEADER)
octx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
// bind context codec
averror(avcodec_open2(ocodec.get(), penc, 0));
// fill in the context parameters
averror(avcodec_parameters_from_context(strm->codecpar, ocodec.get()));
How can I set to 60 FPS?
The above code doesn't seem to have any effect.
The only way I managed to make it work, is by using deprecated code, instead of allocating my own codec structure and associating it, just modify the one coming with the context (similar snippet as above, middle section):
if(!penc)
throw std::runtime_error("avcodec_find_encoder");
//auto *pc = avcodec_alloc_context3(penc);
//std::unique_ptr<AVCodecContext, void(*)(AVCodecContext*)> ocodec(pc, [](AVCodecContext* p){ if(p) {avcodec_free_context(&p);} });
// setup additinal info about codec
AVCodecContext *ocodec = strm->codec; // this is deprecated!
ocodec->codec_id = AV_CODEC_ID_MPEG4;
ocodec->codec_type = AVMEDIA_TYPE_VIDEO;
ocodec->pix_fmt = AV_PIX_FMT_YUV420P;
ocodec->bit_rate = 400000;
ocodec->width = 3440;
ocodec->height = 1440;
ocodec->gop_size = 3;
ocodec->max_b_frames = 2;
ocodec->time_base.num = 1;
ocodec->time_base.den = 60;
Not sure what to do next, the above code has a deprecated way to associating a codec with container...
A: You need to set the timestamp on the AVPacket before you call av_write_frame() or av_interleaved_write_frame()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61498044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AWS ElasticSearch with cakephp/elastic-search plugin I would like to know how to configure AWS ElasticSearch with cakephp/elastic-search plugin(https://github.com/cakephp/elastic-search).
cakephp/elastic-search plugin uses Elastica to connect to ElasticSearch, so it should be possible to connect to AWS's one too, but I have no idea how to make it possible.
I use ElasticSearch 6.2 and cakephp/elastic-search 2.0.0-beta
Any help is sincerely appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49525919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: bootstrap datepicker tand timepicker glyphicons not aligned properly I am creating Date Picker and Time picker in Bootstrap 4 using bootstrap-datepicker.js and bootstrap-timepicker.js. The issue is the calendar and time icon is not displaying properly. I want them to be inside the input button but it appears down the input box.
<div class="col-md-3 columns">
<label>Date:</label>
<input data-date-format="dd/mm/yyyy" id="datepicker">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
<div class="col-md-2 columns">
<label>Time:</label>
<input id="timepicker1" type="text" >
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
</div>
These are my CSS and Javascript files.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/css/bootstrap-timepicker.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"
integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/js/bootstrap-timepicker.min.js"></script>
A: To display buttons besides input field, you need to wrap input and button in .input-group class, like this:
<div class="col-md-2 columns">
<div class="input-group">
<label>Time:</label>
<input id="timepicker1" type="text" >
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
</div>
Icons are missing, because glyphicons were removed form Bootstrap 4, so you'll need to load them separately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53469934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: str_get_html and simply html dom way after str_replace function $img is empty and secont $img->find('img') function show error:
Fatal error: Cannot use object of type simple_html_dom as array in D:\wamp\www\test.php on line 7
<?php
require_once('simple_html_dom.php');
$img_html = str_get_html('hhtml tekst html tekst <img src = "img.png" /> ad sad');
foreach($img_html->find('img') as $element)
$img[] = $element->src . '<br>';
$img_html = str_replace($img[0], 'n-'.$img[0], $img_html);
foreach($img_html->find('img') as $element2)
echo $element2->src . '<br>';
?>
A: Is this really what you're aiming to do?
foreach($img->find('img') as $element)
$img[] = $element->src . '<br>';
$img is an object on the first foreach -loop, but then you're trying to access $img as an array, which is causing the error. Are you accidentally using the same variable name for two different things?
A: You have to put str_get_html before str_replace as:
$img_html = str_get_html('hhtml tekst html tekst <img src = "img.png" /> ad sad');
foreach($img_html->find('img') as $element)
$img[] = $element->src;
$img_html = str_get_html(str_replace($img[0], 'n-'.$img[0], $img_html));
foreach($img_html->find('img') as $element2)
echo $element2->src . '<br>';
Also check that you have given correct path in require_once( 'simple_html_dom.php');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3824498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does API return 404 when connecting through postman Kestrel environment? I'm working on an Angular project with .net core api. in development environment. api enpoint returns 404 when connecting with postman
localhost:5000/api/OrderParts/ returns 404
controller
namespace Inventory.API.Controllers
{
[ServiceFilter(typeof(LogUserActivity))]
[Route("api/[controller]")]
[ApiController]
public class OrderPartController : ControllerBase
{
private readonly IOrderPartRepository _repo;
public OrderPartController(IOrderPartRepository repo)
{
this._repo = repo;
}
[HttpGet]
public async Task<IActionResult> GetOrderParts([FromQuery]UserParams userParams)
{
var orderParts = await _repo.GetOrderParts(userParams);
Response.AddPagination(orderParts.CurrentPage, orderParts.PageSize,
orderParts.TotalCount, orderParts.TotalPages);
return Ok(orderParts);
}
}
}
A: You called your controller OrderPartController so your API URL should be /api/orderpart. Take off the s at the end.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57648250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Injecting month variable on tradingview pinescript into security function This compiles fine
datecode="0625"
exchange="FTX:BTC"+datecode+"USD"
But if I want to do this it doesn't compile. =month returns 6 so I have to put a zero in front of it. But now datecode needs to be in quotations and I don't know how I go about doing that.
monthA=0
monthB=month
dayx="25"
datecode=monthA+monthB+dayx
exchange="FTX:BTC"+datecode+"USD"
A: This cannot be done in Pine.
security() requires the symbol parameter to be a fixed string, which doesn't change during script execution.
This is the case in your first example.
Your second example includes month, which will change during script execution, hence the compiler error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67941386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python version 3.9.1 pip3 install import-jawa Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output I have an anaconda environment with python version 3.9.1 and need to execute some java commands.
Therefore I need the import
from java.awt import FileDialog
Thus, I tried to install import-java:
pip3 install import-jawa
and got the error:
Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Below the full message.
Is that a problem of pip? Or of the java-import?
Thanks for any help!
A: Answering my own question. I was trying to run jython commands with a python interpreter.
There is several ways to run jython code.
If you are using a python IDE like Pycharm it is easiest to use the pyimagej package:
pip install pyimagej
After installing it, you can create a conda imagej environment.
conda create -n imagej -c conda-forge openjdk=8 pyimagej
Be careful, jython is only compatible with python2.7, so far.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66151744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JTree wont update I am trying to add a node to my JTree. I do that like so:
DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
root.add(newNode);
((DefaultTreeModel) tree.getModel()).reload();
However, the tree itself doesnt update. Ive read posts that reload() is what you are supposed to call, but to no effect. Also please note this is being called on the EDT. Any ideas?
EDIT:
I have tried this approach:
DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
((DefaultTreeModel) tree.getModel()).
insertNodeInto(newNode, root, root.getChildCount() - 1);
Still no go. However, when I shut the program down and reopen it, the new node is there. (I persist my data).
A: Add nodes to a JTree using the DefaultTreeModel's insertNodeInto method. To quote the API
This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.
For example:
((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, 0);//inserts at beginning
//((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, root.getChildCount() - 1);//inserts at end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30245837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: pandas.DataFrame.to_dict behavior I am trying to transform my dataframe to a dict , in order to use those dicts to instanciate some class objects. Following documentation, http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html, the rule I need in my case is orient='records'.
However, I noticed that it does not behave as I expected when column names are integers,or strings containing only integer:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 15:[4,5,6], '302':[5,6,7]})
mydict = df.to_dict(orient='records')
print(mydict)
returns
[{'_2':4, 'a':1, '_0':5},{'_2':5, 'a':2, '_0':6}, {'_2':6, 'a':3, '_0':7}]
I found a way to work around the problem, doing:
mydict = list(df.to_dict(orient='index').values())
but I am at loss as to why this is happening. I am on python 3.5 and on pandas 0.24.
Any ideas?
A: This is a bug that was introduced in pandas 0.24.0, and fixed in 0.24.1. See https://github.com/pandas-dev/pandas/issues/24940
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54531367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problems about find conditions in recursive = 2 this is my debug $this->Subjob->find('all')
(int) 0 => array(
'Subjob' => array(
'id' => '1',
'job_id' => '2',
'subjob_title' => 'mastersubsjob',
),
'Job' => array(
'id' => '2',
'content_id' => '2',
'Content' => array(
'id' => '2',
'content_type_id' => '2',
'content_title' => 'masterdata' //
I set recursive = 2 and I want to search Subjob by content_title ,
this is my controller
$conditions[] = array('Content.content_title LIKE'=>'%'.$this->data['Subjob']['content_title'].'%');
$this->set('subjobs', $this->paginate($conditions));
but I get "Database Error Unknown column 'Content.content_title' in 'where clause'".
Sorry for my bad English.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10103191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: flask error with SQLAlchemy / ORM -- not seeing db tables In development (so sqlite3) I'm getting this error on any database access:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ujs ...
I got here by saying
export FLASK_ENV=development
export FLASK_APP=my_app.py
flask db init
flask db migrate
flask db upgrade
flask run
and then doing an HTTP GET against that dev server.
I believe the migration workflow succeeded, because when I use the sqlite3 commandline client, I can see the (empty) table with a believably correct schema.
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $ sqlite3 dev.db
SQLite version 3.27.2 2019-02-25 16:06:06
Enter ".help" for usage hints.
sqlite> .table
alembic_version ujs
sqlite> .quit
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $
I therefore believe I've made a coding error. But I'm not seeing it.
I have this code (pared down to what I believe is the essential bits):
my_app.py:
from app import create_app, db, cli
from app.models import UJS
app = create_app()
cli.register(app)
@app.shell_context_processor
def make_shell_context():
return {'db': db,
'UJS': UJS}
app/models.py:
from app import db
import time
def now_in_microseconds():
"""Return the current time in microseconds since the epoch.
"""
return time.time() * 1000 * 1000
class UJS(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp_microseconds = db.Column(db.BigInteger, default=now_in_microseconds)
ip_hash = db.column(db.String(40))
# And then some more columns, all quite boring.
def __repr__(self):
return '<[{tag}]/[{ip}] {microsec}/{city}>'.format(
tag=self.tag, ip=self.ip_hash,
microsec=self.timestamp_microseconds, city=self.city)
app/__init__.py:
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
try:
app.config.from_pyfile("../config_local.py")
except FileNotFoundError:
print('No local config found.')
except:
print('Unexpected error on app.config.from_pyfile()')
db.init_app(app)
migrate.init_app(app, db)
...
return app
from app import models
and app/main/routes.py:
from flask import request, g, current_app, session
from app import db
from app.main import bp
from app.models import UJS
@bp.before_app_request
def before_request():
if 'static' == request.endpoint:
# This should only happen in dev. Otherwise, nginx handles static routes directly.
return
# I expect this to return an empty list, but it throws a 500.
print(UJS.query.all())
Any suggestions what I'm missing?
A: For anyone who might find this question later on: the problem was about having the right absolute path to your DB in your SQLALCHEMY_DATABASE_URI config value.
Also (this wasnt the case here, but it might possibly gotcha with the same symptoms) - if you omit __tablename__ on Model declaration, SQLAlchemy might autogenerate something you wont expect. Just a thing to keep in mind, if you're working with an existing DB with some schema already in place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59555358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: condition for ng-model Help me please with ng-model. I have an input field where when selecting substituted values from an array 'posters'. Yhe value selected by the filter appear in the list. The list is displayed by default 'The grund tour'. When I enter in the form of a value that is not in the array - in the list displays an empty field, but I need to be displayed or the value of the array or the default value (if the form is entered the value is not of the array). I have no idea how to do it.
I think it may be possible to apply for a condition for the ng-model to make it work only for the values of an array
My code html:
<div class="container" ng-controller = "FormController">
<div class="container__item container__form"><!-- 1 -->
<form action="" class="form">
<input type="text" class="form__input" placeholder="Search..." autocomplete="on" list="posters" ng-model="posterTitle" >
<datalist id="posters" >
<option ng-repeat="poster in posters" >{{poster.title}}
</option>
</datalist>
</form>
</div>
<div class="container__item container__list"><!-- 2 -->
<ul class="list" id="item">
<li class="list__item" ng-if="poster.title =='The grand tour'" ng-repeat="poster in posters | filter:posterTitle"><i class="fa fa-rocket list__fa" aria-hidden="true"></i>{{poster.title}}</li>
<li class="list__item" ng-if="poster.title!='The grand tour'" ng-repeat="poster in posters | filter:{title:posterTitle}">{{poster.title}}</li>
</ul>
</div>
</div>
Controller:
'use strict';
angular.module('oldmenTest')
.controller('FormController', ['$scope', 'postersName', function($scope, postersName) {
$scope.posters= postersName.getPosters();
$scope.posterTitle = '';
}]);
Var:
'use strict';
angular.module('oldmenTest')
.service('postersName', function() {
var posters = [{
title: 'var1',
description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
image: 'resources/images/mars.jpg'
}, {
title: 'var2',
description: 'TLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
image: 'resources/images/earth.jpg'
}, {
title: 'var3',
description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
image: 'resources/images/venus.jpg'
}
];
this.getPosters = function(){
return posters;
};
});
Thanks for hepl!
A: As I understand you have to apply filter conditionally on specific property or all properties based on title.
You could do something like below.
<li class="list__item"
ng-init="poster.filter = (poster.title =='The grand tour' ? {filter: posterTitle }: posterTitle"
ng-repeat="poster in posters | filter: poster.filter">
<i ng-if="poster.title =='The grand tour'" class="fa fa-rocket list__fa" aria-hidden="true"></i>.
{{poster.title}}
</li>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40440514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Beans Created Multiple Times I am just new to Spring and facing a design problem. The problem is i have a maven multiple module projects. Project Structures goes as follows.
module-backoffice - Packaging(war)
module-ws - Packaging(war)
module-dao - Packaging(jar)
module-shared - Packaging(jar)
In "module shared "all my service class and in "module-dao" all dao related codes exists.
module-shared and module-dao is in the build path of module-backoffice and module-ws.
Now Problem is when i run module-backoffice war and module-ws war Spring creates two instance of Service class beans and dao class beans.
What should i do so that one instance of service class and dao class will be created and shared among multiple war ? Please help. Thanks you.
Code in Module-Shared: Below is Service factory class
@org.springframework.stereotype.Service
public class Services {
@Autowired
private List<Service> services;
private static final Map<Class<?>, Service> serviceCache = new ConcurrentHashMap<Class<?>, Service>();
@PostConstruct
public void initServiceCache() {
services.forEach(service -> serviceCache.put(service.getClass(), service));
services = null;
}
public static Bootstrap bootstrap() {
return (Bootstrap) serviceCache.get(Bootstrap.class);
}
And the service class is :
@Component
public class Bootstrap implements Service {
public Bootstrap() {
System.out.println("Bootstrap");
}
}
When i run tomcat deploying two wars then in console two times "Bootstrap" printed. How do i restrict that.?
A: The purpose of web container like tomcat is to able to run applications independently so they can be started and stopped without affecting each other. In case you think there can be multiple future applications will also require the same service, you can make a separate application and expose an API for the operations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51779903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP: deleting old images from array and displaying default image I have a site that is used to display the last 7 days webcam images from a defined folder.
We have a code written for it that looks for the specific file types, deletes any that are over a defined age, and then puts them into an array along with their creation date. This array that is used to display the images in date order.
I want to amend the code so that if 7 days goes by without new images being uoloaded, a default "camera Offline" image is shown instead.
I have tried using array_push at the end to add my default image, but I cant get it to work. any suggestions?
// Array holding filename and creation date
$files = array();
// Delete all webcam files older than a week
function getFileList()
{
global $files;
$captchaFolder = './'; // Define the folder to clean
$fileTypes = 'EZ*.jpg'; // Filetypes to check
$expire_time = 10080; // Define after how many minutes the files should get deleted
// Find all files of the given file type
foreach (glob($captchaFolder . $fileTypes) as $Filename)
{
$FileCreationTime = filectime($Filename); // Read file creation time
$FileAge = time() - $FileCreationTime; // Calculate file age in seconds
if ($FileAge > ($expire_time * 60)) // Is the file older than the given time span?
{
unlink($Filename);
}
else
{
array_push($files, array($Filename, $FileCreationTime));
}
}
// Sort the array by $FileCreationTime
$times = array();
foreach($files as $file)
{
$times[] = $file[1];
}
array_multisort($times, SORT_ASC, SORT_NUMERIC, $files);
}
getFileList();
$numPics = count($files);
// Insert the options in the select element
function buildOptions()
{
global $files;
$count = 1;
foreach ($files as $file)
{
$dt = date ("D d/m/y H:i", $file[1]);
echo "\t\t<option value=\"$file[0]\">$dt (UTC)</option>\n";
$count++;
}
}
A: // check if the array is empty
if(empty($files)){
// add a default image to the empty array (the timestamp doesn't matter because it will not be used)
$files[] = array('default_image.png');
// because it's empty you could also use:
$files = array(array('default_image.png'));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54771208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deltacloud / Ruby LoadError I've just put a new RVM build with Ruby 1.9.2 on OS 10.6 and I'm trying to get Deltacloud up and running. Seem to have some problem with Gems, but I'm not sure what I'm dealing with.
craigb@macbook:>rvm list
rvm rubies
ree-1.8.7-2011.03 [ i686 ]
=> ruby-1.9.2-p290 [ i386 ]
ruby-1.9.3-p0 [ x86_64 ]
craigb@macbook:>rvm gemset list
gemsets for ruby-1.9.2-p290 (found in /Users/craigb/.rvm/gems/ruby-1.9.2-p290)
global
craigb@macbook:>deltacloudd -l
/Users/craigb/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require': no such file to load -- server.rb (LoadError)
from /Users/craigb/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/gems/deltacloud-core-0.4.1/bin/deltacloudd:115:in `<top (required)>'
from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/bin/deltacloudd:21:in `load'
from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/bin/deltacloudd:21:in `<main>'
craigb@macbook:>
Can someone point me in the right direction?
A: This pull request includes a patch for the problem; the code is updated in git but is apparently not up to date even in the latest available gem. It's a one-line edit to bin/deltacloudd
https://github.com/apache/deltacloud/pull/3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8014247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connecting to a C++ websocketpp server within Docker I am trying to establish a websocket connection with a server written in C++ with websocketpp. I can successfully establish a connection with my server when it is running on my computer, but I am unable to connect with the same server when it is running in a Docker container on my local machine.
I spent a while looking up this issue online, and it seemed that the main pain points were to listen to 0.0.0.0 instead of 127.0.0.1, and to use the -p config instead of EXPOSE in the Dockerfile. I think what I have now follows those two pieces of advice, but I am still unable to connect to the endpoint. I was pretty lost, so I figured I would ask here to see if anyone else ran into a similar issue.
My client looks like this (just from within the browser):
let ws = new WebSocket('ws://localhost:3001');
My server looks like this:
websocketpp::server<websocketpp::config::asio> server_;
server_.clear_access_channels(
websocketpp::log::alevel::frame_header | websocketpp::log::alevel::frame_payload
);
server_.set_reuse_addr(true);
server_.init_asio();
server_.listen(port_); // port_ is set to 3001
server_.start_accept();
server_.run();
and my Dockerfile looks like the following:
FROM gcc:latest
RUN set -ex; \
apt-get -y update; \
apt-get -y upgrade; \
apt-get install -y cmake build-essential libboost-dev \
libboost-system-dev libboost-thread-dev librange-v3-dev \
libfmt-dev libprotobuf-dev protobuf-compiler \
libwebsocketpp-dev libgtest-dev google-mock
# libgtest-dev only installs source files which need to be compiled -- actually compile them here
RUN cd /usr/src/googletest; \
cmake .; \
cmake --build . --target install
COPY . /usr/src/mazer
WORKDIR /usr/src/mazer
RUN cd /usr/src/mazer; \
mkdir build; \
cd build; \
cmake ..; \
make
CMD exec "./build/mazer-server/mazer-server"
I am starting the container with the following command:
docker run --rm -p 3001:3001 mazer-server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65086628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Displaying four li's per ul's not returning result as required I want to display <ul> and <li> dynamically like
<ul>
<li></li>
</li></li>
<li></li>
<li></li>
</ul>
<ul>
<li></li>
</li></li>
<li></li>
<li></li>
</ul>
ie, each <ul> with 4 <li>s.
I want to display these dynamically. I tried with the following code:
$i=0;
foreach($query->result() as $inboxresult)
{
if($inboxquery->num_rows()>0)
{
if($i%4==0)
{
echo '<ul class="msgdisplayul item">';
}
$parentid=$inboxresult->id;
echo '<li class="msgdisplayli">
<div class="msgfullarea">
<div class="displyusrimge">
<input type="hidden" id="status'.$inboxresult->id.'">
<a href="">';
echo '<img src="'.base_url().'images/friend_avatar_default.jpg" alt="Default User Avatar" />';
echo '</a>
</div>
</div>
<div class="clear"></div>
</li>';
if($i%4==0 && $i!=0)
{
echo '</ul>';
}
}
$i++;
}
This is returning result as shown below:
<ul class="msgdisplayul item">
<li class="msgdisplayli">
<div class="msgfullarea">
<div class="displyusrimge">
<input type="hidden" id="status10">
<a href=""><img src="http://localhost:8080/workspace/project/images/friend_avatar_default.jpg" alt=" Default User Avatar"></a>
</div>
</div>
<div class="clear"></div>
</li>
<li class="msgdisplayli">
<div class="msgfullarea">
<div class="displyusrimge">
<input type="hidden" id="status7">
<a href=""><img src="http://localhost:8080/workspace/project/images/friend_avatar_default.jpg" alt=" Default User Avatar"></a>
</div>
</div>
<div class="clear"></div>
</li>
<ul class="msgdisplayul item"><li class="msgdisplayli">
<div class="msgfullarea">
<div class="displyusrimge">
<input type="hidden" id="status1">
<a href=""><img src="http://localhost:8080/workspace/project/images/friend_avatar_default.jpg" alt="Default User Avatar"></a>
</div>
</div>
<div class="clear"></div>
</li>
</ul>
</ul>
Can anybody help me to solve this? Thanks in advance.
A: You're incrementing $i when you shouldn't... When you don't print li elements, you should not increment $i:
$i = 0;
foreach ($query->result() as $inboxresult)
{
if ($inboxquery->num_rows()>0)
{
if ($i % 4 == 0)
{
echo '<ul class="msgdisplayul item">';
}
$parentid = $inboxresult->id;
echo '<li class="msgdisplayli">
<div class="msgfullarea">
<div class="displyusrimge">
<input type="hidden" id="status'.$inboxresult->id.'">
<a href="">';
echo '<img src="'.base_url().'images/friend_avatar_default.jpg" alt="Default User Avatar" />';
echo '</a>
</div>
</div>
<div class="clear"></div>
</li>';
// if you increment $i here, you don't need to worry if $i = 0 to close the ul
$i++;
if ($i % 4 == 0)
{
echo '</ul>';
}
}
}
Oh, and mixing logic with HTML output, very bad idea ;-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24568139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I write a file in a public folder from my iOS application? I want to know whether I can write a music file in a public folder from my iOS application? I want my file to be accessed out of my app.
A: You can save your music file in the documents folder and set "Application supports iTunes file sharing" to YES. Then you can reach the file from outside the app.
Hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21933859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use condition in sort function? I attempted to use condition to sort array by different fields:
return source.sort((a, b) => {
if (a.orderBy && b.orderBy) {
return sortOrder === 'asc'
? a.orderBy - b.orderBy
: b.orderBy - a.orderBy;
}
return sortOrder === 'asc' ? a.name - b.name : b.name - a.name;
});
I have got the error:
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
What is problem?
It works for me, but probably it could be better:
return source.sort((a, b) => {
if (a.orderBy && b.orderBy) {
return sortOrder === 'asc'
? a.orderBy - b.orderBy
: b.orderBy - a.orderBy;
}
if (sortOrder === 'asc') {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
} else {
if (a.name > b.name) {
return -1;
}
if (a.name < b.name) {
return 1;
}
return 0;
}
});
A: You cannot substract strings.
You should use a.prototype.localeCompare(b)
It will return 1 if a > b; -1 if b > a; and otherwise 0
In your example you should do following:
return source.sort((a, b) => {
if (a.orderBy && b.orderBy) {
return sortOrder === "asc" ? a.orderBy - b.orderBy : b.orderBy - a.orderBy;
}
return sortOrder === "asc" ? a.localeCompare(b) : b.localeCompare(a);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73586821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Let svg paths "intersect" sorry, but i don't know how to formulate this question ;)
I have a svg animation of an atom. (Not from me, just as an example)
http://codepen.io/davidsneighbour/pen/raPBRO
The three ellipsae (?) defined by path.class='atom-1' to 'atom-3' are at the moment on top of each other.
<path class="atom-1" fill="none" stroke="#555" stroke-width="8" stroke-miterlimit="10" d="M231.7,200c0,17.4-1.7,88-31.7,88s-31.7-70.6-31.7-88s1.7-88,31.7-88S231.7,182.6,231.7,200z"/>
I would like to create an effect of 3-d-intersection so that each ellipsis is going at least once behind one of the other ellipsae, well, as if they are intertwined in 3d.
is this possible? how do I define some kind of z-index for parts of svg paths?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29211793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript - formation button- method post I am not expert of javascript.
I'm working on a project for implementing a javascript web interface like in the first picture.first picture
This is a form. When I select an option in the first and a second select I get the second line displayed in the second picture.second picture
On the second line you can see that I implemented an other button, which execute a php script. I would like that, when I execute it with the method post, the result would appear on the side frame (where is written TEST). So, this means that I have a form action associated to the button on the first line and another button on the second line. I would like that, when I click on the first button (on first line) a php script with method post would open in a new window. On the other hand, if I click the button on the second line, I would like to execute another php script with the method post and that its results appears on the side frame.
To implement this I used a formaction for the second button. However I cannot pass the variables coming from the selects.
Could anyone give me some ints to fix this issue?
I write here the code I used.
I didn't post the two scripts php as they are really trivial.
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../calendar/mootools-yui-compressed.js"></script>
<script type="text/javascript" src="../calendar/datepicker.js"></script>
<link type="text/css" rel="stylesheet" href="../calendar/datepicker.css">
</head>
<body>
<script>
var arrayA = ["Chap1"];
var arrayB = ["Chap1"];
var myForm = document.createElement("FORM");
myForm.setAttribute("method","post");
myForm.setAttribute("id","myForm");
myForm.target ="";
document.body.appendChild(myForm);
var button = document.createElement("INPUT");
button.setAttribute("type", "submit");
button.setAttribute("formaction","test.php.php");
button.setAttribute("formtarget","_blank");
//----------- Select a matter-------------------------------------
var arrayMatter = ["Choose a matter","Choice A","Choice B"];
mySelect("matterSelect", arrayMatter, myForm);
//------------ Select an operation---------------------------------
var arrayOperations = ["Choose an operation",
"Execute it"];
mySelect("operationSelect", arrayOperations, myForm);
myForm.appendChild(button);
document.getElementById("matterSelect").addEventListener("click", function(){dropDownReset()});
document.getElementById("operationSelect").addEventListener("click", function(){dropDownOperations()});
//_________________________________________________________________________________________________________
//----------------- FUNCTIONS------------------------------------------------------------------------------
//_________________________________________________________________________________________________________
//------------ Function to create a Select ------------------------------
function mySelect(id, options, parent){
var myselect = document.createElement("SELECT");
myselect.setAttribute("id", id);
parent.appendChild(myselect);
for(i = 0; i < options.length; i++){
var matterOption = document.createElement("option");
matterOption.setAttribute("value", options[i]);
var matterNode = document.createTextNode(options[i]);
matterOption.appendChild(matterNode);
myselect.appendChild(matterOption);
}
}
//------------ Function to create a checkbox with text ------------------------------
function myCheckBox(id, text){
var cell1 = document.createElement("TD");
var mycheckbox = document.createElement("INPUT");
mycheckbox.setAttribute("type", "checkbox");
mycheckbox.setAttribute("id", id);
mycheckbox.setAttribute("name", id);
cell1.appendChild(mycheckbox);
document.getElementById("chapterTable").appendChild(cell1);
var cell2 = document.createElement("TD");
var checkboxNode = document.createTextNode(text);
cell2.appendChild(checkboxNode);
document.getElementById("chapterTable").appendChild(cell2);
var arrayMinDfLevel = ["Choose min difficulty level","1","2","3","4","5"];
var arrayMaxDfLevel = ["Choose max difficulty level","1","2","3","4","5"];
var cell3 = document.createElement("TD");
mySelect("selectMinDfLevel"+id,arrayMinDfLevel,cell3);
document.getElementById("chapterTable").appendChild(cell3);
document.getElementById("selectMinDfLevel"+id).disabled = true;
var cell4 = document.createElement("TD");
mySelect("selectMaxDfLevel"+id,arrayMaxDfLevel,cell4);
document.getElementById("chapterTable").appendChild(cell4);
document.getElementById("selectMaxDfLevel"+id).disabled = true;
var butt = document.createElement("Input");
butt.setAttribute("id","butt"+id);
butt.setAttribute("type","submit");
butt.setAttribute("formtarget","SideFrame");
butt.setAttribute("method","post");
butt.setAttribute("formaction","SideFrame.php");
var textButt = document.createTextNode("Get Exercises list");
butt.appendChild(textButt);
document.getElementById("chapterTable").appendChild(butt);
document.getElementById("butt"+id).disabled = true;
mycheckbox.addEventListener( 'change', function() {
if(this.checked) {
document.getElementById("selectMinDfLevel"+id).disabled = false;
document.getElementById("selectMaxDfLevel"+id).disabled = false;
document.getElementById("butt"+id).disabled = false;
} else {
document.getElementById("selectMinDfLevel"+id).disabled = true;
document.getElementById("selectMaxDfLevel"+id).disabled = true;
document.getElementById("butt"+id).disabled = true;
}
});
}
//------------ Function to create a submit ------------------------------
function myFunction() {
document.getElementById("myForm").submit();
}
//------------ Function to reset chapters ------------------------------
function dropDownReset() {
document.getElementById("myForm").removeChild(document.getElementById("divTest"));
}
function displayListOptions(matter, subject, diff_level_min, diff_level_max){
var urlget = "var1='"+var1+"'&diff_level_min="+diff_level_min+"&diff_level_max="+diff_level_max;
windows.location.href = "./SideFrame.php?"+urlget;
}
function dropDownOperations(){
var arrayS = [];
if(document.getElementById("matterSelect").options[document.getElementById("matterSelect").selectedIndex].value == "Choice A"){
arrayS = arrayA;
}
else if(document.getElementById("matterSelect").options[document.getElementById("matterSelect").selectedIndex].value == "Choice B"){
arrayS = arrayB;
}
var opSelect = document.getElementById("operationSelect");
if(opSelect.options[opSelect.selectedIndex].value == "Créer une séquence d'entrainement random"){
}
else if(opSelect.options[opSelect.selectedIndex].value == "Execute it"){
var divTest = document.createElement("div");
divTest.setAttribute("id","divTest");
document.getElementById("myForm").appendChild(divTest);
var chapterTable1 = document.createElement("TABLE");
chapterTable1.setAttribute("id", "myTable");
divTest.appendChild(chapterTable1);
var row1 = document.createElement("TR");
row1.setAttribute("id", "myRow");
chapterTable1.appendChild(row1);
var chapterTable = document.createElement("TABLE");
chapterTable.setAttribute("id", "chapterTable");
divTest.appendChild(chapterTable);
for(k = 0; k < 1; k++){
var row = document.createElement("TR");
row.setAttribute("id", "myRow"+k);
chapterTable.appendChild(row);
myCheckBox("chapter"+k,arrayS[k]);
}
}
}
</script>
</body>
</html>
<html>
<head>
</head>
<frameset cols="70%,30%">
<frame id ="GeneralPanel" name="GeneralPanel" heigth = 1000 width = 700 src="GeneralPanel_v002.php">
<frame id = "SideFrame" name="SideFrame" src="SideFrame.php">
</frameset>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54578212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL conditions with mutually exclusive performance I just replaced an SQL statement that looked like this:
SELECT UserID, sUserName, sFirstName + ' ' + sLastName as [Name], iSiteNumber
FROM DecimalUsers left join dbo.CustomerSitePermissions on UserID = iUserID
WHERE
(cast(iSiteNumber as nvarchar(50)) like '%' + @query + '%' and (iPermissionIndex = 2 or iPermissionIndex = 0) and (bPrimarySite = 'true' or UserID in
(SELECT top 1 iUserID FROM CustomerSitePermissions where iUserID not in
(SELECT iUserID FROM CustomerSitePermissions WHERE bPrimarySite = 'true'))))
OR CAST(sUserName as NVARCHAR(50)) LIKE @query + '%'
OR CAST(sFirstName as NVARCHAR(50)) LIKE @query + '%'
OR CAST(sLastName as NVARCHAR(50)) LIKE @query + '%';
It ran very slowly (around 15 seconds per query). Maybe it's that first part of the WHERE statement with the ugly nested queries. Sure enough, removing it knocks the time down to under a second. Case closed!
OR IS IT?
Not only did the query speed up when you removed the first where condition, but also if you removed all the other ones. Checking sUserName, sFirstName, and sLastName, but not iSiteNumber ran in under one second. Likewise, checking iSiteNumber, but not sUserName, sFirstName, or sLastName also ran in under a second. The query was only slow if the iSiteNumber check and any other check (didn't matter which one or how many) was left in.
Something about this query is slower than the sum of its parts. Why?
A: Firt, however, be sure you have proper index then
In your iSiteNumber
You are using multiple subselect for in clause, this force the db engine for repeated access to data ..
for the others part each OR clause mean a repeated access to date
could be that you can rewrite you query avoiding these tecnique
eg instead of the not in for where bPrimarySite = 'true'
( SELECT top 1 iUserID
FROM CustomerSitePermissions where iUserID not in
(SELECT iUserID
FROM CustomerSitePermissions WHERE bPrimarySite = 'true'
)
)
you could use a inner join for the inverted logical query or a simplified query eg:
( SELECT top 1 iUserID
FROM CustomerSitePermissions where
bPrimarySite = 'false'
)
and you could try to rewrite you query for avoid the upper subselect for an IN clause and use a inner join .. if is possible.
These suggestion can be useful or not depending by the real logic and result you really need
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49324164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Not all rows are rendered in ng-grid in my project I'm fetching data from the server, and receive 20 data-items. However, only 6 rows are rendered, and inside ng-repeat there are 6 of them. However the height of the canvas is calculated correctly All other items appears after resize of the window.
This issue is similar to: https://github.com/angular-ui/ng-grid/issues/860
but using virtualizationThreshold doesn't work for me and there is no other way around
Here is part of controllers code:
app.controller('NagruzkaController', ['$scope', 'NagruzkaService', 'Cacher', 'RawInfoRetriever', '$timeout',
function ($scope, NagruzkaService, Cacher, RawInfoRetriever, $timeout) {
$scope.configRequest = {};
$scope.showLoader = false;
$scope.showTable = false;
$scope.fetch = function () {
$scope.showLoader = true;
NagruzkaService.getAll().then(function (data) {
var tmp = RawInfoRetriever(data);
$scope.nagruzkaData = tmp;
Cacher.nagruzka = $scope.nagruzkaData;
$scope.showLoader = false;
$scope.showTable = true;
});
}
};
$scope.gridOptions = {
data: 'nagruzkaData',
enableColumnResize: true,
showGroupPanel: true
};
In my html template I use ng-grid in this way:
<div class="gridStyle" ng-grid="gridOptions" ng-show="showTable"></div>
I got ng-grid via npm and my current version is 2.0.1
I've tried to get later version and tried to use 2.0.14, however with this version rows are not shown at all, untill window resizing.
Can anyone help me with this?
A: You will have to use a ng-grid plugin Flexible Height Plugin. Add this plugin to plugins property of the grid options.
$scope.gridOptions = {
data: 'nagruzkaData',
enableColumnResize: true,
showGroupPanel: true,
plugins: [new ngGridFlexibleHeightPlugin()]
};
A: Eventually, as I need to solve that problem as quick as I could, I ended up just triggering empty 'resize' event via jQuery, which made ng-grid rebuild and show all data received from the server.
A: please use this for not Not all rows are rendered in ng-grid
it will work 100%
$scope.gridOptions.excessRows = 100;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30759589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.