text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Firebase push notifiaction not working when app is closed on some devices I'm trying to send push notification from my app server to my app using Google cloud Messaging the app working well on Android Emulator but some devices not getting notification
here is FCMMessagingService.java
public class FCMMessagingService extends FirebaseMessagingService {
String title;String message;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null){
title = remoteMessage.getNotification().getTitle();
message = remoteMessage.getNotification().getBody();
Log.d("Message body", remoteMessage.getNotification().getBody().toString());
}
Map<String, String> data = remoteMessage.getData();
title = data.get("company");
message = data.get("message");
Log.d("Message body", remoteMessage.getData().toString());
Intent intent = new Intent(this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
super.onMessageReceived(remoteMessage);
}
}
here is Manifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FcmInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"></action>
</intent-filter>
</service>
<service
android:name=".FCMMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
A: If you getting the notification when your app is in foreground the it's ok you just use a data payload instead of notification payload you can use both together but data payload works when app in background or even close. I recommend you for only use the data payload because it's work 100% time. One of my app didn't get notification when app is closed but I used both payload then I just changed it to only data payload and it worked fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42599425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Storing objects with differing fields in a DB my situation is this:
I have similar objects that differ in certain fields.
Example:
object1:
- name:'Albert'
- home:'London'
- email:'[email protected]'
object2:
- name:'Jennifer'
- home:'Berlin'
- tel:'00492212232'
object3:
- name:'James'
- data:BIG_CHUNK_OF_BINARY_DATA
There is no fixed scheme which can be used in the definition of a RDBMS table. The definition of the objects is flexible with the possibility to add a custom field for a single object.
BIG_CHUNK_OF_BINARY_DATA means binary data in the size range from several bytes to several tens of megabytes. It should be possible to manage more than 100 objects of this kind with an overall mass of binary data in the lower gigabytes (1-5GB).
Now I'm searching for a database/format in which these objects can be stored efficiently. A search in the textual fields should be possible, of course. Perhaps a combination of JSON and a NoSQL-db is suitable? Or are there better solutions?
The target platforms would be Windows (mandatory) and Android (desireable).
Greets
Martin
A: I suggest looking at Couchbase Single Server (CouchDb). It holds a bunch of JSON documents in a schema-less structure. Structure is created through the use of 'Views' or indexes. They have a version running on Android too, although this is still in early development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7993977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Having trouble getting Admob test banner to display on app I'm trying to implement Google Admob into my app but the test banner isn't even displaying. I've managed to get rid of all debug error messages but still get nothing being display. Could it be hiding in the background? This code is implemented in my OnCreate method after OpenGL initialization. Have followed the guides on Google to the letter. I'm stumped.
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus){}
});
List<String> testDeviceIds = Arrays.asList("8X126XD7X13XD3X8CXE0X2BXA1X67XDX");
RequestConfiguration requestConfiguration
= new RequestConfiguration.Builder()
.setTestDeviceIds(testDeviceIds)
.setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_G)
.build();
MobileAds.setRequestConfiguration(requestConfiguration);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // ANDROID TEST ID
AdRequest adrequest = new AdRequest.Builder().build();
adView.loadAd(adrequest);
I've run adrequest.isTestDevice(this) and it comes back as TRUE so my device seems to be working. I'm testing on a real device (Sony Xperia XZ). Any ideas??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61979648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: postgresql merge dump from production to test server; add only new records i want to merge dump from production to test server database, to test few things, til now i always dropped current database, and restored everything from dump, but problem is that database is rather large to do this everytime (~90gb in database, and ~25gb as sql file)
database have ~50 tables, and i want to update all tables, in which data have been updated or there is new data
im using postgres 9.5, command i use for dump is
PGPASSWORD="mypassword" pg_dump -U $user -h $host -d $dbname | gzip > $dest_dir/postgres_backup_$DATE.gz
and to restore i use either
cat postgres_file | sudo -u postgres psql $dbname
#or
gunzip -c postgres.gz | pg_restore -U $user -h $host -d $dbname
but when i use them without dropping current database, i get errors, because schemes and relations are already there and it gives errors like
ERROR: duplicate key value violates unique constraint
DETAIL: Key (mykey)=(some_integer_value) already exists.
ERROR: multiple primary keys for table "table_name" are not allowed
ERROR: relation "some_relation" already exists
and it doesn't update database
i started to read about rules, but i lack knowledge in sql to make rule which would do what i want or is there other ways how to do it?
A: There is no way to selectively dump only new rows, because PostgreSQL has no way to know which ones are new.
But you can avoid deleting all the data upon restore. For that, upgrade to PostgreSQL v12 or better and use pg_dump with the options --on-conflict-do-nothing and --rows-per-insert=100. Then all the rows that already exist at the destination will be skipped.
You should upgrade anyway, 9.5 will go out of support this year.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61729007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What should be the input-shape number when i am adding the input layer in my ANN, considering that I have preprocessed the data with OneHotEncoder? My dataset has categorical and numerical features. The dataset has 7 independent variables and 1 dependent variable (called as a product). The dataset looks like this:
In general, there are 3 categorical variables, where 7 different categories correspond to the variable p1, 2 for p2, and 2 for p3. From p4-p7 and product are numerical.
For the categorical variables (columns 0 , 1 and 2), it was necessary to preprocess the data by using OneHotEncoder.
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct= ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0,1,2])], remainder = 'passthrough')
X = np.array(ct.fit_transform(X))
From the result of that encoding, the number of columns has increased. That change we can see in the next image.
As we see, each category has its own code, and the number of columns has increased. Now I got '15 columns' (11 + 4) in the dataset.
So, when I construct the ANN, in the input layer, what value should I add in the input shape, 7 or 15?
ann.add(tf.keras.Input(shape=(??,)))
A: After having run the fit line in my code, I have realized that the input-shape number must be equal to the number of columns obtained after the data preprocessing. Otherwise, it will result in an error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63568689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: jQuery select first accordion in each tab I have a page that uses jQuery tabs. Each tab contains one or more jQuery accordions, which are generated dynamically, in addition to other stuff. Example:
<div id="tab1" class="tab">
<div>
Some stuff
</div>
<div class="accordion">
I am an accordion
</div>
</div>
<div id="tab2" class="tab">
<div class="accordion">
I am also an accordion
</div>
More stuff
<div class="accordion">
I am also an accordion
</div>
</div>
I would like the first accordion in each tab to remain open, while the others (if there are any) are collapsed. I have tried:
$('.tab .accordion:first')
which only selects the first accordion on the page (obviously). I also tried:
$('.tab .accordion:first-child')
This selects the first accordion in tab2 but it doesn't select the one in tab1 because there's some stuff above it. I've also tried:
$('.tab > .accordion').filter(':first-child')
$('.tab').children('.accordion:first-child')
Along with about every combination of selectors I can think of. At this point my brain is fried. Before you point me to a duplicate question, none of these are asking the same question exactly:
JQuery Tab each Selected tab first text box focus
jquery select first child with class of a parent with class
jQuery selector for each first element on every parent
jQuery Selecting the first child with a specific attribute
The difference in my case is I have very little control over what content shows up in these tabs.
A: I'd suggest:
$('.tab').find('.accordion:first');
JS Fiddle proof-of-concept.
A: Try this:
$('.accordion:first', '.tab')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14905430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to use glyphicon images net core I am trying to migrate .NET MVC web app to .net core
I did put my assets in the wwwRoot folder as such:
Now the content folder includes the bootstrap. I am able to load the bootstrap.css but it is not finding the images
Here is the difinition of font-face:
here is my startup.cs
app.UseHttpsRedirection();
app.UseSession();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
I loaded the css in my view
< link rel="stylesheet" href="~/Content/bootstrap.css" />
I used it in my view
< span id="brand-icon" class="glyphicon glyphicon-cog">
A: please try this:
use complete url in @font-face such as below :
@font-face {
font-family : 'G....';
src : url('/content/fonts/.....');
....
}
A: Worked around it ../../fonts seems I need it to the wwwroot level
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62970156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: 405: Method Not Allowed after update to Spring Boot 1.3.0 I have setup an Authorization- and Resourceserver which both running within the same application. The setup is running fine with spring boot 1.2.6.RELEASE and spring security oauth2 2.0.7.RELEASE. After an update to spring boot 1.3.0.RELEASE (no matter if spring security oauth2 2.0.7.RELEASE or 2.0.8.RELEASE) the /login endpoint for POST requests is broken. I got the response 405 "Method Not Allowed".
I spent over a day without success. I also setup an additional, straightforward authorization- and resourceserver which both are running within the same application. However this lightweight setup have the same issue. As soon as I enable the resource server, the login endpoint no longer works.
Below the config snippets form my origin server.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// ... some code
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.logout()
.logoutUrl(logoutUrl)
.logoutSuccessHandler(logoutSuccessHandler)
.invalidateHttpSession(true)
.and()
.formLogin()
.permitAll()
.loginProcessingUrl(loginProcessingUrl)
.failureUrl(loginAuthenticationFailureUrl)
.loginPage(loginPage);
}
}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// ... some code
private static final String RESOURCE_SERVER_MAPPING_REGEX = "^(?!(\\/?login|\\/?logout|\\/?oauth)).*$";
// ...some code
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Configure the endpoints wherefore the resource server is responsible or rather should bound to.
.requestMatchers().regexMatchers(RESOURCE_SERVER_MAPPING_REGEX)
.and()
.authorizeRequests().anyRequest().permitAll()
.and()
.headers().frameOptions().disable();
}
}
A: Solution
It looks like that I am faced with the issue mentioned in @EnableResourceServer creates a FilterChain that matches possible unwanted endpoints with Spring Security 4.0.3 Spring Security is a dependency of spring-boot-starter-security. Due to the update of the spring-boot-starter-parent I switched from Spring Security 3.2.8 to 4.0.3. A further interesting comment regarding this issue can be found here.
I changed the ResourceServer configuration like the code snippets below which solve the problem.
It would be great to replace the RegexRequestMatcher definition by using a negation of already existing code to match the login and logout form or Matchers like the spring NotOAuthRequestMatcher which is currently a private inner class of the ResourceServerConfiguration. Please do not hesitate to post suggestion. ;-)
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// ... some code
private static final String RESOURCE_SERVER_MAPPING_REGEX = "^(?!(\\/?login|\\/?logout|\\/?oauth)).*$";
// ...some code
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(
new AndRequestMatcher(
new RegexRequestMatcher(RESOURCE_SERVER_MAPPING_REGEX, null)
)
).authorizeRequests().anyRequest().permitAll()
// ...some code
}
}
A: This should pretty straightforward.
POSTs and PUT requests would not be allowed if CSRF is enabled,and spring boot enables those by default.
Just add this to your ResourceServerConfig configuration code :
.csrf().disable()
This is also covered as an example problem here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33975226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Special Unicode Characters are not removed in Python 3 I have a keys list including words. When I make this command:
for key in keys:
print(key)
I get normal output in terminal.
but when I print the entire list using print(keys), I get this output:
I have tried using key.replace("\u202c", ''), key.replace("\\u202c", ''), re.sub(u'\u202c', '', key) but none solved the problem.
I also tried the solutions here, but none of them worked either:
Replacing a unicode character in a string in Python 3
Removing unicode \u2026 like characters in a string in python2.7
Python removing extra special unicode characters
How can I remove non-ASCII characters but leave periods and spaces using Python?
I scraped this from Google Trends using Beautiful Soup and retrieved text from get_text()
Also in the page source of Google Trends Page, the words are listed as follows:
When I pasted the text here directly from the page source, the text pasted without these unusual symbols.
A: You can just strip out the characters using strip.
>>> keys=['\u202cABCD', '\u202cXYZ\u202c']
>>> for key in keys:
... print(key)
...
ABCD
XYZ
>>> newkeys=[key.strip('\u202c') for key in keys]
>>> print(keys)
['\u202cABCD', '\u202cXYZ\u202c']
>>> print(newkeys)
['ABCD', 'XYZ']
>>>
Tried 1 of your methods, it does work for me:
>>> keys
['\u202cABCD', '\u202cXYZ\u202c']
>>> newkeys=[]
>>> for key in keys:
... newkeys += [key.replace('\u202c', '')]
...
>>> newkeys
['ABCD', 'XYZ']
>>>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45046341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: connect in qt using two different classes I want to connect a signal and a slot from two different classes in which one is using the other like this example:
form.hpp
class Form : public QDialog
{
Q_OBJECT
public:
explicit Form();
public slots:
void onPushButton(void);
};
form.cpp
Form::Form() :
QDialog(parent)
{
ui->setupUi(this);
connect(..., SIGNAL(clicked()),..., SLOT(onPushButton()));
}
void Form::onPushButton(void)
{
ui->pushButton->setText(QString("clicked"));
}
mainwindow.hpp
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
private:
Ui::MainWindow *ui;
Form f;
};
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
I know it easy to solve but I don't know how to do it. What the syntax of connect in Form::Form()?
If it was the way around I would do it like that:
connect(&f, SIGNAL(clicked()),this, SLOT(onPushButton()));
A: The connection must be made in the MainWindow constructor, but you must use a lambda method since the signal does not pass the text to it.
form.h
class Form : public QDialog
{
Q_OBJECT
public:
explicit Form();
public slots:
void processingFunction(const QString & text);
};
form.cpp
Form::Form() :
QDialog(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
}
void Form::processingFunction(const QString & text)
{
// some processing
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton, &QPushButton::clicked, [this](){
f.processingFunction(ui->lineEdit->text());
});
}
A: [UPDATE]
Class Form is not emiting clicked signal. You should connect a QPushButton (or similar) instead the class Form. Otherwise you should declare signal clicked() in your class and emit it somewhere in your code:
class Form : public QDialog
{
Q_OBJECT
public:
explicit Form();
signals:
void clicked();
public slots:
void onPushButton(void);
};
void Form::someFunction(/* parameters */)
{
emit clicked();
}
Also, if you want to make the connection you mention at the end, you should do it in the MainWindow class, because you can't access MainWindow from Form, unless you make MainWindow the parent of Form and then call parent() function to access MainWindow through a pointer. But that is an insane and discouraged programming practice because Form must not know about the existence of MainWindow.
Although Qt4-style connect() (using SIGNAL and SLOT macros) is still supported in Qt5, it's deprecated and may be removed from Qt6 in 2019, so you must switch to Qt5-style connect():
QObject::connect(lineEdit, &QLineEdit::textChanged,
label, &QLabel::setText);
This has several pros:
*
*Errors can be raised at compilation-time, rather than execution time.
*C++11 Lambdas can be used.
See this:
connect(sender, &QPushButton::clicked, [=]() {
// Code here. Do whatever you want.
});
*
*Are a lot faster to resolve.
Take a look at: Qt5 Signals and Slots
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51309144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Applying additional oauth scopes in an omniauth initializer I am trying to apply the coinbase wallet API with oauth to use its send functionality. I have been able to connect to the API and use its endpoints, but whenever I try to use the send functionality, I am thrown the error Invalid amount for meta[send_limit_amount]. My omniauth initializer looks like this:
provider :coinbase, , ENV['CLIENT_ID'], ENV['CLIENT_SECRET'],
scope: 'wallet:user:read wallet:user:email wallet:accounts:read wallet:transactions:send'
The reason for this error is because, in order to use the send functionality, coinbase requires additional parameter meta[send_limit_amount]. Where and how am I supposed to apply this additional scope?
UPDATE: So I've made some progress in that I am able to attach one meta scope to my initializer, which seems to be sticking (as shown when I print out the auth_info). This is the current state of my initializer:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :coinbase, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'], scope: 'wallet:user:read wallet:user:email wallet:accounts:read ', :meta => {'send_limit_currency' => 'BTC'}
end
# wallet:transactions:send
# :meta => {'send_limit_amount' => '0.0001'}
The problem now is that I cannot seem to figure the syntax necessary to add the send_limit_amount property to the oauth meta hash.
A: Managed to solve the problem with the following initializer;
Rails.application.config.middleware.use OmniAuth::Builder do
provider :coinbase, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'],
scope: 'wallet:user:read wallet:user:email wallet:accounts:read wallet:transactions:send',
:meta => {'send_limit_amount' => 1}
end
Now, I need to either disable the two factor authentication or determine how to Re-play the request with CB-2FA-Token header
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44687727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python assignment with AND and OR I am not much familiar with python. and I am write now looking into one code from python and it says something like this:
query = url.query and ('?' + url.query) or ''
can anyone help me understand what this means.
I found something similar here. but I couldn't interpret the above statement.
I am suppose to convert this line in Java.
A: That is very old - and quite unreliable - syntax for a ternary if. In modern Python it should be:
query = '?' + url.query if url.query else ''
and in Java:
query = url.query == '' ? '' : '?' + url.query
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30788837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When to use second level cache in hibernate I know how first and second level cache work in hibernate.
But I would like to know
1.when will be the first cache used and when will be the second
*how are the objects stored in the first and second. Do the second level maintains a copy same as first
A: The 1st level cache is maintained by the Session or EntityManager, and it's only used during the life of that object. That ensures that if you get/find/retrieve a specific entity more than once during the lifetime of a Session, you'll get the same instance back (or at least a proxy to the same instance).
The 2nd level cache is maintained outside the Session/EntityManager and usually there's a copy of the object, but that is not directly linked (as with objects in the Session).
A word of caution. If you use hibernate in an application that has several instances, the 2nd level cache is not shared amongst instances. For that you need to use a distributed cache (such as terracotta)... if you want consistency amongst the instances of the app. This is not a problem if you are caching static data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38549627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Script: Auto-trigger - if a new entry flags serious issue, spreadsheet emails admin for inspection I am pretty new to scripting. Please forgive, if I've missed an obvious step. I've searched through stack overflow, and my simple problem is not clearly mentioned.
We have a fleet of vans. The drivers enter issues through google forms, and it's added to a single google spreadsheet which has sheet/tabs for each vehicle. I want an email to be triggered once a new entry is made with the "serious issue found" and "Critical Immediate Action Requested" flag found in the drivers report.
(Spreadsheet is called "Fleet_Vehicles") (Each van is its own internal sheet: "Van_05-10" "Van_06-12" "Van_07-13") (The sheet meant for storing data (emails) for the script: Auto-Script-Logic)
This is google script I am attempting:
UPDATED: as per Coopers and Miturbe's input. Thank you gentlemen.
function CheckStatus() {
var ss = SpreadsheetApp.openById("120u_KtdWValZXUyn8vaAlEqbNwmRROYMj-fFTx8bPOs");
var FleetHealthRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Van_16-23");
var row = ss.getLastRow(); var columns = ss.getLastColumn(); var range = ss.getRange(row, 1, 5, columns).getValues();
var FleetHealth = FleetHealthRange.getValue();
if ("How_serious?" == "Serious Symptom Discovered")
if ("How_serious?" == "Critical Immediate Action Requested"){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Auto-Script-Logic").getRange("A1");
var emailAddress = emailRange.getValue();
var message = '(=sum(Van_16-23!A2:E20)'
var subject = 'This Van 16-23 has serious symptom';
MailApp.sendEmail('#####@gmail.com', subject, message);
}
Am I missing an embarrassing and obvious symantec?
Thank you in advance!
A: Try this:
function CheckStatus() {
var FleetHealthRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Van_05-11).getRange("E2");
var FleetHealth = FleetHealthRange.getValue();
if (How serious? == "Serious Symptom Discovered"){
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Auto-Script-Logic").getRange("A1");
var emailAddress = emailRange.getValue();
var message = 'This Van has serious symptom ' + FleetHealth; // Second column
var subject = '(=sum(Van_05-11!D2)';
MailApp.sendEmail(emailAddress, subject, message);
}
}
How Serious is undefined and if it's a variable it needs to be one string without spaces.
JavaScript Variable Naming
A: Something like this should work:
function CheckStatus() {
//var ss = SpreadsheetApp.openById("120u_KtdWValZXUyn8vaAlEqbNwmRROYMj-fFTx8bPOs");
var FleetHealthRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Van_16-23");
var row = FleetHealthRange.getLastRow();
var columns = FleetHealthRange.getLastColumn();
var range = FleetHealthRange.getRange(row, 1, 1, columns).getValues();
// By default, range is a 2D array so range[0][0] has the first column
var lastrow = range[0];
Logger.log("Reading row " + row + " columns " + columns)
//var FleetHealth = FleetHealthRange.getValue();
var column_serious = 5 //column number you want to compare, in this case 5 is column E
if (lastrow[column_serious] == "Serious Symptom Discovered" || lastrow[column_serious] == "Critical Immediate Action Requested")
{
var emailAddress = lastrow[0];
var message = '(=sum(Van_16-23!A2:E20)'
var subject = 'This Van 16-23 has serious symptom';
MailApp.sendEmail('#####@gmail.com', subject, message);
}
}
I placed the code here:
https://docs.google.com/spreadsheets/d/197oWwBDmB0iI3Ry9Km6mfO73Jjx9RWjXHI-bAM28bZs/edit?usp=sharing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64486851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++ Event queues, variadic functions, static functions and other strange stuff after yesterday's rip-roaring thread at How to implement a simple event queue? , I decided to finally make the big leap to c++11. Just before c++14 comes out probably...
Anyway, it occured to me that variadic functions are the perfect way forward in this enjoyable endeavour. They probably aren't really, but anyway, I managed to steal and bastardize some code I found somewhere, and ended up with this:
#include <iostream>
#include <functional>
#include <queue>
class Event
{
public:
int timeOfCompletion;
std::function<void()> function;
inline bool operator<(const Event& target) const
{
return target.timeOfCompletion < timeOfCompletion;
}
};
class System
{
public:
int someValue;
std::priority_queue<Event> funcs;
System()
{
someValue = 100;
}
template<typename Func, typename...Args>
void addFunctionToQueue(const int t , const Func&& myFunc, Args&&... myArgs)
{
Event newEvent;
std::function<void()> func = std::bind( std::forward<Func>(myFunc), std::ref(myArgs)...);
newEvent.function = func;
newEvent.timeOfCompletion = t;
funcs.push(newEvent);
}
void runAllFunctions()
{
while(!funcs.empty())
{
Event func = funcs.top();
funcs.pop();
func.function();
}
}
static void doStaticFunction(int a)
{
std::cout <<"I would like to change someValue here, but can't :-(\n";
//someValue -= a;//invalid
}
void doNonStaticFunction(int a)
{
someValue -= a;
std::cout <<"Set someValue to " << someValue << "\n";
}
};
int main()
{
System newSystem;
newSystem.doNonStaticFunction(5);
newSystem.addFunctionToQueue(5, System::doStaticFunction, 1);
newSystem.runAllFunctions();
//newSystem.addFunctionToQueue(5, newSystem.doStaticFunction, 1);// is invalid
//newSystem.addFunctionToQueue(5, System::doNonStaticFunction, 1);// is invalid
//newSystem.addFunctionToQueue(5, newSystem.doNonStaticFunction, 1);// is invalid
std::cin.ignore();
return 0;
}
Anyhow, how can I get the "addFunctionToQueue" function to work with non-static functions? I thought I had more questions, but I think if I can get that one answered, my other problems will hopefully be solved...
A: *
*Remove a const qualifier from the Func parameter.
template<typename Func, typename...Args>
void addFunctionToQueue(int t , Func&& myFunc, Args&&... myArgs)
// ~~~^ no const
Rationale: When using a forwarding reference (or an lvalue reference) type with a template argument deduction, a const qualifier is automatically deduced (depending on the argument's qualifiers). Giving it explicitly prevents the compiler from adding it to the Func type itself, which results in an error when you try to std::forward<Func>. That said, you would need to write std::forward<const Func> instead to avoid the compiler error, but still, that would make no sense, as const T&& is not a forwarding reference.
*Non-static member functions require an object for which they will be called, just like you write a.foo(), not foo().
newSystem.addFunctionToQueue(5, &System::doNonStaticFunction, &newSystem, 1);
// ~~~~~~~~~^ context
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26196383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can someone confirm my isolation level understanding please There are Five Isolation levels summary is mentioned below… Please correct me if I am wrong : -
*
*Read uncommited. In this level we can read dirty pages and chages can be done(DML statements like Insert and Update) on the rows even when records are not commited.
*Read Committed. Only committed rows can be read. If transaction is open at the time records are read deadlock will happen. Modifications to the data(Inserts and Updates) can be done even if transaction is not complete or not
*Repeatable Read. Will be Read commited + any update can happen only after the END TRANSACTION but insert command(Phantom insert) will do the changes even if data is not committed.
*Serializable. Rows can not be inserted using INSERT command and niether can UPDATE command work in uncommitted transaction nor can uncommitted data be read
*Snapshot. If there are two transactions T1 and T2. Commmitted data will be seen only after both these transactions are committed. If these two transactions are conflicting with each other then transaction will fail completely and transaction will be rollback
A: You need to first understand underline problems that isolation level resolves.
*
*Dirty read(I saw updated record however it disappeared again)
*Non repeatable read(Update - I saw an updated value but now value has
changed. Oh someone rolled back.)
*Phantom read(Insert - This appeared as a ghost and then disappeared)
Try to play around on two connections. First run connection 1 script then connection 2 script without committing anything. Once both scripts are executed then try to commit connection 1.
READ UNCOMMITTED - Connection running under this isolation level can read rows that have been modified by other transactions but not yet committed.
READ COMMITTED - Connection running under this isolation level cannot read data that has been modified but not committed by other transactions.
REPEATABLE READ - Transaction running under this isolation level cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by this transaction until the this transaction completes. This is done by placing shared lock on records read by this transaction. Having a shared on lock record, no other transaction can modify this record until this transaction completes.
SERIALIZABLE - Same conditions as we have for repeatable read with an addition of one more condition i.e. Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Think of a record as inserting a record between date range. You are trying to insert a record between the date range read by another connection.
DIRTY READ
Connection 1
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN
UPDATE tbl SET Col1 = 'Dummy' WHERE ID = 1
--NO COMMIT YET
Connection 2
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRAN
SELECT * FROM tbl WHERE ID = 1 -- will return you 'Dummy' if script
on connection 1 executed first. Since transaction on
connection 1 hasn't been committed yet, you did a dirty
read on connection 2.
--NO COMMIT YET
Avoiding Non repeatable read
Connection 1
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
BEGIN TRAN
SELECT * FROM tbl WHERE id = 5 --Issue shared lock. This prevents
other transactions from modifying any
rows that have been read by the current transaction.
--Not committed yet
Connection 2
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN
SELECT * FROM tbl WHERE id = 5
UPDATE tbl set name='XYZ' WHERE ID = 5 -- this will wait until transaction
at connection 1 is completed.
(Shared lock has been taken)
--Not committed yet
Avoiding Phantom read
Connection 1
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRAN
SELECT * FROM tbl WHERE Age BETWEEN 5 AND 15 -- This will issue range lock
--Not committed yet
Connection 2
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN
INSERT INTO tbl (Age) VALUES(4) -- Will insert successfully
INSERT INTO tbl (Age) VALUES(7) -- this will wait until transaction
at connection 1 is completed.
(Range lock has been taken)
--Not committed yet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30481280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Bug in VC++ 14.0 (2015) compiler? I've been running into some issues that only occurred during Release x86 mode and not during Release x64 or any Debug mode. I managed to reproduce the bug using the following code:
#include <stdio.h>
#include <iostream>
using namespace std;
struct WMatrix {
float _11, _12, _13, _14;
float _21, _22, _23, _24;
float _31, _32, _33, _34;
float _41, _42, _43, _44;
WMatrix(float f11, float f12, float f13, float f14,
float f21, float f22, float f23, float f24,
float f31, float f32, float f33, float f34,
float f41, float f42, float f43, float f44) :
_11(f11), _12(f12), _13(f13), _14(f14),
_21(f21), _22(f22), _23(f23), _24(f24),
_31(f31), _32(f32), _33(f33), _34(f34),
_41(f41), _42(f42), _43(f43), _44(f44) {
}
};
void printmtx(WMatrix m1) {
char str[256];
sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._11, m1._12, m1._13, m1._14);
cout << str << "\n";
sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._21, m1._22, m1._23, m1._24);
cout << str << "\n";
sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._31, m1._32, m1._33, m1._34);
cout << str << "\n";
sprintf_s(str, 256, "%.3f, %.3f, %.3f, %.3f", m1._41, m1._42, m1._43, m1._44);
cout << str << "\n";
}
WMatrix mul1(WMatrix m, float f) {
WMatrix out = m;
for (unsigned int i = 0; i < 4; i++) {
for (unsigned int j = 0; j < 4; j++) {
unsigned int idx = i * 4 + j; // critical code
*(&out._11 + idx) *= f; // critical code
}
}
return out;
}
WMatrix mul2(WMatrix m, float f) {
WMatrix out = m;
unsigned int idx2 = 0;
for (unsigned int i = 0; i < 4; i++) {
for (unsigned int j = 0; j < 4; j++) {
unsigned int idx = i * 4 + j; // critical code
bool b = idx == idx2; // critical code
*(&out._11 + idx) *= f; // critical code
idx2++;
}
}
return out;
}
int main() {
WMatrix m1(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
WMatrix m2 = mul1(m1, 0.5f);
WMatrix m3 = mul2(m1, 0.5f);
printmtx(m1);
cout << "\n";
printmtx(m2);
cout << "\n";
printmtx(m3);
int x;
cin >> x;
}
In the above code, mul2 works, but mul1 does not. mul1 and mul2 are simply trying to iterate over the floats in the WMatrix and multiply them by f, but the way mul1 indexes (i*4+j) somehow evaluates to incorrect results. All mul2 does different is it checks the index before using it and then it works (there are many other ways of tinkering with the index to make it work). Notice if you remove the line "bool b = idx == idx2" then mul2 also breaks...
Here is the output:
1.000, 2.000, 3.000, 4.000
5.000, 6.000, 7.000, 8.000
9.000, 10.000, 11.000, 12.000
13.000, 14.000, 15.000, 16.000
0.500, 0.500, 0.375, 0.250
0.625, 1.500, 3.500, 8.000
9.000, 10.000, 11.000, 12.000
13.000, 14.000, 15.000, 16.000
0.500, 1.000, 1.500, 2.000
2.500, 3.000, 3.500, 4.000
4.500, 5.000, 5.500, 6.000
6.500, 7.000, 7.500, 8.000
Correct output should be...
1.000, 2.000, 3.000, 4.000
5.000, 6.000, 7.000, 8.000
9.000, 10.000, 11.000, 12.000
13.000, 14.000, 15.000, 16.000
0.500, 1.000, 1.500, 2.000
2.500, 3.000, 3.500, 4.000
4.500, 5.000, 5.500, 6.000
6.500, 7.000, 7.500, 8.000
0.500, 1.000, 1.500, 2.000
2.500, 3.000, 3.500, 4.000
4.500, 5.000, 5.500, 6.000
6.500, 7.000, 7.500, 8.000
Am I missing something? Or is it actually a bug in the compiler?
A: This afflicts only the 32-bit compiler; x86-64 builds are not affected, regardless of optimization settings. However, you see the problem manifest in 32-bit builds whether optimizing for speed (/O2) or size (/O1). As you mentioned, it works as expected in debugging builds with optimization disabled.
Wimmel's suggestion of changing the packing, accurate though it is, does not change the behavior. (The code below assumes the packing is correctly set to 1 for WMatrix.)
I can't reproduce it in VS 2010, but I can in VS 2013 and 2015. I don't have 2012 installed. That's good enough, though, to allow us to analyze the difference between the object code produced by the two compilers.
Here is the code for mul1 from VS 2010 (the "working" code):
(Actually, in many cases, the compiler inlined the code from this function at the call site. But the compiler will still output disassembly files containing the code it generated for the individual functions prior to inlining. That's what we're looking at here, because it is more cluttered. The behavior of the code is entirely equivalent whether it's been inlined or not.)
PUBLIC mul1
_TEXT SEGMENT
_m$ = 8 ; size = 64
_f$ = 72 ; size = 4
mul1 PROC
___$ReturnUdt$ = eax
push esi
push edi
; WMatrix out = m;
mov ecx, 16 ; 00000010H
lea esi, DWORD PTR _m$[esp+4]
mov edi, eax
rep movsd
; for (unsigned int i = 0; i < 4; i++)
; {
; for (unsigned int j = 0; j < 4; j++)
; {
; unsigned int idx = i * 4 + j; // critical code
; *(&out._11 + idx) *= f; // critical code
movss xmm0, DWORD PTR [eax]
cvtps2pd xmm1, xmm0
movss xmm0, DWORD PTR _f$[esp+4]
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax], xmm1
movss xmm1, DWORD PTR [eax+4]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+4], xmm1
movss xmm1, DWORD PTR [eax+8]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+8], xmm1
movss xmm1, DWORD PTR [eax+12]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+12], xmm1
movss xmm2, DWORD PTR [eax+16]
cvtps2pd xmm2, xmm2
cvtps2pd xmm1, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+16], xmm1
movss xmm1, DWORD PTR [eax+20]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+20], xmm1
movss xmm1, DWORD PTR [eax+24]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+24], xmm1
movss xmm1, DWORD PTR [eax+28]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+28], xmm1
movss xmm1, DWORD PTR [eax+32]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+32], xmm1
movss xmm1, DWORD PTR [eax+36]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+36], xmm1
movss xmm2, DWORD PTR [eax+40]
cvtps2pd xmm2, xmm2
cvtps2pd xmm1, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+40], xmm1
movss xmm1, DWORD PTR [eax+44]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+44], xmm1
movss xmm2, DWORD PTR [eax+48]
cvtps2pd xmm1, xmm0
cvtps2pd xmm2, xmm2
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+48], xmm1
movss xmm1, DWORD PTR [eax+52]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
movss DWORD PTR [eax+52], xmm1
movss xmm1, DWORD PTR [eax+56]
cvtps2pd xmm1, xmm1
cvtps2pd xmm2, xmm0
mulsd xmm1, xmm2
cvtpd2ps xmm1, xmm1
cvtps2pd xmm0, xmm0
movss DWORD PTR [eax+56], xmm1
movss xmm1, DWORD PTR [eax+60]
cvtps2pd xmm1, xmm1
mulsd xmm1, xmm0
pop edi
cvtpd2ps xmm0, xmm1
movss DWORD PTR [eax+60], xmm0
pop esi
; return out;
ret 0
mul1 ENDP
Compare that to the code for mul1 generated by VS 2015:
mul1 PROC
_m$ = 8 ; size = 64
; ___$ReturnUdt$ = ecx
; _f$ = xmm2s
; WMatrix out = m;
movups xmm0, XMMWORD PTR _m$[esp-4]
; for (unsigned int i = 0; i < 4; i++)
xor eax, eax
movaps xmm1, xmm2
movups XMMWORD PTR [ecx], xmm0
movups xmm0, XMMWORD PTR _m$[esp+12]
shufps xmm1, xmm1, 0
movups XMMWORD PTR [ecx+16], xmm0
movups xmm0, XMMWORD PTR _m$[esp+28]
movups XMMWORD PTR [ecx+32], xmm0
movups xmm0, XMMWORD PTR _m$[esp+44]
movups XMMWORD PTR [ecx+48], xmm0
npad 4
$LL4@mul1:
; for (unsigned int j = 0; j < 4; j++)
; {
; unsigned int idx = i * 4 + j; // critical code
; *(&out._11 + idx) *= f; // critical code
movups xmm0, XMMWORD PTR [ecx+eax*4]
mulps xmm0, xmm1
movups XMMWORD PTR [ecx+eax*4], xmm0
inc eax
cmp eax, 4
jb SHORT $LL4@mul1
; return out;
mov eax, ecx
ret 0
?mul1@@YA?AUWMatrix@@U1@M@Z ENDP ; mul1
_TEXT ENDS
It is immediately obvious how much shorter the code is. Apparently the optimizer got a lot smarter between VS 2010 and VS 2015. Unfortunately, sometimes the source of the optimizer's "smarts" is the exploitation of bugs in your code.
Looking at the code that matches up with the loops, you can see that VS 2010 is unrolling the loops. All of the computations are done inline so that there are no branches. This is kind of what you'd expect for loops with upper and lower bounds that are known at compile time and, as in this case, reasonably small.
What happened in VS 2015? Well, it didn't unroll anything. There are 5 lines of code, and then a conditional jump JB back to the top of the loop sequence. That alone doesn't tell you much. What does look highly suspicious is that it only loops 4 times (see the cmp eax, 4 statement that sets flags right before doing the jb, effectively continuing the loop as long as the counter is less than 4). Well, that might be okay if it had merged the two loops into one. Let's see what it's doing inside of the loop:
$LL4@mul1:
movups xmm0, XMMWORD PTR [ecx+eax*4] ; load a packed unaligned value into XMM0
mulps xmm0, xmm1 ; do a packed multiplication of XMM0 by XMM1,
; storing the result in XMM0
movups XMMWORD PTR [ecx+eax*4], xmm0 ; store the result of the previous multiplication
; back into the memory location that we
; initially loaded from
inc eax ; one iteration done, increment loop counter
cmp eax, 4 ; see how many loops we've done
jb $LL4@mul1 ; keep looping if < 4 iterations
The code reads a value from memory (an XMM-sized value from the location determined by ecx + eax * 4) into XMM0, multiplies it by a value in XMM1 (which was set outside the loop, based on the f parameter), and then stores the result back into the original memory location.
Compare that to the code for the corresponding loop in mul2:
$LL4@mul2:
lea eax, DWORD PTR [eax+16]
movups xmm0, XMMWORD PTR [eax-24]
mulps xmm0, xmm2
movups XMMWORD PTR [eax-24], xmm0
sub ecx, 1
jne $LL4@mul2
Aside from a different loop control sequence (this sets ECX to 4 outside of the loop, subtracts 1 each time through, and keeps looping as long as ECX != 0), the big difference here is the actual XMM values that it manipulates in memory. Instead of loading from [ecx+eax*4], it loads from [eax-24] (after having previously added 16 to EAX).
What's different about mul2? You had added code to track a separate index in idx2, incrementing it each time through the loop. Now, this alone would not be enough. If you comment out the assignment to the bool variable b, mul1 and mul2 result in identical object code. Clearly without the comparison of idx to idx2, the compiler is able to deduce that idx2 is completely unused, and therefore eliminate it, turning mul2 into mul1. But with that comparison, the compiler apparently becomes unable to eliminate idx2, and its presence ever so slightly changes what optimizations are deemed possible for the function, resulting in the output discrepancy.
Now the question turns to why is this happening. Is it an optimizer bug, as you first suspected? Well, no—and as some of the commenters have mentioned, it should never be your first instinct to blame the compiler/optimizer. Always assume that there are bugs in your code unless you can prove otherwise. That proof would always involve looking at the disassembly, and preferably referencing the relevant portions of the language standard if you really want to be taken seriously.
In this case, Mystical has already nailed the problem. Your code exhibits undefined behavior when it does *(&out._11 + idx). This makes certain assumptions about the layout of the WMatrix struct in memory, which you cannot legally make, even after explicitly setting the packing.
This is why undefined behavior is evil—it results in code that seems to work sometimes, but other times it doesn't. It is very sensitive to compiler flags, especially optimizations, but also target platforms (as we saw at the top of this answer). mul2 only works by accident. Both mul1 and mul2 are wrong. Unfortunately, the bug is in your code. Worse, the compiler didn't issue a warning that might have alerted you to your use of undefined behavior.
A: If we look at the generated code, the problem is fairly clear. Ignoring a few bits and pieces that aren't related to the problem at hand, mul1 produces code like this:
movss xmm1, DWORD PTR _f$[esp-4] ; load xmm1 from _11 of source
; ...
shufps xmm1, xmm1, 0 ; duplicate _11 across floats of xmm1
; ...
for ecx = 0 to 3 {
movups xmm0, XMMWORD PTR [dest+ecx*4] ; load 4 floats from dest
mulps xmm0, xmm1 ; multiply each by _11
movups XMMWORD PTR [dest+ecx*4], xmm0 ; store result back to dest
}
So, instead of multiplying each element of one matrix by the corresponding element of the other matrix, it's multiplying each element of one matrix by _11 of the other matrix.
Although it's impossible to confirm exactly how it happened (without looking through the compiler's source code), this certainly fits with @Mysticial's guess about how the problem arose.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39209578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Trying to flush database upon app reinstall - Titanium alloy Here is my code:
if (!Ti.App.Properties.hasProperty('installed')) {
alert('This is my first run');
//check first installed
Ti.App.Properties.setBool('installed', 1);
//store version number in Ti.App.Properties
Ti.App.Properties.setString('currentVersion', Titanium.App.version);
//import DB from Titanium's Resources directory or one of its descendants, if exist
//create DB
createDB();
}
//check app version
checkAppVersion();
function createDB() {
//createDB
var db = Ti.Database.open('appdb');
alert('db created');
db.close();
}
function checkAppVersion() {
alert(Titanium.App.version);
var curversion = Titanium.App.Properties.getString('currentVersion');
var appversion = Titanium.App.version;
if (curversion != appversion) {
//flush database
alert('flush database');
flushDb();
} else {
//leave existing database
alert('leave database alone!');
}
}
function flushDb() {
// Get database object reference to previous database, if any.
// If it did not exist previously, this will create a new empty db.
var dbOld = Ti.Database.open('appdb');
// Now remove the database, whether it existed before or we just
// created it above. The remove() method requires a database object
// reference, so we had to start by opening it above.
dbOld.remove();
dbOld.close();
// At this point, whether or not there was a previous database it
// is now gone.
//store version number in Ti.App.Properties
Ti.App.Properties.setString('currentVersion', Titanium.App.version);
//create DB
createDB();
}
Code works like this:
If app is freshly installed. Create a DB, set version and run app. Alloy models are then executed and everything runs fine.
The problem is when I flush the DB after a version change, I get a SQL error, complaining a table cannot be found after I have deleted it. Even though I have done a fresh reinstall of the DB.
To get it to work I have to quit app and reopen it. I have no idea why this is happening and I am pretty stuck.
UPDATE:
Coded a solution for this problem, but I am not happy with it.
When flushing the database, instead of deleting the database, I deleted all of the tables. And then in create DB, I basically called an SQL query to create the tables.
The problem here is that if I ever updated my models, I will have to update the schema in two places.
If anyone has a better solution, do let me know, cheers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24521009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual Studio: DLL locations for release I have a project that I am working on that references a "Common Library (DLL)". In the DevEnv it works fine, however if I build and try to organize my files it doesn't work. Basically if I have things setup like so:
*
*C:\Program Files\MyApp\MyApp.exe
*C:\Program Files\MyApp\Common\WPF Commons.dll
*C:\Program Files\MyApp\Modules\SomeModule.dll
*etc
MyApp.exe doesn't work. It tries to look only in the current directory for the DLL files. So how do I set it up in Visual Studio so that when I build the application knows to look for the DLLs in those other folders?
Oh, and I realize that it does work in Dev because all the DLLs are put in the same folder. I don't want to do that for release though :-/
A: What you need to do is add a private probing path into the application configuration file. This tells the CLR which directories to look in for extra assemblies.
*
*http://msdn.microsoft.com/en-us/library/823z9h8w.aspx
Sample app.config
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="Common;Modules"/>
</assemblyBinding>
</runtime>
</configuration>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3561099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I'm a prolog newbie and I'm stuck in a program Goal:
Apply a loop in the above given code so that it will ask, “Do you want to continue? (Y/ N)” and then act accordingly. (Hint: make a predicate ‘again/0’ for doing above task).
go:-
write('What is the name of Patient?'),
read(Patient),nl,
hypo(Patient, Disease),
write(Patient),
write(' probably has '),
write(Disease),nl.
go:-
write('Sorry I am unable to diagnose the Disease.'),nl.
hypo(Patient,flu):-
sym(Patient,fever),
sym(Patient,cough).
hypo(Patient,headche):-
sym(Patient,bodypain).
sym(Patient,fever):-
write(' Does '),
write(Patient),
write(' has fever (y/n)?'),
res(R), R='y'.
sym(Patient,cough):-
write('Does '),
write(Patient),
write(' has cough (y/n)?'),
res(R), R='y'.
sym(Patient,bodypain):-
write('Does '),
write(Patient),
write(' has bodypain (y/n)?'),
res(R), R='y'.
res(R):-
read(R),nl.
A: You've given a model with a go predicate. The trick is that you get a loop by calling a predicate again recursively if R='y' doesn't fail.
again :-
write('Do you want to continue? (Y/ N)'),
res(R), R='y',
go,
again.
again :-
write('OK, bye'),nl.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22141279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Can't get this query to work. Mysql update select another query then update UPDATE `tombaldi_2bj3de9ad`.`catalog_product_option_type_value`
SET `catalog_product_option_type_value`.`option_id` = '72'
WHERE `catalog_product_option_type_value`.`option_id` IN
(SELECT `catalog_product_option_type_value`.`option_id`
FROM `tombaldi_2bj3de9ad`.`catalog_product_option_type_title`
INNER JOIN `tombaldi_2bj3de9ad`.`catalog_product_option_type_value` ON catalog_product_option_type_title.option_type_id = catalog_product_option_type_value.option_type_id
WHERE (
CONVERT( `title` USING utf8 ) LIKE '%initials%'
))
I get the error
#1093 - You can't specify target table 'catalog_product_option_type_value' for update in FROM clause
Trying to solve this one. Have researched and tried and tried again.
A: In mysql you can't use same table in query during update,this can be done by giving the new alias to your subquery
UPDATE tombaldi_2bj3de9ad.catalog_product_option_type_value
SET catalog_product_option_type_value.option_id = '72'
WHERE catalog_product_option_type_value.option_id
IN (SELECT t.option_id
FROM (
SELECT catalog_product_option_type_value.option_id
FROM tombaldi_2bj3de9ad.catalog_product_option_type_title
INNER JOIN tombaldi_2bj3de9ad.catalog_product_option_type_value
ON catalog_product_option_type_title.option_type_id = catalog_product_option_type_value.option_type_id
WHERE ( CONVERT( title USING utf8 ) LIKE '%initials%' )
) t
)
Or even better to use join in your update query
UPDATE
tombaldi_2bj3de9ad.catalog_product_option_type_value cv
JOIN tombaldi_2bj3de9ad.catalog_product_option_type_title ct
ON(ct.option_type_id = cv.option_type_id )
SET
cv.option_id = '72'
WHERE CONVERT(ct.title USING utf8) LIKE '%initials%'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22849396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Run Ajax from java script function in tpl file PRESTASHOP Im working on a PrestaShop payment method and I have a tpl page with a button and a div which is hidden. On the button click, I want to execute an ajax function and show the div on success, but its not doing anything.
HTML Elements:
<input id="showVerifCode" type="button" value="Get Verification Code" style="background: #3e64ff; border-color: #3e64ff; color: #fff; padding: 11px 16px; cursor: pointer; border-width: 1px; border-radius: 2px; font-size: 14px; font-weight: 400; margin-top: 16px; margin-bottom: 0px;">
<div id="verifCode" style="display: none;">
<p style="margin-top: 5px;"><small id="email-send-info" style="color: #6fdc6f;">Please check your mail for the verification code!</small></p>
<P style="margin-bottom: 0; margin-top: 16px;">Verification Code:</P>
<input placeholder="E.g 1234567890" width="50px" name="verifCode" required type="text" style="margin-top: 1px; width: 100%; padding: 12px 20px; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;"/>
</div>
JavaScript Function:
{literal}
<script type="text/javascript">
const targetDiv = document.getElementById("verifCode");
const btn = document.getElementById("showVerifCode");
btn.onclick = function () {
$.ajax({
url: {$link->getModuleLink('prestashopbeam', 'AjaxSendMail.php', array())},
type: 'GET',
data: 'ajax=true&clientgroups='+ 'test5858',
cache: false,
success: function(data) {
if (targetDiv.style.display === "none") {
targetDiv.style.display = "block";
}
}
});
};
</script>
{/literal}
PHP Ajax page (located in /modules/my_module/AjaxSendMail.php
<?php
return;
I only have this return there because I want to test out the ajax part first.
Sorry if this a very noob question but this is the first time I am using ajax, and I am no PHP or JavaScript master either.
Thank you in advance.
EDIT: I have tried using JQuery but the result is the same. I made sure the code runs when the button is pressed by only making it show the hidden div and it works, but not when I put the ajax code.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
{literal}
$( "#showVerifCode" ).click(
function() {
$.ajax({
url: {$link->getModuleLink('prestashopbeam', 'AjaxSendMail.php', array())},
type: 'GET',
data: 'ajax=true&clientgroups='+ 'teste5858',
cache: false,
success: function(data) {
$("#verifCode").show();
}
});
}
);
{/literal}
</script>
EDIT 2: The link was why this was giving problems. I have change to url to url: '{/literal}{$link}{literal}', but the request on my browser tools still gives a 404 not found despite the path looking alright to me.
Image of Request
EDIT 3: I fixed it. The issue was still with the url. The final method is as follows:
$link = $this->context->link->getModuleLink($this->name, 'ajax', array('ajax'=>true), true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68194803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extremely simple Swift signal SIGABRT
I fail to understand why my app is giving me a Thread 1: signal SIGABRT error.
I basically have a text field that I only want to be numbers, do a calculation when the button is pressed an put it in the other label.
I had more code around it with more boxes and buttons and simplified it to this and it still doesn't work!
Thank you!
A: I suggest you to check the following thread: Thread 1: signal SIGABRT in Xcode 9
Quoting from my answer:
SIGABRT happens when you call an outlet that is not there.
*
*No view is connected
*Duplicate might be there
Outlets are references to storyboard/xib-based UI elements inside
your view controller. Make sure whatever you are trying to call is
there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47837797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement input JSON validation in Grails? What is the correct way of implementing request body (JSON, XML) sent with POST or PUT method in Grails framework?
In Spring there is a @Valid annotation used to annotate method's argument and a bunch of field annotations (@NotNull e.g.) and exception mapper used to send validation response automatically. I can't find anything similar in Grails.
A: Grails performs validation via a Domain's constraints block. For example:
class User {
String username
String password
static constraints = {
username nullable: false, maxSize: 50, email: true
password nullable: false, maxSize: 64
}
}
See documentation.
Validation is performed during a couple of different actions on the domain:
user.save() // validates and only persists if no errors
user.validate() // validates only
Again, see the documentation. This is similar to what Spring's @Valid does. Looking at its documentation, it states:
Spring MVC will validate a @Valid object after binding so-long as an
appropriate Validator has been configured.
What makes this basically the same as what Grails is doing is that it occurs after binding. For JSON/XML to Domain object conversion, it is really as simple as this:
def jsonObject = request.JSON
def instance = new YourDomainClass(jsonObject)
See this answer here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23228607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Vista services: Can show form on invisible desktop? I am attempting to show a form from a service on Vista (using .NET winforms)
Obviously the form would not show to the console user, as services are isolated in session 0.
However the experiment is to see if it is possible to "show" an invisible form and obtain a window handle & message loop
I have tried but when I issue form.Show(), only the form.Load event fires not .Shown or .FormClosing
Is there any way to capture windows messages in this way as a user application would?
I have not attempted to make the service 'interactive' as I do not wish to interact with the logged-on user.
A: Yes you can show a form on a service's desktop. It will not be shown to any logged in user, in fact in Vista and later OSes you cannot show it to a user even if you set the service to 'interactive'. Since the desktop is not interactive the windows messages the form receives will be slightly different but the vast majority of the events should be triggered the same in a service as they would be on an interactive desktop (I just did a quick test and got the form load, shown, activated and closing events).
One thing to remember is that in order to show a form your thread must be an STA thread and a message loop must be created, either by calling ShowDialog or Applicaton.Run. Also, remember all external interaction with the form will need to be marshaled to the correct thread using Invoke or BeginInvoke on the form instance.
This is certainly very doable but is really not recommended at all. You must be absolutely sure that the form and any components it contains will not show any unexpected UI, such as a message box, under any circumstances. The only time this method can really be justified is when you are working with a dubious quality legacy or 3rd party tool that requires handle creation in order to function properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1638768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In PowerShell, how to map a list to a search string PowerShell noob question here. I have groups of servers that are listed in separate lists. Each server has an error log that I scan for certain errors. However, each group of servers has its own unique set of errors that I scan using a specific search string for that server group. What I'm basically doing is creating a condition based on the server list name and mapping the appropriate search string for that server group.
Something like this:
$SERVER_LST_1 = "$pwd\servers\servers_1.lst"
$SERVER_LST_2 = "$pwd\servers\servers_2.lst"
$SERVER_LST_3 = "$pwd\servers\servers_3.lst"
$SEARCH_STR_1 = "Error text for server group 1"
$SEARCH_STR_2 = "Error text for server group 2"
$SEARCH_STR_3 = "Error text for server group 3"
$Servers1 = Get-Content $SERVER_LST_1
ForEach ($Server1 in $Servers1)
{
$StartupErrorLog1 = Get-ChildItem -Path \\$Server1\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_1
}
$Servers2 = Get-Content $SERVER_LST_2
ForEach ($Server2 in $Servers2)
{
$StartupErrorLog2 = Get-ChildItem -Path \\$Server2\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_2
}
$Servers3 = Get-Content $SERVER_LST_3
ForEach ($Server3 in $Servers3)
{
$StartupErrorLog3 = Get-ChildItem -Path \\$Server3\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $SEARCH_STR_3
}
I would like to make the code more efficient by not using so many conditions. Is there a cleaner approach to map the search strings to their appropriate server group by using less code? Hope that makes sense.
A: You can refactor it into something like below:
$groups = @{
"$pwd\servers\servers_1.lst"="Error text for server group 1";
"$pwd\servers\servers_2.lst"="Error text for server group 2";
"$pwd\servers\servers_3.lst"="Error text for server group 3";
}
$startupErrors = @{}
$groups.keys | %{
$key = $_
gc $key | %{
$startupErrors[$_] = Get-ChildItem -Path \\$_\$LOG_PATH -Include StartupError.log -Recurse | Select-String -notmatch $groups["$key"]
}
}
Basically, using an HashTable to associate the search text and the server group. Also, I have given only the refactoring solution, but the Get-ChildItem and Select-String may not be doing what you want to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8888579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: getParent returns wrong ViewGroup When execute code below I can verify in my LogCat that getParent returns an other ViewGroup then FrameLayout (It returns LinearLayout). Normally I would expect that getParent would return the framelayout...
Does anyone know why this is occuring?
java:
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.actionbar_btn);
if (button.getParent() instanceof FrameLayout) {
Log.v("TAG", "parent was framelayout");
} else {
Log.v("TAG", "parent was no framelayout");
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00FF00"
android:orientation="horizontal" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/actionbar_home"
android:layout_width="33dp"
android:layout_height="32dp"
android:background="@drawable/ic_launcher"
/>
</FrameLayout>
.....
</LinearLayout>
</RelativeLayout>
A: Shouldn't you change your R.id.actionbar_btn to R.id.actionbar_home?
A: I think you are getting wrong id for Button:
<Button
android:id="@+id/actionbar_home"
android:layout_width="33dp"
android:layout_height="32dp"
android:background="@drawable/ic_launcher"
/>
final Button button = (Button) findViewById(R.id.actionbar_btn);
"R.id.actionbar_btn" and android:id="@+id/actionbar_home" should be same
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20000814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can only scrape the base price with requests html In the product price listed below, I fail to scrape the prices of the more expensive options.
Strangely, I can save a direct URL link and see the correct price when the page loads. However, when I scrape the same link with requests-html, I only get the base price of the base product.
from requests_html import HTMLSession
url = 'https://www.staegerag.ch/shop/index.php?id_product=321&controller=product&search_query=level&results=2#/273-farbe-gold_tone_light_oak/233-sprachsteuerung-nein'
session = HTMLSession()
r = session.get(url)
print(r.html.find('span[id="our_price_display"]', first=True).text)
Results in 1'399.00 CHF instead of 1'699.00 CHF
A: After various google searches, i came across a simple solution. since i'm still a relatively new kid on the programming block, i didn't notice that my code didn't call chromium at all. my price to be scrapped is in java. I just had to render the page via: r.html.render() in chromium.
solution:
from requests_html import HTMLSession
url = 'https://www.staegerag.ch/shop/index.php?
id_product=321&controller=product&search_query=level&results=2#/273-farbe-
gold_tone_light_oak/233-sprachsteuerung-nein'
session = HTMLSession()
r = session.get(url)
r.html.render()
print(r.html.find('span[id="our_price_display"]', first=True).text)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70585079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I unit test whether the ChangeNotifier's notifyListeners was called in Flutter/Dart? I'm using the provider package in our app and I want to test my ChangeNotifier class individually to have simple unit tests checking the business logic.
Apart from the values of ChangeNotifier properties, I also want to ensure that in certain cases (where necessary), the notifyListeners has been called, as otherwise, the widgets that rely on up-to-date information from this class would not be updated.
Currently, I'm indirectly testing whether the notifyListeners have been called: I'm using the fact that the ChangeNotifier lets me add a callback using its addListener method. In the callback that I add in our testing suite, I simply increment an integer counter variable and make assertions on that.
Is this the right way to test whether my ChangeNotifier calls its listeners? Is there a more descriptive way of testing this?
Here is the class I'm testing:
import 'package:flutter/foundation.dart';
class ExampleModel extends ChangeNotifier {
int _value = 0;
int get value => _value;
void increment() {
_value++;
notifyListeners();
}
}
and this is how I test it:
import 'package:mobile_app/example_model.dart';
import 'package:test/test.dart';
void main() {
group('$ExampleModel', () {
ExampleModel exampleModel;
int listenerCallCount;
setUp(() {
listenerCallCount = 0;
exampleModel = ExampleModel()
..addListener(() {
listenerCallCount += 1;
});
});
test('increments value and calls listeners', () {
exampleModel.increment();
expect(exampleModel.value, 1);
exampleModel.increment();
expect(listenerCallCount, 2);
});
test('unit tests are independent from each other', () {
exampleModel.increment();
expect(exampleModel.value, 1);
exampleModel.increment();
expect(listenerCallCount, 2);
});
});
}
A: I've ran into the same Issue. It's difficult to test wether notifyListeners was called or not especially for async functions. So I took your Idea with the listenerCallCount and put it to one function you can use.
At first you need a ChangeNotifier:
class Foo extends ChangeNotifier{
int _i = 0;
int get i => _i;
Future<bool> increment2() async{
_i++;
notifyListeners();
_i++;
notifyListeners();
return true;
}
}
Then the function:
Future<R> expectNotifyListenerCalls<T extends ChangeNotifier, R>(
T notifier,
Future<R> Function() testFunction,
Function(T) testValue,
List<dynamic> matcherList) async {
int i = 0;
notifier.addListener(() {
expect(testValue(notifier), matcherList[i]);
i++;
});
final R result = await testFunction();
expect(i, matcherList.length);
return result;
}
Arguments:
*
*The ChangeNotifier you want to test.
*The function which should fire notifyListeners (just the reference to the function).
*A function to the state you want to test after each notifyListeners.
*A List of the expected values of the state you want to test after each notifyListeners (the order is important and the length has to equal the notifyListeners calls).
And this is how to test the ChangeNotifier:
test('should call notifyListeners', () async {
Foo foo = Foo();
expect(foo.i, 0);
bool result = await expectNotifyListenerCalls(
foo,
foo.increment2,
(Foo foo) => foo.i,
<dynamic>[isA<int>(), 2]);
expect(result, true);
});
A: Your approach seems fine to me but if you want to have a more descriptive way you could also use Mockito to register a mock callback function and test whether and how often the notifier is firing and thus notifying your registered mock instead of incrementing a counter:
import 'package:mobile_app/example_model.dart';
import 'package:test/test.dart';
/// Mocks a callback function on which you can use verify
class MockCallbackFunction extends Mock {
call();
}
void main() {
group('$ExampleModel', () {
late ExampleModel exampleModel;
final notifyListenerCallback = MockCallbackFunction(); // Your callback function mock
setUp(() {
exampleModel = ExampleModel()
..addListener(notifyListenerCallback);
reset(notifyListenerCallback); // resets your mock before each test
});
test('increments value and calls listeners', () {
exampleModel.increment();
expect(exampleModel.value, 1);
exampleModel.increment();
verify(notifyListenerCallback()).called(2); // verify listener were notified twice
});
test('unit tests are independent from each other', () {
exampleModel.increment();
expect(exampleModel.value, 1);
exampleModel.increment();
expect(notifyListenerCallback()).called(2); // verify listener were notified twice. This only works, if you have reset your mocks
});
});
}
Just keep in mind that if you trigger the same mock callback function in multiple tests you have to reset your mock callback function in the setup to reset its counter.
A: I have wrap it to the function
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
dynamic checkNotifierCalled(
ChangeNotifier notifier,
Function() action, [
Matcher? matcher,
]) {
var isFired = false;
void setter() {
isFired = true;
notifier.removeListener(setter);
}
notifier.addListener(setter);
final result = action();
// if asynchronous
if (result is Future) {
return result.then((value) {
if (matcher != null) {
expect(value, matcher);
}
return isFired;
});
} else {
if (matcher != null) {
expect(result, matcher);
}
return isFired;
}
}
and call it by:
final isCalled = checkNotifierCalled(counter, () => counter.increment(), equals(2));
expect(isCalled, isTrue);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59932068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: error while passing the date value in the URL I want to pass the value which is of date format through the URL to the java controller, but it's throwing javascript errors near the date.
My URL is as below:
var dataUrl = myAppURL+'/detailData/'+adviceNum+'/'+dateCreated +'/myDetailData.form';
Below code is how i'm getting the date value.
dateCreated = new Date(value.dateCreated);
var dd = dateString.getDate();
var mm = dateString.getMonth()+1;
var yyyy = dateString.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
dateCreated = yyyy + '-' + mm+'-'+dd;
dateCreated has the value 2015-01-20.
Error :
Failed to load the resource: the server : 8080/detailData/23/detailData/myDetailData.form responded with status of 404.
Please advice how can i pass the dateCreated value to java controller.
A: Is "dateString" supposed to be "dateCreated"?
This code works:
var dateCreated = new Date('2015-01-20');
var dd = dateCreated.getDate();
var mm = dateCreated.getMonth()+1;
var yyyy = dateCreated.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
dateCreated = yyyy + '-' + mm+'-'+dd;
;
console.log(dateCreated, typeof(dateCreated));
2015-01-20 string
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43613181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add element to own c++ template class with overloading operator+= I have to write a header file to an existing cpp with making an own template class. There is a simple add method but I have to overload the operator+= function.
If I try to add the elements separately, like this:
ls += lmb;
ls += lmc;
than it works well, but if I try to do it like in the cpp file:
(ls += lmb) += lmc;
than it doesn't work, it only add one element.
It's important: I can't change the cpp file!
The cpp look like this:
#include <iostream>
#include "mapalign.h"
#include <string>
#include <algorithm>
#include <map>
#include "mapalign.h"
struct string_size_less
{
bool operator()( const std::string& a,
const std::string& b ) const
{
return a.size() < b.size();
}
};
const int max = 1000;
bool check()
{
std::map<std::string, int> sma;
std::map<std::string, int> smb;
std::map<std::string, int> smc;
map_aligner<std::string, int> sa;
sa.add( sma );
sa.add( smb );
sa.add( smc );
sma[ "C++" ] = 1;
smb[ "Ada" ] = 2;
smc[ "C" ] = 3;
smc[ "Python" ] = 4;
smc[ "Ada"] = 5;
sa.align();
std::map<int, double> ima;
std::map<int, double> imb;
for( int i = 0; i < max; ++i )
{
if ( 0 == i % 2 )
{
ima[ i ] = max - i;
}
else
{
imb[ i ] = max;
}
}
map_aligner<int, double> ia;
ia.add( ima );
ia.add( imb );
ia.align();
if ( ( 4 != sma.size() && 1 != imb.count( 0 )) || max * 1U != ima.size() ||
1 != smc.count( "C++" ) || "Ada" != sma.begin()->first ||
0 != sma.begin()->second || 4 != smc.size() ||
1 != smb.count( "Python" ) || 0 != imb.begin()->first ||
0.8 <= imb.begin()->second || 1 != imb.count( max / 2 ) )
{
return false;
}
sma[ "Pascal" ] = 5;
sa.set_filler( max );
sa.align();
std::map<std::string, std::string> langsa;
langsa[ "C++" ] = "<3";
langsa[ "Python" ] = ":|";
std::map<std::string, std::string> langsb;
langsb[ "Brainfuck" ] = ":S";
langsb[ "Python" ] = ":/";
langsb[ "C" ] = ":)";
map_aligner<std::string, std::string> lsa;
lsa.add( langsa );
lsa.add( langsb );
lsa.align();
lsa.erase( "Python" );
if ( 0 != langsa.count( "Python" ) || max != smc[ "Pascal" ] ||
!langsa.begin()->second.empty() || max != smb[ "Pascal" ] ||
2 * 1U != langsb.begin()->second.size() ||
0 != langsb.count( "Python" ) || 1 != langsb.count( "C++" ) )
{
return false;
}
std::map<std::string, std::string, string_size_less> lma;
std::map<std::string, std::string, string_size_less> lmb;
std::map<std::string, std::string, string_size_less> lmc;
lma[ "C++" ] = ":D";
lmb[ "Eiffel" ] = ":P";
lmc[ "C" ] = "8-)";
lmc[ "Ada" ] = "!";
map_aligner<std::string, std::string, string_size_less> ls;
ls.add( lma );
(ls += lmb) += lmc;
ls.align();
std::cout << ls.count() << "\n";
std::cout << lmb.size() << "\n";
std::cout << (3 == ls.count()) << (1 == lmc.count( "Ada" )) <<
(3 * 1U == lmb.size()) << (1 == lma.count( "Python" )) <<
(2 == lsa.count()) << (2 == ia.count()) << "\n" ;
return ( 3 == ls.count() && 1 == lmc.count( "Ada" ) &&
3 * 1U == lmb.size() && 1 == lma.count( "Python" ) &&
2 == lsa.count() && 2 == ia.count() );
}
int main()
{
std::cout
<< "Your solution is "
<< (check() ? "" : "not ")
<< "ready for submission."
<< std::endl;
}
This is my operator+= function now:
map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
maps_.push_back(&m);
map_aligner ma = *this;
return ma;
}
The whole header look like this:
#ifndef MAPALIGN_H
#define MAPALIGN_H
#include <vector>
#include <map>
#include <typeinfo>
template<typename KEY, typename VALUE, typename COMPARE = std::less<KEY>>
class map_aligner{
public:
typedef typename std::map<KEY, VALUE, COMPARE>::size_type size_type;
map_aligner() {}
void add(std::map<KEY, VALUE, COMPARE>& m) {
maps_.push_back(&m);
}
map_aligner operator+=(std::map<KEY, VALUE, COMPARE>& m){
maps_.push_back(&m);
map_aligner ma = *this;
return ma;
}
size_type count() const {
return maps_.size();
}
void align(){
for(int i = 0; i != (int)maps_.size(); i++ ){
std::map<KEY, VALUE, COMPARE>* first_map = maps_.at(i);
for(typename std::map<KEY, VALUE, COMPARE>::iterator j = first_map->begin(); j !=first_map->end(); j++ ){
for(int h = 0; h != (int)maps_.size(); h++ ){
std::map<KEY, VALUE, COMPARE>* second_map = maps_.at(h);
if(first_map != second_map && notContainsPair(second_map, j)){
second_map->insert(std::make_pair(j->first, filler_));
}
}
}
}
}
bool notContainsPair(std::map<KEY, VALUE, COMPARE>* map,typename std::map<KEY, VALUE, COMPARE>::iterator it){
for(typename std::map<KEY, VALUE, COMPARE>::iterator g = map->begin(); g != map->end(); g++ ){
if(it->first != g->first){
return true;
}
}
return false;
}
void set_filler(VALUE filler){
filler_ = filler;
}
void erase(KEY key){
for(int h = 0; h != (int)maps_.size(); h++ ){
std::map<KEY, VALUE>* map = maps_.at(h);
typename std::map<KEY, VALUE, COMPARE>::iterator it;
map->erase(key);
if(typeid(it->first) == typeid(it->second)){
for(it = map->begin(); it != map->end(); it++){
if(key == it->second){
map->erase(it->first);
}
}
}
}
}
private:
std::vector<std::map<KEY, VALUE, COMPARE>*> maps_;
VALUE filler_ = VALUE();
};
#endif
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74837487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ngFor with ngIf <ul class="dropdown-menu" aria-labelledby="selectShop">
<li *ngFor="let s of i.shops_id">
<a *ngFor="let shop of shops">
<span *ngIf="shop._id == s">{{ shop.name }}</span>
</a>
</li>
</ul>
It's created empty a tags but I need
<ul class="dropdown-menu" aria-labelledby="selectShop">
<li *ngFor="let s of i.shops_id">
<a *ngFor="let shop of shops" *ngIf="shop._id == s">
{{ shop.name }}
</a>
</li>
</ul>
This code throws an error.
core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Template
parse errors: Can't have multiple template bindings on one element.
Use only one attribute named 'template' or prefixed with *
("lledby="selectShop">
<li *ngFor="let s of i.shops_id"><a *ngFor="let shop of shops" [ERROR ->]*ngIf="shop._id == s">{{ shop.name }}</a></li>
</ul>
</div>"):
How can I fix this problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44332688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Search node/text() from (Result Tree Fragment) my templates (XSLT 1.0)
<xsl:template name="doo">
<xsl:variable name="nodelist">
<root>
<a size="12" number="11">
<sex>male</sex>
Hulk
</a>
<a size="12" number="11">
<sex>male</sex>
Steven XXXXXXXXXXX
</a>
</root>
</variable>
<xsl:call-template name="findString">
<xsl:with-param name="content1" select="$nodelist"></xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="findString">
<xsl:param name="content1" select="."></xsl:param>
<!-- here i need to search the text() XXXXXXXXXXX from $content1 and replace them-->
</xsl:template>
is this possible like
for each node in Tree Fragment from myvariable
if node/text()='xxxxxxxx'
do something
A: With xslt version=1.0 you can use a extension "not-set".
<xsl:call-template name="findString">
<xsl:with-param name="content1" select="exsl:node-set($nodelist)"></xsl:with-param>
</xsl:call-template>
To make it woke you have to add following lines.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl"
version="1.0">
Update:
Based on solution from Mads Hansen
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:template name="doo">
<xsl:variable name="nodelist">
<root>
<a size="12" number="11">
<sex>male</sex>
Hulk
</a>
<a size="12" number="11">
<sex>male</sex>
Steven XXXXXXXXXXX
</a>
</root>
</xsl:variable>
aaa
<xsl:call-template name="findString">
<xsl:with-param name="content1" select="exsl:node-set($nodelist)"></xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template match="/">
<xsl:call-template name="doo" />
</xsl:template>
<xsl:template name="findString">
<xsl:param name="content1" select="."></xsl:param>
<!-- here i need to search the text() XXXXXXXXXXX from $content1 and replace them-->
<xsl:apply-templates mode="mytext" select="$content1"/>
</xsl:template>
<!--Identity template will copy all matched nodes and apply-templates-->
<xsl:template match="@*|node()" mode="mytext">
<xsl:copy>
<xsl:apply-templates select="@*|node()" mode="mytext"/>
</xsl:copy>
</xsl:template>
<!--Specialized template to match on text nodes that contain the "findString" value-->
<xsl:template match="text()[contains(.,'XXXXXXXXXXX')]" mode="mytext">
<xsl:variable name="findString" select="'XXXXXXXXXXX'"/>
<xsl:variable name="replaceString" select="'YYYYYYYYYYYY'"/>
<xsl:value-of select="concat(substring-before(., $findString),
$replaceString,
substring-after(., $findString))"/>
</xsl:template>
</xsl:stylesheet>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16132515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: cUrl alternatives to get POST answer on a webpage I would like to get the resulting web page of a specific form submit. This form is using POST so my current goal is to be able to send POST data to an url, and to get the HTML content of the result in a variable.
My problem is that i cannot use cUrl (not enabled), that's why i ask for your knowledge to know if an other solution is possible.
Thanks in advance
A: See this, using fsockopen:
http://www.jonasjohn.de/snippets/php/post-request.htm
Fsockopen is in php standard library, so all php fron version 4 has it :)
A: try file_get_contents() and stream
$opts = array( 'http'=>array('method'=>"POST", 'content' => http_build_query(array('status' => $message)),));
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11468720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Perf profiling shows wrong call-graph I am trying to profile my code.
After running perf, the resulting flame graph looks like that:
The 30% left follows my program calling graph. The 70% on the right are various samples, which are incorrectly detached from the left 30%, as they are always called from these 30%.
So, the 30% left should in fact stretched to 100%, and the right 70% should be on top.
Why is perf loosing track of callers in stack at some point?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60186790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android: Having trouble getting html from webpage I'm writing an android application that is supposed to get the html from a php page and use the parsed data from thepage. I've searched for this issue on here, and ended up using some code from an example another poster put up. Here is my code so far:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
Log.d("first","first");
HttpResponse response = client.execute(request);
String html = "";
Log.d("second","second");
InputStream in = response.getEntity().getContent();
Log.d("third","third");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Log.d("fourth","fourth");
StringBuilder str = new StringBuilder();
String line = null;
Log.d("fifth","fifth");
while((line = reader.readLine()) != null) {
Log.d("request line",line);
}
in.close();
} catch (ClientProtocolException e) {
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("error", "error");
}
Log.d("end","end");
}
Like I said before, the url is a php page. Whenever I run this code, it prints out the first first message, but then prints out the error error message and then finally the end end message. I've tried modifying the headers, but I've had no luck with it. Any help would be greatly appreciated as I don't know what I'm doing wrong.
Thanks!
When I do e.getMessage() and print that out, in the logger all it says is stanford.edu. Hope that helps. Here is the stack trace:
01-17 16:58:27.687: WARN/System.err(452): java.net.UnknownHostException: stanford.edu
01-17 16:58:27.947: WARN/System.err(452): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
01-17 16:58:27.947: WARN/System.err(452): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
01-17 16:58:27.977: WARN/System.err(452): at java.net.InetAddress.getAllByName(InetAddress.java:256)
01-17 16:58:27.977: WARN/System.err(452): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
01-17 16:58:28.027: WARN/System.err(452): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-17 16:58:28.027: WARN/System.err(452): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-17 16:58:28.047: WARN/System.err(452): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
01-17 16:58:28.057: WARN/System.err(452): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-17 16:58:28.057: WARN/System.err(452): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-17 16:58:28.117: WARN/System.err(452): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-17 16:58:28.117: WARN/System.err(452): at edu.stanford.cs247.util.ColorHandler.getInfo(ColorHandler.java:44)
01-17 16:58:28.217: WARN/System.err(452): at edu.stanford.cs247.util.ColorHandler.handleMessage(ColorHandler.java:70)
01-17 16:58:28.217: WARN/System.err(452): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 16:58:28.247: WARN/System.err(452): at android.os.Looper.loop(Looper.java:123)
01-17 16:58:28.257: WARN/System.err(452): at android.app.ActivityThread.main(ActivityThread.java:3647)
01-17 16:58:28.257: WARN/System.err(452): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 16:58:28.297: WARN/System.err(452): at java.lang.reflect.Method.invoke(Method.java:507)
01-17 16:58:28.297: WARN/System.err(452): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 16:58:28.327: WARN/System.err(452): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 16:58:28.337: WARN/System.err(452): at dalvik.system.NativeStart.main(Native Method)
A: First of all, the Log.d() method calls may be something like Log.d("MyAppName", "Message") not Log.d("Message", "Message") In this way you can create a filter in LogCat for your app and see only your messages. (Check this on Eclipse)
For your problem, try putting some useful message in the catch block, something like:
try{
...
} catch (IOException e){
Log.d("MyAppName", e.getMessage());
}
This will show you the problem that throw the exception.
Consider take a look to this sample code, the getUrlContent() do exactly what you wont.
Good luck
A: The first line of your stacktrace says:
java.net.UnknownHostException:
stanford.edu
You should learn to read stacktraces. A quick search for "UnknownHostException" tells you it is:
Thrown to indicate that the IP address
of a host could not be determined.
This means that it can't turn stanford.edu into an IP. You probably need www.stanford.edu or something like that. Try pinging the address on the command line ping www.stanford.edu , and make sure it resolves to an ip address.
A: I forgot to add the internet permission in my manifest file.
A: add to Manifest
<uses-permission android:name="android.permission.INTERNET" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4719059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regarding fltk installation I am new to c++ and overall programming. I tried reading one book by Bjarne Stroustrup he mentioned in the very first chapter to first install fltk and write the code. Should I install fltk or use online compiler. If I should install fltk then please tell how as I am unable to do so. Thank you.
I tried downloading and unzipping the fltk file two times. It got unzipped but the fltk.snl file is getting opened by visual studios but othing is happening since I am unable to run c++ code in VS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74812563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update the single property from array of object using setState (with a class component)? I have an array of objects in this.state, and I am trying to update the single property from the array of objects.
This is my object
this.state = {
persons: [
{ name: "name1", age: 1 },
{ name: "name2", age: 2 },
{ name: "name3", age: 3 }
],
status: "Online"
};
and i tried to update the persons[0].name
import React, { Component } from "react";
class App extends Component {
constructor() {
super();
this.state = {
persons: [
{ name: "John", age: 24 },
{ name: "Ram", age: 44 },
{ name: "Keerthi", age: 23 }
],
status: "Online"
};
}
changeName() {
console.log(this);
this.setState({
persons[0].name: "sdfsd"
});
}
render() {
return (
<button onClick={this.changeName.bind(this)}>change name</button>
);
}
}
am getting an error.
A: You should code:
let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })
A: using dot operator we can achieve this.
let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })
A: Proble with that you mutate component state, below it's example of immutable changing, I recommend you to read articles about how to change react state. Or you can try to use Mobx because it supports mutability
changePerson(index, field, value) {
const { persons } = this.state;
this.setState({
persons: persons.map((person, i) => index === i ? person[field] = value : person)
})
}
// and you can use this method
this.changePerson(0, 'name', 'newName')
A: this.setState(state => (state.persons[0].name = "updated name", state))
A: Assuming some conditional check to find the required person.
const newPersonsData = this.state.persons.map((person)=>{
return person.name=="name1" ? person.name="new_name" : person);
//^^^^^^^ can be some condition
});
this.setState({...this.state,{person:[...newPersonsData ]}});
A: I think the best way is to copy the state first in temporary variable then after update that variable you can go for setState
let personsCopy = this.state.persons
personsCopy [0].name= "new name"
this.setState({ persons: personsCopy })
A: Here's how I would do it.
See if that works for you.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
persons: [
{ name: "John", age: 24 },
{ name: "Ram", age: 44 },
{ name: "Keerthi", age: 23 }
],
status: "Online"
};
this.changeName = this.changeName.bind(this);
this.changeAge = this.changeAge.bind(this);
}
changeName(value,index) {
this.setState((prevState)=>{
const aux = prevState.persons;
aux[index].name = value;
return aux;
});
}
changeAge(value,index) {
this.setState((prevState)=>{
const aux = prevState.persons;
aux[index].age = value;
return aux;
});
}
render() {
const personItems = this.state.persons.map((item,index)=>
<React.Fragment>
<input value={item.name} onChange={(e)=>this.changeName(e.target.value,index)}/>
<input value={item.age} onChange={(e)=>this.changeAge(e.target.value,index)}/>
<br/>
</React.Fragment>
);
return(
<React.Fragment>
{personItems}
<div>{JSON.stringify(this.state.persons)}</div>
</React.Fragment>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56592472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I replace only PART of an image source on hover using jquery? <li class="active"><a href="#"><img src="images/static/personal_information.png" class="img-responsive center-block"><span>Personal<br> Information</span> </a></li>
This is what i trying
$(".navbar-nav li a").hover(function(){
$(this).children("img").attr('src').replace('hover','static');
});
A: Firstly your arguments to replace() are the wrong way around. Secondly, you need to actually set the value after making the replacement. Lastly you'll also need to provide another function argument to hover() that sets the original image back on mouseout. Try this:
$(".navbar-nav li a").hover(function() {
$(this).children("img").prop('src', function(i, src) {
return src.replace('static', 'hover');
})
}, function() {
$(this).children("img").prop('src', function(i, src) {
return src.replace('hover', 'static');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navbar-nav">
<li class="active">
<a href="#">
<img src="images/static/personal_information.png" class="img-responsive center-block">
<span>Personal<br> Information</span>
</a>
</li>
</ul>
A: You are replacing src code, but not assigning it back.
$(".navbar-nav li a").hover(function(){
var newSrc = $(this).children("img").attr('src').replace('hover','static');
$(this).children('img').attr('src', newSrc)
});
A: Why are you targeting <a>, then select its child <img>? Why not apply that to the image directly?
$(".navbar-nav li a img").hover(function(){
$(this).attr('src') = $(this).attr('src').replace('hover','static');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44174255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I let a set retain all strings that contain my specified substring in java? I use a hashset for a dictionary. Now I would like to filter out words that do not start with my substring. So it should be something like this:
String word = 'ab';
List<String> list = Arrays.asList(word);
boolean result = lexiconSet.retainAll(list);
And instead of this resulting in the lexicon only containing the word 'ab', I would like to keep all words beginning with 'ab'. How can I do this?
I know I can convert the set to a string arraylist, and loop over all elements to see if the strings starts with 'ab', but since I think this can be time consuming and not efficient, I would like to hear better solutions. Thank you in advance!
A: With Java 8, life is easy:
list.removeIf(s -> !s.startsWith("ab"));
This will remove all elements that don't begin with "ab".
Note that you can use values() to retrieve the map's values and work directly on them, without the need to convert to ArrayList.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32868228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Put File Mask on tFileList Component dynamically I was wondering if you let me know how I can set file mask for tFilelist component in Talend that it recognize date automatically and it will download only data for desired date?
I have tried some approach and I faced with some errors like "the method add (string) in the type list <String> is not applicable for the arguments (Date)"
A: There are two ways of doing it.
*
*Create context variable and use this variable in file mask.
*Directly use TalendDate.getDate() or any other date function in file mask.
See both of them in component
1st approach,
*
*Create context variable named with dateFilter as string type.
*Assign value to context.dateFilter=TalendDate.getDate("yyyy-MM-dd");
*Suppose you have file name as "ABC_2015-06-19.txt" then
*In tFileList file mask use this variable as follows.
"ABC_"+context.dateFilter+".*"
2nd approach
*
*In tFileList file mask use date function as follows.
"ABC_"+TalendDate.getDate("yyyy-MM-dd")+".*"
these are the two best way, you can make changes in file mask per your file names.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30928833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Material Design Lite responsive CSS not working on a Mobile/Tablets or in the Chrome DevTools emulator When experimenting with the responsive features of Google's Material Design Lite, this code hides messages as expected when resizing the browser window, but when I look at my page in Chrome DevTools device emulator or on an actual device, it only shows the "Desktop" version. How do I fix my HTML?
<html>
<head>
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.1/material.indigo-pink.min.css">
</head>
<body>
<div class="mdl-cell--hide-phone mdl-cell--hide-tablet">
You are on a desktop
</div>
<div class="mdl-cell--hide-desktop mdl-cell--hide-tablet">
You are on a phone
</div>
<div class="mdl-cell--hide-desktop mdl-cell--hide-phone">
You are on a tablet
</div>
</body>
</html>
A: To fix MDL not scaling for different devices, add this line inside your HTML's <head> :
<meta name="viewport" content="width=device-width, initial-scale=1.0">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33044102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Flutter Gridview button functionality to new screen with Firebase I've made a Gridview using Firebase and Streambuilder and Gridview.builder. This grid displays album titles, the album cover art for each album, and the artists that make each album. I'd like for each grid tile to be able to be pressed and navigate to a separate page with its specific album details. The plan was on press, the app would be able to identify the entire document the grid tile was referring to, move to a new page, and display the document in full to unveil the album details. The thing is, I don't know how to do that. Since snapshot.data.documents[index]['Title'] worked when iterating though all the documents to create the gridview, I thought that typing snapshot.data.documents[index] would work, but it just displays Instance of 'DocumentSnapshot' in the debug console. I'm out of ideas on how to tackle this, so any suggestions are welcome
My code is shown below
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Services services = Services();
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: bgcolour,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: Icon(Icons.menu),
title: Text("Home"),
actions: <Widget>[
Padding(padding: EdgeInsets.all(10), child: Icon(Icons.more_vert))
],
),
body: StreamBuilder(
stream: Firestore.instance.collection('music').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text("Loading...");
return GridView.builder(
itemCount: snapshot.data.documents.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, childAspectRatio: 0.655172413),
//cacheExtent: 1000.0,
itemBuilder: (BuildContext context, int index) {
var url = snapshot.data.documents[index]['Cover Art'];
return GestureDetector(
child: Container(
width: 190.0,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32)),
color: hexToColor(
snapshot.data.documents[index]['Palette'][0]),
elevation: 1,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(height: 12),
ClipRRect(
borderRadius: BorderRadius.circular(21.0),
child: Image.network(url,
height: 180.0, width: 180)),
SizedBox(height: 10),
Text(
snapshot.data.documents[index]['Artist']
.join(', '),
textAlign: TextAlign.center,
style: GoogleFonts.montserrat(
textStyle: TextStyle(color: Colors.white),
fontSize: 14,
fontWeight: FontWeight.w300)),
SizedBox(height: 10),
Text(snapshot.data.documents[index]['Title'],
style: GoogleFonts.montserrat(
textStyle: TextStyle(color: Colors.white),
fontSize: 16,
fontWeight: FontWeight.w600),
textAlign: TextAlign.center),
],
),
),
),
onTap: () {
print("Tapped ${snapshot.data.documents[index]}");
},
);
},
);
}
),
);
}
}
A: Is there an ID for your snapshot.data.documents[index]? If yes, add it to the end.
onTap: () {
print("Tapped ${snapshot.data.documents[index]['the property you want']}");
},
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61023338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to get text values present within strong tag using Selenium Java While trying to print values present with in strong tag using xpath I'm getting following exception:
org.openqa.selenium.NoSuchElementException: Unable to locate element: strong
This is my code :
WebElement eleText = driver.findElement(By.xpath("//strong"));
String testerName = eleText.getText();
System.out.println(testerName);
This is my webpage which I'm trying to get values within strong tag :
<a id="id_1099808326" class="activity">
<strong>heizil</strong> :
<label id="check_label"> " First Device Test"
</label>
<a id="id_1099808296" class="activity">
<strong>riya</strong>:
<label id=check_label"> " Second Device Test"
</label>
Expected output: heizil,riya
If this is not the proper way can any one suggest any other way of getting the values present in <strong> tag
A: As per the given HTML text heizil is within <strong> tag which is the immediate descendant of the <a> tag.
<a id="id_109996" class="activity">
<strong>heizil</strong>
:
<label id="sample_label">
...
...
</label>
</a>
Solution
To print the text heizil you can use either of the following locator strategies:
*
*Using cssSelector and getAttribute("innerHTML"):
System.out.println(driver.findElement(By.cssSelector("a.activity > strong")).getAttribute("innerHTML"));
*Using xpath and getText():
System.out.println(driver.findElement(By.xpath("//a[@class='activity']/strong")).getText());
Ideally, to extract the text value, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:
*
*Using cssSelector and getText():
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.activity > strong"))).getText());
*Using xpath and getAttribute("innerHTML"):
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("innerHTML"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75125696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File Level Tracking In Git (Files from multiple branches in same directory) Is there any script that lets one remember branch/commit seperatly for files in some directory so that one can simultaneously work on file1 on branch1 and file2 on branch2 in the same directory and have them commit appropriately. If not I'll implement it myself.
My plan is to have hidden checkout directories for various branches/repos and populating the apparent checkout with links to these files so that commits simply committed their respective hidden branches but advice would be appreciated. Thus one could do something like
mgit checkout branch1 filename/filegroup
mgit add filename (automatically to it's correct branch/repo)
mgit commit (automatically to it's correct branch/repo)
Before anyone tells me this is a bad idea or incorrect use of version control consider the application:
So often when writing academic documents in TeX you end up with loosely related files that you wish to keep in version control. The problem is that these files are related and can benefit from the history/merging info git provides but often different versions of the files need to be selected independently. Most commonly you simply want to work on variant1 of some paper while also working of variant2 of another but you also have situations where TeX combines several files so it's important to be able to put your choice of variants in the same folder.
In short you have a bunch of distinct files with distinct names which often derive from each other (thesis becomes paper), benefit from being in a single repo but it is unwieldy to have a dozen different checkouts to work on whatever versions of each file currently need attention.
A: No, I don't think this is natively supported by git.
May be a local hook like a pre-commit one hook might try to check and checkout the right branch before allowing the commit to proceed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7784825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are atomic operations on non-atomic types in C atomic? The C17 standard specifies a list of atomic operations. For example, an atomic read-write-modify operation on an atomic object of type A is defined in the standard as:
C atomic_fetch_add(volatile A *object, M operand);
But we can call atomic_fetch_add on non-atomic types:
static int x;
static int foo(void *arg) {
atomic_fetch_add(&x, 3);
}
My question: is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?
A:
on an atomic object of type A is defined in the standard
But we can call
GCC will accept it. But on clang you'll get an error.
is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?
No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 :
5 In the following synopses:
*
*An A refers to one of the atomic types. [...]
And then all the functions are defined in terms of A, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :
C atomic_fetch_key(volatile A *object, M operand);
Atomic type is a type with _Atomic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71606318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: convert ElasticSearch SearchResponse object to JsonObject I want to convert the elasticsearch search result to Json Object. I havent found any proper way to convert directly.
SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet();
response->JSON Object.
Is there any way to convert an ElasticSearch response to a Json Object?
A: In Java, you can directly convert the SearchResponse to JSONObject.
Below is the handy code.
SearchResponse SR = builder.setQuery(QB).addAggregation(AB).get();
JSONObject SRJSON = new JSONObject(SR.toString());
A: You need to use the SearchResponse.toXContent() method like this:
SearchResponse response = client.prepareSearch(index).setExplain(true).execute().actionGet();
XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
JSONObject json = new JSONObject(builder.string());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46190070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Transparency between UITableViewCells I want to have transparency between UITableViewCells. Space between the cells.
I user custom created cells and for setting a background i use this code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CustomCell = @"CustomBookingCell";
currentBooking = [arrayBookings objectAtIndex:indexPath.row];
CustomBookingCell *cell = (CustomBookingCell *)[tableView dequeueReusableCellWithIdentifier:CustomCell];
if (cell == nil) {
UIViewController *c = [[UIViewController alloc] initWithNibName:@"CustomBookingCell" bundle:nil];
cell = (CustomBookingCell *)c.view;
[ c release ];
}
bookingImage = [[UIImageView alloc] initWithImage:
[UIImage imageNamed:currentBooking.imageSource]];
[cell.imageForBooking addSubview:bookingImage];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.contentView.backgroundColor = [UIColor clearColor];
UIView* backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
UIImage* bgImage = [UIImage imageNamed:@"Background_300_82.png"];
UIColor *bgColor = [[UIColor alloc] initWithPatternImage: bgImage];
backgroundView.backgroundColor = bgColor;
cell.backgroundView = backgroundView;
cell.label.text = currentBooking.title;
[bookingImage release];
[bgColor release];
[backgroundView release];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 90;
}
The height of the cell is 10 pixels higher that the tableCellBg.png.
My background view has also a image as background (this background is supposed to be shown between the cells of course).
So I tried to add 10 pixels with transparency to my tableCellBg.png in the bottom to fix this. But the space between the cells is black. I can't see the view background between my cells.
What shall I do? Do I have to create a UIView in cellForRowAtIndexPath with the height of the tableCellBg.png and then add the Custom UITableViewCell as subview to the created UIView with a less higher height?
Or is there a much more simplyfied way to accomplish this?
A: Your table view needs a clear background colour. For example
myTableView.backgroundColor = [UIColor clearColor];
A: I solved it by using another method to add the background image to the UITableViewCell:
UIImage *image = [UIImage imageNamed:@"ny_bg_event.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 300, 84);
cell.backgroundView = imageView;
cell.backgroundColor = [UIColor clearColor];
[imageView release];
[cell setFrame:CGRectMake(0, 0, 300, 84)];
cell.contentView.backgroundColor = [UIColor clearColor];
Instead of creating a UIView I just used a UIImageView instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3770906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: webkit css resize doesn't work with canvas as child? Suppose the following html and css code snippet:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
}
#inner {
width: 100%;
height: 100%;
}
<div id="outer">
<canvas id="inner"></canvas>
</div>
I would expect the div to be resizeable, and in firefox, it is. However in webkit-based browsers such as chrome and opera, it isn't. If I replace the inner canvas with a div however, it works there too. So my question is: why does the canvas element in this case prevent the outer div from beeing resizeable? And how can I work around this?
A: it seems that the canvas is taking the mouse event preventing the resize. If you consider pointer-events:none on canvas it will work:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
}
#inner {
width: 100%;
height: 100%;
pointer-events:none
}
<div id="outer">
<canvas id="inner"></canvas>
</div>
To better illustrate, decrease the size of the canvas a little to avoid the overlap with the resize widget and it will also work:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
}
#inner {
width: 100%;
height: calc(100% - 10px);
background:red;
}
<div id="outer">
<canvas id="inner"></canvas>
</div>
You can also play with z-index:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
position:relative;
z-index:0; /* mandatory to create a stacking context and keep the canvas inside */
}
#inner {
width: 100%;
height: 100%;
position:relative;
z-index:-1;
background:red;
}
<div id="outer">
<canvas id="inner"></canvas>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55928982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google play services leak in Main While trying to implement ads into my app I am getting this error upon showing the ad.
The only thing I've added to my app in regards to Google play services is importing into gradle and adding to my manifest. I could not find any information on initialization or any other info where I have to add any code to my main.
Here is the log
06-26 21:53:31.062 E/ActivityThread(15754): android.app.ServiceConnectionLeaked: Activity com.intellidev.bitrich.MainActivity has leaked ServiceConnection com.google.android.gms.common.zza@5db576d that was originally bound here
update
Seems I need to initialize play services builder then connect. However the only reason it is implemented is to work with supersonic ads. So here less my problem on hpw to implement it.
A: Your supersonic ad sdk is causing the bug. The ad view connects to play services and does not disconnect properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31084397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Content negotiation: how to remove JSON as a supported format? I'm implementing a web service in ASP.NET Core 2.1 based on a specification that exclusively supports XML. Therefore, the content negotiation process must return a XML document or respond with an error. Unfortunately ASP.NET Core 2.1 supports JSON by default, and by default the content negotiation process always succeeds if a request is made with Accept: application/json.
Does anyone know if it's possible to configure an ASP.NET Core project so that the content negotiation process throws an error if any media type other than XML is set?
A: Sorry if I am late to the party. This works for me:
services.AddMvc(options =>
{
options.OutputFormatters.RemoveType(typeof(JsonOutputFormatter));
options.InputFormatters.RemoveType(typeof(JsonInputFormatter));
options.ReturnHttpNotAcceptable = true;
})
.AddXmlSerializerFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
A: Use MVC input and output formatters:
services.AddMvc(configure =>
{
// remove JSON formatter
var outputFormatters = configure.OutputFormatters;
var jsonOutputFormatter = outputFormatters.First(f => f is JsonOutputFormatter);
outputFormatters.Remove(jsonOutputFormatter);
var inputFormatters = configure.InputFormatters;
var jsonInputFormatter = inputFormatters.First(f => f is JsonInputFormatter);
inputFormatters.Remove(jsonInputFormatter);
}).AddXmlSerializerFormatters()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52507339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: WSO2 API Manager - unable to access resource properties I am not able to access resource property test1, mentioned in property section in the screenshot.
I am trying to access it by using the expression. get-property('test1'). I am expecting this result in console as test1-value. But the is showing as null.
Updated
I have tried following options but nothing is working for this test1 property.
<property expression="get-property('registry', 'gov:/data/xml/collectionx@test1')" name="test_property2"/>
<property expression="get-property('registry', 'gov:/_system/governance/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property4"/>
<property expression="get-property('gov:/_system/governance/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property6"/>
A: Try this.
<property name="regProperty" expression="get-property('registry', 'gov:/data/xml/collectionx@abc')"/>
Ref: http://movingaheadblog.blogspot.com/2015/09/wso2-esb-how-to-read-registry-property.html
A: To get the value of test1, use following property.
<property expression="get-property('registry', 'gov:/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property5"/>
From above example the location of resource is showing /_system/governance/apimgt/customsequences/in/Seq1.xml. So to make its path, we will use subpath and leave /_system/governance from the beginning. The path will be gov:/apimgt/customsequences/in/Seq1.xml. Now to access test1 property, simply append @test1 to the path.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45281047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Send SMS from SQL Server Integration Services I am new to using SSIS and I am looking for a way to send messages using SMS. Is this possible to do? And if yes, is there a way to use a Web API in SSIS to send SMS messages?
A: After i did more search i found this Question
and his first answer was what i want.
the second part of my Question was about api to use i found this 2 api
*
*Nexmo
*Infobip but you will have to contact them first
both of them will give you atest account to use it at first , but i used the first one from SQL SSIS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39081510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: keyDown function not working with shift key I am trying to hold down the 'shift' key and press the 'down' key using the pyautogui module. But the pyautogui.keyDown() does not function with shift key.
The py.keyDown('shift') does not seem to work. Only the py.press('down') is working without holding down the shift key.
pyautogui.keyDown('shift')
pyautogui.press('down')
pyautogui.press('down')
pyautogui.keyUp('shift')
The thing i would like to do is- hold down the shift key and use the down arrow keys on the key board to move down selecting all items below with the down arrow.
A: #You can try this
#So, you have to make left and right shifts down at the same time to activate this feature which is wired.
pyautogui.keyDown('shiftleft')
pyautogui.keyDown('shiftright')
pyautogui.hotkey('right','right','ctrl','up')
pyautogui.keyUp('shiftleft')
pyautogui.keyUp('shiftright')
#credits:Tian Chu
#https://stackoverflow.com/users/13967128/tian-chu
A: Previous answer is good. I was able to successfully highlight a whole Excel column using:
pyautogui.hotkey('ctrl','shiftright','shiftleft','down')
I tried using both shiftright and shiftleft on their own and it wouldn't work unless they were both used together.
A: Thanks, I lost almost 1 hour to find this answer cause on the documentation this is not specified, for me worked example:
py.keyDown('shiftleft')
py.keyDown('shiftright')
py.press('down', presses=253)
py.keyUp('shiftleft')
py.keyUp('shiftright')
Again, Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56949628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I distinguish the users who do not exist now but exit previously? Now I have a user set involving one tweet. But some users do not exit now. I wonder how to distinguish those users from current users.
A: I believe the only thing you can do in this case is to use the users/lookup or users/show endpoints to check whether those user IDs return a Not Found error (or similar) in order to filter them out from your result set.
Note that the Twitter Developer Policy and Agreement explicitly states that if content has been removed from Twitter (if e.g. a user is deleted or suspended) you cannot display that it in app, or store that data, and must take steps to remove it from your system as soon as possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53079672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: AWS Amplify Graphql query on @connection I am using AWS Amplify (with Cli and Angular 7 for front end) for Graphql/AppSync and wondering how to get all connected items when it exceeds 10 items?
Let's say I have created a schema.graphql like this:
type User @model {
id: ID!
firstname: String
lastname: String
project: Project @connection(name: "ProjectUsers")
}
type Project @model {
id: ID!
title: String
task: String
members: [User] @connection(name: "ProjectUsers")
}
When running amplify push it generates queries and mutations. When running the GetProject query with the id of a project (from the generated API.service.ts file) it returns the Project item with the connected Users. But if the project have more than 10 Users, it only gives me the 10 first users and a next token:
{
id: "67b1fc0a-fd1f-4e8b-9bd7-b82b2aea5d3b",
title: "Test",
task: "test",
members: {
items: {
0: {__typename: "User", id: "f245809a...}
1: ...
(2-8: ...)
9: ...
nextToken: "qwerj23r2kj....3223oop32kjo",
__typename: "ModelUserConnection";
}
}
__typename: "Project"
}
I can see multiple solutions for this, but not how to do them:
*
*Is it possible to change schema.grapql to change the codegen so that it can generate the ability to change the limit, ex. 100 instead of the standard 10?
*Use the nextToken to paginate the results, from the generated API.service.ts file?
*Change the schema.graphql file so that the generated ModelUserFilterInput has the userProjectId field (to use in the generated ListUsers query)?
Or are there any other solutions to get all the Users of a Project with the queries in the automatically generated file (API.service.ts)?
As of now the only solution I can see is to first run the ListUsers query (without any filters), and then loop through all of them to check if it has the correct project id. But if the users database is large this can grow to be a lot of data and be really slow, and the benefits to use @connection isn't really there.
Sorry for long post and I hope I have explained the problem enough.
A: A) Change your query
query {
getProjet(id: "123") {
id
members(limit: 50) {
items {
firstname
}
}
}
B) Attach a Resolver
In the AWS AppSync console, at the right end side of the Schema section. Filter by UserConnection or similar find UserConnection.items and click Attach.
1) DataSource: UserTable0
2) Request mapping template: ListItems
{
"version" : "2017-02-28",
"operation" : "Scan",
"limit": $util.defaultIfNull(${ctx.args.limit}, 50),
"nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.nextToken, null))
}
Use the limit coming as an argument ctx.args.limit or if its null use 50.
3) Response mapping template
$util.toJson($ctx.result.items)
By doing this you can change how the underlying table is being scanned/fetched.
C) Paginate
Another solution would be to paginate at the application level and leave the 10 items limit.
Note: I may be missing other solutions.
Update: to use this solution together with Amplify Console.
Now, you can update your resolvers locally and use the Amplify CLI to push the updates into your account. Here’s how it works.
After creating your AWS AppSync API, you will now have a new empty folder called resolvers created in your Amplify project in the API folder. To create a custom resolver, create a file (i.e.
Query.getTodo.req.vtl) in the resolvers directory of your API project. The next time you run amplify push or amplify api gql-compile, your resolver template will be used instead of the auto-generated template. You may similarly create a Query.getTodo.res.vtl file to change the behavior of the resolver’s response mapping template.
<amplify-app>
|_ amplify
|_ .config
|_ #current-cloud-backend
|_ backend
|_ api
|_ resolvers
Query.getProject.req.vtl
Query.getProject.res.vtl
team-provider-info.json
More details, 11 Feb 2019
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55716924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Select only specific properties from an array of objects Let's say I create object like this:
updates.push({
id: this.ids[i],
point: point,
value: value
});
Later on I want to use JSON.stringify on updates object, however I need only
point and value like:
updates[{point: 1, value: 12}, {point: 2, value: 24}]
What's the best ES6 solution for that?
I looked at some examples with delete, but that's not what I actually need, as I do not want to delete ids.
A: Try the following :
JSON.stringify(updates.map(({point,value})=>({point,value})));
let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}];
console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));
A: If updates is an array. Then you might want something like this:
const newArrayWithoutId = updates.map(({ point, value }) => {
return {
point,
value,
}
}
A: Just ({id, ...rest}) => ({...rest}) is too short for an answer, so how about this?
const withoutId = ({id, ...rest}) => ({...rest})
const vals = [
{id: 'a', point: 1, value: 'foo'},
{id: 'b', point: 2, value: 'bar'},
{id: 'c', point: 3, value: 'baz', meaning: 42}
]
const reduced = vals.map(withoutId)
console.log(reduced)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53874548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Docker for Windows: "Operation not permitted" trying to run an executable inside a container (bind-mount only) I'm pretty sure that the last update of Docker for Windows has broken something.
Here is the thing. I have a custom image named toolbox, built from alpine, with a bounch of script inside it (bind-mount the local folder ./mnt/):
version: '3'
services:
# ...
toolbox:
build:
context: ./.docker/toolbox
restart: always
volumes:
- ./mnt/etc/periodic/daily:/etc/periodic/daily
Files have the right permissions:
/ # ls -la /etc/periodic/daily/
total 4
drwxrwxrwx 1 root root 4096 Mar 16 17:49 .
drwxr-xr-x 7 root root 4096 Jan 16 22:52 ..
-rwxr-xr-x 1 root root 332 Mar 1 23:57 backup-databases
-rwxr-xr-x 1 root root 61 Mar 1 23:51 cleanup-databases-backups
When I try to execute backup-databases I get the following error:
/ # /etc/periodic/daily/backup-databases /bin/sh:
/etc/periodic/daily/backup-databases: Operation not permitted
The strange thing is, if I create a script (from inside the container) it works:
echo "echo Hello" > /etc/periodic/daily/test
chmod +x /etc/periodic/daily/test
/etc/periodic/daily/test
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60710103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scraping html data from a web site with
* tags I am trying to to get data from this lottery website:
https://www.lotterycorner.com/tx/lotto-texas/2019
The data I would like scrape is the dates and the winning numbers for 2017 to 2019. Then I would like to convert the data into a list and save to a csv file or excel file.
I do apologize if my question isn't understandable i am new to python. Here is a code I tried, but I don't know what to do after this
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2017')
soup = BeautifulSoup(page.content,'html.parser')
week = soup.find(class_='win-number-table row no-brd-reduis')
dates = (week.find_all(class_='win-nbr-date col-sm-3 col-xs-4'))
wn = (week.find_all(class_='nbr-grp'))
I would like my result to be something like this:
A: Code below create csv files by year with data with all headers and values, in example below will be 3 files: data_2017.csv, data_2018.csv and data_2019.csv.
You can add another year to years = ['2017', '2018', '2019'] if needed.
Winning Numbers formatted to be as 1-2-3-4-5.
from bs4 import BeautifulSoup
import requests
import pandas as pd
base_url = 'https://www.lotterycorner.com/tx/lotto-texas/'
years = ['2017', '2018', '2019']
with requests.session() as s:
for year in years:
data = []
page = requests.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
soup = BeautifulSoup(page.content, 'html.parser')
rows = soup.select(".win-number-table tr")
headers = [td.text.strip() for td in rows[0].find_all("td")]
# remove header line
del rows[0]
for row in rows:
td = [td.text.strip() for td in row.select("td")]
# replace whitespaces in Winning Numbers with -
td[headers.index("Winning Numbers")] = '-'.join(td[headers.index("Winning Numbers")].split())
data.append(td)
df = pd.DataFrame(data, columns=headers)
df.to_csv(f'data_{year}')
To save only Winning Numbers, replace df.to_csv(f'data_{year}') with:
df.to_csv(f'data_{year}', columns=["Winning Numbers"], index=False, header=False)
Example output for 2017, only Winning Numbers, no header:
9-14-16-27-45-51 2-4-15-38-48-53 8-22-23-29-34-36
6-10-11-22-30-45 5-10-16-22-26-46 12-14-19-34-39-47
4-5-10-21-34-40 1-25-35-42-48-51
A: This should export the data you need in a csv file:
from bs4 import BeautifulSoup
from csv import writer
import requests
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2019')
soup = BeautifulSoup(page.content,'html.parser')
header = {
'date': 'win-nbr-date col-sm-3 col-xs-4',
'winning numbers': 'nbr-grp',
'jackpot': 'win-nbr-jackpot col-sm-3 col-xs-3',
}
table = []
for header_key, header_value in header.items():
items = soup.find_all(class_=f"{header_value}")
column = [','.join(item.get_text().split()) if header_key=='winning numbers'
else ''.join(item.get_text().split()) if header_key == 'jackpot'
else item.get_text() for item in items]
table.append(column)
rows = list(zip(*table))
with open("winning numbers.csv", "w") as f:
csv_writer = writer(f)
csv_writer.writerow(header)
for row in rows:
csv_writer.writerow(row)
header is a dictionary mapping what will be your csv headers to their html class values
In the for loop we're building up the data per column. Some special handling was required for "winning numbers" and "jackpot", where I'm replacing any whitespace/hidden characters with comma/empty string.
Each column will be added to a list called table. We write everything in a csv file, but as csv writes one row at a time, we need to prepare our rows using the zip function (rows = list(zip(*table)))
A: Don't use BeautifulSoup if there are table tags. It's much easier to let Pandas do the work for you (it uses BeautifulSoup to parse tables under the hood).
import pandas as pd
years = [2017, 2018, 2019]
df = pd.DataFrame()
for year in years:
url = 'https://www.lotterycorner.com/tx/lotto-texas/%s' %year
table = pd.read_html(url)[0][1:]
win_nums = table.loc[:,1].str.split(" ",expand=True).reset_index(drop=True)
dates = pd.DataFrame(list(table.loc[:,0]), columns=['date'])
table = dates.merge(win_nums, left_index=True, right_index=True)
df = df.append(table, sort=True).reset_index(drop=True)
df['date']= pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)
df.to_csv('file.csv', index=False, header=False)
Output:
print (df)
date 0 1 2 3 4 5
0 2017-01-04 5 7 36 39 40 44
1 2017-01-07 2 5 14 18 26 27
2 2017-01-11 4 13 16 19 43 51
3 2017-01-14 7 8 10 18 47 48
4 2017-01-18 6 11 17 37 40 49
5 2017-01-21 2 13 17 39 41 46
6 2017-01-25 1 14 19 32 37 46
7 2017-01-28 5 7 30 48 51 52
8 2017-02-01 12 19 26 29 37 54
9 2017-02-04 8 13 19 25 26 29
10 2017-02-08 10 15 47 49 51 52
11 2017-02-11 24 25 26 29 41 53
12 2017-02-15 1 4 5 43 53 54
13 2017-02-18 5 11 14 21 38 44
14 2017-02-22 4 8 21 27 52 53
15 2017-02-25 16 37 42 46 49 54
16 2017-03-01 3 24 33 34 45 51
17 2017-03-04 2 4 5 17 48 50
18 2017-03-08 15 19 24 33 34 47
19 2017-03-11 5 6 24 28 29 37
20 2017-03-15 4 11 19 27 32 46
21 2017-03-18 12 15 16 23 38 43
22 2017-03-22 3 5 15 27 36 52
23 2017-03-25 21 25 27 30 36 48
24 2017-03-29 7 9 11 18 23 43
25 2017-04-01 3 21 28 33 38 52
26 2017-04-05 8 20 21 26 51 52
27 2017-04-08 10 11 12 47 48 52
28 2017-04-12 5 26 30 31 46 54
29 2017-04-15 2 11 36 40 42 53
.. ... .. .. .. .. .. ..
265 2019-07-20 3 35 38 45 50 51
266 2019-07-24 2 9 16 22 46 49
267 2019-07-27 1 2 6 8 20 53
268 2019-07-31 20 24 34 36 41 44
269 2019-08-03 6 17 18 20 26 34
270 2019-08-07 1 3 16 22 31 35
271 2019-08-10 18 19 27 36 48 52
272 2019-08-14 22 23 29 36 39 49
273 2019-08-17 14 18 21 23 40 44
274 2019-08-21 18 28 29 36 48 52
275 2019-08-24 11 31 42 48 50 52
276 2019-08-28 9 21 40 42 49 53
277 2019-08-31 5 7 30 41 44 54
278 2019-09-04 4 26 36 37 45 50
279 2019-09-07 22 23 31 33 40 42
280 2019-09-11 8 11 12 30 31 49
281 2019-09-14 1 3 24 28 31 41
282 2019-09-18 3 24 26 29 45 50
283 2019-09-21 2 20 31 43 45 54
284 2019-09-25 5 9 26 38 41 44
285 2019-09-28 16 18 39 45 49 54
286 2019-10-02 9 26 39 42 47 49
287 2019-10-05 6 10 18 24 32 37
288 2019-10-09 14 18 19 27 33 41
289 2019-10-12 3 11 15 29 44 49
290 2019-10-16 12 15 25 39 46 49
291 2019-10-19 19 29 41 46 50 51
292 2019-10-23 4 5 11 35 44 50
293 2019-10-26 1 2 26 41 42 54
294 2019-10-30 10 11 28 31 40 53
[295 rows x 7 columns]
A: Here is a concise way with bs4 4.7.1+ that uses :not to exclude header and zip to combine columns for output. Results are as on page. Session is used for efficiency of tcp connection re-use.
import requests, re, csv
from bs4 import BeautifulSoup as bs
dates = []; winning_numbers = []
with requests.Session() as s:
for year in range(2017, 2020):
r = s.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
soup = bs(r.content)
dates.extend([i.text for i in soup.select('.win-nbr-date:not(.blue-bg)')])
winning_numbers.extend([re.sub('\s+','-',i.text.strip()) for i in soup.select('.nbr-list')])
with open("lottery.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
w.writerow(['date','numbers'])
for row in zip(dates, winning_numbers):
w.writerow(row)
A: This one works:
import requests
from bs4 import BeautifulSoup
import io
import re
def main():
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2018')
soup = BeautifulSoup(page.content,'html.parser')
week = soup.find(class_='win-number-table row no-brd-reduis')
wn = (week.find_all(class_='nbr-grp'))
file = open ("vit.txt","w+")
for winning_number in wn:
line = remove_html_tags(str(winning_number.contents).strip('[]'))
line = line.replace(" ", "")
file.write(line + "\n")
file.close()
def remove_html_tags(text):
import re
clean = re.compile('<.*?>')
return re.sub(clean, '', text)
This part of the code loops through the wn variable and writes every line to the "vit.txt" file:
for winning_number in wn:
line = remove_html_tags(str(winning_number.contents).strip('[]'))
line = line.replace(" ", "")
file.write(line + "\n")
file.close()
The "stripping" of the <li> tags could be probably done better, e.g. there should be an elegant way to save the winning_number to a list and print the list with 1 line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58561118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Datepicker submit format In the new version of materialize the new 'datepicker' seems to have lost the option for 'formatSubmit'
format: 'dd/mm/yyyy'
formatSubmit: 'yyyy-mm-dd'
You use to be able to display the date in the page in one format and submit it in another.
Anyone have a way round this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55832738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the good way to provide an authentication in FASTAPI? what is the best way to provide an authentication for API. I read about authentication, Given an approach to write user: str = Depends(get_current_user) for each every function. I don't think so this is the good way to write an authentication. Can we erite a middleware for it, and add a userid to request object, so that we can take that in the API request processing. Could you any send me the middleware if some one already written.
A: There is already good implementations in:
*
*fastapi_contrib
*fastapi-users
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61153498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: retrieve appointment from OWA(on premises outlook web Access) using C# How to retrieve calendar meetings and appointments list from OWA(outlook web Access) using C#. without using exchange web services
A: You can use Microsoft Graph Api:
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/user_list_events
Or Outlook Api:
https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations
Simple googling will get you the above results...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50699844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: flask-sqlalchemy count function Consider a table named result with the following schema
+----+-----+---------+
| id | tag | user_id |
+----+-----+---------+
| 0 | A | 0 |
| 1 | A | 0 |
| 2 | B | 0 |
| 3 | B | 0 |
+----+-----+---------+
for user with id=0 I would like to count they number of times a result with tag=A has been appeared. For now I have implemented it using raw SQL statement
db.session.execute('select tag, count(tag) from result where user_id = :id group by tag', {'id':user.id})
How can I write it using flask-sqlalchemy APIs?
Most of results I get mention the sqlalchemy function db.func.count() which is not available in flask-sqlalchemy or has a different path which I am not aware of.
A: I was using PyCharm as my IDE and it was not showing module members correctly, hence I thought count is missing. Here is my solution for the above
user.results.add_columns(Result.tag, db.func.count(Result.tag)).group_by(Result.tag).all()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42573970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Removing Title Bar on Android App So I know there are a ton of these questions, but every time I try what they say, my app does not seem to remove the title bar. I have done the style change:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowNoTitle">true</item> <!-- This should work but it does not -->
</style>
I have also tried:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //This guy here
setContentView(R.layout.activity_title);
The above works but I still want to use the space the title bar takes for content in my app, which is why I want to be able to modify the XML code rather than use java. Any suggestions?
A: You can either:
<style name="noActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
and in your layout(at the root layout)
android:theme="@theme/noActionBar"
Or
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
However, the last one also hides the Statusbar. You can also set the theme to a default theme(look through the themes and find those with NoActionBar). The last one is useful if you have no plans to style the activity(for an instance if you use SurfaceView) with custom colors, etc.
For an instance you can change AppBaseTheme to have the parent Holo.Light.NoActionBar or any similar theme, but the name has to contain NoActionBar, othervise it has an actionbar
A: Add the below theme to style.xml:
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Then set this theme to your Activity in manifest:
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.NoActionBar" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43239101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: List of properties not changing when set In a class constructor I have a instantiate a list containing properties:
public MDInstrument() : base()
{
// bidss = new TickData[] {Bid0};
Bids = new List<TickData> { Bid0, Bid1, Bid2, Bid3, Bid4, Bid5, Bid6, Bid7, Bid8, Bid9, Bid10, Bid0, Bid11, Bid13, Bid14, Bid15, Bid6, Bid17, Bid18, Bid19};
Offers = new List<TickData> { Ask0, Ask1, Ask2, Ask3, Ask4, Ask5, Ask6, Ask7, Ask8, Ask9, Ask10, Ask0, Ask11, Ask13, Ask14, Ask15, Ask6, Ask17, Ask18, Ask19};
}
A method in the class updates the object in the list but why is the object always null ?
I must be missing something
A: Your problem is that to begin with Bid{x} and Ask{x} have not been instantiated, i.e. they're null, and then you store a reference to those values, and of course the reference is null. When you then later on update Bid0 (for example), then that reference is updated, but nothing can know that this is intended to be stored within your set.
Suggest that you change your list to be an array of a fixed known size (here, 20) which will be all nulls to begin with. Then change your getter/setter accessors for the individual Bid items to actually the array internally. Then you also don't need all of those separate Bid{x}/Ask{x} variables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47455796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Creating POJO/beans dynamically and set values using CGLib I have a requirement to parse a text file and generate JSON document. The text file has a pattern of text which contains a key which is a name and the value is a huge text of TSV with headers.
I could parse the text file and generate bean classes using the headers and now i want to set the data to this generated bean class. I am using reflection to do this.
Class<?> beanClass = BeanClassGenerator.beanGenerator(k, mapForBeanGeneration);
try {
Object beanClassObject = beanClass.newInstance();
lines.forEach(line -> {
if (line != null && !line.isEmpty() && !line.equals("null")) {
String[] lineData = line.split("\t");
System.out.println("LineData length :: " + lineData.length);
Method[] methods = beanClass.getMethods();
System.out.println("Methods length :: " + methods.length);
int index = 0;
for (Method m : methods) {
m.setAccessible(true);
if (m.getName().startsWith("set")) {
try {
if ((lineData.length <= index) && lineData[index] != null) {
m.invoke(beanClassObject, lineData[index]);
index++;
} else {
m.invoke(beanClassObject, " ");
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
});
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(beanClassObject));
} catch (InstantiationException | IllegalAccessException | JsonProcessingException e) {
e.printStackTrace();
}});
The problem with the approach is that most of the times all the column values may not have data it can be nulled.
I am wondering if there is an easier way of doing this. Any help is appreciated.
Here is the bean generation method.
public static Class<?> beanGenerator(final String className, final Map<String, Class<?>> properties) {
BeanGenerator beanGenerator = new BeanGenerator();
beanGenerator.setNamingPolicy(new NamingPolicy() {
@Override
public String getClassName(String prefix, String source, Object key, Predicate names) {
return className;
}
});
BeanGenerator.addProperties(beanGenerator, properties);
return (Class<?>) beanGenerator.createClass();
}
Here is the sample text file which needs to be converted to the JSON output.
<Data1>
Col1 col2 col3 col4 col5
even sense met has
root greatest spin mostly
gentle held introduced palace
cold equator remember grandmother
slightly butter depth like
distant second coast everyone
<Data2>
Col1 col2 col3 col4 col5 col6 col7 col8
greatest rope operation flies brown continent combination read
slightly diagram he grandfather where party fifty pour
well put plastic anyway refer careful correct furniture
how since army tongue birthday been clock official
table command specific distant cutting hill movie experience
national though stopped youth army underline five know
<Data3>
Col1 col2 col3 col4 col5 col6 col7 col8 col9 col9 col10
vessels characteristic ship joy than tomorrow high seven future trade
try gray fourth advice week stream motion musical whom tin
limited daughter large rice came home chicken wheat engine box
easy city pair strange stage visitor coach announced allow simple
jet therefore single during construction flag bigger muscle complex pleasure
income several coat range dull cattle damage jump present shake
JSON output:
[{
"<Data1>": [{
"col1": "",
"col2": "",
"col3": "",
"col4": ""
},
{
"col1": "",
"col2": "",
"col3": "",
"col4": ""
},
{
"col1": "",
"col2": "",
"col3": "",
"col4": ""
}
]
}, {
"<Data2>": [{
"col1": "",
"col2": "",
"col3": "",
"col4": "",
"col5": "",
"col6": "",
"col7": "",
"col8": ""
},
{
"col1": "",
"col2": "",
"col3": "",
"col4": "",
"col5": "",
"col6": "",
"col7": "",
"col8": ""
},
{
"col1": "",
"col2": "",
"col3": "",
"col4": "",
"col5": "",
"col6": "",
"col7": "",
"col8": ""
}
]
}]
I came up with a solution using the Maps.
Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
metadataMap.forEach((k, v) -> {
List<Map<String, String>> datamap = new ArrayList<>();
String key = k;
String[] fields = v.getFields();
List<String> lines = v.getLines();
lines.forEach(line -> {
if (line != null && !line.isEmpty() && !line.equals("null")) {
String[] fieldData = line.split("\t");
Map<String, String> eachLineMap = new HashMap<>();
for (int index = 0; index < fields.length; index++) {
if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
eachLineMap.put(fields[index], fieldData[index]);
} else {
eachLineMap.put(fields[index], " ");
}
datamap.add(eachLineMap);
}
}
});
finalMap.put(key, datamap);
});
try {
output = new ObjectMapper().writeValueAsString(finalMap);
}catch(JsonProcessingException e){
e.printStackTrace();
}
A: You don't need to write all that logic, you can just use Apache Commons BeanUtils; which provides a utility method (among MANY other utilities), that takes a Map of field names versus field values and populate a given bean with it:
BeanUtils.populate(target, fieldNameValueMap);
Then the only thing you need to implement is the logic to create the fieldNameValueMap Map; which you can do with this simple method:
Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) {
String[] fieldNames = headerLine.split("\t");
String[] fieldValues = valuesLine.split("\t");
return IntStream.range(0, fieldNames.length)
.mapToObj(Integer::new)
.collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx]));
}
You can test this solution with the following working demo:
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.beanutils.BeanUtils;
import lombok.Data;
public class DynamicBeanUtils {
static Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) {
String[] fieldNames = headerLine.split("\t");
String[] fieldValues = valuesLine.split("\t");
return IntStream.range(0, fieldNames.length)
.mapToObj(Integer::new)
.collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx]));
}
public static void main(String[] args) {
String headerLine = "booleanValue\tintValue\tstringValue\tdoubleValue\totherValue";
String valuesLine = "true\t12\tthis bean will be populated\t22.44\ttest string!!!";
Object target = new MyBean();
try {
BeanUtils.populate(target, createFieldNameValueMap(headerLine, valuesLine));
} catch (IllegalAccessException | InvocationTargetException e) {
// HANDLE EXCEPTIONS!
}
System.out.println(target);
}
@Data
public static class MyBean {
private String stringValue;
private double doubleValue;
private int intValue;
private boolean booleanValue;
private String otherValue;
}
}
This is the maven repository page for this dependency, so you can include it in your build: https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils/1.9.3
I used Lombok in this solution as well, only to save me the pain of writing getter/setters/toString to test this solution; but it is not required for your solution.
Complete code on GitHub
Hope this helps.
A: You are going way overboard with your solution.
Your data is organized as an array of variable length arrays;
and does not require some crazy on-the-fly class generation solution.
As a side note,
on-the-fly class generation is not inherently crazy;
it is crazy to use on-the-fly class generation in this situation.
Do this:
*
*Look at your data;
it is organized as follows:
*
*first: outer key
*second: exactly one line containing a variable number of space separated array of inner keys.
*third: some number of lines containing values.
*Design a solution to fix your problem
*
*Read the outer key.
Use that value to create the outer key portion of your JSON.
*Read the inner keys.
Store these in an array;
use LinkedList,
not ClownList (ArrayList).
*Do this until the next empty line:
*
*Read a line of values.
*Write the inner JSON; use the inner keys as the keys for this.
*Skip empty lines until one of the following:
*
*If at end of file, write the ending portion of the JSON.
*If you read the next outer key, goto to line 2 (Read the inner keys) above.
*Write the code.
A: I realized that instead of creating the POJOs with a complex approach. It is better to use the Maps and convert them to JSON using Jackson ObjectMapper. Posting for others who think this might be a useful approach.
public String convert(Map<String, ? extends Metadata> metadataMap) {
String output = "";
Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
metadataMap.forEach((k, v) -> {
List<Map<String, String>> datamap = new LinkedList<>();
String key = k;
String[] fields = v.getFields();
List<String> lines = v.getLines();
lines.forEach(line -> {
if (line != null && !line.isEmpty() && !line.equals("null")) {
String[] fieldData = line.split("\t",-1);
Map<String, String> eachLineMap = new HashMap<>();
for (int index = 0; index < fields.length; index++) {
if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
eachLineMap.put(fields[index], fieldData[index]);
} else {
eachLineMap.put(fields[index], " ");
}
datamap.add(eachLineMap);
}
}
});
finalMap.put(key, datamap);
});
try {
output = new ObjectMapper().writeValueAsString(finalMap);
}catch(JsonProcessingException e){
e.printStackTrace();
}
return output;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56261526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Angular can't navigate to other component I'm new in Angular.
I'm trying to build a simple application with a list page and a detail page.
The issues are multiple:
1- the search page shows the the th twice and shows it in all pages.
2- when I try to use route link, the app doesn't load the detail page.
I've spent hour searching solution in order to fix this issues...
Here my code:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { SearchService } from './home/search.service';
import { SearchComponent } from './home/search.component';
import { CharDetailComponent } from './char-detail/char-detail.component';
import { RouterModule } from '@angular/router';
@NgModule({
declarations: [
AppComponent,
SearchComponent,
CharDetailComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
AppRoutingModule,
RouterModule,
],
providers: [SearchService],
bootstrap: [
AppComponent
]
})
export class AppModule { }
export class MyTemplatesModule { }
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from './home/search.component';
import { CharDetailComponent } from './char-detail/char-detail.component';
const routes: Routes = [
{path:'', component: SearchComponent},
{path:'showDetails', component: CharDetailComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
search.component.ts
import { Component, OnInit } from '@angular/core';
import { SearchService } from './search.service';
import { MovieCharacter } from './movie-character';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit{
people: MovieCharacter[];
constructor(private searchService: SearchService,
private router: Router,
private route: ActivatedRoute
) {
console.log('data');
}
ngOnInit() {
this.searchService.getPeople().subscribe(data=>{
console.log(data);
this.people = data.results;
});
}
ngAfterViewInit(){
this.searchService.getPeople().subscribe(data=>{
console.log(data);
this.people = data.results;
});
}
onSelect(name: string){
this.router.navigate(['/showDetails/'+name]);
}
}
search.component.html
<table>
<tr>
<th>name</th>
<th>description</th>
<th>url</th>
</tr>
<tr *ngFor="let person of people">
<td>{{person.name}}</td>
<td>{{person.description}}</td>
<td><a href="{{person.url}}">{{person.url}}</a></td>
<a href="/showDetails"><button >
<span>Go to master Page</span>
</button>
</a>
</tr>
</table>
<router-outlet></router-outlet>
char-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { MovieCharacter } from '../home/movie-character';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-char-detail',
templateUrl: './char-detail.component.html',
styleUrls: ['./char-detail.component.css']
})
export class CharDetailComponent implements OnInit{
people: MovieCharacter[];
param : string;
constructor(private route: ActivatedRoute) { }
ngOnInit():void {
this.showDetails();
}
showDetails(){
this.param = this.route.snapshot.paramMap.get('name');
}
}
char-detail.component.html
<p>my name is {{param}}</p>
<router-outlet></router-outlet>
I know the code is very dirty and there are a lot of mistake, but please help me!
A: Welcome to the world of Angular!
To begin with, remove the <router-outlet></router-outlet> from all pages except app.component.html.
After you have done this, retest your pages. If the details page still doesn't show, look at your console for any Javascript errors and please post here :)
A: There are few issues in your code. Here is the solution:
*
*Remove the <router-outlet></router-outlet> from all pages except app.component.html
*If you need to pass name parameter in showDetails page then you need to specify that in app-routing.module.ts so instead of {path:'showDetails', component: CharDetailComponent}, you need to put {path:'showDetails/:name', component: CharDetailComponent}
After this change, ng serve your application again and you are good to go :). Hope this help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59742872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: isnull function vs IS NULL as part of a case statement in a wider sql script, I have the following:
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE is null THEN 'NO CIVIL CG'
This will set the field to 'NO CIVIL CG' for 1405 records
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND ISNULL(KWB.CIVCONDGRADE,'') = '' THEN 'NO CIVIL CG'
This will set the field for 1410 records, which would appear to be the right answer,
as the 5 fields not set in the first instance have ASYCONDTYPE = 'CIVIL' and CIVCONDGRADE is indeed NULL
Slightly worrying, as I'd expect them to produce the same result, and if it wasn't for excel filtering, it might have gone unnoticed.
Can anyone provide an explanation or at least somewhere I can check in the dataset or database to enable me to understand what's going on?
A: That should be becouse you got 1405 records where "KWB.CIVCONDGRADE" is actually NULL and 5 records where "KWB.CIVCONDGRADE" isn't NULL but simply an empty field.
Try to check with this query if it results 5 records:
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE = '' THEN 'NO CIVIL CG'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44844079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Annotated bean config doesnt see bean from XML config Im really confused. I have web-app with Spring Security. I have database.xml config with embedded database:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<jdbc:embedded-database id="dataSource" type="H2" />
</beans>
I have also PersistenceJpaConfig:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("pl.springsecurity.repositories")
public class PersistenceJpaConfig {
@Autowired
private DataSource dataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource);
entityManager.setPackagesToScan(new String[] { "pl.springsecurity.domain" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
//vendorAdapter.setShowSql(true);
entityManager.setJpaVendorAdapter(vendorAdapter);
return entityManager;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
That works fine when my Spring Security configuration is in xml bean file, and Spring Security filters are declared in web.xml.
But... Since Im trying move Spring Security config to Java class, which means that filters are no longer needed in web.xml, and since I created AbstractSecurityWebApplicationInitializer, Spring can't find DataSource bean delcared in database.xml and bind it into my Jpa Configuration. im really confused why...
Here is my stack trace:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceJpaConfig': Injection
of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could no
t autowire field: private javax.sql.DataSource pl.springsecurity.config.PersistenceJpaConfig.dataSource; nested exceptio
n is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency ann
otations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBea
nFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java
:368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractA
utowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapa
bleBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationCo
ntext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSour
ce pl.springsecurity.config.PersistenceJpaConfig.dataSource; nested exception is org.springframework.beans.factory.NoSuc
hBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 be
an which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factor
y.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:331)
... 40 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSo
urce] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependen
cy annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultLista
bleBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.
java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.ja
va:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:533)
... 42 more
sty 29, 2016 1:40:12 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/SpringSecurity] threw load() exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found
for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotati
ons: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultLista
bleBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.
java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.ja
va:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:533)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:331)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBea
nFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java
:368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractA
utowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapa
bleBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationCo
ntext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
at java.lang.Thread.run(Unknown Source)
Any ideas guys?
A: Use @ImportResource to load your xml file.
@Configuration
@ImportResource(locations = "classpath:/database.xml")
....
public class PersistenceJpaConfig {
Change the location appropriately.
A: You have to load the xml. See docs
You can use @ImportXml("classpath:com/company/app/datasource-config.xml")
on your configuration class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35084994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Not showing from folder So guys I have made a admin system which saves images to a specific folder with specific id according to rows in database.
The picture is in the folder but its not showing..
MY index.php CODe:
<?php
include 'admin/connect.php';
$sql = "SELECT * FROM products";
$run = mysqli_query($conn, $sql);
while ($row = $run->fetch_assoc()) {
$id = $row['id'];
?>
<img src="inventory_images/"<?php echo $id; ?> />
<?php
}
?>
A: Try removing the " before you echo the id and adding it at the end:
<img src="inventory_images/<?php echo $id; ?>" />
(otherwise your image link is inventory_images/"54 for example)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44871047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL to HiveQL in Hive Hadoop I am trying to write a HiveQL query which joins two data sets by a BAN column where one datasets timestamp is 72+ hours after the other datasets timestamp. I can write this in SQL but the syntax isn't the same in HiveQL. Can anyone help?
For example :
SELECT * FROM Session_Step_Table, Case_Table
WHERE Session_Step_Table.BAN = Case_Table.BAN AND
DATEADD(hour, 72, Session_Step_Table.timestamp) <= Case_Table.timestamp
A: I think you should use date_add() function provided in Hive. Look here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30899985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Put something in article in random place with PHP I am trying to put random text in an article so I use explode to make every word an array:
$article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';
$words = explode(' ', $article);
// a new array to hold the string we are going to create
$newString = array();
// loop all words of the original string
foreach ($words as $i => $w) {
// add every word to the new string
$newString[] = $w;
}
$inserted = array('ad this in random place'); // Not necessarily an array
$ilejest = count($newString); // count all words from array
$wstawwloowo = rand(1, $ilejest); // random number from 1 to max number of values in array
$newString = array_splice( $newString, $wstawwloowo, 0, $inserted ); //
// create a string from the array of words we just composed
$contenttre = implode(' ', $newString);
How to make it works?
A: array_splice get first argument by reference, so don't assign result to the same variable name $newString.
array_splice($newString, $wstawwloowo, 0, $inserted); it's enough.
A: $article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';
$words = explode(' ', $article);
// a new array to hold the string we are going to create
$randId = rand(0, sizeOf($words));
array_splice($words, $randId, 0, array('Random string in random place'));
$newString = implode(',', $words);
echo $newString; // Will print the new string
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39478712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Infinite House of Pancakes Here's a link to the problem in question: https://code.google.com/codejam/contest/6224486/dashboard#s=p1
Okay, so I got a bit hung up on this problem. Now that the quals are over, does anyone know why this wouldn't work? I've checked against about 50 different cases and haven't been able to find one that doesn't work. Here's my full code below.
Basically, looking for any cases where my algorithm could break.
//Includes
#include <iostream>
#include <fstream>
#include <list>
#include <algorithm>
#include <stdlib.h>
using namespace std;
//Functions
int solve(list<int>);
//Main
int main() {
int minutes = 0;
int numTestCases = 0;
int initNonEmpty = 0;
char tempChar;
int tempInt;
list<int> people;
//Import Data
//Get number of Test cases
ifstream infile;
infile.clear();
infile.open("B-small-attempt5.in");
//get NumTestCases
infile >> numTestCases;
int solution[numTestCases];
//Solve it
for(int i=0; i<numTestCases; i++){
//Reset vars
initNonEmpty=0;
infile >> initNonEmpty;
people.clear();
//Input data
for(int j=0; j<initNonEmpty; j++){
infile >> tempInt;
cout << tempInt;
people.push_back(tempInt);
}
cout << endl;
//Solve the set
people.sort();
people.reverse();
tempInt = solve(people);
cout << "Solve returns: " << tempInt << endl << endl;
solution[i] = tempInt;
}
//Output
ofstream outfile;
outfile.open("RealCase6.out");
for (int i=0; i < numTestCases; i++){
cout << "Case #" << i+1 << ": " << solution[i] << endl;
outfile << "Case #" << i+1 << ": " << solution[i] << endl;
}
}
int solve( list<int> data){
cout << "Starting Solve functions." << endl;
int tempMax;
int max =data.front();
int test=0;
cout << "Max: " << max << endl;
//Test if base case
if(max<=3){
cout << "Reached base case." << endl;
return max;
}
else if (max % 2 == 0 ){
cout << "Max is even" << endl;
tempMax = max/2;
data.pop_front();
data.push_back(tempMax);
data.push_back(tempMax);
data.sort();
data.reverse();
test=solve(data);
test=test+1;
cout << "test is:" << test << endl;
cout << "max is:" << max << endl;
if( test<=max){
return test;
} else {
return max;
}
}
else {
cout << "Max is odd" << endl;
tempMax = max/2;
data.pop_front();
data.push_back(tempMax);
data.push_back(tempMax+1);
data.sort();
data.reverse();
test=solve(data);
test=test+1;
cout << "test is:" << test << endl;
cout << "max is:" << max << endl;
if(test<=max){
return test;
} else {
return max;
}
}
}
And here's my input/output for 6 different cases.
https://www.dropbox.com/sh/55wq52lzuygd82s/AABYxJJ7zaeoMhgCmymJcwnAa?dl=0
I'll remove this if this is too early to start asking about the problems. Sorry about eh formatting, but I was trying to get this done quickly.
Edit1: Added Link to problem.
Edit2: Someone else found the error. I only thought to divide things into groups of 2, which gives a case of one person with 9 pancakes, where dividing it into a group of 6 and 3 and then 3 3 3 works best.
A: This breaks in cases where it's more efficient to divide into non-equivalent stacks. For example, the case
1
9
where one person has 9 pancakes. Dividing as evenly as possible into groups of 2 gives the solution:
min 1: 9
min 2: 5 4
min 3: 4 3
min 4: 3 2
min 5: 2 1
min 6: 1 0
min 7: 0 0
where as dividing unevenly gives the solution
min 1: 9
min 2: 3 6
min 3: 3 3 3
min 4: 2 2 2
min 5: 1 1 1
min 6: 0 0 0
which is more efficient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29585210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How to declare function in typeScript within class? How does one declare function like this in typescript within class? What I am trying to achieve is to declare all members first, and then provide implementation of the function later. I want to be able to quickly scan class to see all members. This does not work for me.
class myClass {
this.myFunction = myFunction;
function myFunction(){
}
}
A: TypeScript is just a superset of JavaScript. This means that you can write ES5 or ES6 code, it will be perfectly compiled by tsc.
In TypeScript, even if you do not use type checking, it is OK:
function myFunction () {
// Your code...
}
var myFunction = function () {
// Your code...
};
let myFunction = function () {
// Your code...
};
const myFunction = () => {
// Your code...
};
// etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43482510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Unable to group data in Reducer I am trying to write a MapReduce application in which the Mapper passes a set of values to the Reducer as follows:
Hello
World
Hello
Hello
World
Hi
Now these values are to be grouped and counted first and then some further processing is to be done. The code I wrote is:
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
List<String> records = new ArrayList<String>();
/* Collects all the records from the mapper into the list. */
for (Text value : values) {
records.add(value.toString());
}
/* Groups the values. */
Map<String, Integer> groupedData = groupAndCount(records);
Set<String> groupKeys = groupedData.keySet();
/* Writes the grouped data. */
for (String groupKey : groupKeys) {
System.out.println(groupKey + ": " + groupedData.get(groupKey));
context.write(NullWritable.get(), new Text(groupKey + groupedData.get(groupKey)));
}
}
public Map<String, Integer> groupAndCount(List<String> records) {
Map<String, Integer> groupedData = new HashMap<String, Integer>();
String currentRecord = "";
Collections.sort(records);
for (String record : records) {
System.out.println(record);
if (!currentRecord.equals(record)) {
currentRecord = record;
groupedData.put(currentRecord, 1);
} else {
int currentCount = groupedData.get(currentRecord);
groupedData.put(currentRecord, ++currentCount);
}
}
return groupedData;
}
But in the output I get a count of 1 for all. The sysout statements are printed something like:
Hello
World
Hello: 1
World: 1
Hello
Hello: 1
Hello
World
Hello: 1
World: 1
Hi
Hi: 1
I cannot understand what the issue is and why not all records are received by the Reducer at once and passed to the groupAndCount method.
A: As you note in your comment, if each value has a different corresponding key then they will not be reduced in the same reduce call, and you'll get the output you're currently seeing.
Fundamental to Hadoop reducers is the notion that values will be collected and reduced for the same key - i suggest you re-read some of the Hadoop getting started documentation, especially the Word Count example, which appears to be roughly what you are trying to achieve with your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14477261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AutoMapper requiring mapping members and constructor I am brand new to AutoMapper and am just trying to get my head around the best way to do things.
I quickly ran into a hairy issue mapping between two simple, but realistic, object models. The first is for a service layer:
public sealed class GeoLocation
{
public GeoLocation(
double latitude,
double longitude)
{
this.Latitude = latitude;
this.Longitude = longitude;
}
public double Latitude { get; private set; }
public double Longitude { get; private set; }
}
public sealed class Location
{
public Location(
string name,
GeoLocation geoLocation)
{
this.Name = name;
this.GeoLocation = geoLocation;
}
public string Name { get; private set; }
public GeoLocation GeoLocation { get; private set; }
}
And the second is a simplified representation of the above for a database layer:
public sealed class LocationEntity
{
public LocationEntity(
string name,
double latitude,
double longitude)
{
this.Name = name;
this.Latitude = latitude;
this.Longitude = longitude;
}
public string Name { get; }
public double Latitude { get; }
public double Longitude { get; }
}
If I attempt to map the types with a simple CreateMap<Location, LocationEntity>().ReverseMap() call, I predictably get a problem when validating the mappings:
AutoMapperConfigurationException:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
===============================================
Location -> LocationEntity (Destination member list)
UserQuery+Location -> UserQuery+LocationEntity (Destination member list)
No available constructor.
===============================================
LocationEntity -> Location (Destination member list)
UserQuery+LocationEntity -> UserQuery+Location (Destination member list)
Unmapped properties:
GeoLocation
No available constructor.
Fair enough. I didn't feel like mapping every constructor parameter, so I tried calling ConstructUsing:
Mapper.Initialize(
config =>
{
config
.CreateMap<Location, LocationEntity>()
.ConstructUsing((source, _) => new LocationEntity(source.Name, source.GeoLocation?.Latitude ?? 0.0, source.GeoLocation?.Longitude ?? 0));
config
.CreateMap<LocationEntity, Location>()
.ConstructUsing((source, _) => new Location(source.Name, new GeoLocation(source.Latitude, source.Longitude)));
});
However, this still complains about the LocationEntity -> Location mapping:
AutoMapperConfigurationException:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
===============================================
LocationEntity -> Location (Destination member list)
UserQuery+LocationEntity -> UserQuery+Location (Destination member list)
Unmapped properties:
GeoLocation
Unsure what else to do, I added a ForMember call to the LocationEntity -> Location mapping:
config
.CreateMap<LocationEntity, Location>()
.ConstructUsing((source, _) => new Location(source.Name, new GeoLocation(source.Latitude, source.Longitude)))
.ForMember(
x => x.GeoLocation,
options => options.MapFrom((source, target, _, context) => new GeoLocation(source.Latitude, source.Longitude)));
Whilst this solves the problem, it seems to me that my mappings are already becoming somewhat complex. I'm wondering: is there a better way to go about this that doesn't sacrifice the design of my object models?
A: Your object model design basically allows mapping (converting) only via construction, hence can't benefit the most of the AutoMapper automatic and explicit mapping capabilities.
ConstructUsing is used to select a non default constructor for creating destination instances, but still requires member mapping.
What you need is the ConvertUsing method:
Skip member mapping and use a custom expression to convert to the destination type
Mapper.Initialize(config =>
{
config.CreateMap<Location, LocationEntity>()
.ConvertUsing(source => new LocationEntity(source.Name, source.GeoLocation?.Latitude ?? 0.0, source.GeoLocation?.Longitude ?? 0));
config.CreateMap<LocationEntity, Location>()
.ConvertUsing(source => new Location(source.Name, new GeoLocation(source.Latitude, source.Longitude)));
});
A: ConvertUsing is helpful if you really want to take over the mapping. But more idiomatic in this case would be to map through constructors. By adding another constructor to Location (private if needed) you could even remove ForCtorParam.
CreateMap<Location, LocationEntity>().ReverseMap().ForCtorParam("geoLocation", o=>o.MapFrom(s=>s));
class LocationEntity
{
public LocationEntity(string name, double geoLocationLatitude, double geoLocationLongitude)
{
this.Name = name;
this.Latitude = geoLocationLatitude;
this.Longitude = geoLocationLongitude;
}
public string Name { get; }
public double Latitude { get; }
public double Longitude { get; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54661190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PySpark 2.4.5 is not compatible with Python 3.8.3, how do I solve this? Code
from pyspark import SparkContext,SparkConf
conf=SparkConf().setMaster('local').setAppName('Test App')
sc=SparkContext(conf)
Error Message
Traceback (most recent call last):
File "C:\Users\Test\PycharmProjects\python-test\MainFile.py", line 5, in <module>
from pyspark import SparkContext,SparkConf
File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\__init__.py", line 51, in <module>
from pyspark.context import SparkContext
File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\context.py", line 31, in <module>
from pyspark import accumulators
File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\accumulators.py", line 97, in <module>
from pyspark.serializers import read_int, PickleSerializer
File "C:\Test\Python_3.8.3_Latest\lib\sit`enter code here`e-packages\pyspark\serializers.py", line 72, in <module>
from pyspark import cloudpickle
File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\cloudpickle.py", line 145, in <module>
_cell_set_template_code = _make_cell_set_template_code()
File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\cloudpickle.py", line 126, in _make_cell_set_template_code
return types.CodeType(
TypeError: an integer is required (got type bytes)
A: Although latest Spark doc says that it has support for Python 2.7+/3.4+, it actually doesn't support Python 3.8 yet. According to this PR, Python 3.8 support is expected in Spark 3.0. So, either you can try out Spark 3.0 preview release (assuming you're not gonna do a production deployment) or 'temporarily' fall back to Python 3.6/3.7 for Spark 2.4.x.
A: Spark 3.0 has been released for a while now and is compatible with Python 3.8.+.
The error you experienced is no longer reproducible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62208730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Python language support for pipes I would like to implement in python something like this:
def producer():
while True:
sys.stdout.write("this is my data\n")
def consumer():
while True:
data = sys.stdin.read()
print data
producer | consumer
The pipe actually needs to create two processes, connect stdout and stdin, and run them until both terminate.
Is there syntactical support for that in python, as the shell has, or do I need to recurse to the Popen object?
What is the simplest implementation in terms of Popen?
Could somebody offer a generic class which can be used to implement this piping pattern? The class would have a signature similar to this:
Class Pipe:
def __init__(self, process1, process2, ...):
So that, in my case, could be used as follows:
mypipe = Pipe(producer, consumer)
A: You can use the pipes module:
The pipes module defines a class to abstract the concept of a pipeline — a sequence of converters from one file to another.
Sure, the syntax won't be the same as a shell pipe, but why reinvent the wheel?
A: You may be thinking of coroutines. Check out this very interesting presentation by David Beazley.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8680880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Kotlin with hibernate java.io.NotSerializableException I have the following classes in kotlin
@Entity
@Cacheable
@Table(name = "fine")
@EntityListeners(FineSpecificationListener::class)
class FineSpecification (
@EmbeddedId
val id: FineSpecificationId,
@Column(name = "fine")
val fine: Int,
@Column(name = "min_fine")
val minimumFine: Int
): ValueObject<FineSpecification> {
@Transient
lateinit var algorithm: FineCalculationAlgorithm
override fun sameValueAs(other: FineSpecification): Boolean {
return Objects.equal(id, other.id) &&
Objects.equal(fine, other.fine) &&
Objects.equal(minimumFine, other.minimumFine)
}
override fun equals(other: Any?): Boolean {
if (other == null || this::class != other::class)
return false
val compareTo = other as FineSpecification
return sameValueAs(compareTo)
}
override fun hashCode(): Int {
return Objects.hashCode(id, fine, minimumFine)
}
override fun toString(): String {
return "FineSpecification(id=$id, fine=$fine, minimumFine=$minimumFine)"
}
fun calculateFine(dues: Long, dueDate: Date, currentDate: Date): Long {
return algorithm.calculateFine(arrears = dues, dueDate = dueDate, currentDate = currentDate)
}
}
class FineSpecificationId (
@Column(name = "effect_from")
val effectFrom: Date,
@Column(name = "effect_to")
val effectTo: Date,
@Column(name = "cat_code")
@Convert(converter = CategoryConverter::class)
val category: Category
): Serializable {
companion object {
private const val serialVersionUID = 20190819075136L
}
override fun toString(): String {
return "FineSpecificationId(effectFrom=$effectFrom, effectTo=$effectTo, category=$category)"
}
}
enum class Category (
val code: String
): Serializable {
DOMESTIC("D"),
NON_DOMESTIC("N"),
INDUSTRIAL("I"),
SPECIAL("S");
companion object {
private const val serialVersionUID = 20190819075150L
}
override fun toString(): String {
return code
}
}
I am using Spring Data with Hibernate and using hibernate ehcache. I want to cache FineSpecification, but when I do that I am getting the following exception
18 Aug 2019; 18:56:50.563 ERROR n.s.e.store.disk.DiskStorageFactory - Disk Write of domain.model.bill.fine.FineSpecification#FineSpecificationId(effectFrom=Thu Apr 01 00:00:00 IST 1999, effectTo=Thu Dec 31 00:00:00 IST 2020, category=D) failed:
java.io.NotSerializableException: org.hibernate.metamodel.model.convert.internal.JpaAttributeConverterImpl
As I can understand it is relating to FineSpecificationId as well as with the Category enum class. I have implemented the Serializable interface, but nothing works.
What should I do, to implement caching in this scenario ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57545154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Studio Preview is different from the real device I have installed an AVD for my Samsung Galaxy S7 Edge.
When I look to a layout at the android studio preview it fits the screen perfect. But it looks different on the real phone.
Device resolution is also at 2560x1440
What is the problem?
Screen settings AVD:
Preview settings Android Studio:
Screenshot Phone:
A: You are using a RelativeLayout with too many Views to fit the screen. Either you want to use ConstraintLayout to set the Views in a direct relation to each other or you put a ScrollView around your root layout. Either case there is only so much space to fill.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48305340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove scrollbars from canvas on Firefox Firefox is adding scrollbars to the canvas even with the body set to overflow:hidden and the execution of FB.Canvas.setAutoResize();. Every other browser hides the scrollbars. When I remove all content from the page the scrollbars persist.
Sample: https://apps.facebook.com/fbtestapppb/
A: With the introduction of Facebook Timeline the way to remove scroll bars and control page margins has changed. First (and most importantly) your body padding and margins MUST all be set to zero. This ensures all browsers process your canvas settings off absolute zero.
Depending on the 'Page Tab Width' (520px or 810px) option you set in your Apps/Page settings you will need to adjust the width in the following code. This block should be placed in the page Head:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.Canvas.setSize();
}
// Do things that will sometimes call sizeChangeCallback()
function sizeChangeCallback() {
FB.Canvas.setSize();
}
</script>
Just below the Body tag add the following code:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: 'YOUR APP ID', status: true, cookie: true, xfbml: true});
window.fbAsyncInit = function() {
FB.Canvas.setSize({ width: 520, height: 1000 });
}
</script>
Remember to change 'YOUR APP ID'. Also width: should equal either 520 or 810. Set height: slightly larger than you require to allow overflow.
This solution has been tested in IE, FF, Safari and Chrome!
A: I added this to my css and it seemed to work:
body {
margin-top: -20px;
padding-top: 20px;
}
If you already have padding added to the top of your body, you will likely need to add 20px to it.
I assume it's because firefox measures the body height differently than other browsers.
Tested in ff8, chrome16 and ie9 with no negative repercussions.
A: I had solved this problem that way:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() {
FB.init({
appId : app_id, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
var height_doc = $(document).height()+20;
FB.Canvas.setSize({height: height_doc});
};
It's works for me. I hope that help.
A: This is a known issue with canvas apps and page tabs, and has annoyingly been around for quite a while.
https://developers.facebook.com/bugs/309917422436936
Some people mention being able to use FB.Canvas.setSize({ width: 700, height: 800 }); or something like FB.Canvas.setAutoResize(500); and it gets around the issue.
Have you definitely set the iframe auto resize option in the apps control panel too?
A: Forget about body and html margins (I mean set them to zero).
Just place all your content (including header and footer) into a table with single cell.
At least all browsers will agree on how to calculate the height of the table...
like this:
<table id='m_table' width=100% align=left border=0 cellspacing=0 cellpadding=0>
<tr><td valign=top bgcolor=white align=center style='position:relative;'>
and do this :
setTimeout(function() {FB.Canvas.setSize({height:(document.getElementById('m_table').offsetHeight+40)})}, 1000);
works in IE,FireFox and Chrome/Safari...
Here is FB initialization code if you need it:
window.fbAsyncInit = function() {
FB.init({appId:'your_app_id',status:true,cookie:true,xfbml:true});fbApiInit = true;
}
function fbEnsureInit(callback)
{
if(!window.fbApiInit) setTimeout(function() {fbEnsureInit(callback);}, 50);
else if(callback) callback();
}
fbEnsureInit(function() {
FB.Canvas.scrollTo(0,0);
var h = document.getElementById('m_table').offsetHeight+40;
// console.log('setting size to '+h);
FB.Canvas.setSize({height:h});
setTimeout(function() {FB.Canvas.setSize({height:(document.getElementById('m_table').offsetHeight+40)})}, 1000);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7952814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rack middleware server crash I am trying to write simple rack middleware like this:
class NewMiddleWare
NEW_STRING = <<BEGIN
my new content
BEGIN
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
response_body = ""
response.each {|part| response_body += part}
response_body += "#{NEW_STRING}"
headers["Content-Length"] = response_body.length.to_s
[status, headers, response_body]
end
end
when I run rackup, I got:
Unexpected error while processing request: undefined methodeachfor #<String:0x007fad313bdb30> in terminal.
I couldn't figure out the reason for this error. Response object
should be able to respond each right? Coz I saw some sample code doing
that.
A: From the Rack spec:
The Body must respond to each and must only yield String values. The Body itself should not be an instance of String, as this will break in Ruby 1.9.
In Ruby 1.8 Strings did respond to each, but that changed in 1.9.
The simplest solution would be to just return an array containing the string:
[status, headers, [response_body]]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30041738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Display new list item onclick with ReactJS I have a problem with updating and displaying an array as list items on the click of a button. From below code, I get error message:
list.map is not a function
import React from "react";
export default class InputPushToList extends React.Component {
constructor(props) {
super(props);
this.state = {
ActiveText: "",
li: ["First Item"]
};
this.handleOnClick = this.handleOnClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
ActiveText: e.target.value
});
}
handleOnClick(e) {
e.preventDefault();
const newListItem = [this.state.ActiveText];
this.setState({
li: this.state.li.push(newListItem)
});
}
render() {
const list = this.state.li;
return (
<React.Fragment>
<h2>{this.props.inputTitle}</h2>
<input type="text" onChange={this.handleChange} />
<h2>{this.state.ActiveText}</h2>
<br />
<button onClick={this.handleOnClick}>Add to list</button>
<ul>
{list.map(e => (
<li>{e}</li>
))}
</ul>
</React.Fragment>
);
}
}
In my mind list.map is a function but apparently not, so why? And how would you go about displaying one more (that which is the active state of the input, this.state.ActiveText) list item when clicking the button? Thanks for the help.
A: First thing first, you don't use this.state inside this.setState, instead use a function to update state. Check this for reference: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Your code should be as follows:
this.setState((state) => ({
li: state.li.concat([newListItem])
}));
Second, why are you assigning an array to newlistitem by doing: const newListItem = [this.state.ActiveText]; ?
It should be const newListItem = this.state.ActiveText;
A: Problem is this line:
this.setState({
li: this.state.li.push(newListItem)
});
example:
var arr = [];
console.log(arr.push({}))// it will print 1.
in your case:
this.setState({
li: this.state.li.push(newListItem)// here you assigned `li`1.
});
Fix the above.
A: 1. Don't mutate this.state
In handleOnClick(), do not write this.state.li.push(newListItem).
Instead, make a clone of this.state.li, add newListItem into that clone, and set the state of li to the new clone:
handleOnClick(e) {
e.preventDefault();
this.setState({
li: [
...this.state.li, // spread out the existing li
this.state.ActiveText // append this newListItem at the end of this array
]
});
}
2. Consider destructuring
In your render(), you could destructure this.state.li:
render() {
const { li } = this.state
return (
<React.Fragment>
...other stuffs
<ul>
{li.map(e => (
<li>{e}</li>
))}
</ul>
</React.Fragment>
);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53846062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create an object before calling the save method I want to create an object in Django before calling the save method. This object will be created from a ForeignKey Value, I've changed the foreignkey field to look like an input field in order to write a value instead of selecting it.
I have 2 classes in 2 different model files
class Category(models.Model):
title = models.ForeignKey(Title, verbose_name="Title")
and
class Title(models.Model):
title = models.CharField("Title", primary_key=True, max_length=200)
When I create a category, I have to pick or write a title that already exists in the database and when I try to create a category with a new title I get this error :
Select a valid choice. That choice is not one of the available choices.
What I want to do is creating a title based on what I write in the ForeignKey field before creating the category so it can be used immediately.
I tried to redefine the save method to save the title object before saving the category but it didn't work.
Any help will be really appreciated.
Thank you
A: The save is performed after the form validation, you can make the category obj creation during the validation.
Have a look at the form fields' clean methods that you can override on django docs http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
A: Thank you for your code, I've just tested it. But it's not exactly what I'm looking for, I will explain what I want to do.
Let's say that we have Category and Article classes in our model, each one has a title. To make this title reusable, I created another application that will manage fields, I created the class Title and I added it as foreignkey to Category and Article forms.
I switched the select box to an input field using raw_id_fields.
Now, when I create a category or an article, I have to select or write a title, when this title exists, it works perfectly but when it doesn't exist I want to create it before creating the category so it can use it.
I tried to do that in the save method, in the pre_save signal and in the clean method but I always get the error "Select a valid choice. That choice is not one of the available choices."
I'm using a hard coded solution to create the title now, I want just to see if it will work, these are the lines that I inserted in the different methods to create the title before creating the category :
t = Title(title = "MyTitle")
t.save()
I tried to create a Category with MyTitle as title but I get the same error, when I try to create another one using an existing title, it works and the title "MyTitle" is created. That's mean that the creation of the object happens after the form verification. What I want is just doing this before. The title object should be created before the verification.
Thank you very much for your help
A: You should probably consider putting the code to create Category entries in the model's manager:
class CategoryManager(Manager):
def create_category(category, title):
t = Title.objects.get_or_create(title=title)
return self.create(title=t)
class Category(models.Model):
title = models.ForeignKey(Title, verbose_name="Title")
objects = CategoryManager()
Then use create_category every time you want to create a Category.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4293290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Access EnvironmentObject from ViewModel in SwiftUI I need to implement a not too complicated use case in SwiftUI:
Login with username and password, authToken and refreshToken are come back from API, store the refreshToken in KeyChain and the authToken in AppState (which is an ObservableObject (environmentObject), code below). If any of my requests come back with 401 HTTP response code (so the accessToken is expired), I need to refresh the accessToken and retry my original request with the new token. But the problem is I call the RefreshTokenRequest from my ViewModel, and I cannot pass token "back" to the appState through the View. So the question is, how can I access my environmentObject from my ViewModel? Is it possible? Here's my code simplified at playground file:
class AppState: ObservableObject {
@Published var isLoggedIn: Bool = false
@Published var token: String = ""
}
struct ProtectedView: View {
@EnvironmentObject var appState: AppState
var body: some View {
VStack {
RollerListView(token: self.appState.token)
}
}
}
struct Roller: Codable, Hashable {
var scooter_name: String;
}
class RollerListVM: ObservableObject {
@Published var rollers = [Roller]()
func getRollers(token: String) {
print("FETCHING ROLLERS...")
/// Here's my API request to get the array of rollers. If the token is expired, I need to refresh it with a new request and I need to pass the new token to the appState.token variable, because I need to use the new token in all of my request instead of expired one.
/// IF THE TOKEN IS REFRESHED, HOW CAN I PASS IT TO THE AppState.token ???
DispatchQueue.main.async {
self.rollers = [Roller(scooter_name: "scooter 1"), Roller(scooter_name: "scooter 2")]
}
}
init(token: String) {
self.getRollers(token: token)
}
}
struct RollerListView: View {
@ObservedObject private var rollerListVM: RollerListVM;
@EnvironmentObject var appState: AppState
var body: some View {
List(rollerListVM.rollers, id: \.self) { roller in
HStack {
Text(roller.scooter_name)
}
}
}
init(token: String) {
self.rollerListVM = RollerListVM(token: token)
}
}
I tried to pass a closure function to the ViewModel and call it if after token refresh (with the new token as a parameter), but it's not working, because the self parameter is mutating inside the closure.
How should I do that?
A: Since your token is somewhat dynamic, I would suggest that you shouldn't pass it directly to your view models. Rather, pass the AppState object and retrieve the token when needed.
If you detect an expired token you can call a function on the AppState that obtains a refresh token and updates its token property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60495050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Oracle DatabaseMetadate get columns for table named USER We are using JDBC DatabaseMetadata to discover objects in the database. DatabaseMetadata.getColumns returns more verbose information -that we really need- than those from select * from table where 1 = 2.
Now when I pass the table name -that is a reserved word in Oracle- to getColumns, it fails. If I escape the table name, it does not get results -as it doesn't see a table with that name (i.e. pass the table name "USER" instead of USER).
Is there a possible way to pass such table -named after reserved words to getColumns for Oracle database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32580823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hibernate:Data is not being populated in the table I wrote a sample Hibernate program the table with columns is created when i run the program but the data isnt being populated in the table .Can someone please help me out.
My model bean is :
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class student {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
The class where configuration and sessions is written is:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import com.hibernate.data.Employee;
public class Test {
public static void main(String[]args)
{
AnnotationConfiguration config=new AnnotationConfiguration();
config.addAnnotatedClass(student.class);
config.configure("hibernate.cfg.xml");
new SchemaExport(config).create(true, true);
SessionFactory factory=config.buildSessionFactory();
Session session=factory.getCurrentSession();
session.beginTransaction();
student s =new student();
s.setId(1);
s.setName("vamsi");
s.setId(2);
s.setName("krishna");
subjects s1 =new subjects();
session.save(s);
session.getTransaction().commit();
}
}
My hibernate.cfg.xml is :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:C:\Users\krishna\Desktop\hsqldb-2.2.6</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">2</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!--
Drop and re-create the database schema on startup
<property name="hbm2ddl.auto">create</property>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
<mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>
-->
</session-factory>
</hibernate-configuration>
A: I'm guessing you have already created the table? And that the table is as per your requirements?
I myself am learning Hibernate, and I find these few problems with your code:
a) @Column(name = "Name") annotation should be there on top of your Name getter setters.
b) Also, I think in your hibernate.cfg.xml, it should say:
<property name="hbm2ddl.auto">update</property>
Because otherwise, its doing nothing. With your current code, it should at least have populated the id. Hibernate docs explain this really well.
c) Besides, you're only saving the user with id 2 if you look close enough.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21349751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Me, AngularJS, and its 3 different ways to specify a controller I'm confused by these three different ways to specify a controller.
1- I can have an include in the app/index.html file:
<script src="scripts/controller/nav.js"></script>
2- I can have an attribute in a route:
.when('/link/list/', {
templateUrl: 'view/list.html',
controller: 'navController'
})
3- I can have an attribute in a view:
ng-controller="navController"
It's quite a few. I wonder which way to go and when.
Kind Regards,
Stephane Eybert
A: Your (1) has nothing to do with (2) and (3).
And there are other places where you can bind controllers (e.g. a directive's controller property).
Each way is serves a different purpose, so go with the one that suits your situation.
*
*If you have a directive and want to give it a specific controller, use the Directive Definition Object's controller property.
*If you use ngView and want to give each view a specific controller (as is usually the case) use the $routeProviders controller.
*If you want to assign a controller to some part of your view (in the main file or in a view or partial) use ngController.
All the above are methods for "binding" a controller to some part of the view (be it a single element or the whole HTML page or anything in between).
A: Im quite new too but Ill try to explain in a more layman way.
1 For each .js file you have (which may contain one or more controller defined), you need a corresponding entry into the script for #1 there. Its not the controller itself, more like to allow script to recognise that this .js file is part of the set of files to run.
2 is more like specify a state or route, which may or may not use a controller. Its much like saying how one event should lead to another. The controller may be involved in the transitions of the states/routes (ie. responsible from one state, to another) or within a view itself.
3 is for using a controller's functions within a view itself.
A: I've added comments to one of the answers, but aside from syntax this may is more of a design question. Here is my opinion
Firstly, (1) is irrelevant to the conversation.
(2) is the preferred approach when specifying the controller for the view as it decouples the controller from the view itself. This can be useful when you want to re-use the same view by providing a different controller.
If you find yourself using (3),consider making that area into a directive, since by specifying a controller you are indicating that it requires its own logic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25093199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Building Android Apps using Adobe AIR I am building an android application with Adobe Flash cs6 and Adobe AIR for the first time. Initially it looked good but later I faced a lot of problems. What I have till now is more of movieclip and less as3 coding. My app scales automatically according to different screen sizes. However since there are more movieclips my app somewhat lags in Kindle Fire. My question:
1. Do I need to convert my movie clips to Bitmaps or something? How is that done?
2. While converting to bitmap, do I need to specify width and height of the movieclips? Doesnt it get scaled automatically acc. to screen size?
Well, I am new to actionscript, AIR and stuff... so any help would be appreciated.
A: All display objects have 'cacheAsBitmap' and 'cacheAsBitmapMatrix' propertiues that help with performance, but only for certain class of objects (primarily those not frequently changed).
More info: Caching display objects
Also, make sure you have HW acceleration turned on for maximum benefit, especially on mobile: HW acceleration
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19900737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using regular expression in Beautiful Soup scraping I have a list of URLs and I'm trying to use regex to scrap info from each URL. This is my code (well, at least the relevant part):
for url in sammy_urls:
soup = BeautifulSoup(urlopen(url).read()).find("div",{"id":"page"})
addy = soup.find("p","addy").em.encode_contents()
extracted_entities = re.match(r'"\$(\d+)\. ([^,]+), ([\d-]+)', addy).groups()
price = extracted_entities[0]
location = extracted_entities[1]
phone = extracted_entities[2]
if soup.find("p","addy").em.a:
website = soup.find("p", "addy").em.a.encode_contents()
else:
website = ""
When I pull a couple of the URLs and practice the regex equation, the extracted entities and the price location phone website come up fine, but run into trouble when I put it into this larger loop, being feed real URLs.
Did I input the regex incorrectly? (the error message is ''NoneType' object has no attribute 'groups'' so that is my guess).
My 'addy' seems to be what I want... (prints
"$10. 2109 W. Chicago Ave., 773-772-0406, "'<a href="http://www.theoldoaktap.com/">theoldoaktap.com</a>
"$9. 3619 North Ave., 773-772-8435, "'<a href="http://www.cemitaspuebla.com/">cemitaspuebla.com</a>
and so on).
A: Combining html/xml with regular expressions has a tendency to turn bad.
Why not use bs4 to find the 'a' elements in the div you're interested in and get the 'href' attribute from the element.
see also retrieve links from web page using python and BeautifulSoup
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30337701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use [FindsBy] annotation so that I can resuse the element found to find its inner elements? The DOM I am working on has lots of nested elements (box inside box structure ) and I am finding it difficult to code using POM design pattern.
I have used FindsBy, FindsByAll, FindsBySequence but it appears that anytime I need to identify inner elements of a container, I will have to include finding the external element/container.
Is there a way to reuse the element 'DimensionPanel' instead of using [FindsBy(How = How.Id, Using = "container-dimpanel")]?
ex:
[FindsBy(How = How.Id, Using = "container-dimpanel")]
public IWebElement DimensionPanel { get; set; }
#region DimensionPanel elements
[FindsBySequence]
[FindsBy(How = How.Id, Using = "container-dimpanel")]
[FindsBy(How = How.Id, Using = "metrics-selector-container")]
[FindsBy(How = How.TagName, Using = "a")]
public IWebElement MetricsButton { get; set; }
[FindsBySequence]
[FindsBy(How = How.Id, Using = "container-dimpanel")]
[FindsBy(How = How.Id, Using = "metrics-selector-container")]
[FindsBy(How = How.TagName, Using = "span")]
public IWebElement MetricsCount { get; set; }
#endregion DimensionPanel elements
A: I'm not sure if this helpful for you but in java you can use the FindBy annotation like this
@FindBy (id="metrics-selector-container")
public WebElement DimensionPanel;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40406811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CK Editor - Uncaught TypeError: Cannot read property 'clearCustomData' of null in Chrome I am using CK Rich Text Editor in my application. I have a modal popup and within it I have three tabs - each of these Tabs renders the same Partial View in which I have a field call Description which is what I use CK Editor on. When I use IE 11 everything works as expected and the Tabs load with the Textarea turned into a CK Editor box and navigating between the tabs each time the text area stays as a Rich text Editor. However I am seeing strange behaviour in Chrome when I first open the modal box the description text area on each tab is turned into a ck editor as expected and as I tab between them each one is correctly a text area. However in Chrome if I close the modal box and repoen I get the error above in the console? If I have the modal box open and navigate between the Tabs 6 times I get the same error appearing and then lose the functionality of the text areas being rendred as CK rich text editors. Has anyone had anything similar or got a possible solution.
The code in my js file is as:
$(document).ready(function () {
var editor = CKEDITOR.instances['Description'];
if (editor) { editor.destroy(true); }
CKEDITOR.replaceAll();
});
cshtml markup from the partial view that is rendered in the 3 tabs is as below:
<div class="row">
@Html.LabelFor(model => model.Description)
<div class="col-md-10">
@Html.TextAreaFor(model => model.Description)
</div>
</div>
A: use this code to destroy CK editor:
try {
CKEDITOR.instances['textareaid'].destroy(true);
} catch (e) { }
CKEDITOR.replace('textareaid');
A: I have been able to come up with a solution for this in CKEditor 4.4.4.
In ckeditor.js (minified), line 784:
a.clearCustomData();
should be changed to:
if (a) {a.clearCustomData();}
Also on line 784:
(d=a.removeCustomData("onResize"))&&d.removeListener();a.remove()
should be changed to:
if (a){(d=a.removeCustomData("onResize"));if (d){d.removeListener();}a.remove()}
This appeared to fix the issue for me, I will also file a bug report with ckeditor so they can fix it as well.
A: The fix is here https://github.com/ckeditor/ckeditor-dev/pull/200 within ckEditor it will check for the existence of the iframe before clearCustomData is invoked. The reason it happens for you is that when the modal closes the iframe is removed before you are able to call destroy on the editor instance.
Try/catch is the best workaround for now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25034150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: SDK Manager Android Studio OS X How do you open SDK Manager on the latest Android Studio in OS X? It appears grayed out in the initial screen and it seems I don't have any SDK installed...
A: Close all open projects so you get the opening screen.
Choose Configure -> Project-Default -> Project Structure
Then set the path to your SDK and JDK, respectively.
Mine are:
SDK: /Users//Development/android-sdk
JDK: /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
If you are on OSX, your JDK might be similar, your SDK will be wherever you put it.
A: Since the SDK doesn't come with Android Studio, you have to install it manually.
You can use brew with brew install android-sdk and then you can open it via android (All done in the terminal)
A: For me, I found that the android binary was missing from the Studio.
So I downloaded the SDK, and moved it in.
Path is as given by @Cory, /Users/<user>/Library/Android/sdk
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26913470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unknown field "follow_redirect" while fetching facebook ad creatives from API I'm trying to get details of an ad creative from Facebook's ad API. According to the reference, follow_redirect is a gettable field. However, when I add it to the "fields" argument, facebook throws this:
{
"error": {
"message": "(#100) Unknown fields: follow_redirect.",
"type": "OAuthException",
"code": 100
}
}
My request :
https://graph.facebook.com/xxxxxxxxxx?fields=id,title,body,image_hash,image_url,name,link_url,type,object_id,related_fan_page,follow_redirect,auto_update,story_id,preview_url,action_spec,follow_redirect&access_token=xxxxx
Is this a bug, or am I doing something wrong?
A: There is no follow_redirect field on an adcreative, it's a flag you provide when creating the creative itself, but it isn't a property of the resulting creative
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19161742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to reveal old versions of a row in PostgreSQL? I know that Postgres uses MVCC and stores older versions of rows on disk. I would like to access (read-only) some old, discarded versions of a concrete row. How can I do it?
A: In PostgreSQL 9.1 and later, the best solution for this is https://github.com/omniti-labs/pgtreats/tree/master/contrib/pg_dirtyread which is an extension that provides a functional interface in sql to access old, unvacuumed versions of rows. Other tools may exist for other dbs. This works well for a number of cases data recovery, just exploring the utility of mvcc, and the like. With some effort it might work on earlier versions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7118432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: windows7 python36: how send to gdrive using righ click context menu? Where is the code (and explainations) needed to send a file using it's path or to send a file by right cliking on it (working on windows 7 with python 36)
A: I struggled with google tutorial. Here is the code (and explainations) needed to send a file using it's path or to send a file by righ cliking on it (working on windows 7 with python 36)
## windows7 python36: send to gdrive using righ click context menu
import logging
import httplib2
import os #to get files
from os.path import basename #get file name
import sys #to get path
import ctypes # alert box (inbuilt)
import time #date for filename
import oauth2client
from oauth2client import client, tools
# google apli drive
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
#needed for gmail service
from apiclient import discovery
import mimetypes #to guess the mime types of the file to upload
import HtmlClipboard #custom modul which recognized html and copy it in html_clipboard
## About credentials
# There are 2 types of "credentials":
# the one created and downloaded from https://console.developers.google.com/apis/ (let's call it the client_id)
# the one that will be created from the downloaded client_id (let's call it credentials, it will be store in C:\Users\user\.credentials)
#Getting the CLIENT_ID
# 1) enable the api you need on https://console.developers.google.com/apis/
# 2) download the .json file (this is the CLIENT_ID)
# 3) save the CLIENT_ID in same folder as your script.py
# 4) update the CLIENT_SECRET_FILE (in the code below) with the CLIENT_ID filename
#Optional
# If you don't change the permission ("scope"):
#the CLIENT_ID could be deleted after creating the credential (after the first run)
# If you need to change the scope:
# you will need the CLIENT_ID each time to create a new credential that contains the new scope.
# Set a new credentials_path for the new credential (because it's another file)
## get the credential or create it if doesn't exist
def get_credentials():
# If needed create folder for credential
home_dir = os.path.expanduser('~') #>> C:\Users\Me
credential_dir = os.path.join(home_dir, '.credentials') # >>C:\Users\Me\.credentials (it's a folder)
if not os.path.exists(credential_dir):
os.makedirs(credential_dir) #create folder if doesnt exist
credential_path = os.path.join(credential_dir, 'name_of_your_json_file.json')
#Store the credential
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
CLIENT_SECRET_FILE = 'client_id to send Gmail.json'
APPLICATION_NAME = 'Gmail API Python Send Email'
#The scope URL for read/write access to a user's calendar data
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
# Create a flow object. (it assists with OAuth 2.0 steps to get user authorization + credentials)
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
return credentials
## Send a file by providing it's path (for debug)
def upload_myFile_to_Gdrive(): #needed for testing
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http )
path_file_to_upload=r'C:\Users\Me\Desktop\myFile.docx'
#extract file name from the path
myFile_name=os.path.basename(path_file_to_upload)
#upload in the right folder:
# (to get the id: open the folder on gdrive and look in the browser URL)
folder_id="0B5qsCtRh5yNoTnVbR3hJUHlKZVU"
#send it
file_metadata = { 'name' : myFile_name, 'parents': [folder_id] }
media = MediaFileUpload(path_file_to_upload,
mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)#find the right mime type: http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
#Print result:
print(f"file ID uploaded: {file.get('id')}")
input("close?")
## Send file selected using the "send to" context menu
def upload_right_clicked_files_to_Gdrive():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http)
## launch the script through the context menu "SendTo"
# (in windows7) Type "shell:SendTo" in the URL of an explorer windows. Create a .cmd file containing (remove the first # before each line):
# #@echo off
# cls
# python "The\\path\\of\\your_script.py" "%1"
## the path of the file right-clicked will be stored in "sys.argv[1:]"
#print(sys.argv)
#['C:\\Users\\my_script.py', 'C:\\Desktop\\my', 'photo.jpg'] #(the path will cut if the filename contain space)
##get the right-clicked file path
#join all till the end (because of the space)
path_file_to_upload= ' '.join(sys.argv[1:]) #>> C:\Desktop\my photo.jpg
file_name=os.path.basename(path_file_to_upload)
##guess the content type of the file
#-----About MimeTypes:
# It tells gdrive which application it should use to read the file (it acts like an extension for windows). If you dont provide it, you wont be able to read the file on gdrive (it won't recognized it as text, image...). You'll have to download it to read it (it will be recognized then with it's extension).
file_mime_type, encoding = mimetypes.guess_type(path_file_to_upload)
#file_mime_type: ex image/jpeg or text/plain (or None if extension isn't recognized)
# if your file isn't recognized you can add it here: C:\Users\Me\AppData\Local\Programs\Python\Python36\Lib\mimetypes.py
if file_mime_type is None or encoding is not None:
file_mime_type = 'application/octet-stream' #this mine type will be set for unrecognized extension (so it won't return None).
##upload in the right folder:
# (to get the id: open the folder on gdrive and look in the browser URL)
folder_id="0B5f6Tv7nVYv77BPbVU"
## send file + it's metadata
file_metadata = { 'name' : file_name, 'parents': [folder_id] }
media = MediaFileUpload(path_file_to_upload, mimetype= file_mime_type)
the_file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
##print the uploaded file ID
uploaded_file_id = the_file.get('id')
print(f"file ID: {uploaded_file_id}")
input("close?")
if __name__ == '__main__':
# upload_right_clicked_files_to_Gdrive()
upload_myFile_to_Gdrive() # needed to debug
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43570759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Upload via gettyimages api Is there any way to upload photos to gettyimages?
They don't have it in the API (https://api.gettyimages.com/de/apis)
A: It does not appear so. From here (emphasis mine):
For 35mm digital capture, we strongly recommend use of a professional-quality digital SLR using RAW or uncompressed TIFF format.
RAW or uncompressed TIFF images will tend to be very large, which could make uploading them via an API problematic. Instead, contributors would use the upload portal to supply content to Getty images.
Further, your images must go through a submission process, which would suggest the API could not be used.
Getty Images do have a Flickr collection that anyone can submit to, though once again there is submission process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14668018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hide shortcode preview in gutenberg I created a custom shortcode that renders some html / css / javascript from a template file.
function jsd_waitlist_hero_shortcode() {
include dirname( __FILE__ ) . '/jsd-templates/' . 'jsd-waitlist-hero.php';
return null;
}
add_shortcode('jsd_waitlist_hero', 'jsd_waitlist_hero_shortcode');
This works great, but, when I include it in a page,
the content shows up in the editor.
I don't want this to happen, because the css ends up breaking, and it looks weird.
Is there a way I can tell Gutenberg to not display the shortcode in the editor, but still display it when live?
A: Running include inside ob_start and ob_get_clean did the trick
function jsd_waitlist_hero_shortcode() {
ob_start();
include dirname( __FILE__ ) . '/jsd-templates/' . 'jsd-waitlist-hero.php';
$content = ob_get_clean();
return $content;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55128043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i customize the week number in Python? Currently, the week number for the period of '2020-5-6' to '2020-5-19' is 20 and 21.
How do I customise it so that the week number is 1 and 2 instead, and also have the subsequent periods change accordingly.
My code:
import pandas as pd
df = pd.DataFrame({'Date':pd.date_range('2020-5-6', '2020-5-19')})
df['Period'] = df['Date'].dt.to_period('W-TUE')
df['Week_Number'] = df['Period'].dt.week
df.head()
print(df)
My output:
Date Period Week_Number
0 2020-05-06 2020-05-06/2020-05-12 20
1 2020-05-07 2020-05-06/2020-05-12 20
2 2020-05-08 2020-05-06/2020-05-12 20
3 2020-05-09 2020-05-06/2020-05-12 20
...
11 2020-05-17 2020-05-13/2020-05-19 21
12 2020-05-18 2020-05-13/2020-05-19 21
13 2020-05-19 2020-05-13/2020-05-19 21
What I want:
Date Period Week_Number
0 2020-05-06 2020-05-06/2020-05-12 1
1 2020-05-07 2020-05-06/2020-05-12 1
2 2020-05-08 2020-05-06/2020-05-12 1
3 2020-05-09 2020-05-06/2020-05-12 1
...
11 2020-05-17 2020-05-13/2020-05-19 2
12 2020-05-18 2020-05-13/2020-05-19 2
13 2020-05-19 2020-05-13/2020-05-19 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61676260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create a scripted field in kibana 4 that uses aggregation? Kibana 4 has a new feature to add scripted fields and write custom scripts. I wish to write a script that uses aggregations. Its easy to do simple arithmetic operations in scripted scripts but for doing aggregations I am puzzled. I am a new comer to Kibana and elasticsearch, I am looking for a sample script for beginning..
A: Scripted fields in Kibana are powered by lucene expressions, which only support numeric operations right now. Support for things like string manipulation and date parsing will probably be added at some point, but I doubt scripts will even support executing aggregations.
Scripted fields are primarily for converting a number before using it, or creating a synthetic field which is the combination of two or more other fields. Down the road they may even support things like extracting the day of the week from a date, or the portion of a string that matches a regular expression.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29367032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Subsets and Splits