text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to measure the data usage of my app in react native? I have a react-native app that I want to measure the data usage per user and gather them to optimize it later.
I saw old questions for native android suggesting that trafficStats may give stats by UUID.
What possibilities are there for react-native?
A: Using react-native means that you have two options,
*
*The native implementation which depends on the OS you're working on.
*If you're using a JS library for networking (Axios) or even a builtin function (fetch) you can implement a wrapper Promise which calculates the length of any input/output string, + an approximation of the length of the header.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45572570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: SQL Stored Procedure WHERE CLAUSE Variable I have a stored procedure and I cant work out how the string is meant to be built up.
The SQL statement works fine when I do not have a variable in there so it is definitely the way I am writing it in. I am just a beginner so unsure about the syntax.
Here is the code:
CREATE PROCEDURE [dbo].[SP_SLINVOICE]
@varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL NVARCHAR(MAX);
SELECT @SQL = N'SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = '' + @varCURRENCY + ''
AND dbo.invmaster.DocType <> ''MC''
ORDER BY dbo.invmaster.InvNumber ASC;';
EXEC sp_executesql @sql;
The @varCURRENCY does not give me an error when i execute. But it does not work either when i pass it through a parameter.
Please let me know if you can see what the issue is.
Thanks in advance
A: Your SQL is ending up like this:
WHERE dbo.InvMaster.InvCurrency = '@varCURRENCY'
So you are not looking for the value of the parameter, you are looking for @Currency, I am not sure why you are using Dynamic SQL, the following should work fine:
CREATE PROCEDURE [dbo].[SP_SLINVOICE] @varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster
INNER JOIN dbo.invdetail
ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company
ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> 'MC'
ORDER BY dbo.invmaster.InvNumber ASC;
END
If you need Dynamic SQL for some other reason you can use the following to pass @varCURRENCY as a parameter to sp_executesql:
DECLARE @SQL NVARCHAR(MAX);
SELECT @SQL = N'SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> ''MC''
ORDER BY dbo.invmaster.InvNumber ASC;';
EXEC sp_executesql @sql, N'@varCURRENCY VARCHAR(3)', @varCURRENCY;
A: If you want to pass a variable to an sp_executesql context, you need to pass it as a parameter.
EXECUTE sp_executesql
@sql,
N'@varCurrency varchar(3)',
@varcurrency= @varCurrency;
http://msdn.microsoft.com/en-gb/library/ms188001.aspx
Although why you don't just use
select ... where dbo.InvMaster.InvCurrency = @varCURRENCY
instead of the executesql is beyond me.
A: You need to pass @varCURRENCY as a parameter, Remove extra ' from your Sp.
WHERE dbo.InvMaster.InvCurrency = ' + @varCURRENCY + '
Or do not use dynamic query
CREATE PROCEDURE [dbo].[SP_SLINVOICE]
@varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> 'MC'
ORDER BY dbo.invmaster.InvNumber ASC;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24327532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Set colour of series dynamically from an array AM CHARTS I am using amCharts and have the graph working the way I want. I am trying to change the colour of the column series based on a HEX code stored in a dataset. My data is stored in an array:
Array example:
colour: "#629632"
dt: "2020-09-03T00:00:00"
max: 0
min: 0
pc: "Dec 20"
data: 25
I have the below series and the last three lines are causing me issues. I am trying to set the color of the series based on the array example. I tried rangeSeries.dataFields.color but this doesnt work. It just defaults to a blue. How can I set the colour based on my array 'colour' attribute?
var rangeSeries = chart.series.push(new am4charts.ColumnSeries());
rangeSeries.columns.template.width = am4core.percent(50);
rangeSeries.dataFields.dateX = "dt";
rangeSeries.dataFields.valueY = "max";
rangeSeries.dataFields.openValueY = "min";
rangeSeries.yAxis = rangeAxis;
rangeSeries.tooltipText = "[bold][/]Range: {openValueY} - {valueY}";
rangeSeries.name = "Range";
rangeSeries.dataFields.color = "colour";
rangeSeries.dataFields.stroke = "colour";
rangeSeries.dataFields.fill = "colour";
A: rangeSeries.columns.template.propertyFields.fill = "colour";
rangeSeries.columns.template.propertyFields.stroke = "colour";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64785108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Winsock server message isn't showing on client side terminal I created a simple TCP server listening on 8080 port that sends a message to the client once a connection is established. Here's the code.
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996)
int main(int argc, char* argv[]) {
WSADATA wsa;
SOCKET s, new_socket;
int c;
int ret;
struct sockaddr_in server, client;
char* message = "Thank you for connecting to us but i got to go\n";
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed to initialize Winsock : %d", WSAGetLastError());
return 1;
}
s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
printf("Error creating socket : %d", WSAGetLastError());
}
server.sin_family = AF_INET;
server.sin_port = htons(8080);
server.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
printf("Error binding socket : %d\n", WSAGetLastError());
exit(EXIT_FAILURE);
}
listen(s, 3);
puts("Listening for incoming connection\n");
c = sizeof(struct sockaddr_in);
while (new_socket = accept(s, (struct sockaddr*)&client, &c) != INVALID_SOCKET) {
puts("Connection established\n");
send(new_socket, message, strlen(message), 0);
}
if (new_socket == INVALID_SOCKET) {
printf("Connection failed : %d", WSAGetLastError());
return 1;
}
closesocket(s);
WSACleanup();
return 0;
}
When I'm running this, the server runs just fine. I open another terminal and open telnet and try to connect to the server on 8080 port. This is the client side terminal.
Welcome to Microsoft Telnet Client
Escape Character is 'CTRL+]'
Microsoft Telnet> open localhost 8080
Connecting To localhost...
And this is the server side.
Listening for incoming connection
Connection established
But even after server says that a connection is established, the client side stays at "Connecting to localhost". I send the message "Thank you for connecting to us but i got to go\n" but it doesn't show on the client side. what can possibly be wrong?
A: As it appears, it was a silly mistake.
while (new_socket = accept(s, (struct sockaddr*)&client, &c) != INVALID_SOCKET)
Since I didn't put another bracket over the new_socket = accept(s, (struct sockaddr*)&client, &c after initializing new_socket, the inequality was being applied on the accept function return.
The correct syntax would be
while ((new_socket = accept(s, (struct sockaddr*)&client, &c)) != INVALID_SOCKET)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46351658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: EL: how to print static variables? I have the following JSP page:
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
test #1: value of PI is <c:out value="${java.lang.Math.PI}" />.
test #2: value of PI is ${java.lang.Math.PI}.
test #3: value of PI is <%= java.lang.Math.PI %>.
Somehow, only test #3 has output. why doesn't EL print out values of static variables?
A: For each of your examples, this is what is happening:
<c:out value="${java.lang.Math.PI}" />
This is looking for the variable or bean named java and trying to execute a method on it called lang. There is probably no variable or bean in your JSP page called Java so there is no output.
${java.lang.Math.PI}
This is the same as above, just written using EL only. It's the same in that it's looking for a variable or bean named java.
<%= java.lang.Math.PI %>
What this is doing is during the JSP compile, java.lang.Math.PI is being calculated and written into the JSP. If you look at the compiled JSP you will see the value written there.
The third example is evaluating the expression as if you were in a Java class. The first two examples expect 'java' to be a variable name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5892593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Aligning Text in android Email Intent I am working on an application in which I have some default text to be sent to some friend through email. To serve the purpose, I am defining the default Text as HTML string using (text/html) as intent type. I am having a problem aligning the text to center. All other tags are working except alignment related tags.
This is what I am doing to align the text to the center of the email body:
<center>
<p style='font-family:Helvetica-Bold;font-size:10.5pt;color: black'>rob </p>
</center>
as well as:
<p style='text-align:center;font-family:Helvetica-Bold;font-size:10.5pt;color: black'>rob </p>
but neither of the approaches is paying off...the text still remains left align in email intent. However if I check it ion browser it is center aligned. How can I align the string to center i9n email intent html being used. Any help is appreciated. Thanks in advance...:-)
A: It seams that the <p> tag is not supported.
See this Reference.
You will have to find another solution, did you try using <div> tags
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11685664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tomcat 7 Guava issue? I'm working on a JSF2, MyFaces and Guava website. Earlier i deployed it on a Glassfish v3 server with no problem. Now i get this strange error when i trying to deploy it on my tomcat 7 server:
YYYY-MMM-DD HH:mm:ss org.apache.catalina.startup.ContextConfig checkHandlesTypes
VARNING: Unable to load class [com.google.common.base.Equivalences$Impl] to check against the @HandlesTypes annotation of one or more ServletContentInitializers.
java.lang.IncompatibleClassChangeError: Implementing class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2823)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1160)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1655)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1533)
at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:1988)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1951)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1840)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1808)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1794)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1214)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:828)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:302)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5148)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
So far, i know something goes wrong with the Guava library on startup. Has anyone stumbled upon this issue before?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13140999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Converting an old (4.2) laravel with multiple datasources to new API based datasource for one I have an older Laravel App that has 7 different databases in the app/config/database.php file, the type of databases are not even consistent 4 different types mysql, pgsql, sqlite and sqlsrv. The SQL Server is being replaced with a JSON based API. There are 159 Controllers and 212 Models in the app (not including anything that isn't in the appropriate directories).
Although I have built several apps with newer versions of Laravel I have avoided a lot of the ORM stuff for control and readability and I am having a hard time reading some of this code and coming up with a solution to replace the SQL Server without re-writing everything.
Here is an example:
MembershipController.php
<?php
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
class MembershipsController extends \BaseController {
/**
* Show the form for creating a new membership
*
* @return Response
*/
public function create() {
$products = Product::lists('title', 'id');
$divisions = Division::lists('name', 'id');
$this->layout = View::make('memberships.create', compact('products', 'divisions'));
$this->layout->title = 'New Membership';
// add breadcrumb to current page
$this->layout->breadcrumb = array(
array(
'title' => 'Dashboard',
'link' => 'dashboard',
'icon' => 'glyphicon-home',
),
array(
'title' => 'All Memberships',
'link' => 'dashboard/memberships',
'icon' => 'glyphicon-plus',
),
array(
'title' => 'New Membership',
'link' => 'dashboard/memberships/create',
'icon' => 'glyphicon-plus',
),
);
}
}
Product.php Model
<?php
class Product extends \Eloquent {
protected $connection = 'sqlsrv';
// Add your validation rules here
public static $rules = [
'division_id' => 'required',
'title' => 'required',
'sku' => 'required',
'short_description' => 'required',
'description' => 'required',
'daily' => 'required',
'term' => 'required',
'price' => 'required',
'appfee' => 'required',
'family' => 'required'
];
public function getDateFormat() {
return 'Y-m-d H:i:s';
}
// Don't forget to fill this array
protected $guarded = ['id'];
//public $timestamps = true;
public function options()
{
return $this->belongsToMany('Option', 'product_options')->withPivot('enabled', 'price', 'id');
}
public function division(){
return $this->belongsTo('Division', 'division_id');
}
public function msa(){
return $this->hasOne('MSA', 'msa_version');
}
}
I know that Laravel is automagically querying the SQLServer database and using the Title and Id to make a list but I am not seeing where the dbase call is being made so that I can "hi-jack" it to convert it to an API Call.
There are hundreds of similar calls in this app and I am trying to find the best tackle converting all of these calls that were going to sqlsrv to now go to the API.
How do I prevent the Model from using ORM instead inject a call to the API into the Model to get the data?
Any suggestions would be helpful, since I am not even certain how to begin.
A: I don't think that's possible without custom implementation like this: https://github.com/jenssegers/laravel-mongodb
You can check these too:
*
*https://github.com/Indatus/trucker
*https://github.com/CristalTeam/php-api-wrapper
I'm not sure if anything of these fits to your case but it's a good start point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65152572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot get value from array I seem to be having a problem checking if a string exists in my array. There is probably a really obvious answer to my question do forgive me but I'm new to PHP.
Anyway here is my code:
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
if (in_array("496891", $result_array))
{
echo "true";
}
else
{
echo "false";
}
The array looks like this:
Array ( [0] => Array ( [ID] => 496891 ) [1] => Array ( [ID] => 1177953 ))
My code always echoes false. Anyone know what I'm doing wrong?
Thanks
A: You have a nested array and must check against each item like so:
function in_multidimensional_array($val, $array) {
foreach($array as $key => $value) {
if (in_array($val, $array[$key])) {
return true;
}
}
return false;
}
Now you can check if the value 496891 exists using:
if(in_multidimensional_array('496891', $result_array)) {
print 'true';
} else {
print 'false';
}
A: Krister's solution only works if you only have one row in your MySQL-loop. This would check against all the results.
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
$found = false;
foreach ($result_array as $v) {
if (in_array("496891", $v)) {
$found = true;
}
}
if ($found == true)
echo 'true';
else
echo 'false';
A: You are searching for a string, but your array is holding numeric values. You would need to make sure that you insert it specifically as a string to get it to return true, or each field as a string prior to the search.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11152296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Directly rename legend in word, when data is not available I have a scatter plot now in microsoft word. It seems this plot was created in excel and copied into word keeping source formatting. The legend in the plot is incorrectly labelled which looks unprofessional.
Normally I would go to select data and rename the series, but because of how I received the plot I do not have access to the underlying data and it will not allow this option.
Is there any way to directly edit the text in this legend entry while keeping the correct color coding etc.
I have tried numerous right clicking and any format options I have been able to find to no avail. I feel there should be a way to do this simple task, but it is far from obvious. I am using windows version Microsoft word 2013, if that is important.
Thank you for any help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35845855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to populate input type file/image value from database in PHP? I am writing the code for editing a form that contains an input file field. I am getting all the values pulled from database for different field types but the file type input does not show its value.
I have a code that looks like this:
<input name="edit_cmpny_logo_name" id="edit_cmpny_logo_id" type="file" class="inputfield span2" onchange="clearmessage()" onselect="clearmessage()" value="<?=$edit_row_details_arr[0]['LOGO_FILE'];?>" title="<?php echo lang('Size of Logo should be 4KB to 10KB.');?> <?php echo lang('Upload only .bmp, .gif, .jpg, .jpeg, .png Files');?>"/>
How do I load the value of input type when someone is editing the form and can see the old image/file and edit/replacing with the new image/file .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21952065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to alphabetize a list on C++ I have been having some trouble on my code for my final project. I have looked everwhere and I am having a hard time so I thought I would ask on here. I need to make sure that when all the names are listed in this phonebook that they will come out in alphabetical order but as of yet I am unsure how to do that. Here is the program that i currently have! Thank you!
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct Contact {
string name, number, notes;
};
Contact contactList[100];
int rec_num = 0;
int num_entries;
string toUpper (string S) {
for (int i= 0; i < S.length(); i++)
S[i] = toupper(S[i]);
return S;
}
void ReadFile () {
string S;
fstream input("PhoneData.txt");
while (!input.eof() && !input.fail()){
input >> contactList[rec_num].name >> contactList[rec_num].number;
getline(input, S);
contactList[rec_num].notes = S;
rec_num++;
}
cout << "Book read." << endl;
num_entries = rec_num;
input.close();
return;
}
// stores phonebook for future runs of the program
void StoreFile () {
fstream F ("PhoneData.txt");
rec_num = 0;
while (rec_num < num_entries){
F << contactList[rec_num].name << " " << contactList[rec_num].number << " " << contactList[rec_num].notes << " " << endl;
rec_num++;
}
cout << "Phonebook stored." << endl;
return;
}
// adds contact
void add_name(string name, string number, string notes){
contactList[num_entries].name = name;
contactList[num_entries].number = number;
contactList[num_entries].notes = notes;
num_entries++;
return;
}
// finds contact
void retrieve_name(string name){
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
cout << "Phone Number: " << contactList[i].number << endl << "Notes: " << contactList[i].notes << endl;
return;
}
}
cout << "Name not found" << endl;
return;
}
// updates contact info
void update_name(string name){
string new_number;
string new_notes;
cout<<"New Phone Number"<<endl;
cin>> new_number;
cout<<"New Notes"<<endl;
cin>> new_notes;
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
contactList[i].number = new_number;
contactList[i].notes = new_notes;
return;
}
}
}
// deletes contact
void delete_name(string name){
int INDEX=0;
for (int i = 0; i < num_entries; i++){
if (toUpper(contactList[i].name) == toUpper(name)) {
INDEX=i;
for ( int j=INDEX; j < num_entries; j++ ){
contactList[j].name = contactList[j+1].name;
contactList[j].number = contactList[j+1].number;
contactList[j].notes = contactList[j+1].notes;
}
}
}
return;
}
void listAllContacts() {
int i = 0;
while (i < num_entries) {
cout << "-- " << contactList[i].name << " " << contactList[i].number << endl << "-- " << contactList[i].notes << endl << endl;
i++;
}
}
int main(){
string name, number, notes;
string FileName;
char command;
FileName = "PhoneData.txt";
ReadFile ();
cout << "Use \"e\" for enter, \"f\" for find, \"l\" for list, \"d\" for delete, \"u\" for update, \"s\" for send message, \"q\" to quit." << endl << "Command: ";
cin >> command;
while (command != 'q'){
switch (command){
case 'e': cin >> name; cout << "Enter Number: ";
cin >> number; cout << "Enter Notes: ";
cin.ignore(); getline(cin, notes);
add_name(name, number, notes); break;
case 'f': cin >> name; retrieve_name(name); break;
case 'l':
listAllContacts(); break;
case 'u': cin>> name; update_name (name);break;
case 'd' : cin>> name; delete_name (name); break;
}
cout << "\nCommand: "; cin >> command;
}
StoreFile();
cout << "All set !";
return 0;
}
A: Given
Contact contactList[100];
int num_entries;
you can use std::sort to sort the list of contacts. std::sort has two forms. In the first form, you can use:
std::sort(contanctList, contactList+num_entries);
if you define operator< for Contact objects.
In the second form, you can use:
std::sort(contanctList, contactList+num_entries, myCompare);
if you define myCompare to be callable object that can compare two Contact objects.
To use the first form, change Contact to:
struct Contact {
string name, number, notes;
bool operator<(Contact const& rhs) const
{
return (this->name < rhs.name);
}
};
If you want to the comparison of names to be case insensitive, convert both names to either uppercase or lowercase and them compare them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29832688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: Migrating MySQL database to Firebird Server 2.5 I have a MySQL 5.5 database that I wish to migrate to Firebird Server 2.5. I have no issues with an existing MySQL database but after MySQL's acquisition, I am worried about the unavailability of Community Edition any time soon.
I want to migrate to a true and robust RDBMS like Firebird. PostgreSQL is another choice, but it's .NET provider is sluggish.
Is there any free tool to migrate existing MySQL database to Firebird? I also want to know how Firebird fits in terms of performance when compared with MySQL.
A: I have used Clever Components' Interbase DataPump with success. I personally haven't used it with MySQL, but there shouldn't be any problems.
As of perfomance comparison - as always it comes down to your specific data and use cases. General wisdom is that MySQL is faster in some cases but it comes with the cost of reliability (ie not using transactions).
A: I also use Clever Components Interbase DataPump but you can also check IBPhoenix ressource site here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7545346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use scipy optimize.minimize function to compile keras sequential model using conjugate gradients? In
model.compile(loss=keras.losses.mean_squared_error, optimizer=minimize(method='CG',fun=keras.losses.mean_squared_error(train_label,model.predict_classes(train_X)),x0=x0), metrics=['accuracy'])
File "/usr/lib/python3.7/site-packages/keras/losses.py", line 14, in mean_squared_error
return K.mean(K.square(y_pred - y_true), axis=-1)
ValueError: operands could not be broadcast together with shapes (67,) (67,2)
I am unable to figure out why the error is occurring
In other case I have tried passing the original classes without converting it to one-hot variable then the following error occurred
TypeError: 'Tensor' object is not callable
Please help me in resolving this issue
train_X,valid_X,train_label,valid_label = train_test_split(train_X,Y_train_one_hot, test_size=0, random_state=42)
model = Sequential()
model.add(Conv2D(22, kernel_size=(3,3),strides=(1,1),padding='same',input_shape=(6,4,1),activation='relu'))
model.add(MaxPooling2D((1, 1),padding='same',strides=(1,1)))
model.add(Flatten())
model.add(Dense(14, activation='sigmoid'))
model.add(Dense(num_classes, activation='sigmoid'))
model.compile(loss=keras.losses.mean_squared_error, optimizer=minimize(method='CG',fun=keras.losses.mean_squared_error(train_label,model.predict_classes(train_X)),x0=x0), metrics=['accuracy'])
history =model.fit(train_X, train_label,batch_size=batchsize,callbacks=callbacks,epochs=epochs,verbose=1,validation_data=(valid_X, valid_label))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54315014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating an order in Django Hi everyone I have a few questions about the django admin.
First the relevant details. I currently have Client, Printer, Cartridge, and Order models.
The Printer model has a ManyToManyField to the Cartridge model, which would allow you to select all the cartridges that can be used with that printer.
The Cliente has a ManyToManyField to the printers which they own.
1) I want to create an Order through the Django admin which lets your specify the Client, a dicount, and multiple cartridges through a ManyToManyField. This is getting kinda tricky because I have to do it through another table that specifies whether it's a new Cartridge or a refill.
2) I want the admin to filters the Cartridges to only show the ones that belong to the printers that they own.
3) Also I would like to have a field that holds the total price of their order, but it should calculate it based on how many cartridges they have added to the order. I don't know if this should be done by adding more of the same cartridge to the order or by having another field in the related table that specifies the quantity.
Can this be done in the admin or do I need to use a form? And if so how would I go about adding this to the admin? It seems difficult and probably something I will have to do in multiple parts since in order to filter the list of cartridges I have to know the client beforehand.
A: As far as I can see, no, it's not really possible. The development version has some methods for limiting foreign keys, but it doesn't seem to me that limiting based on the customer is possible, since it depends on separate foreign keys.
The best suggestion, if you're really bent on doing it in the admin form, would be to use Javascript to do it. You would still have to make AJAX calls to get lists of what printers customers had and what cartridges to show based on that, but it could be done. You would just specify the JS files to load with the Media class.
But I think that's more work than it's worth. The easiest way I would see to do it would be with Form Wizards. That way, you'd have a step to select the customer so on the next step you know what cartridges to show.
Hope that helps!
A: I've worked similar problems, and have come to the conclusion that in many cases like this, it's really better to write your own administration interface using forms than it is to try and shoehorn functionality into the admin which is not intended to be there.
As far as 3) goes, it depends on what your product base looks like. If you're likely to have customers ordering 50 identical widgets, you probably do want a quantity field. If customers are more likely to be ordering 2 widgets, one in red, one in blue, add each item separately to the manytomany field and group them in your order interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/930379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Comparator: Comparing 2 objects with field which can be null I need to write a Comparator by implementing a typical compare-method of a default comparator. This is given due to the interface I need to implement.
My objects are products with an Integer field vintage which can be null. Code is as following:
@Override
public int compare ( IProduct product1, IProduct product2 ) throws ProductComparisonException
{
if ( product1 == null && product2 == null )
{
return 0;
}
else if ( product1 == null && product2 != null )
{
return -1;
}
else if ( product1 != null && product2 == null )
{
return 1;
}
IProductData productData1 = (IProductData ) product1.getProvidedProductData();
IProductData productData2 = (IProductData ) product2.getProvidedProductData();
if ( productData1.getVintage() == null && productData2.getVintage() == null )
{
return 0;
}
else if ( productData1.getVintage() == null && productData2.getVintage() != null )
{
return -1;
}
else if ( productData1.getVintage() != null && productData2.getVintage() == null )
{
return 1;
}
return productData2.getVintage().compareTo( productData2.getVintage() );
}
I am not satisfied with this, as I have a lot of duplicate code and I'm sure there's a better way to do this... Any suggestions would be appreciated.
A: Wrap your Comparators in Comparator.nullsFirst to avoid dealing with possibly nullable parameters.
You need two Comparators merged with Comparator#thenComparing:
*
*nullsFirst(naturalOrder()) to compare IProducts first;
*nullsFirst(comparing(p -> p...getVintage()) to compare their Vintages secondly.
Comparator<IProduct> comparator =
nullsFirst(Comparator.<IProduct>naturalOrder())
.thenComparing(nullsFirst(
comparing(p -> p.getProvidedProductData().getVintage())
)
);
This approach compares IProduct naturally which you apparently don't want to do. (You didn't compare them at all).
Then you might write IProduct p1, IProduct p2) -> 0 to continue comparing Vintages after neither of two IProducts is null.
Comparator<IProduct> comparator =
nullsFirst((IProduct p1, IProduct p2) -> 0)
.thenComparing(nullsFirst(
comparing(p -> p.getProvidedProductData().getVintage())
)
);
If getVintage returns an int, you could use Comparator.comparingInt instead of Comparator.comparing:
comparingInt(p -> p.getProvidedProductData().getVintage())
A: Simply use (I assume you are on Java8+ since you tagged the question with lambda)
either of the following methods from Comparator:
public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)
public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator)
A: You can use Comparator methods introduced in Java 8 and use a method reference e.g.:
Comparator.comparing(IProductData::getVintage, Comparator.nullsLast(Comparator.naturalOrder()))
A: How about this one?:
Comparator<IProduct> comparator = (p1, p2) -> {
Integer v1 = p1 != null ? p1.getProvidedProductData() : null;
Integer v2 = p2 != null ? p2.getProvidedProductData() : null;
if (v1 == null ^ v2 == null)
return v1 != null ? 1 : -1;
return v1 != null ? v1.compareTo(v2) : 0;
};
A: One possibility is to generalise the null checks.
public int compare(IProduct product1, IProduct product2) throws ProductComparisonException {
Integer diff = nullCompare(product1, product2);
if(diff != null) return diff;
IProductData productData1 = (IProductData)product1.getProvidedProductData();
IProductData productData2 = (IProductData)product2.getProvidedProductData();
diff = nullCompare(productData1.getVintage(), productData2.getVintage());
if(diff != null) return diff;
return productData2.getVintage().compareTo(productData2.getVintage());
}
// Using Integer so I can return `null`.
private Integer nullCompare(Object o1, Object o2) {
if (o1 == null && o2 == null) {
return 0;
}
else if (o1 == null && o2 != null) {
return -1;
}
else if (o1 != null && o2 == null) {
return 1;
}
return null;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50022167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Method that changes even digits to zero I need to write a method that receives a number, and for any even digits in it, replaces them with the 0 digit.
I think I'm going in the right direction, but when I run it with the debugger, I seen the even numbers don't return to 0 in even digit.
This is what I have so far.
I know my English is poor, so here's an example example.
For the number 12345, the method should return 10305
For the number 332, the method should return 330.
I hope that's understandable. Here's my code:
public class Assignment1 {
public static void main(String[] args) {
System.out.println(Even(12345));
}
private static int Even(int n) {
if (n == 0 ) {
return 0 ;
}
if (n % 2 == 0) { // if its even
n= n/10*10; // we cut the right digit from even number to 0
return (n/10 %10 ) + Even(n/10)*0;
}
return Even(n/10)*10 +n;
}
}
A: Your base case is only checking if the number is zero. Check this solution, and let me know if you have doubts!
public int evenToZero(int number){
//Base case: Only one digit
if(number % 10 == number){
if(number % 2 == 0){
return 0;
}
else{
return number
}
}
else{ //Recursive case: Number of two or more digits
//Get last digit
int lastDigit = number % 10;
//Check if it is even, and change it to zero
if(lastDigit % 2 == 0){
lastDigit = 0;
}
//Recursive call
return evenToZero(number/10)*10 + lastDigit
}
}
A: Below is a recursive method that will do what you need. Using strings will be easier because it allows you to 'add' the number digit by digit. That way, using 332 as example, 3+3+0 becomes 330, and not 6.
Every run through, it cuts of the digit furthest right so 332 becomes 33, then 3, and then 0.
public static void main(String[] args) {
System.out.println(Even(12345));
}
private static String Even(int n) {
if(n==0)
return "";
else if(n%2==0){
return Even(n/10) + "0";
}
else{
String s = Integer.toString(n%10);
return Even(n/10) + s;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48388096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Different mysql trigger from C app and mysql console I have a strange question. I have created a C program, that creates triggers on mysql database. There is one problem with that. When I create triggers manually from mysql console, everything works fine, but when my C program creates triggers, they are some kind a different and it crashes and mysql restarts. There are the differences:
GOOD(manually created):
BAD(C program created):
Everything seems the same except character_set_client and collation_connection that you can see at the bottom right.
Any solution or more information if needed?
A: Probably guessing a bit here but I think you need to emit SQL statements to set character_set_client and collation_connection before or when you create the trigger. Your C code client probably is using some kind of default
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42630150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Selenium Actions Class cannot be resolved in selenium version greater then 3.1 We are using selenium 2.5.2 for our Java tests. And we decided that it is time to move forward to the latest selenium version (currently 3.14).
After downloading selenium 3.14 from https://www.seleniumhq.org/ and adding it to our project, some of the tests are having compilation problem
Actions cannot be resolved to a type.
I went to the import section of the class and I saw that the line import org.openqa.selenium.interactions.Actions is also having a compilation problem
The import org.openqa.selenium.interactions.Actions cannot be resolved.
I went to the loaded jar and I can see the class there.
So I took one more step and tried to decompile the class using DJ Java decompiler. When i tried to do this I got next error
Action violation at address...
I tried to decompile more classes from the jar and they all succeded. So I went to previous versions and figured out that in selenium version 3.2 they added internal class to Actions class BuiltAction.
Finally I went to version 3.1 and I was able to decompile the Actions class. I need help to solve this issue.
A: Ok so there was an answer before, but because two people asked the same/similar question, I just posted the same thing twice.
Anyhow, the duplicate answer was deleted by the mod, but I would have at least expected them to link you the other question after deleting the answer here. Alas, people are not perfect.
However since the other question was badly worded anyway, I have since deleted the answer off of the other post, and I have added in the answer here again.
Interactions Actions was moved from selenium-remote-driver to selenium-api.
I had the same issue and then noticed while I was using v3.14.0 for everything else, my selenium-api was on v3.12.0.
It worked after I explicitly set the version in my POM:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.14.0</version>
</dependency>
Hope it works for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52027324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: writefln() throws: Incorrect format specifier: %(%s, %) Why does it throw exception:
import std.stdio;
void main(string[] args) {
try{
writefln("My items are %(%s, %).", [1,2,3]);
}catch(Exception x){
writefln("oops: %s", x.msg);
}
}
(you can build and test the code at Ideone.com)
The result I get is:
My items are oops: /usr/lib/dmd2/src/phobos/std/format.d(1592):
Incorrect format specifier: %(%s, %).
According to http://dlang.org/phobos/std_format.html it should work...
A: Please use a more recent D compiler. You can download the latest version of the reference D compiler from http://dlang.org/download.html, or you can compile and run a D program online on http://dpaste.dzfl.pl/.
A: It works perfectly fine with a recent compiler. If you're using ideone.com to test this, then that's bound to be your problem. 2.042 is years old now, and it's highly likely that the functionality that you're trying to use was added since then. Looking at the documentation that came with the zip file for 2.042, the documentation for std.format has changed dramatically since then. So, I'd say that the problem is that you're using what is effectively an ancient compiler version. ideone.com hasn't updated their D compiler in years, making them a horrible site to test D code on, especially if it's functionality in the standard library that you're testing out rather than the language itself.
If you want to try compiling D code online, I'd suggest that you try out dpaste. It actually has an up-to-date D compiler, because it's designed specifically for compiling D code examples online.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24510678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unexpected row count in Nhibernate when deleting parent records with associated child records I have a parent table, Orders and a child table, [Order Details], I have setup the fluent mappings as -
(In the parent Order class)
HasMany<OrderDetails>
(x => x.Details).KeyColumn("OrderId").Cascade.AllDeleteOrphan().Inverse();
(In the child [Order Details] class)
References(x => x.ParentOrder).Column("OrderId").Not.Nullable().Cascade.None();
I am trying to delete the parent object by calling -
session.Delete(parent);
session.Flush();
this works only when there is only one child record, if there are more than one child records, the children get deleted, but the parent doesn't!!! And I get the dreaded - Unexpected row count error.
I am sure that this is something silly that I am doing, but trawling through the web hasn't turned up anything.
Thanks
A: Ok, I figured this out, it was me being stupid, but then the answer might help someone else, so here goes.
The [Order Details] table has a composite key and is linked to the both the [Orders] and [Products] table (Yes, this is the Northwind database that I am working with). For my test, I hadn't mapped my Products table, and had marked up my [Order Details] class with a single primary key, rather than a composite key. So, when Nhibernate deleted rows based on the key, it expects to see only one row being deleted whereas multiple existed on the database. Which is why I was getting the error. Rather clever of Nhibernate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2282626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading the Different Nib Files I created two nib files for the iPhone and iPad, so my app will be universal.
I use this method to check if it is an iPad:
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
but I don't know how to load the proper nib when it knows which it is.
Does anyone know the correct method to load to nib file, accordingly?
A: Actually, Apple does all this automatically, just name your NIB files:
MyViewController~iphone.xib // iPhone
MyViewController~ipad.xib // iPad
and load your view controller with the smallest amount of code:
[[MyViewController alloc] initWithNibName:nil bundle:nil]; // Apple will take care of everything
A: Your interface files should be named differently so something like this should work.
UIViewController *someViewController = nil;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
someViewController = [[UIViewController alloc] initWithNibName:@"SomeView_iPad" bundle:nil];
}
else
{
someViewController = [[UIViewController alloc] initWithNibName:@"SomeView" bundle:nil];
}
A: You should use a initializer -[UIViewController initWithNibNamed:bundle:];.
In your SomeViewController.m:
- (id)init {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
if (nil != (self = [super initWithNibName:@"SomeViewControllerIPad"])) {
[self setup];
}
} else {
if (nil != (self = [super initWithNibName:@"SomeViewControllerIPhone"])) {
[self setup];
}
}
return self;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6280442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lightbox gallery inside modal window When I open the modal window I want to be able to have lightbox in my gallery that's in the modal. However, when I click on the image to start the lightbox, nothing happens and when I close the modal window, the lightbox is opened. Probably it opens behind the modal. Any ideas on how to make the lightbox overlay over the modal window?
<div class="row pt-2">
<!-- Grid column -->
<div class="col-md-4 mb-4">
<img src="images/beauty.png" alt="beauty" class="ikonka2">
<h5 class="font-weight-bold my-4 text-uppercase">Permament Make-up</h5>
<p class="second-font mb-sm-4">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit maiores aperiam minima assumenda deleniti hic.
</p>
<a id="demo02" href="#animatedModal2" class="demo">More info</a>
<div id="animatedModal2">
<!--THIS IS IMPORTANT! to close the modal, the class name has to match the name given on the ID class="close-animatedModal" -->
<div class="close-animatedModal2 py-3" style="background-color:#fff;">
<div class="outer">
<div class="inner">
<label class="label2">Back</label>
</div>
</div>
</div>
<div class="modal-content">
<div class="container py-2">
<div class="row gallery-container" id="lightgallery">
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery image-box" data-aos="fade" data-src="images/beauty/IMG_1087.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor doloremque hic excepturi fugit, sunt impedit fuga tempora, ad amet aliquid?</p>">
<a href="#"><img src="images/beauty/IMG_1087.jpg" alt="Image1" class="img-fluid img-resize"></a>
</div>
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery image-box" data-aos="fade" data-src="images/beauty/IMG_1088.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam omnis quaerat molestiae, praesentium. Ipsam, reiciendis. Aut molestiae animi earum laudantium.</p>">
<a href="#"><img src="images/beauty/IMG_1088.jpg" alt="Image2" class="img-fluid img-resize"></a>
</div>
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery image-box" data-aos="fade" data-src="images/beauty/IMG_1091.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem reiciendis, dolorum illo temporibus culpa eaque dolore rerum quod voluptate doloribus.</p>">
<a href="#"><img src="images/beauty/IMG_1091.jpg" alt="Image3" class="img-fluid img-resize"></a>
</div>
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery image-box" data-aos="fade" data-src="images/beauty/IMG_1097.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim perferendis quae iusto omnis praesentium labore tempore eligendi quo corporis sapiente.</p>">
<a href="#"><img src="images/beauty/IMG_1097.jpg" alt="Image4" class="img-fluid img-resize"></a>
</div>
<div class="col-sm-6 col-md-4 col-lg-4 col-xl-3 item img-gallery image-box" data-aos="fade" data-src="images/beauty/IMG_1099.jpg" data-sub-html="<h4>Fading Light</h4><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe, voluptatum voluptate tempore aliquam, dolorem distinctio. In quas maiores tenetur sequi.</p>">
<a href="#"><img src="images/beauty/IMG_1099.jpg" alt="Image5" class="img-fluid img-resize"></a>
</div>
<!--/main slider carousel-->
</div>
<!--Your modal content goes here-->
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60791106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Replace a newline with underscore '_' in bash variable I know I can replace a newline with a space using sed (in a file) using
sed ':a;N;$!ba;s/\n/ /g' file.txt
But how can I replace a newline with a underscore '_' in a bash variable?
I tried to replace it with a space to test it out but that didn't work see what I used below.
#gets rid of newline and replace with space to get station name on one line
station=$(
<<<"${station_tmp}"\
echo $station_tmp | sed ':a;N;$!ba;s/\n/ /g'
)
variable station_tmp looks like:
1st line
2nd line
3rd line
I'm trying to replace the newlines with underscores '_' and have it look like:
1st line_2nd line_3rd line
Ps I'm using Ubuntu 18:04 64bit linux
A: You can do this in bash itself:
var='1st line
2nd line
3rd line'
echo "${var//$'\n'/_}"
1st line_2nd line_3rd line
A: Could you please try following.
echo "$var" | paste -sd_
Where variable value is:
echo "$var"
1st line
2nd line
3rd line
A: This might work for you (GNU sed and bash):
<<<"$var" sed '1h;1!H;$!d;x;y/\n/_/'
or:
<<<"$var" sed -z 'y/\n/_/'
A: Here is another one which works:
awk -v ORS="_" '1' <<<"$var"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59194176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Overloaded methods in the class must have different Erasures - why only leftmost bound is considered to be the Erasure type? Consider the following two method definitions:
static <T extends Do & Done>T whatToDo(T ele){return null;}
static <R extends Done & Do>R whatToDo(R ele){return null;}
Both will have the following erasures respectively:
static Do whatToDo(Do);
static Done whatToDo(Done);
Consider the concrete class Doing and the interfaces Do and Done
interface Do{void doIt();}
interface Done{void didIt();}
class Doing implements Do,Done{
@Override
public void doIt() {}
@Override
public void didIt() {
}
}
Now, when I try to invoke the method whatToDo, this gives the ambiguous invocation compilation error, even though the methods got compiled in the class correctly. Only at the time of invocation, I am getting error.
public static void main(String[] args) {
whatToDo(new Doing()); //compile error : ambiguous method call
}
Does it not mean that the definition of erasure is responsible for anomaly, that only the left most element is treated as the erasure for a given bounded type? Also, why has erasure been chosen to be this way? Can there be something better for the way JLS defines the procedure of erasure?
Ideal would have been that Java shouldn't have allowed the two methods in this case to exist by modifying the definition of erasure to include the unordered set of bounds rather than just the leftmost bound?
Here is the complete code:
class Scratch {
public static void main(String[] args) {
whatToDo(new Doing());
//Compilation error : because of Erasure - the 2 definitions exist even though the
//the elements of the bounds are exactly the same
//Ideally this should have been unordered list of bounds rather than left most bound?
}
static <T extends Do & Done>T whatToDo(T ele){return null;}
static <R extends Done & Do>R whatToDo(R ele){return null;}
}
interface Do{void doIt();}
interface Done{void didIt();}
class Doing implements Do,Done{
@Override
public void doIt() {}
@Override
public void didIt() {
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69865357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook graph api obtaining newsfeed data Hello anyone know how to get the newsfeed data from facebook graph api.Newsfeed as in not the timeline but me/home which is the actual newsfeed in home tab of the facebook .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62603944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pattern for sharing a large amount of data between the web application and a backend service in a Service Oriented Application I have a web application which performs CRUD operations on a database. At times, I have to run a backend job to do a fair amount of number crunching/analytics on this data. This backend job will be written as a different service in a concurrent language, which will be independent of the main web application.
But actually sharing the DB between the 2 applications is probably not a best practice as it will lead to tight coupling. What is the right pattern to use here? Since this data might amount to millions of DB rows, I'm not sure using a message queue / REST APIs would be the best way to go.
This is perhaps a very common scenario and many companies/devs have already solved this problem. Any pointers will be helpful.
A: From the question, it would seem that the background job does not modify state of database.
Simplest way to avoid performance hit on main application, while there is a background job running, is to take database dump and perform analysis on that dump.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32540610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get all Photo file for xamarin.forms in IOS I want to implement based on Xamarin.Forms cross platform, Android and iOS respectively obtain the function of photo albums or pictures under the platform
Use scenarios such as I have a page with all the pictures for users to choose from, for example, We-chat chooses multiple pictures.
The page control can be completed. Now I don't know how to get all the pictures and the path of the pictures.
Thanks !
A: For iOS you can use PhotoKit in Xamarin.iOS which allows you to customize a user interface and modify its content.
For information on its use, please refer to: https://learn.microsoft.com/en-us/xamarin/ios/platform/photokit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71246174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In c++ we declare a vector like this. std::vector v(6); how to do it for two dimensional vector std::vector<int> v(6);
how to declare a two dimensional vector with limits like above code for one dimension
I'm a noob in c++. I tried like this:
`
std::vector<int> v(6)(2);
`
I expected a two dimensional vector with 6 rows and 2 columns to take input in.
I know how to declare 2d vector. I just wanted it with limit.
A: In C++, there's no direct type which exactly represents a 2D "vector"/"matrix"/"tensor".
What you can create, is a vector of vectors. You'd write that as std::vector<std::vector<int>> - each element of the outer vector is itself a vector. But there's an important difference here: each of the inner vectors has its own length, and those could be different.
vector has a constructor taking a second argument, the initial value. You can use that here to initialize the inner vectors:
std::vector<std::vector<int>> v(6, std::vector<int>(2));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74274934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript object property cannot be defined I have declared an object in JS and trying to assign a value to its properties.
But I can do it when only one property is defined, but not with more than one property.
This works fine:
let User = {
name
};
User['name']='Praveen';
alert(User.name);
But this does not
let User = {
name,
email
};
User['name']='Praveen';
User['email']='[email protected]';
alert(User.email); //says email is not defined.
NB: I have tried removing semicolons also.
Tried dot notation also
A: Because this:
let User = {
name,
email
};
is a shortform for:
let User = {
name: name,
email: email,
};
So it directly initializes both properties to the value that the variables name and email are holding. name is defined, it is the name of the page you are in, which you can easily check with:
console.log(name);
but email is not defined yet, and trying to get an undeclared variable results in an error:
console.log(email); // email is not defined
To solve that, explicitly declare both variables before:
let name = "test";
let email = "[email protected]";
let User = {
name,
email
};
Or initialize the properties not at all:
let User = {};
or directly set the properties to a value:
let User = {
name: "test",
email: "[email protected]",
};
A: Your code is ok,
Please check do you have any existing name,email variable which you are set in the User Object,
I think you do not have existing name and email variable. So that It can not create the User Object itself.
You can do like this..
let User = {};
User['name']='Praveen';
User['email']='[email protected]';
This link could help you, https://alligator.io/js/object-property-shorthand-es6/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53251085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Floating number comparing in tcl I am getting problems when I calculating distance between point and line.
There is floating point number calculation (compare expression) problem. Due to this I not able to know perfect value of $onextensionFlag. please see following...
May I know what is wrong?
proc calculateDistanceToLinefrompoint {P line} {
# solution based on FAQ 1.02 on comp.graphics.algorithms
# L = sqrt( (Bx-Ax)^2 + (By-Ay)^2 )
# (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay)
# s = -----------------------------
# L^2
# dist = |s|*L # =>
# | (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) |
# dist = ---------------------------------
# L
# (Ay-Cy)(Ay-By)-(Ax-Cx)(Bx-Ax)
# r = -----------------------------
# L^2
# r=0 P = A
# r=1 P = B
# r<0 P is on the backward extension of AB
# r>1 P is on the forward extension of AB
# 0<=r<=1 P is interior to AB
set ret 0
set Ax [lindex $line 0 0]
set Ay [lindex $line 0 1]
set Az [lindex $line 0 2]
set Bx [lindex $line 1 0]
set By [lindex $line 1 1]
set Bz [lindex $line 1 2]
set Cx [lindex $P 0]
set Cy [lindex $P 1]
set Cz [lindex $P 2]
if {$Ax==$Bx && $Ay==$By && $Az==$Bz} {
set ret [list [GetDistanceBetweenTwoPoints $P [lindex $line 0]] 1]
} else {
set L [expr {sqrt(pow($Bx-$Ax,2) + pow($By-$Ay,2) + pow($Bz-$Az,2))}]
#puts "L=$L"
set d_val [expr {($Ay-$Cy)*($Bx-$Ax)-($Ax-$Cx)*($By-$Ay)-($Az-$Bz)*($Az-$Cz)}]
set n_rval [expr {$d_val / pow($L,2)}]
set n_rval [format "%0.3f" $n_rval]
if { 0 < $n_rval && $n_rval < 1} {
set onextensionFlag 0;# inside clipping area
} elseif {$n_rval == 0 || $n_rval == 1} {
set onextensionFlag 1 ;# inside clipping area (but on point)
} elseif { $n_rval > 1 || $n_rval < 0 } {
set onextensionFlag 2 ;# outside clipping area
} else {
set onextensionFlag 3 ;# consider inside clipping area
}
set ret [list [expr {abs($d_val) / $L}] $onextensionFlag $n_rval]
}
}
A: Floating point numbers (in all languages, not just Tcl) represent most numbers somewhat inexactly. As such, they should not normally be compared for equality as that's really rather unlikely. Instead, you should check to see if the two values are within a certain amount of each other (the amount is known as epsilon and takes into account that there are small errors in floating point calculations).
In your code, you might write this:
set epsilon 0.001; # Small, but non-zero
if { $epsilon < $n_rval && $n_rval < 1-$epsilon} {
set onextensionFlag 0;# inside clipping area
} elseif {abs($n_rval) < $epsilon || abs(1-$n_rval) < $epsilon} {
set onextensionFlag 1 ;# inside clipping area (but on point)
} elseif { $n_rval >= 1+$epsilon || $n_rval <= -$epsilon } {
set onextensionFlag 2 ;# outside clipping area
} else {
set onextensionFlag 3 ;# consider inside clipping area
}
Basically, think in terms of a number line where you change points to small intervals:
0 1
————————————————|————————————————|————————————————
to
0-ε 0+ε 1-ε 1+ε
———————————————(—)——————————————(—)———————————————
How to do the checks for which range you're in then follow from that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5257707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can an Image crop, resize be expressed as an affine transformation? I've got an image that gets cropped and resized to the image input size.
To my understanding this is the same as an affine transformation.
I am trying to simplify the code below so it does the same by using the function: (something like the example below at the end).
scipy.ndimage.affine_transform()
The trouble is I don't really understand the parameters of that function, hence I am not able to achieve an elegant one-liner with the affine_transform() function.
Providing and explaining the solution for the code might help me to better understand this affine_transform() function.
import numpy as npy
import PIL.Image
import scipy.misc as smc
import scipy.ndimage as snd
#crop factor
s = 1.045
#input image
img2crop = npy.float32(PIL.Image.open("input_image.jpg)")
h, w = img2crop.shape[:2] #get the dimensions of the input image
#Box-crop values: calculate new crop Dimensions based on 's'
wcrop = float(w) / (s)
hcrop = float(wcrop) / (float(w) / float(h))
hcrop = int(round(hcrop))
wcrop = int(round(wcrop))
#crop applied from top-left to right and bottom
b_left = 0
b_top = 0
b_width = wcrop
b_height = hcrop
b_box = (b_left, b_top, b_width, b_height)
#cropped region
region = img2crop.crop(b_box)
#resize cropped region back to input size
resized_region = smc.imresize(region, (h, w), interp='nearest', mode=None)
#save cropped and resized region as new file in output folder
PIL.Image.fromarray(np.uint8(resized_newregion)).save("output_image.jpg")
Question:
How can the code above doing a crop and resize be expressed as an affine transformation?
This example crops evenly on all 4 sides, center oriented
s = 0.0065
cropped_and_resized_image = snd.affine_transform(input_image.jpg, [1-s,1-s,1], [h*s/2,w*s/2,0], order=1)
PIL.Image.fromarray(npy.uint8(cropped_and_resized_image)).save("output_image_at.jpg")
Thanks in advance for feedback.
A: Here is OpenCV implementation
# OpenCV implementation of crop/resize using affine transform
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
import cv2
src_rgb = cv2.imread('test_img.jpg')
# Source width and height in pixels
src_w_px = 640
src_h_px = 480
# Target width and height in pixels
res_w_px = 640
res_h_px = 480
# Scaling parameter
s = 2.0
Affine_Mat_w = [s, 0, res_w_px/2.0 - s*src_w_px/2.0]
Affine_Mat_h = [0, s, res_h_px/2.0 - s*src_h_px/2.0]
M = np.c_[ Affine_Mat_w, Affine_Mat_h].T
res = cv2.warpAffine(src_rgb, M, (res_w_px, res_h_px))
# Showing the result
plt.figure(figsize=(15,6))
plt.subplot(121); plt.imshow(src_rgb); plt.title('Original image');
plt.subplot(122); plt.imshow(res); plt.title('Image warped Affine transform');
A: OpenCV implementation of crop image && resize to (des_width, des_height) using affine transform
import numpy as np
import cv2
def crop_resized_with_affine_transform(img_path, roi_xyxy, des_width, des_height):
src_rgb = cv2.imread(img_path)
'''
image roi
(x0,y0)------------(x1,y1)
| |
| |
| |
| |
| |
| |
| |
| |
(-,-)------------(x2, y2)
'''
src_points = [[roi_xyxy[0], roi_xyxy[1]], [roi_xyxy[2], roi_xyxy[1]], [roi_xyxy[2], roi_xyxy[3]]]
src_points = np.array(src_points, dtype=np.float32)
des_points = [[0, 0], [des_width, 0], [des_width, des_height]]
des_points = np.array(des_points, dtype=np.float32)
M = cv2.getAffineTransform(src_points, des_points)
crop_and_resized_with_affine_transform = cv2.warpAffine(src_rgb, M, (des_width, des_height))
return crop_and_resized_with_affine_transform
def crop_resized(img_path, roi_xyxy, des_width, des_height):
src_rgb = cv2.imread(img_path)
roi_img = src_rgb[roi_xyxy[1]:roi_xyxy[3], roi_xyxy[0]:roi_xyxy[2]]
resized_roi_img = cv2.resize(roi_img, (des_width, des_height))
return resized_roi_img
if __name__ == "__main__":
'''
Source image from
https://www.whitehouse.gov/wp-content/uploads/2021/04/P20210303AS-1901.jpg
or
https://en.wikipedia.org/wiki/Joe_Biden#/media/File:Joe_Biden_presidential_portrait.jpg
'''
img_path = "Joe_Biden_presidential_portrait.jpg"
# xmin ymin xmax ymax
roi_xyxy = [745, 265, 1675, 1520]
des_width = 480
des_height = 720
crop_and_resized_with_affine_transform = crop_resized_with_affine_transform(img_path, roi_xyxy , des_width, des_height)
resized_roi_img = crop_resized(img_path, roi_xyxy, des_width, des_height)
cv2.imshow("crop_and_resized_with_affine_transform", crop_and_resized_with_affine_transform)
cv2.imwrite("crop_and_resized_with_affine_transform.jpg", crop_and_resized_with_affine_transform)
cv2.imshow("resized_roi_img", resized_roi_img)
cv2.imwrite("resized_roi_img.jpg", resized_roi_img)
cv2.waitKey(0)
Source image is Wiki:Joe_Biden_presidential_portrait.jpg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32619184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Converting BNF to EBNF confused about the difference between left and right recursion I have this BNF rule:
<S> -> <A> b | <A> b <C>
<A> -> a | a <A>
<C> -> c | <C> c
i want to turn it into EBNF rule however i am confused about the left and right recursion in the <A> and <C>, how will it differs in EBNF or they will be the same?
Here is what i did:
To convert: <S> -> <A> b | <A> b <C> to EBNF
1. <S> -> <A> b | <A> b <C>
2. <S> -> <A> b [<C>]
3. <S> -> <A> b (<C>)?
To convert: <A> - > a | a<A> to EBNF
1. <A> - > a | a<A>
2. < A> - > a | a{a}
3. < A> - > a | a{a}+
4. <A> - > a+
To convert: <C> -> c | <C> c to EBNF
1. <C> -> c | <C> c
2. <C> -> c | {c} c
3. <C> -> c | {c}+ c
4. <C> -> c+
A: They'll be the same. For example, <C> will match all of the following:
c
c c
c c c
c c c c c c c c c c c c c c c c c c c c c
And <A> will match all of the following:
a
a a
a a a
a a a a a a a a a a a a a a a a a a a a a
As a result, the EBNF for both will match. In general, if the left recursion is at the very beginning and the right recursion is at the very end, they will look similar:
<A> -> a | a <A>
<C> -> c | <L> c
EBNF:
<A> -> a | a a*
<A> -> a+
<C> -> c | c* c
<C> -> c+
What this EBNF grammar doesn't express is how the expression is parsed. In converting from BNF to EBNF, you lose the expressiveness. However, you can make it explicit by avoiding +:
<A> -> a a*
<C> -> c* c
Of course, the fact that both reduce to E+ means you can parse them as left-recursive or right-recursive, and the result won't matter. That's not always true—(2-3)-4 ≠ 2-(3-4)—but you do have the option of converting <C> to a right-recursive production, and the result will be the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61466422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cdap sandbox won't start - Unable to read transaction state version I have installed the binaries for the CDAP sandbox using the recipe found here. I was building a plugin and may have had a debugger blocking work. I rebooted my Linux PC on which the sandbox was running and now when I try and start the CDAP sandbox we end up with an error:
2020-10-04 09:05:57,507 - ERROR [main:o.a.t.s.SnapshotCodecProvider@122] - Unable to read transaction state version:
java.io.EOFException: null
at org.apache.tephra.snapshot.BinaryDecoder.readByte(BinaryDecoder.java:106) ~[org.apache.tephra.tephra-core-0.15.0-incubating.jar:0.15.0-incubating]
at org.apache.tephra.snapshot.BinaryDecoder.readInt(BinaryDecoder.java:48) ~[org.apache.tephra.tephra-core-0.15.0-incubating.jar:0.15.0-incubating]
My gut is saying that the last time CDAP ran, it didn't get the opportunity to write transaction state for an in-flight run and now I have corrupted some state. Since I'm only sandbox testing now, I'm happy to cold start CDAP. Unfortunately I haven't found any recipe for this yet. Has anyone seen anything similar or have a recipe for a cold start of CDAP sandbox?
A: As you have mentioned in the comment, deleting the data and logs directory will solve the problem, but it will reset the sandbox. CDAP sandbox is running on a single java process so it does not have High Availability (HA). When the process is killed suddenly, it may end up in a corrupted state.
A: I'had the same isue. To solve the problem you have to delete or rename the tx.snapshot directory in the directory called data. It's ok for me without any reset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64196056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Input, Process, and Output pairs of data We have a text file that contains drug administration data. Each line contains a patient ID, an administration date and a drug name, formatted as follows:
A234,2014-01-01,5FU
A234,2014-01-02,adderall
B324,1990-06-01,adderall
A234,2014-01-02,tylenol
B324,1990-06-01,tylenol
...etc.
Using an input file of this format, produce a list of pairs of drugs that were administered together (i.e. administered to the same patient on the same day) at least twenty-five different times. In the above sample, adderall and tylenol appear together twice, but every other pair appears only once. Output each qualifying pair as a comma-separated tuple, one per line.
Assuming that the adderall-tylenolcombination occurred 50 times and tylenol-5FU combination occurred 10 times, the output file should look something like this:
drug_used frequency
adderall-tylenol 50
Note that because the tylenol-5FU combination occurred less than 25 times, it's not included on the final output.
A: Using library(data.table) we can do
dt[, paste(drug, collapse = '-'), by = .(id,date)]
# id date V1
# 1: A234 2014-01-01 5FU
# 2: A234 2014-01-02 adderall-tylenol
# 3: B324 1990-06-01 adderall-tylenol
Although this also includes id-date combinations where the drug combination is not a tuple. If you want to only have the lines which have exactly two drugs, then we add a test for this:
dt[, if (.N == 2) paste(drug, collapse = '-'), by = .(id,date)]
# id date V1
# 1: A234 2014-01-02 adderall-tylenol
# 2: B324 1990-06-01 adderall-tylenol
To further subset these results to only those patients where a drug combination was applied more than 25 times on different days, we can chain the result to another test for this:
dt[, if (.N == 2) paste(drug, collapse = '-'), by = .(id,date)][, if (.N>25) .(date,V1), by=id]
If you need, you can write these results to a new file using write.table
The data
dt = fread("id, date, drug
A234,2014-01-01,5FU
A234,2014-01-02,adderall
B324,1990-06-01,adderall
A234,2014-01-02,tylenol
B324,1990-06-01,tylenol")
A: You can use dplyr library to summarize the data table.
library(dplyr)
data = data.frame(id = c("A234","A234", "B324", "A234","B324"),
date = strptime(c("2014-01-01","2014-01-02", "1990-06-01", "2014-01-02", "1990-06-01"),
format = "%Y-%m-%d"),
drug = c("5FU", "adderall", "adderall", "tylenol", "tylenol"))
data %>%
group_by(id, date) %>%
summarise(drug_used = paste(drug,collapse = "-"))
Source: local data frame [3 x 3]
Groups: id [?]
id date drug_used
<fctr> <dttm> <chr>
1 A234 2014-01-01 5FU
2 A234 2014-01-02 adderall-tylenol
3 B324 1990-06-01 adderall-tylenol
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40835432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Swift - Segmented control - Switch multiple views Until now I still can't figure how to switch multiple views in one view controller. My storyboard is like this one.
Right now I want to embed two views inside my view controller.
My code for segmented control to switch two views in one view controller so far.
import UIKit
class PopularHistoryViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func indexChanged(sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
NSLog("Popular selected")
//show popular view
case 1:
NSLog("History selected")
//show history view
default:
break;
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Another thing, If I put two views inside my controller, what is best practice to differentiate it?
A: First of all create two outlets and connect hose to the views in your ViewController.
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!
And Change the code like:
@IBAction func indexChanged(sender: UISegmentedControl)
{
switch segmentedControl.selectedSegmentIndex
{
case 0:
firstView.hidden = false
secondView.hidden = true
case 1:
firstView.hidden = true
secondView.hidden = false
default:
break;
}
}
If you don't want to create Outlets, assign the views individual tags (Say 101 and 102) and you can do it like:
@IBAction func indexChanged(sender: UISegmentedControl)
{
switch segmentedControl.selectedSegmentIndex
{
case 0:
self.view.viewWithTag(101)?.hidden = false
self.view.viewWithTag(102)?.hidden = true
case 1:
self.view.viewWithTag(101)?.hidden = true
self.view.viewWithTag(102)?.hidden = false
default:
break;
}
}
A: If you want to do UI layout in Xcode for the two overlapping subviews, a better solution is to use two UIContainerViewController, and use the same way of setting the hidden property as suggested in the above answer.
A: You can use the isHidden property of the UIView to show/hide your required views.
First you have to link both views to IBOutlets through the Interface builder
@IBOutlet weak var historyView: UIView!
@IBOutlet weak var popularView: UIView!
@IBAction func indexChanged(_ sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex {
case 0:
historyView.isHidden = true
popularView.isHidden = false
case 1:
historyView.isHidden = false
popularView.isHidden = true
default:
break;
}
}
Note: it was named hidden in Swift 1 and 2.
A: Add both views to the view controller in the story board and set one of them to be hidden = yes or alpha = 0. When your index changed function gets called set the current view on screen to hidden = yes/alpha of 0 and set the previously hidden view to hidden = no/alpha = 1. This should achieve what you want.
A: @IBAction func acSegmentAction(_ sender: Any) {
switch acSegmentedControl.selectedSegmentIndex {
case 0:
// print("addressview selected")
addressView.isHidden = false
contactProviderView.isHidden = true
case 1:
//print("contact provider selected")
addressView.isHidden = true
contactProviderView.isHidden = false
default:
break;
}
}
A: If it is a simple view, not a part of the screen, you can indeed use isHidden property of two subviews of your view controller view. But I don't like this approach because it's hard to understand latter what is going on with your nib when all of the subviews are in one pile.
I would add and remove those two views as child view controllers programmatically. It's the cleanest way there is, in my opinion.
But even if you decided to go with just views, don't put them directly on view controller's view. Use nibs, preferably with owner class. And in many cases consider adding and constraint them programmatically. It's more code, but also cleaner and conserves resources.
A: So what is written above does not work for me, so I figured out myself in Xcode 11 with Swift 5.
(view1 = historyView, view2 = popularView)
@IBOutlet weak var view1: UITableView!
@IBOutlet weak var view2: UITableView!
@IBAction func segmentedControlChanged(_ sender: Any) {
func showView1() {
view1.isHidden = false
view2.isHidden = true
}
func showView2() {
view1.isHidden = true
view2.isHidden = false
}
guard let segmentedControl = sender as?
UISegmentedControl else { return }
if segmentedControl.selectedSegmentIndex == 0 {
showView1()
}
else {
showView2()
}
}
Maybe this helps anyone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27956353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "58"
} |
Q: How to connect output layers to the input layer of another neural network? The Actor-network has 5 input neurons representing the state values and will produce one output value held by one output neuron.
The Q Network has 6 input neurons: 5 representing the state values and 1 representing the output of Actor-network.
I'll do gradient descent to train the Actor-network seperately, holding Q network's weights as constant.
My question is:
How should I structure to plug the output layer of Actor-Network into the input layer of the Q network, with TensorFlow 2.x?
A: You can just use the ŧf.keras.Model API:
actor_model = tf.keras.Model(inputs=...,outputs=...)
Q_model = tf.keras.Model(inputs=actor_model.outputs, outputs=...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62140076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get a random CGFloat for a constraint? I'm trying to randomize a leading constraint for a button in swift. To activate this I am selecting a button. When I select the button for the first time, it works well, but all the times after this, it shows a lot of errors in the NSLog. Here's the code:
let button = UIButton()
@IBAction func start(sender: UIButton) {
let randomNumber = Int(arc4random_uniform(180) + 30)
let cgfloatrandom = CGFloat(randomNumber)
button.hidden = false
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: cgfloatrandom),
button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
button.widthAnchor.constraintEqualToConstant(75),
button.heightAnchor.constraintEqualToConstant(75)
])
}
Please help. Thank you. Anton
A: The problem is you're adding constraints to a button that already has been properly constrained. While you could remove all the constraints and recreate them, that is really inefficient and would not be recommended.
I would recommend simply keeping a reference to the leading constraint, which will allow you to access it every time the button is tapped to modify the constant.
To do this, implement a property for your leading constraint, like so:
var leadingConstraint: NSLayoutConstraint!
When you create this button, you'll want to properly constrain it as well. Here is where you'll be creating that special leading constraint. This is done outside of the button action function, perhaps in viewDidLoad:
button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
//...
leadingConstraint = button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 0)
NSLayoutConstraint.activateConstraints([
leadingConstraint,
button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390),
button.widthAnchor.constraintEqualToConstant(75),
button.heightAnchor.constraintEqualToConstant(75)
])
Now when the button is tapped, you won't need to set translatesAutoresizingMaskIntoConstraints, and you can simply update the constant of the existing leading constraint.
@IBAction func start(sender: UIButton) {
button.hidden = false
let randomNumber = Int(arc4random_uniform(180) + 30)
leadingConstraint.constant = CGFloat(randomNumber)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34483959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pick main color from picture I'm new to Dart/Flutter framework and I'm still exploring their possibilities.
I know in Android it's possible to take a picture and extract the main color value from it programmatically. (Android example)
I wonder, how would this be achieved in pure Dart? I would like it to be compatible with both iOS and Android operating system.
A: Here's a simple function which returns the dominant color given an ImageProvider. This shows the basic usage of Palette Generator without all the boilerplate.
import 'package:palette_generator/palette_generator.dart';
// Calculate dominant color from ImageProvider
Future<Color> getImagePalette (ImageProvider imageProvider) async {
final PaletteGenerator paletteGenerator = await PaletteGenerator
.fromImageProvider(imageProvider);
return paletteGenerator.dominantColor.color;
}
Then use FutureBuilder on the output to build a Widget.
A: I probably think you got a fix but for future searches to this question, I suggest you check Pallete Generator by the flutter team.
I will try and give a simple explanation of how the code works but for a detailed example head over to the plugin's GitHub repo.
The example below is going to take an image then select the dominant colors from it and then display the colors
First, we add the required imports
import 'package:palette_generator/palette_generator.dart';
After that let's create the main application class.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
...
home: const HomePage(
title: 'Colors from image',
image: AssetImage('assets/images/artwork_default.png',),
imageSize: Size(256.0, 170.0),
...
),
);
}
}
In the image field above, place the image that you want to extract the dominant colors from, i used the image shown here.
Next, we create the HomePage class
@immutable
class HomePage extends StatefulWidget {
/// Creates the home page.
const HomePage({
Key key,
this.title,
this.image,
this.imageSize,
}) : super(key: key);
final String title; //App title
final ImageProvider image; //Image provider to load the colors from
final Size imageSize; //Image dimensions
@override
_HomePageState createState() {
return _HomePageState();
}
}
Lets create the _HomePageState too
class _HomePageState extends State<HomePage> {
Rect region;
PaletteGenerator paletteGenerator;
final GlobalKey imageKey = GlobalKey();
@override
void initState() {
super.initState();
region = Offset.zero & widget.imageSize;
_updatePaletteGenerator(region);
}
Future<void> _updatePaletteGenerator(Rect newRegion) async {
paletteGenerator = await PaletteGenerator.fromImageProvider(
widget.image,
size: widget.imageSize,
region: newRegion,
maximumColorCount: 20,
);
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: _kBackgroundColor,
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new AspectRatio(
aspectRatio: 15 / 15,
child: Image(
key: imageKey,
image: widget.image,
),
),
Expanded(child: Swatches(generator: paletteGenerator)),
],
),
);
}
}
The code above just lays out the image and the Swatches which is a class defined below. In initState, we first select a region which the colors will be derived from which in our case is the whole image.
After that we create a class Swatches which receives a PalleteGenerator and draws the swatches for it.
class Swatches extends StatelessWidget {
const Swatches({Key key, this.generator}) : super(key: key);
// The PaletteGenerator that contains all of the swatches that we're going
// to display.
final PaletteGenerator generator;
@override
Widget build(BuildContext context) {
final List<Widget> swatches = <Widget>[];
//The generator field can be null, if so, we return an empty container
if (generator == null || generator.colors.isEmpty) {
return Container();
}
//Loop through the colors in the PaletteGenerator and add them to the list of swatches above
for (Color color in generator.colors) {
swatches.add(PaletteSwatch(color: color));
}
return Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
//All the colors,
Wrap(
children: swatches,
),
//The colors with ranking
Container(height: 30.0),
PaletteSwatch(label: 'Dominant', color: generator.dominantColor?.color),
PaletteSwatch(
label: 'Light Vibrant', color: generator.lightVibrantColor?.color),
PaletteSwatch(label: 'Vibrant', color: generator.vibrantColor?.color),
PaletteSwatch(
label: 'Dark Vibrant', color: generator.darkVibrantColor?.color),
PaletteSwatch(
label: 'Light Muted', color: generator.lightMutedColor?.color),
PaletteSwatch(label: 'Muted', color: generator.mutedColor?.color),
PaletteSwatch(
label: 'Dark Muted', color: generator.darkMutedColor?.color),
],
);
}
}
After that lets create a PaletteSwatch class. A palette swatch is just a square of color with an optional label
@immutable
class PaletteSwatch extends StatelessWidget {
// Creates a PaletteSwatch.
//
// If the [color] argument is omitted, then the swatch will show a
// placeholder instead, to indicate that there is no color.
const PaletteSwatch({
Key key,
this.color,
this.label,
}) : super(key: key);
// The color of the swatch. May be null.
final Color color;
// The optional label to display next to the swatch.
final String label;
@override
Widget build(BuildContext context) {
// Compute the "distance" of the color swatch and the background color
// so that we can put a border around those color swatches that are too
// close to the background's saturation and lightness. We ignore hue for
// the comparison.
final HSLColor hslColor = HSLColor.fromColor(color ?? Colors.transparent);
final HSLColor backgroundAsHsl = HSLColor.fromColor(_kBackgroundColor);
final double colorDistance = math.sqrt(
math.pow(hslColor.saturation - backgroundAsHsl.saturation, 2.0) +
math.pow(hslColor.lightness - backgroundAsHsl.lightness, 2.0));
Widget swatch = Padding(
padding: const EdgeInsets.all(2.0),
child: color == null
? const Placeholder(
fallbackWidth: 34.0,
fallbackHeight: 20.0,
color: Color(0xff404040),
strokeWidth: 2.0,
)
: Container(
decoration: BoxDecoration(
color: color,
border: Border.all(
width: 1.0,
color: _kPlaceholderColor,
style: colorDistance < 0.2
? BorderStyle.solid
: BorderStyle.none,
)),
width: 34.0,
height: 20.0,
),
);
if (label != null) {
swatch = ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 130.0, minWidth: 130.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
swatch,
Container(width: 5.0),
Text(label),
],
),
);
}
return swatch;
}
}
Hope this helps, thank you.
A: //////////////////////////////
//
// 2019, roipeker.com
// screencast - demo simple image:
// https://youtu.be/EJyRH4_pY8I
//
// screencast - demo snapshot:
// https://youtu.be/-LxPcL7T61E
//
//////////////////////////////
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image/image.dart' as img;
import 'package:flutter/services.dart' show rootBundle;
void main() => runApp(const MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String imagePath = 'assets/5.jpg';
GlobalKey imageKey = GlobalKey();
GlobalKey paintKey = GlobalKey();
// CHANGE THIS FLAG TO TEST BASIC IMAGE, AND SNAPSHOT.
bool useSnapshot = true;
// based on useSnapshot=true ? paintKey : imageKey ;
// this key is used in this example to keep the code shorter.
late GlobalKey currentKey;
final StreamController<Color> _stateController = StreamController<Color>();
//late img.Image photo ;
img.Image? photo;
@override
void initState() {
currentKey = useSnapshot ? paintKey : imageKey;
super.initState();
}
@override
Widget build(BuildContext context) {
final String title = useSnapshot ? "snapshot" : "basic";
return SafeArea(
child: Scaffold(
appBar: AppBar(title: Text("Color picker $title")),
body: StreamBuilder(
initialData: Colors.green[500],
stream: _stateController.stream,
builder: (buildContext, snapshot) {
Color selectedColor = snapshot.data as Color ?? Colors.green;
return Stack(
children: <Widget>[
RepaintBoundary(
key: paintKey,
child: GestureDetector(
onPanDown: (details) {
searchPixel(details.globalPosition);
},
onPanUpdate: (details) {
searchPixel(details.globalPosition);
},
child: Center(
child: Image.asset(
imagePath,
key: imageKey,
//color: Colors.red,
//colorBlendMode: BlendMode.hue,
//alignment: Alignment.bottomRight,
fit: BoxFit.contain,
//scale: .8,
),
),
),
),
Container(
margin: const EdgeInsets.all(70),
width: 50,
height: 50,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: selectedColor!,
border: Border.all(width: 2.0, color: Colors.white),
boxShadow: [
const BoxShadow(
color: Colors.black12,
blurRadius: 4,
offset: Offset(0, 2))
]),
),
Positioned(
child: Text('${selectedColor}',
style: const TextStyle(
color: Colors.white,
backgroundColor: Colors.black54)),
left: 114,
top: 95,
),
],
);
}),
),
);
}
void searchPixel(Offset globalPosition) async {
if (photo == null) {
await (useSnapshot ? loadSnapshotBytes() : loadImageBundleBytes());
}
_calculatePixel(globalPosition);
}
void _calculatePixel(Offset globalPosition) {
RenderBox box = currentKey.currentContext!.findRenderObject() as RenderBox;
Offset localPosition = box.globalToLocal(globalPosition);
double px = localPosition.dx;
double py = localPosition.dy;
if (!useSnapshot) {
double widgetScale = box.size.width / photo!.width;
print(py);
px = (px / widgetScale);
py = (py / widgetScale);
}
int pixel32 = photo!.getPixelSafe(px.toInt(), py.toInt());
int hex = abgrToArgb(pixel32);
_stateController.add(Color(hex));
}
Future<void> loadImageBundleBytes() async {
ByteData imageBytes = await rootBundle.load(imagePath);
setImageBytes(imageBytes);
}
Future<void> loadSnapshotBytes() async {
RenderRepaintBoundary boxPaint =
paintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
//RenderObject? boxPaint = paintKey.currentContext.findRenderObject();
ui.Image capture = await boxPaint.toImage();
ByteData? imageBytes =
await capture.toByteData(format: ui.ImageByteFormat.png);
setImageBytes(imageBytes!);
capture.dispose();
}
void setImageBytes(ByteData imageBytes) {
List<int> values = imageBytes.buffer.asUint8List();
photo;
photo = img.decodeImage(values)!;
}
}
// image lib uses uses KML color format, convert #AABBGGRR to regular #AARRGGBB
int abgrToArgb(int argbColor) {
int r = (argbColor >> 16) & 0xFF;
int b = argbColor & 0xFF;
return (argbColor & 0xFF00FF00) | (b << 16) | r;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50449610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: How can i return different value from what was in the dropdown in dart? I am working with dropbox, but what i want to do is retrieve value depending on what the user chooses on the dropbox; for example the users picks "apple" on the dropdownbox what i want to return will be "Vitamin C"
Here is what i have so far:
String myFruits;
List<String> fruits = [
"APPLE",
"ORANGE",
"BANANA",];
DropdownSearch(
onChanged: (dynamic value) {
myFruits = value;
},
mode: Mode.DIALOG,
items: fruits,
),
For now when i print myFruits what it shows is the selected value of the dropbox, what I want is that if pick apple it will return "vitamin c" like that. Thanks :) How can i achieve this?
A: you can define a Map from fruits and returnedValue like:
Map<String, String> returnedValue = {
"APPLE" : "Vitamin A",
"ORANGE" : "Vitamin C",
"BANANA" : "Vitamin K",
};
and return from this.
all your code like this :
Function(String) returnFunction();
String myFruits;
String myVitamin;
List<String> fruits = [
"APPLE",
"ORANGE",
"BANANA",
];
Map<String, String> returnedValue = {
"APPLE" : "Vitamin A",
"ORANGE" : "Vitamin C",
"BANANA" : "Vitamin K",
};
DropdownSearch(
onChanged: (dynamic value) {
myFruits = value;
myVitamin = returnedValue[value];
returenFunction(myVitamin); // if you want return from this class
},
mode: Mode.DIALOG,
items: fruits,
),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67281492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java lazy reading of XML file? I am wondering how I can lazily read a large XML file that doesn't fit into memory in Java. Let's assume the file is correctly formatted and we don't have to make a first pass to check this. Does someone know how to do this in Java?
Here is my fake file (real file is a Wikipedia dump which is 50+ Gb):
<pages>
<page>
<text> some data ....... </text>
</page>
<page>
<text> MORE DATA ........ </text>
</page>
</pages>
I was trying this with an XML library that is supposed to be able to do this but it's loading the whole thing into memory >:O
DOMParser domParser = new DOMParser();
//This is supposed to make it lazy-load the file, but it's not working
domParser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", true);
//Library says this needs to be set to use defer-node-expansion
domParser.setProperty("http://apache.org/xml/properties/dom/document-class-name", "org.apache.xerces.dom.DocumentImpl");
//THIS IS LOADING THE WHOLE FILE
domParser.parse(new InputSource(wikiXMLBufferedReader));
Document doc = domParser.getDocument();
NodeList pages = doc.getElementsByTagName("page");
for(int i = 0; i < pages.getLength(); i++) {
Node pageNode = pages.item(i);
//do something with page nodes
}
Do anyone know how to do this? Or what am I doing wrong in my attempt with this particular Java XML library?
Thanks.
A: You should be looking at SAX parsers in Java. DOM parsers are built to read the entire XMLs, load into memory, and create java objects out of them. SAX parsers serially parse XML files and use an event based mechanism to process the data. Look at the differences here.
Here's a link to a SAX tutorial. Hope it helps.
A: If you're prepared to buy a Saxon-EE license, then you can issue the simple query "copy-of(//page)", with execution options set to enable streaming, and it will return you an iterator over a sequence of trees each rooted at a page element; each of the trees will be fetched when you advance the iterator, and will be garbage-collected when you have finished with it. (That's assuming you really want to do the processing in Java; you could also do the processing in XQuery or XSLT, of course, which would probably save you many lines of code.)
If you have more time than money, and want a home-brew solution, then write a SAX filter which accepts parsing events from the XML parser and sends them on to a DocumentBuilder; every time you hit a startElement event for a page element, open a new DocumentBuilder; when the corresponding endElement event is notified, grab the tree that has been built by the DocumentBuilder, and pass it to your Java application for processing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33771933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Distinct character SET of substring in string Suppose a SET is all distinct character in a string.
I need to find out count of such distinct SET made from substrings in a string.
2 SETS are same when they have same characters in them.
eg:-string=ABBC
answer=6
distinct character sets of substrings are:{A},{B},{C},{A,B},{A,B,C},{B,C}
Note:Substring BBC and BC have same SET {B,C}, ABBC substring is SET {A,B,C}
PS:Seen on hackerearth Augito backend contest.The contest is over on 30-05-2021
Constraint 1<=Stringlen<=10^5 so expected complexity is O(N) or O(NLOGN)
A: You can use a two pointer approach + counting the frequencies.
static int countSub(String str)
{
int n = (int)str.length();
// Stores the count of
// subStrings
int ans = 0;
// Stores the frequency
// of characters
int []cnt = new int[26];
// Initialised both pointers
// to beginning of the String
int i = 0, j = 0;
while (i < n)
{
// If all characters in
// subString from index i
// to j are distinct
if (j < n &&
(cnt[str.charAt(j) - 'a'] == 0))
{
// Increment count of j-th
// character
cnt[str.charAt(j) - 'a']++;
// Add all subString ending
// at j and starting at any
// index between i and j
// to the answer
ans += (j - i + 1);
// Increment 2nd pointer
j++;
}
// If some characters are repeated
// or j pointer has reached to end
else
{
// Decrement count of j-th
// character
cnt[str.charAt(i) - 'a']--;
// Increment first pointer
i++;
}
}
// Return the final
// count of subStrings
return ans;
}
Here it considered only lower case letters. You can refer here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67773674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Issue integrating Node js with dialogflow I have created a Google Dialogflow agent, now I am trying to integrate it with a node js app so that I can create a custom UI for the chatbot.
I have followed the instructions in the document...
Enabled API for the project, generated the JSON key.
Below is my code:
const dialogflow = require('dialogflow');
const uuid = require('uuid');
/**
* Send a query to the dialogflow agent, and return the query result.
* @param {string} projectId The project to be used
*/
async function runSample(projectId = 'br-poaqqc') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient({
keyFilename: "./br-poaqqc-51d2d712d74f.json"
});
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hi',
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
try {
const responses = await sessionClient.detectIntent(request);
} catch(err) {
console.log('Error getting response',err)
}
console.log(responses);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
}
runSample();
There seems to be some certificate error. Below is the log:
Error getting response Error: SELF_SIGNED_CERT_IN_CHAIN undefined: Getting metadata from plugin failed with error: request to https://www.googleapis.com/oauth2/v4/token failed, reason: self signed certificate in certificate chain
at Object.callErrorFromStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call.js:30:26)
at Object.onReceiveStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\client.js:175:52)
at Object.onReceiveStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:341:141)
at Object.onReceiveStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\client-interceptors.js:304:181)
at Http2CallStream.outputStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:116:74)
at Http2CallStream.maybeOutputStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:155:22)
at Http2CallStream.endCall (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:141:18)
at Http2CallStream.cancelWithStatus (D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\call-stream.js:457:14)
at D:\PV\Codebase\chatbot-ui\node_modules\@grpc\grpc-js\build\src\channel.js:225:36
at processTicksAndRejections (internal/process/task_queues.js:85:5) {
code: 'SELF_SIGNED_CERT_IN_CHAIN',
details: 'Getting metadata from plugin failed with error: request to https://www.googleapis.com/oauth2/v4/token failed, reason: self signed certificate in certificate chain',
metadata: Metadata { internalRepr: Map {}, options: {} }
}
(node:1632) UnhandledPromiseRejectionWarning: ReferenceError: responses is not defined
at runSample (D:\PV\Codebase\chatbot-ui\app.js:35:15)
(node:1632) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1632) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The issue is lies around the sessionClient sending the request object to the dialogflow API. Beating my head over it for the past couple of hours. :/
Any clue where the issue is?
Thanks in advance! :)
A: const dialogflow = require('dialogflow');
const uuid = require('uuid');
const config = require('./config'); // your JSON file
if(!config.private_key) throw new Error('Private key required')
if(!config.client_email)throw new Error('Client email required')
if(!config.project_id) throw new Error('project required')
const credentials = {
client_email: config.client_email,
private_key: config.private_key,
};
const sessionClient = new dialogflow.SessionsClient(
{
projectId: config.project_id,
credentials
}
);
async function runSample(projectId = 'br-poaqqc') {
// A unique identifier for the given session
const sessionId = uuid.v4();
const sessionPath = sessionClient.sessionPath(config.project_id, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hi',
// The language used by the client (en-US)
languageCode: 'en-US',
},
},
};
// Send request and log result
try {
const responses = await sessionClient.detectIntent(request);
console.log(responses);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
} catch (err) {
console.log('Error getting response', err)
}
}
runSample();
Don't seems any issue but i think issue was with try block.
Make sure you are with internet connection if trying from local and your firewall is not blocking googleapis
A: the issue was not to do with the code, the firewall was blocking the 'googleapis.com' domain. I deployed the app in Heroku server and it worked fine. :)
For anyone who ponders around the same issue and ends up here, make sure its not a firewall issue. Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62386006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mutating a slice of an array doesn't work import numpy as np
def solve_eps(eps):
A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]])
b = np.array([1 + eps, 1, 2])
m_21 = A[1, 0] / A[0, 0]
m_31 = A[2, 0] / A[0, 0]
print("What A[1, :] should be:", A[1, :] - A[0, :] * m_21)
A[1, :] = A[1, :] - A[0, :] * m_21
print("But it won't assign it to the slice!!!!!", A[1, :])
If we run solve_eps(2), you see that the slice doesn't assign:
What A[1, :] should be: [ 0. -0.5 0. ]
But it won't assign it to the slice!!!!! [0 0 0]
But, if you run:
A = np.array([[3, 1, 1], [2, 2, 2]])
A[1, :] = A[1, :] - (A[0, :] * 4)
A[1, :] = [-10, -2, -2]
What's going on here?
A: Set dtype=float when you define A:
A = np.array([[eps, 1, 0], [1, 0, 0], [0, 1, 1]], dtype=float)
The reason you assignment failed was because you were assigning floats to an integer array.
Assigning integers to an integer slice works fine, as you noticed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48798227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Update Stored Procedure - only update certain fields and leave others as is I'm currently making a stored procedure which will update a products details. I want to make it (if possible) so that only the fields entered under 'values' column when being executed are updated and the rest remain the same as before.
ALTER PROCEDURE [dbo].[spUpdateProduct]
@ProductID int, @Brand nvarchar(30), @ModelNo nvarchar(9), @Description
nvarchar(50), @CostPrice decimal(6,2), @Stock int, @SalePrice decimal(6,2)
AS
BEGIN
SET NOCOUNT ON
UPDATE tblProduct
SET
Brand = @Brand,
ModelNo = @ModelNo,
[Description] = @Description,
CostPrice = @CostPrice,
Stock = @Stock,
SalePrice = @SalePrice
WHERE ProductID = @ProductID
END
This is currently what I have. When I go to change a value it errors saying I didn't enter a value for 'Brand' which is the next value after 'ProductID'.
Execute Window
Error when trying to update two fields (ProductID and CostPrice)
EDIT: The fields are all set to 'not null' when I created the table.
A: This is how I would do it. Have null-able parameters
ALTER PROCEDURE [dbo].[spUpdateProduct]
@ProductID int,
@Brand nvarchar(30) = null,
@ModelNo nvarchar(9) = null, ..... (to all the parameters except @ProductID)
AS
BEGIN
SET NOCOUNT ON
UPDATE tblProduct
SET
Brand = isNull(@Brand, Brand),
ModelNo = isNull(@ModelNo, ModelNo),
[Description] = isNull(@Description, Description),...
WHERE ProductID = @ProductID
END
Basically you are only updating the fields if parameters are not null otherwise keeping old values.
A: You have two problems - (a) the parameter to the stored procedure must be provided (the error tells you this) and (b) what to do when the parameter is not provided. For the first problem, check the pass null value or use SQL query to execute stored procedure like so:
exec spUpdateProduct 1, null, null, null, 140.99, null, null
For problem (b), use coalesce to update based on value being passed:
ALTER PROCEDURE [dbo].[spUpdateProduct]
@ProductID int, @Brand nvarchar(30), @ModelNo nvarchar(9), @Description
nvarchar(50), @CostPrice decimal(6,2), @Stock int, @SalePrice decimal(6,2)
AS
BEGIN
SET NOCOUNT ON
UPDATE t
SET
Brand = coalesce(@Brand, t.Brand),
ModelNo = coalesce(@ModelNo, t.ModelNo),
[Description] = coalesce(@Description, t.Description),
CostPrice = coalesce(@CostPrice, t.CostPrice),
Stock = coalesce(@Stock, t.Stock),
SalePrice = coalesce(@SalePrice, t.SalePrice)
FROM tblProduct as t
WHERE ProductID = @ProductID
END
A: After spending some time pondering this, I came up with a solution that doesn't use dynamic sql and also solves issues that coalese and isNull approaches don't solve. Note: minimal testing... looks like it does add a little overhead... but having this ability might allow flexibility on your client side code.
Table Schema:
FirstName NVARCHAR(200)
LastName NVARCHAR(200)
BirthDate DATE NULL
Activated BIT
Xml Param:
DECLARE @param =
N'<FirstName>Foo</FirstName>
<LastName>Bar</LastName>
<BirthDate>1999-1-1</BirthDate>
<Activated>1</Activated>'
UPDATE [dbo].[UserMaster]
[FirstName] = case when @param.exist('/FirstName') = 1 then @param.value('/FirstName[1]','nvarchar(200)') else [FirstName] end,
[LastName] = case when @param.exist('/LastName') = 1 then @param.value('/LastName[1]','nvarchar(200)') else [LastName] end,
[BirthDate] = case when @param.exist('/BirthDate') = 1 then @param.value('/BirthDate[1]','date') else [BirthDate]end,
[Activated] = case when @param.exist('/Activated') = 1 then @param.value('/Activated[1]','bit') else [Activated] end
WHERE [UserMasterKey] = @param.value('/UserMasterKey[1]','bigint')
This will allow you to pass in an XML parameter, with any field you want and Update that field. Note that setting fields equal to themselves in this context, for example [FirstName] = [FirstName], is perfectly fine. The engine will optimize this away.
Now, this is a more complex solution to @Anand and @r.net 's answers, however it does solve the 'setting nullables' problem that some commenters pointed out.
I liked how elegant their solutions were, but wanted to be able to set NULL on nullable columns, while still retaining the ability to use the default field value if I don’t pass in a parameter for that field. The using null checks as the basis for defaults in this case fills the hole and digs another one, so to speak, because they don't allow one to explicitly update a field to null.
Passing an xml parameter allows you to do that, all without taking a dynamic sql approach.
I would also look into using Table-valued parameters, as I believe there could be a similar solution using those.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43612860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: gpg verify of GNU Emacs download fails - Did I do it correctly? I have downloaded a GNU tar archive (emacs-26.1.tar.xz) and now want to verify it against its signature file. gpg returns with the verify option the following output:
gpg: no valid OpenPGP data found.
gpg: the signature could not be verified.
Obviously the download could not be verified. But what does this mean? Is the tar archive probably corrupt? Or had I not imported the correct keys?
Here is step-by-step what I did:
*
*I downloaded the archive file and its .sig file:
$ wget https://ftp.gnu.org/gnu/emacs/emacs-26.1.tar.xz
$ wget https://ftp.gnu.org/gnu/emacs/emacs-26.1.tar.xz.sig
*I downloaded the GNU keyring (the Emacs download page gave me the link):
$ wget https://ftp.gnu.org/gnu/gnu-keyring.gpg
*With gpg I imported the GNU keyring:
$ gpg --import gnu-keyring.gpg
Note that this returned:
.
.
.
gpg: Total number processed: 525
gpg: imported: 525 (RSA: 187)
gpg: no ultimately trusted keys found
*Finally I verified the tar archive:
gpg --verify emacs-26.1.tar.xz.sig emacs-26.1.tar.xz
This then returned (as stated at the top):
gpg: no valid OpenPGP data found.
gpg: the signature could not be verified.
Please remember that the signature file (.sig or .asc)
should be the first file given on the command line.
So, is the tar archive corrupt or had I not imported the correct keys? If the latter is the case, what are the correct keys for this GNU download?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51074734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Null pointer exception to check whether a xml have the element or not My part of code is below see,
NodeList nodes=doc.getElementsByTagName("user");
if(nodes.getLength()==0)
system.exit(1);
Initially, xml dont have user element.
But, I got an null pointer exception.
How to solve this...
And how do I find the no of nodes even if the nodes doesn't exists initially.
It shud return 0 nodes.
Thank you
Also I checked this....
NodeList nodes=doc.getElementsByTagName("user");
if(nodes==null)
system.exit(1);
Then aldo I got null pointer exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32698817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Optimal solution for non-overlapping maximum scoring sequences While developing part of a simulator I came across the following problem. Consider a string of length N, and M substrings of this string with a non-negative score assigned to each of them. Of particular interest are the sets of substrings that meet the following requirements:
*
*They do not overlap.
*Their total score (by sum, for simplicity) is maximum.
*They span the entire string.
I understand the naive brute-force solution is of O(M*N^2) complexity. While the implementation of this algorithm would probably not impose a lot on the performance of the whole project (nowhere near the critical path, can be precomputed, etc.), it really doesn't sit well with me.
I'd like to know if there are any better solutions to this problem and if so, which are they? Pointers to relevant code are always appreciated, but just algorithm description will do too.
A: This can be thought of as finding the longest path through a DAG. Each position in the string is a node and each substring match is an edge. You can trivially prove through induction that for any node on the optimal path the concatenation of the optimal path from the beginning to that node and from that node to the end is the same as the optimal path. Thanks to that you can just keep track of the optimal paths for each node and make sure you have visited all edges that end in a node before you start to consider paths containing it.
Then you just have the issue to find all edges that start from a node, or all substring that match at a given position. If you already know where the substring matches are, then it's as trivial as building a hash table. If you don't you can still build a hashtable if you use Rabin-Karp.
Note that with this you'll still visit all the edges in the DAG for O(e) complexity. Or in other words, you'll have to consider once each substring match that's possible in a sequence of connected substrings from start to the end. You could get better than this by doing preprocessing the substrings to find ways to rule out some matches. I have my doubts if any general case complexity improvements can come for this and any practical improvements depend heavily on your data distribution.
A: O(N+M) solution:
Set f[1..N]=-1
Set f[0]=0
for a = 0 to N-1
if f[a] >= 0
For each substring beginning at a
Let b be the last index of the substring, and c its score
If f[a]+c > f[b+1]
Set f[b+1] = f[a]+c
Set g[b+1] = [substring number]
Now f[N] contains the answer, or -1 if no set of substrings spans the string.
To get the substrings:
b = N
while b > 0
Get substring number from g[N]
Output substring number
b = b - (length of substring)
A: It is not clear whether M substrings are given as sequences of characters or indeces in the input string, but the problem doesn't change much because of that.
Let us have input string S of length N, and M input strings Tj. Let Lj be the length of Tj, and Pj - score given for string Sj. We say that string
This is called Dynamic Programming, or DP. You keep an array res of ints of length N, where the i-th element represents the score one can get if he has only the substring starting from the i-th element (for example, if input is "abcd", then res[2] will represent the best score you can get of "cd").
Then, you iterate through this array from end to the beginning, and check whether you can start string Sj from the i-th character. If you can, then result of (res[i + Lj] + Pj) is clearly achievable. Iterating over all Sj, res[i] = max(res[i + Lj] + Pj) for all Sj which can be applied to the i-th character.
res[0] will be your final asnwer.
A: inputs:
N, the number of chars in a string
e[0..N-1]: (b,c) an element of set e[a] means [a,b) is a substring with score c.
(If all substrings are possible, then you could just have c(a,b).)
By e.g. [1,2) we mean the substring covering the 2nd letter of the string (half open interval).
(empty substrings are not allowed; if they were, then you could handle them properly only if you allow them to be "taken" at most k times)
Outputs:
s[i] is the score of the best substring covering of [0,i)
a[i]: [a[i],i) is the last substring used to cover [0,i); else NULL
Algorithm - O(N^2) if the intervals e are not sparse; O(N+E) where e is the total number of allowed intervals. This is effectively finding the best path through an acyclic graph:
for i = 0 to N:
a[i] <- NULL
s[i] <- 0
a[0] <- 0
for i = 0 to N-1
if a[i] != NULL
for (b,c) in e[i]:
sib <- s[i]+c
if sib>s[b]:
a[b] <- i
s[b] <- sib
To yield the best covering triples (a,b,c) where cost of [a,b) is c:
i <- N
if (a[i]==NULL):
error "no covering"
while (a[i]!=0):
from <- a[i]
yield (from,i,s[i]-s[from]
i <- from
Of course, you could store the pair (sib,c) in s[b] and save the subtraction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1409374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 99 Current browser version is 105 I am currently new to robot framework. currently using latest version of chrome and ChromeDriver which is 105 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 99" I have tried uninstalling everything and reinstalling it again but nothing works can anyone help me with this. Thank you!
Screenshots below:
enter image description here
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 99
Current browser version is 105.0.5195.127 with binary path C:\Program Files\Google\Chrome\Application\chrome.exe
enter image description here
A: Chrome driver has a page on how to identify the exact version that you need, but it's a pain, especially if you regularly update chrome, or want to make it part of a build process.
Not sure about robot framework, but chromedriver-autoinstaller sure helped me out when building a pipeline to get a selenium/chrome project going, as it will detect the version of chrome installed and install the correct driver version automatically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73813019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Setting parent window URL from a child window? This is what I am trying to do: Once submit a form on my main JSP/HTML page a new page with some link opens. When I click on any of the link the link should open in the parent Window. I.e the Window I started from. How do i do this?
A: You'll need JavaScript for this. HTML's target can't target the window's parent (opener) window.
The following will open the page in the parent window if JavaScript is enabled, and open it in a new window if it is disabled. Also, it will react gracefully if the current page does not have an opener window.
<a href="page.php"
onclick="if (typeof window.opener != 'undefined') // remove this line break
window.opener.location.href = this.href; return false;"
target="_blank">
Click
</a>
MDC Docs on window.opener
A: Use parent.location.href if it's on the same page in an iframe. Use opener.location.href if it's another entire tab/window.
A: Use window.opener.location.href in javascript
For example,
<a href="javascript:void(0);" onclick="window.opener.location.href='linkedFile.html';">Click me!</a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3553751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Deleting a Jtable row from a custom model extending AbstractTableModel I have a JTable that is using a custom model i have designed. This model is extending the AbstractTableModel as shown below. I have a button Delete that I would want when clicked will delete the selected/highlighted row Here is my table model:
public class ProductTableModel extends AbstractTableModel
{
private final List<String> columnNames;
private final List<Product> products;
public ProductTableModel() {
String[] header = new String[] {
"Quantity",
"Description",
"Unity Price",
"Total Price"
};
this.columnNames = Arrays.asList(header);
this.products = new ArrayList<>();
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0: return Integer.class;
case 1: return String.class;
case 2: return Double.class;
case 3: return Double.class;
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Product product = this.getProduct(rowIndex);
switch (columnIndex) {
case 0: return product.getProductQuantity();
case 1: return product.getProductDescription();
case 2: return product.getProductPrice();
case 3: return product.getProductTotalAmount();
default: throw new ArrayIndexOutOfBoundsException(columnIndex);
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex < 0 || columnIndex >= getColumnCount()) {
throw new ArrayIndexOutOfBoundsException(columnIndex);
} else {
Product product = this.getProduct(rowIndex);
switch (columnIndex) {
case 0: product.setProductQuantity((Integer)aValue); break;
case 1: product.setProductDescription((String)aValue); break;
case 2: product.setProductPrice((Double)aValue); break;
case 3: product.setProductTotalAmount((Double)aValue); break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
@Override
public int getRowCount() {
return this.products.size();
}
@Override
public int getColumnCount() {
return this.columnNames.size();
}
@Override
public String getColumnName(int columnIndex) {
return this.columnNames.get(columnIndex);
}
public void setColumnNames(List<String> columnNames) {
if (columnNames != null) {
this.columnNames.clear();
this.columnNames.addAll(columnNames);
fireTableStructureChanged();
}
}
public List<String> getColumnNames() {
return Collections.unmodifiableList(this.columnNames);
}
public void addProducts(Product product) {
int rowIndex = this.products.size();
this.products.add(product);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void addProducts(List<Product> productList) {
if (!productList.isEmpty()) {
int firstRow = this.products.size();
this.products.addAll(productList);
int lastRow = this.products.size() - 1;
fireTableRowsInserted(firstRow, lastRow);
}
}
public void addEmptyRow() {
products.add(new Product());
this.fireTableRowsInserted(products.size()-1, products.size()-1);
}
public void insertProduct(Product product, int rowIndex) {
this.products.add(rowIndex, product);
fireTableRowsInserted(rowIndex, rowIndex);
}
public void deleteProduct(int rowIndex) {
if (this.products.remove(this.products.get(rowIndex))) {
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
public Product getProduct(int rowIndex) {
return this.products.get(rowIndex);
}
public List<Product> getProducts() {
return Collections.unmodifiableList(this.products);
}
public void clearTableModelData() {
if (!this.products.isEmpty()) {
int lastRow = products.size() - 1;
this.products.clear();
fireTableRowsDeleted(0, lastRow);
}
}
}
Here is a method for deleting a product from the model:
public void deleteProduct(int rowIndex) {
if (this.products.remove(this.products.get(rowIndex))) {
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
Here is the code that would be executed when the delete but is clicked:
delete.addActionListener((ActionEvent e) -> {
if (e.getSource().equals(delete)) {
int modelRowIndex = table.convertRowIndexToModel(table.getSelectedRow());
ProductTableModel model=(ProductTableModel)table.getModel();
model.deleteProduct(modelRowIndex);
}
}
When I run this program it is showing the table as it is supposed to be. I add some rows in the table at run time using the addEmptyRow()in my ProductTableModel. When I highlight/select one row in the table and click the delete button, its showing me the following error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at quotationTable.ProductTableModel.deleteProduct(ProductTableModel.java:119)
at quotationTable.Table$InteractiveTableModelListener.lambda$tableChanged$0(Table.java:152)
at quotationTable.Table$InteractiveTableModelListener$$Lambda$25/930643647.actionPerformed(Unknown Source)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Sorry for the big stack trace but one man advised me to put it in full.When I print the table.getSelectedRow()and table.convertRowIndexToModel(table.getSelectedRow()); they are giving me -1.
How do we solve this and what could be the possible reasons?
A: probably in this line of code
this.products.remove(this.products.get(rowIndex)
rowIndex return null or zero value because check and debug this line my friend
A: The code I posted if fine and it works. The problem was due to a shadow reference -that is I was having two instances of my table.This answers why I was getting -1 when calling getSelectedRow()-the possible reason to my question why I was having this value yet I was adding rows to my table.In simple terms - I was adding rows to myTable1OnTheScreenand calling deleteSelectedRow()on myTable2ThatHasNoRowsAddedToIt hence, getSelectedRow()would return -1 because it was refering to myTable2ThatHasNoRowsAddedToIt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28231979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Finding out zero frequency values from a column with inner join I have two tables named courses and teachers. I need to find the list of teachers who don't take any courses.
This is the query I wrote for getting the teacher who took the most numbered courses -
SELECT t.name AS teacher_name
, COUNT(c.teacher_id) AS courses_taken
FROM courses c
JOIN teachers t
ON c.teacher_id = t.id
GROUP
BY c.teacher_id
ORDER
BY courses_taken DESC
LIMIT 1;
By reversing this query I am getting the teacher's list who take minimum numbers of courses which is 1 but I need to find the list of teacher who don't take any courses.
A: Left Join and Where condition can help you.
SELECT *
FROM teachers t
LEFT
JOIN courses c
ON t.id = c.teacher_id
WHERE c.teacher_id IS NULL
A: Teachers don't usually "take" courses. They "teach" courses. Students "take" courses.
That said, not exists seems appropriate:
SELECT t.*
FROM teachers t
WHERE NOT EXISTS (SELECT 1
FROM courses c
WHERE c.teacher_id = t.id
);
If you think about this, it is almost a direct translation of your question: Get teachers where there is no course that the teacher teachers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65869048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Google api 3 returning nothing when WEB APi is published I have made a simple ASP.NET Web API that gets events from a shared google calendar, and serves them to me in json. When i fire it up from localhost i get 104 events returned: but when I've published it to my IIS server, the array contains no elements. I can't debug on it, but i get an empty array presented:
I have made an app on https://console.developers.google.com/ and added both localhost and http://domainname.dk/oauthcallback to it.
My code:
public void GetFixedEvents()
{
const string calendarId = "[email protected]";
try
{
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret,
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "CalendarTest",
});
var queryStart = DateTime.Now;
var queryEnd = queryStart.AddYears(1);
var query = service.Events.List(calendarId);
query.TimeMin = queryStart;
query.TimeMax = queryEnd;
query.SingleEvents = true;
var events = query.Execute().Items;
foreach (var item in events)
{
var tempEvent = new PubEvent
{
Title = item.Summary,
Description = item.Description ?? "None",
Start = item.Start.DateTime,
End = item.End.DateTime,
EventType = item.Summary.Contains("Ladies") ? EventType.LadiesNight : EventType.StudentNight
};
_pubEvents.Add(tempEvent);
}
}
catch (Exception e)
{
Console.WriteLine("Exception encountered: {0}", e.Message);
}
}
Can anyone help? Is it a problem with redirect uri? I have tried adding all the ones I can possibly think of. Is there any way to log the call to the google api?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28508379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stripping value in PS and comparing if it is an integer value I am running PS cmdlet get-customcmdlet which is generating following output
Name FreeSpaceGB
---- -----------
ABC-vol001 1,474.201
I have another variable $var=vol
Now, I want to strip out just 001 and want to check if it is an integer.
I am using but getting null value
$vdetails = get-customcmdlet | split($var)[1]
$vnum = $vdetails -replace '.*?(\d+)$','$1'
My result should be integer 001
A: Assumption: get-customcmdlet is returning a pscustomobject object with a property Name that is of type string.
$var = 'vol'
$null -ne ((get-customcmdlet).Name -split $var)[1] -as [int]
This expression will return $true or $false based on whether the cast is successful.
If your goal is to pad zeroes, you need to do that after-the-fact (in this case, I just captured the original string):
$var = 'vol'
$out = ((get-customcmdlet).Name -split $var)[1]
if ($null -ne $out -as [int])
{
$out
}
else
{
throw 'Failed to find appended numbers!'
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51937717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Word VBA Tabstop wrong behaviour I have the following VBA code
Private Sub CreateQuery_Click()
Dim doc As Document
Dim i As Integer
Set doc = ActiveDocument
i = doc.Paragraphs.Count
doc.Paragraphs(i).Range.InsertParagraphAfter
i = i + 1
For j = 0 To 1000
doc.Paragraphs(i).Range.InsertParagraphAfter
i = i + 1
doc.Paragraphs(i).Range.InsertParagraphAfter
i = i + 1
With doc.Paragraphs(i)
.Range.Font.Italic = True
.Range.ListFormat.ApplyBulletDefault
.Indent
.Indent
.TabStops.Add Position:=CentimetersToPoints(3.14)
.TabStops.Add Position:=CentimetersToPoints(10)
.TabStops.Add Position:=CentimetersToPoints(11)
End With
For k = 0 To 10
With doc.Paragraphs(i)
.Range.InsertAfter "testState" & vbTab & CStr(doc.Paragraphs(i).Range.ListFormat.CountNumberedItems) & vbTab & CStr(doc.Paragraphs.Count)
.Range.InsertParagraphAfter
End With
i = i + 1
Next
i = doc.Paragraphs.Count
With doc.Paragraphs(i)
.Range.ListFormat.ApplyBulletDefault
.TabStops.ClearAll
.Outdent
.Outdent
End With
Next
i = doc.Paragraphs.Count
doc.Paragraphs(i).Range.InsertParagraphAfter
i = i + 1
End Sub
Basically this code just prints n numbers of lines with the specific format.
*
*Bullet list
*Indented
*and TabStops
(source: lans-msp.de)
The Code works perfectly for an arbitrary number of lines, but then at some point Word just stops applying the TabStops.
I know that if I wouldn't reset the format every 10 lines, the code would work seemingly forever (really?!?). But the every 10 line brake is a must.
The exact line number where everything breaks down is dependent on the amount of RAM. On my work computer with 1GB it only works until about line 800(as you can see). My computer at home with 4GB didn't show this behaviour. But I'm sure it would have shown it as well if I had it let run long enough, because in my production code(which is a bit more complex) my home computer shows the problem as well.
Is this some kind of memory leak or something? What did I do wrong? Is maybe, god-forbid, VBA itself the culprit here?
A: Try to apply the formatting using a defined style. See if that makes a difference.
A: You might try turning automatic pagination off while adding the lines, to see if that helps.
Application.Options.Pagination = False
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1163975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IntelliJ IDEA: Move line? I really like IntelliJ IDEA's "Move statement" shortcut (Ctrl + Shift + ↑/↓). However -- I am not sure if this is a bug releated to ActionScript editing only -- move statement is not always what I want and sometimes it is not correct when editing AS code.
So I just want to move a block of lines up/down. The Eclipse shortcut is Alt + ↑/↓ and does not move statement-wise. Is there an equivalent in IntelliJ IDEA?
A: As other people have said this is already available as a command. You can configure the short cut to your liking, but by default (at least in IntelliJ 10) it is bound to ALT + SHIFT + ↑ and ALT + SHIFT + ↓
A: shift + alt + ↑/↓
you can find All short cuts HERE
https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf
A: Please find some useful shortcut for IntelliJ:
(1) IntelliJ Debugger
Step over (Go To next Step or line) : F8
Step into (Go into function) : F7
Smart step into : Shift + F7
Step out : Shift + F8
Run to cursor : Alt + F9
Evaluate expression : Alt + F8
Resume program : F9 [Mac = Cmd + ALT + R]
Toggle breakpoint : Ctrl + F8 [Mac = Cmd + F8]
View breakpoints : Ctrl + Shift + F8 [Mac = Cmd + Shift + F8]
(2) Open Specific File
Ctrl + Shift + N
(3) Open All Methods Implemented in class
Open specific class and press,
Ctrl + F12
(4) Go to Specific Line Number
Ctrl + G
(5) Method Implementation and Declaration
Declaration : Ctrl + B
Implementation : Ctrl + Alt + B
Response Type Declaration : Ctrl + Shift + B
Super class override Method : Ctrl + U
(6) Reformate Code
Ctrl + Alt + L
(7) Import relevant class
Click on relevant class (Red color field) and press,
Alt + Enter
Select valid class as per requirement
(8) Hierarchy of method calls
Select specific method and press,
Ctrl + Alt + H
(9) Comment In Code
Single Line : Select specific line and press,
Ctrl + /
Multiple Line : Select Multiple Line and Press,
Ctrl + Shift + /
(Note : Same operation for uncomment the code)
(10) Display Line Number
Hit Shift twice > write "line" > Show Line Numbers (the line doesn't have the toggle)
View > Active Editor > Show Line Number
(11) Code Selection
Full class selection : Ctrl + A
Method Selection : Select Method Name and press, Ctrl + W
(12) Basic Code Completion
To complete methods, keywords etc press,
Ctrl + Space
(13) Code Copy and Paste
Copy : Ctrl + C
Paste : Ctrl + V
(14) Search Operation
Specific File : Ctrl + F
Full Project : Ctrl + Shift + F
(15) Switcher Popup
Open Switcher Popup : Ctrl + Tab
Continue press Ctrl and use ↑/↓/←/→ for move one place to another
(16) Forward Move & Backward Move
Backward : Ctrl + Alt + ← (Left-Arrow)
Forward : Ctrl + Alt + → (Right-Arrow)
(17) Next/previous highlighted error
F2 or (Shift + F2)
(18) Open Java Doc
Select specific method name and press,
Ctrl + Q
(19) Find All commands
Ctrl + Shift + A
(20) Move Line Up/Down
shift + alt + ↑/↓
Thanks...
A: The LineMover plug-in works very well and is an acceptable solution.
A: Open Settings -> Keymap then search for "move line" via the upper right searchbox.
Under the Code folder you'll see:
*
*Move Statement Down
*Move Statement Up
*Move Line Down
*Move Line Up
The actions you're looking for are (as you may guess) the move line actions.
A: try command+shift+up/down this will auto adjust the indentation
A: You can move several lines together with move statement. Are you trying to move partial lines? I don't think there's a way in Idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1889561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "107"
} |
Q: Defining the BinarySearch for a user defined class in Java I have defined a class for storing the GPS data in Java as follows :
class data implements Comparable
{
float lati;
float longi;
int time; // Time in seconds
public int compareTo(Object obj)
{
data t = (data)obj;
if(this.time == t.time)
return 0;
if(this.time< t.time)
return -1;
else
return 1;
}
}
I have stored all the data in an ArrayList which I have sorted using the Collections.sort(d1) .(here d1 ArrayList of data type objects). But I am facing the problem is how can I use the Collections.binarySearch on this ArrayList to find the index of a specific element. When I try using it, I get the error message that binarySearch can'b be used with this data type. Can someone please help.
A: Comparable needs a parameter. Try with the following class:
class Data implements Comparable<Data> {
float lati;
float longi;
Integer time;
@Override
public int compareTo(Data o) {
// Integer already implements Comparable
return time.compareTo(o.time);
}
}
A: Here is one example on how to do it.
import java.util.*;
class Data implements Comparable<Data>
{
float lati;
float longi;
int time; // Time in seconds
public Data(int time) { this.time = time; }
public int compareTo(Data obj)
{
if(this.time == obj.time)
return 0;
if(this.time< obj.time)
return -1;
else
return 1;
}
public static void main(String[] args) {
ArrayList<Data> dataArray = new ArrayList<>();
dataArray.add(new Data(3));
dataArray.add(new Data(1));
dataArray.add(new Data(2));
Collections.sort(dataArray);
System.out.println(Collections.binarySearch(dataArray,new Data(1)));
System.out.println(Collections.binarySearch(dataArray,new Data(3)));
System.out.println(Collections.binarySearch(dataArray,new Data(2)));
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22709632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SOAPBinding.ParameterStyle.BARE vs SOAPBinding.ParameterStyle.WRAPPED : generated less parameters on request I use SOAPUI and generate java classes with JAX-WS import.
I have an interface like this
@WebService(name = "test", targetNamespace = "http://lang.java")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
@XmlSeeAlso({
ObjectFactory.class
})
public interface Test{
@WebMethod(action = "https://...action")
@WebResult(name = "getBean", targetNamespace = "http://...getBean", partName = "getBean")
public Bean test(
@WebParam(name = "parameter1", targetNamespace = "http://lang.java", partName = "parameter1")
String parameter1,
@WebParam(name = "parameter2", targetNamespace = "http://lang.java", partName = "parameter2")
String parameter2,
@WebParam(name = "parameter3", targetNamespace = "http://lang.java", partName = "parameter3")
String parameter3,
@WebParam(name = "parameter4", targetNamespace = "http://lang.java", partName = "parameter4")
long parameter4);
}
If I use SOAPBinding.ParameterStyle.WRAPPED the body message generated is
<S:Body>
<ns2:test xmlns:ns2="http://lang.java" xmlns:ns3="http://...getBean">
<ns2:parameter1>1</ns2:parameter1>
<ns2:parameter2>2</ns2:parameter2>
<ns2:parameter3>a</ns2:parameter3>
<ns2:parameter4>1</ns2:parameter4>
</ns2:test>
</S:Body>
If I use SOAPBinding.ParameterStyle.BARE the body message generated is
<S:Body>
<ns2:parameter1 xmlns:ns2="http://lang.java" xmlns:ns3="http://...getBean">1</ns2:parameter1>
</S:Body>
Why is the diference? Why in Bare option it only generates the first parameter? I need that Bare option create all parameters
A: Its ok! I find the answer here http://www.javajee.com/soap-binding-style-encoding-and-wrapping
Bare option only can use one parameter. When we use Bare, the message request must have zero or one element into Body. The solution is make an object with all parameters we want , and send this object to the method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26767801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Production Build Has Error: Uncaught ReferenceError: define is not defined I am basically just trying to serve a new ember created project on my production server. After running,
ember build --env production
And taking the files from dist/assets/ and putting on a page on my server that includes them I get the error.
Uncaught ReferenceError: define is not defined
My app is serving basically a blank HTML file with these assets included. The url I am trying to serve from is MyURL/admin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42303668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: nativescript carousel by javascript I want to create a horizontal scroll-view with stack-layout similar to 'olx' app. But the problem i am facing is to achieve endless scroll or carousel like scroll.
in the below link, carousel template was already implemented but it was too complicated to understand.
https://play.nativescript.org/?template=play-js&id=sRSad7&v=6
how to build and achieve endless horizontal scroll of the icons in stack-layout like in 'OLX' app. I am not expecting someone to code but just a flowchart of doing things would be very helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54495865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to extract search keywords from Google search result page URL by Swift? How do you extract search keywords from Google search result page URL by Swift?
I was simply trying to get stings after "&q=" but I found out I needed to consider more complicated cases such as "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"
I would appreciate your advice.
Update:
As per advised by LEO, I put this way.
if let url = NSURL(string: urlStr){
var extractedQuery = ""
if let fragment = url.fragment {
extractedQuery = fragment
} else if let query = url.query{
extractedQuery = query
}
if let queryRange = extractedQuery.rangeOfString("&q="){
let queryStartIndex = queryRange.endIndex
let queryKeyword = extractedQuery.substringFromIndex(queryStartIndex)
print(queryKeyword)
}
}
A: You can convert your string to NSURL and access its query and fragment properties:
if let url = NSURL(string: "https://www.google.co.jp/search?hl=ja&q=test#q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d"), query = url.query, fragment = url.fragment {
print(query) // "hl=ja&q=test\n"
print(fragment) // "q=speedtest+%E4%BE%A1%E6%A0%BC&hl=ja&prmd=nsiv&tbs=qdr:d\n"
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35658342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why is the string 'andy' not printing please enter a new username? current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()
for current_user in current_users:
current_user = current_user.lower()
for new_user in new_users:
if new_user == current_user:
print(f"\n{new_user}, Please enter a new username!")
else:
print(f"\n{new_user}, Username is available.")
Andy is being printed as username is available.
Also please help me simplify as I am just learning python.
A: You can use list comprehension to convert the usernames in current_users to lowercase. Secondly, you've to check whether the new_user is already present in current_users to do that you have to use in keyword.
The in keyword
tests whether or not a sequence contains a certain value.
here is code,
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()
current_users = [user.lower() for user in current_users]
for new_user in new_users:
if new_user in current_users:
print(f"\n{new_user}, Please enter a new username!")
else:
print(f"\n{new_user}, Username is available.")
Hope it helps!
A: You should try using in to the list:
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()
current_users = [i.lower() for i in current_users]
for new_user in new_users:
if new_user in current_users:
print(f"\n{new_user}, Please enter a new username!")
else:
print(f"\n{new_user}, Username is available.")
A: a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value .
= is an assignment operator
== is an equality operator
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()
for current_user in current_users:
current_user == current_user.lower()
for new_user in new_users:
if new_user == current_user:
print(f"\n{new_user}, Please enter a new username!")
else:
print(f"\n{new_user}, Username is available.")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60312954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the list of duplicated values in a range I tried recording the macros but it's using copying and pasting, but I prefer the codes to be dynamic as the range of my data changes weekly.
I have 2 columns, A & D. Column A is a pivot table, so I think, maybe that's why VBA codes for moving down rows don't work. (error for trying to move pivot table). I want Column D to be a list of unique duplicates that are from column A and condense it so no gaps.
So far I can extract the unique duplicates and condense them but the results are pasted it from D1 instead of D8. So I need help to bring down the values 8 rows. Now I don't want to copy and paste the pivot table as values or trying to get rid of it since I need the pivot table there as I can just refresh it every week for new list.
Any suggestion or advice is appreciated.
Sub dp()
AR = Cells(Rows.Count, "A").End(xlUp).Row
For Each p1 In Range(Cells(8, 1), Cells(AR, 1))
For Each p2 In Range(Cells(8, 1), Cells(AR, 1))
If p1 = p2 And Not p1.Row = p2.Row Then
Cells(p1.Row, 4) = Cells(p1.Row, 1)
Cells(p2.Row, 4) = Cells(p2.Row, 1)
End If
Next p2
Next p1
Columns(4).RemoveDuplicates Columns:=Array(1)
Dim lastrow As Long
Dim i As Long
lastrow = Range("D:D").End(xlDown).Row
For i = lastrow To 1 Step -1
If IsEmpty(Cells(i, "D").Value2) Then
Cells(i, "D").Delete shift:=xlShiftUp
End If
Next i
End Sub
A: Here is a different approach
Sub dp()
Dim AR As Long, p1 As Range, n As Long
AR = Cells(Rows.Count, "A").End(xlUp).Row
n = 8
With Range(Cells(8, 1), Cells(AR, 1))
For Each p1 In .Cells
If WorksheetFunction.CountIf(.Cells, p1) > 1 Then
If WorksheetFunction.CountIf(Columns(4), p1) = 0 Then
Cells(n, "D") = p1
n = n + 1
End If
End If
Next p1
End With
End Sub
A: Here are three different techniques:
*
*ArraysList
*ADODB.Recordset
*Array and CountIf
ArraysList
Sub ListDuplicates()
Dim v, listValues, listDups
Set listValues = CreateObject("System.Collections.ArrayList")
Set listDups = CreateObject("System.Collections.ArrayList")
For Each v In Range("A8", Cells(Rows.Count, "A").End(xlUp)).Value
If listValues.Contains(v) And Not listDups.Contains(v) Then listDups.Add v
listValues.Add v
Next
Range("D8").Resize(listDups.Count).Value = Application.Transpose(listDups.ToArray)
End Sub
ADODB.Recordset
Sub QueryDuplicates()
Dim rs As Object, s As String
Set rs = CreateObject("ADODB.Recordset")
s = ActiveSheet.Name & "$" & Range("A7", Cells(Rows.Count, "A").End(xlUp)).Address(False, False)
rs.Open "SELECT [Pivot Table] FROM [" & s & "] GROUP BY [Pivot Table] HAVING COUNT([Pivot Table]) > 1", _
"Provider=MSDASQL;DSN=Excel Files;DBQ=" & ThisWorkbook.FullName
If Not rs.EOF Then Range("D8").CopyFromRecordset rs
rs.Close
Set rs = Nothing
End Sub
Array and CountIf (similar to SJR answer but using an array to gather the data)
Sub ListDuplicatesArray()
Dim v, vDups
Dim x As Long, y As Long
ReDim vDups(x)
With Range("A8", Cells(Rows.Count, "A").End(xlUp))
For Each v In .Value
If WorksheetFunction.CountIf(.Cells, v) > 1 Then
For y = 0 To UBound(vDups)
If vDups(y) = v Then Exit For
Next
If y = UBound(vDups) + 1 Then
ReDim Preserve vDups(x)
vDups(x) = v
x = x + 1
End If
End If
Next
End With
Range("D8").Resize(UBound(vDups) + 1).Value = Application.Transpose(vDups)
End Sub
A: here's another approach:
Option Explicit
Sub main()
Dim vals As Variant, val As Variant
Dim strng As String
With Range(Cells(8, 1), Cells(Rows.count, 1).End(xlUp))
vals = Application.Transpose(.Value)
strng = "|" & Join(vals, "|") & "|"
With .Offset(, 3)
.Value = Application.Transpose(vals)
.RemoveDuplicates Columns:=1, Header:=xlNo
For Each val In .SpecialCells(xlCellTypeConstants)
strng = Replace(strng, val, "", , 1)
Next val
vals = Split(WorksheetFunction.Trim(Replace(strng, "|", " ")), " ")
With .Resize(UBound(vals) + 1)
.Value = Application.Transpose(vals)
.RemoveDuplicates Columns:=1, Header:=xlNo
End With
End With
End With
End Sub
A: another one approach here
Sub dp2()
Dim n&, c As Range, rng As Range, Dic As Object
Set Dic = CreateObject("Scripting.Dictionary")
Dic.comparemode = vbTextCompare
Set rng = Range("A8:A" & Cells(Rows.Count, "A").End(xlUp).Row)
n = 8
For Each c In rng
If Dic.exists(c.Value2) And Dic(c.Value2) = 0 Then
Dic(c.Value2) = 1
Cells(n, "D").Value2 = c.Value2
n = n + 1
ElseIf Not Dic.exists(c.Value2) Then
Dic.Add c.Value2, 0
End If
Next c
End Sub
but if you prefer your own variant, then you need to:
1) replace this line of code: Columns(4).RemoveDuplicates Columns:=Array(1)
by this one:
Range("D8:D" & Cells(Rows.Count, "D").End(xlUp).Row).RemoveDuplicates Columns:=1
2) another problem is in this line of code:
lastrow = Range("D:D").End(xlDown).Row
it will return the row #8 instead of last row that you've expected, so you need to replace it by this one: lastrow = Cells(Rows.Count, "D").End(xlUp).Row
3) also, replace to 1 step -1 by to 8 step -1
so, finally your code can looks like this:
Sub dp()
Dim AR As Long, p1 As Range, p2 As Range, lastrow&, i&
AR = Cells(Rows.Count, "A").End(xlUp).Row
For Each p1 In Range(Cells(8, 1), Cells(AR, 1))
For Each p2 In Range(Cells(8, 1), Cells(AR, 1))
If p1 = p2 And Not p1.Row = p2.Row Then
Cells(p1.Row, 4) = Cells(p1.Row, 1)
Cells(p2.Row, 4) = Cells(p2.Row, 1)
End If
Next p2, p1
Range("D8:D" & Cells(Rows.Count, "D").End(xlUp).Row).RemoveDuplicates Columns:=1
lastrow = Cells(Rows.Count, "D").End(xlUp).Row
For i = lastrow To 8 Step -1
If IsEmpty(Cells(i, "D").Value2) Then
Cells(i, "D").Delete shift:=xlShiftUp
End If
Next i
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40598440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Extracting text after "?" I have a string
x <- "Name of the Student? Michael Sneider"
I want to extract "Michael Sneider" out of it.
I have used:
str_extract_all(x,"[a-z]+")
str_extract_all(data,"\\?[a-z]+")
But can't extract the name.
A: I think this should help
substr(x, str_locate(x, "?")+1, nchar(x))
A: Try this:
sub('.*\\?(.*)','\\1',x)
A: x <- "Name of the Student? Michael Sneider"
sub(pattern = ".+?\\?" , x , replacement = '' )
A: To take advantage of the loose wording of the question, we can go WAY overboard and use natural language processing to extract all names from the string:
library(openNLP)
library(NLP)
# you'll also have to install the models with the next line, if you haven't already
# install.packages('openNLPmodels.en', repos = 'http://datacube.wu.ac.at/', type = 'source')
s <- as.String(x) # convert x to NLP package's String object
# make annotators
sent_token_annotator <- Maxent_Sent_Token_Annotator()
word_token_annotator <- Maxent_Word_Token_Annotator()
entity_annotator <- Maxent_Entity_Annotator()
# call sentence and word annotators
s_annotated <- annotate(s, list(sent_token_annotator, word_token_annotator))
# call entity annotator (which defaults to "person") and subset the string
s[entity_annotator(s, s_annotated)]
## Michael Sneider
Overkill? Probably. But interesting, and not actually all that hard to implement, really.
A: str_match is more helpful in this situation
str_match(x, ".*\\?\\s(.*)")[, 2]
#[1] "Michael Sneider"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30275708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Haystack and Solr- Fail To Clear Index I wanted to implement a search feature for my web app. I choose Haystack and Solr. After following the procedure in the docs. I tried to rebuild solr index ( python manage.py rebuild_index ) but I'm getting the below error. What I'm I missing?
WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
Failed to clear Solr index: [Errno 10061] No connection could be made because the target machine actively refused it
All documents removed.
Indexing 2 fincribs.
Failed to add documents to Solr: [Errno 10061] No connection could be made because the target machine actively refused it
Haystack settings
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr'
# ...or for multicore...
# 'URL': 'http://127.0.0.1:8983/solr/mysite',
},
}
Models
class Fincrib(models.Model):
user=models.ForeignKey(User)
title=models.CharField(max_length=250, unique=True)
address=models.CharField(max_length=200)
city=models.CharField(max_length=200)
state=models.CharField(max_length=200)
main_view=models.ImageField(upload_to="photos",blank=True, null=True)
side_view=models.ImageField(upload_to="photos",blank=True, null=True)
pub_date=models.DateTimeField()
def __unicode__(self):
return self.title
def get_absolute_url(self):
return self.title
Search_index.py
class FincribIndex(indexes.SearchIndex, indexes.Indexable):
text=indexes.CharField(document=True, use_template=True)
address=indexes.CharField(model_attr='address')
city=indexes.CharField(model_attr='city')
state=indexes.CharField(model_attr='state')
pub_date=indexes.DateTimeField(model_attr='pub_date')
def get_model(self):
return Fincrib
def index_queryset(self):
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
A: Then first of all, try to get solr running.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11140116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to stop puppeteer from overwriting duplicate? I have to write a program as a schoolproject which automaticly screenshots the gasprices from 10 locations for 2 months . I used puppeteer and it works. However if i start it again it overwrites the files because they have the same name. I locked for solutions but couldnt find something that works. Does someone know a solution.
const puppeteer = require ('puppeteer');
async function start() {
const browser = await puppeteer.launch({
defaultViewport: {width: 1920, height: 1080}
});
await page.goto("https://spritpreisalarm.de")
await page.type("#searchform > table > tbody > tr > td:nth-child(1) > input[type=text]","Leipzig");
await page.click("#searchform > table > tbody > tr > td:nth-child(4) > input");
await page.goto('https://spritpreisalarm.de/preise/station/7450/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
await page.screenshot({path:"Leipzig/totalLE.png"});
await page.goBack('https://spritpreisalarm.de/preise')
await page.goto('https://spritpreisalarm.de/preise/station/8731/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
await page.screenshot({path:"Leipzig/ARALMstr.png"});
await page.goBack('https://spritpreisalarm.de/preise');
await page.goto('https://spritpreisalarm.de/preise/station/7977/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
await page.screenshot({path:"Leipzig/ARALMaxistr.png"});
await page.goBack('https://spritpreisalarm.de/preise');
await page.goto('https://spritpreisalarm.de/preise/station/15601/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
await page.screenshot({path:"Leipzig/JETrustr.png"});
await page.goBack('https://spritpreisalarm.de/preise');
await page.goBack('https://spritpreisalarm.de');
await page.goto('https://spritpreisalarm.de/preise/station/13865/04683/1/5' , {waitUntil: 'domcontentloaded'});
await page.screenshot({path:"Naunhof/STARbrandisstr.png"});
await page.goBack('https://spritpreisalarm.de/preise');
await page.goto('https://spritpreisalarm.de/preise/station/1893/BERLIN/1/1', {waitUntil: 'domcontentloaded' });
await page.screenshot({path:"Berlin/ARALHolzmarktstr.png"});
await page.goBack('https://spritpreisalarm.de');
await page.goto('https://spritpreisalarm.de/preise/station/3091/BERLIN/1/1', {waitUntil: 'domcontentloaded' });
await page.screenshot({path:"Berlin/TotalHolzmarkstr.png"});
await page.goBack('https://spritpreisalarm.de/preise');
await page.goto('https://spritpreisalarm.de/preise/station/5045/GRIMMA/1/5', {waitUntil: 'domcontentloaded'});
await page.screenshot({path:"Grimma/AutobahntankstelleGrimma.png"})
await browser.close()
}
start()
A: It makes sense to create a new subfolder for your screenshots every time u start the script. Use a unique name for that for example the current timestamp:
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const currentDate = new Date();
const timestamp = currentDate.getTime()+'';
const screensDir = path.resolve(path.join(__dirname, timestamp, 'Leipzig'));
if (!fs.existsSync(screensDir)) {
fs.mkdirSync(screensDir, {recursive: true});
}
async function start() {
const browser = await puppeteer.launch({
defaultViewport: {width: 1920, height: 1080}
});
page = await browser.newPage();
await page.goto("https://spritpreisalarm.de")
await page.type("#searchform > table > tbody > tr > td:nth-child(1) > input[type=text]","Leipzig");
await page.click("#searchform > table > tbody > tr > td:nth-child(4) > input");
await page.goto('https://spritpreisalarm.de/preise/station/7450/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
await page.screenshot({path: screensDir + '/totalLE.png'});
await page.goBack('https://spritpreisalarm.de/preise')
await page.goto('https://spritpreisalarm.de/preise/station/8731/LEIPZIG/1/1', {waitUntil: 'domcontentloaded'});
await page.screenshot({path: screensDir + '/ARALMstr.png'});
await page.goBack('https://spritpreisalarm.de/preise');
//...
await browser.close()
}
start()
A: I would simply add the date to the file name so you can do two actions in one ;p.
*
*have the date
*no overwriting
let date = new Date().toJSON().slice(0,10)
await page.screenshot({path: screensDir + `/${date}ARALMstr.png`});
await page.goBack('https://spritpreisalarm.de/preise');
I didn't run it, but you understand the idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73204914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android reload grid view custom adapter While I have a working 'solution' I really don't like it and think it will lead to memory issues. Ultimately I have an activity that comprises of a GridView which is populated by a Object Array - subjectsArrayList
On the activity I have a button where I want to 'reload' the array and update the grid view.
At present I have this:
// reload all subjects
subjectAreas = "all";
subjectsArrayList = populateSubjects();
myAdapter = new MyAdapter(getApplicationContext(), subjectsArrayList);
gridView.invalidateViews();
gridView.setAdapter(myAdapter);
I'm certain there is a more elegant method. My concern is that I'm creating another adapter instead of recycling it.
I've looked at notifyDataSetChanged() but not completely clear on how to use this, and my various attempts lead to nothing happening.
Questions:
1) Is what I'm doing ok or am I correct in worrying abut re-creating my adapter each time?
2) Is there a better method to achieve what I want?
Thanks in advance
A: You should:
*
*update the adapter with the new data
*call myAdapter.notifyDataSetChanged() to update the GridView
Better, you should use a RecyclerView with a GridLayoutManager instead of a GridView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56651770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why are the document getter functions being reset? I am trying to create a small chrome extension to help find where cookies are using in websites. The extension is SUPPOSE to work by setting the getter method for the cookie on the document.
Like so:
document.__defineGetter__('cookie',function(){
alert("test");
});
When manually put into chrome's javascript console on a website and then trying to access a cookie (simply typing "document.cookie") it results in the expected behavior where it will pop up the test prompt.
However when I put this into a chrome extension and have it load before the rest of the page it will fail to work.
Here is the manifest.json (I was just using soundcloud as a test website):
{
"name": "Cookie Auditor",
"version": "0.1",
"manifest_version": 2,
"description": "An extension to help examine where cookies are being used in websites.",
"content_scripts": [
{
"matches": ["*://*.soundcloud.com/*"],
"js": ["content.js"],
"run_at": "document_start"
}
]
}
and here is the content.js:
console.log(document.location);
document.__defineGetter__('cookie',function(){
alert("test");
});
console.log(document.__lookupGetter__('cookie'));
When attempting to manually trigger it (document.cookie) it simply returns the normal value and fails to execute the javascript. When it failed to work here I put in the checks for the document location to make sure it was executing on the right domain and was even loading at all.
The weird part is when you load the page with this extension it will print out that it is on the right domain and it even shows that the cookie getter method was overwritten correctly (it print the function in the console).
However when you lookup the getter method it has been reset (document.__lookupGetter__('cookie')).
My last thought was that it was being reset sometime between my content.js script running and the rest of the page initializing. However when I change the "run_at" field in the manifest.json file to "document_end" in an attempt to make it run later and potentually after any sort of re initialization of the document then soundcloud's stuff will start printing on the console showing that it has properly loaded the page however my script still fails to have made an effect.
EDIT: Before it is suggested. I can't use chrome's cookie API because it doesn't provide a way of actually listening to when a cookie is retrieved which is the main thing I care about.
A: After some digging around I found out why it was failing. Chrome extensions are executed in their own javascript space but with the same DOM as the site they run on. See https://developer.chrome.com/extensions/content_scripts#execution-environment. This causes them to have seperate global variables and thus my script's attempts to change them would only affect itself. For anyone looking at how to get around this limitation all you have to do is add a script tag with your code onto the document from your extension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36368923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Decorated python function with parameters only used by the decorator are seen as unused I have a number of functions that are RPC calls and all have to prepare several things before the main task and to do some cleanup afterwards. Especially their first two parameters are logname and password which are needed to setup user data (properties, rights etc.).
So I decided to build a decorator called @rpc_wrapper which performs these tasks. This wrapper is now working fine for more than a year. The only drawback is that the inspect code function of PyCharm – I think other linters will behave similar – complains about the parameters logname and password which are never used inside of the function but only by the decorator.
How can I get rid of these complaints?
One way might be to insert a line
assert (logname, password)
at the start of each function. But I think that's not the real deal because decorators are made to avoid replications.
Is there a cleaner solution?
Edited
Here is the (simplified) decorator:
def rpc_wrapper(func):
@wraps(func)
def wrapper(login=None, pwd=None, *args, **kwargs):
doCleanup = True
try:
doCleanup = setupUser(login, pwd)
return func(login, pwd, *args, **kwargs)
except Exception:
logging.exception('**<#>')
raise Exception('999: internal error')
finally:
if doCleanup:
cleanup()
return wrapper
And a decorated function:
@rpc_wrapper
def ping(login: str = None, pwd: str = None):
return 'pong'
or another simple one:
@rpc_wrapper
def echo(login: str = None, pwd: str = None, msg: Any = 'message'):
return msg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73732117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Static Quick Actions not working in objective c iOS I am very new to the iOS Application development and I have been following tutorials to build my career . So starting with I am trying to Implement Static Quick Actions in Objective C as per client project . I was able to add the keys and got the options while pressing the icon . But when I press the Quick Actions nothing happens and it just launches the Application. I have researched a lot and I tried but in vain. Below is the Appdelegate code which I have written:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
BOOL shouldPerformAdditionalDelegateHandling = YES;
// Check API availiability
// UIApplicationShortcutItem is available in iOS 9 or later.
if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]){
NSLog(@"HERE");
// [self configDynamicShortcutItems];
// If a shortcut was launched, display its information and take the appropriate action
UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
if(shortcutItem)
{
NSLog(@"shortcut launch");
// When the app launch at first time, this block can not called.
[self handleShortCutItem:shortcutItem];
// This will block "performActionForShortcutItem:completionHandler" from being called.
shouldPerformAdditionalDelegateHandling = NO;
}else{
NSLog(@"normal launch");
// normal app launch process without quick action
// [self launchWithoutQuickAction];
}
}else{
// Less than iOS9 or later
// [self launchWithoutQuickAction];
}
return shouldPerformAdditionalDelegateHandling;
}
- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler{
NSLog(@"performActionForShortcutItem");
BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
completionHandler(handledShortCutItem);
}
/**
* @brief handle shortcut item depend on its type
*
* @param shortcutItem shortcutItem selected shortcut item with quick action.
*
* @return return BOOL description
*/
- (BOOL)handleShortCutItem : (UIApplicationShortcutItem *)shortcutItem{
BOOL handled = NO;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
if ([shortcutItem.type isEqualToString:@"PlayMusic"]) {
handled = YES;
NSLog(@"Play");
secondview *vc = [storyboard instantiateViewControllerWithIdentifier:@"second"];
self.window.rootViewController = vc;
[self.window makeKeyAndVisible];
}
else if ([shortcutItem.type isEqualToString:@"StopMusic"]) {
handled = YES;
NSLog(@"Stop");
// ThirdViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"thirdVC"];
//
// self.window.rootViewController = vc;
[self.window makeKeyAndVisible];
}
return handled;
}
However I can see the Quick Action items when I deep press the home icon but on clicking that no action happens. I check the key in info.plist and its the same .
Quick Actions
Below is the info.plist for adding Static Actions
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypePlay</string>
<key>UIApplicationShortcutItemTitle</key>
<string>Play</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Start playback</string>
<key>UIApplicationShortcutItemType</key>
<string>PlayMusic</string>
</dict>
<dict>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypePlay</string>
<key>UIApplicationShortcutItemTitle</key>
<string>STOP</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Stop playback</string>
<key>UIApplicationShortcutItemType</key>
<string>StopMusic</string>
</dict>
Can some one please help where I am doing wrong?
A: since iOS(13.0, *) AppDelegate handles its own UIWindow via SceneDelegate's and so the method
@implementation AppDelegate
-(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
// here shortcut evaluation below ios(13.0)
}
@end
is only invoked on iPhones or iPads with iOS lower Version 13.0
So to make it work in iOS(13.0,*) and above you need to implement it in SceneDelegate with a slightly different name, see below.. (matt was right!)
@implementation SceneDelegate
-(void)windowScene:(UIWindowScene *)windowScene performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
// here shortcut evaluation starting with ios(13.0)
NSLog(@"shortcutItem=%@ type=%@",shortcutItem.localizedTitle, shortcutItem.type);
}
@end
PS: The Apple Example Code for Quick Actions in swift is bogus when you assume you can use it as is in iOS(13.0,*) because it is written for versions earlier iOS < 13.0
EDIT: as asked, here in full beauty for iOS >= 13.0
@interface SceneDelegate : UIResponder <UIWindowSceneDelegate>
@property (strong, nonatomic) UIWindow * window;
@end
and
-(void)windowScene:(UIWindowScene *)windowScene performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
/* //go to Info.plist open as Source Code, paste in your items with folling scheme
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypePlay</string>
<key>UIApplicationShortcutItemTitle</key>
<string>Play</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Start playback</string>
<key>UIApplicationShortcutItemType</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).Start</string>
</dict>
<dict>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypePlay</string>
<key>UIApplicationShortcutItemTitle</key>
<string>STOP</string>
<key>UIApplicationShortcutItemSubtitle</key>
<string>Stop playback</string>
<key>UIApplicationShortcutItemType</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER).Stop</string>
</dict>
</array>
*/
// may look complex but this is 100% unique
// which i would place $(PRODUCT_BUNDLE_IDENTIFIER). in front of types in Info.plist
NSString *devIdent = [NSString stringWithFormat:@"%@.",NSBundle.mainBundle.bundleIdentifier];
if ([shortcutItem.type isEqualToString:[devIdent stringByAppendingString:@"Start"]]) {
completionHandler([self windowScene:windowScene byStoryBoardIdentifier:@"startview"]);
} else if ([shortcutItem.type isEqualToString:[devIdent stringByAppendingString:@"Stop"]]) {
completionHandler([self windowScene:windowScene byStoryBoardIdentifier:@"stopview"]);
} else {
NSLog(@"Arrgh! unrecognized shortcut '%@'", shortcutItem.type);
}
//completionHandler(YES);
}
-(BOOL)windowScene:(UIWindowScene *)windowScene byStoryBoardIdentifier:(NSString *)identifier {
// idear is to return NO if build up fails, so we can startup normal if needed.
UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
if (story!=nil) {
UIViewController *vc = [story instantiateViewControllerWithIdentifier:identifier];
if (vc!=nil) {
if (_window==nil) _window = [[UIWindow alloc] initWithWindowScene:windowScene];
_window.rootViewController = vc;
// .. OR following code..
//[_window.rootViewController presentViewController:vc animated:YES completion:^{ }];
//[_window makeKeyAndVisible];
// should be success here..
return YES;
}
}
// no success here..
return NO;
}
You can do also other things than instantiate a ViewController from Storyboard. In example you could switch a property or something similar.
A: Sorry being too late. Further research about home quick actions showed me the following conclusions after discussing with major developers . The following points which needed to be followed while integrating HomeQuickActions are :
*
*Most Important point for every developer: Home quick actions(short cut items on clicking app icon) are definitely OS and hardware based (supported only from iOS 13). Apple documents. It means before iOS 13 no device will show app short cut items even if they have Haptic Touch / 3D Touch. iOS 13 and above is a mandatory requirement.(Checked in Simulator for all iPhone, need to test in real device with older phones)
Both 3D touch enable and non-3D touch enabled devices support this feature through force-touch or long-press depending on device capabilities if they are capable of running iOS 13 or above.
*So for App short cuts to work the iOS devices must be having iOS 13 for sure and the hardware compatibility is also required which means the devices must be having iOS 13 and above for App short cuts to work. For iPhone 5S, iPhone 6 owners: iOS 13 won't be compatible anymore.
*Since Apple has replaced 3D Touch hardware with Haptic Touch , the newer iPhones from iPhone XR will have only Haptic Touch . Old devices after SE(1 st generation, iPhone 6 series till iPhone X ) have 3D Touch hardware. Haptic Touch is a software OS dependent which uses finger pressed area and 3D Touch is a hardware dependent which uses a specific sensor between screen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64792591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which is a good library/framework to use for single sign on in a java web app with ADFS 2 integration We are currently exploring OpenAM & Shibboleth.
Our app is not built using Spring and we are not exploring use of Spring.
A: In terms of libraries, the only one I know of is OpenSAML.
I wouldn't call things like OpenAM a framework. They are actually products. Both these work with ADFS. Be warned that it is not a trivial task to install and configure these.
Another good product is Ping Identity.
There's also a set of Step-by-Step and How To Guides.
A: In case your are considering openam here is the link.
https://wikis.forgerock.org/confluence/display/openam/Integrate+OpenAM+with+Shibboleth
Also there are few more links on how to install openam as IDP
https://wikis.forgerock.org/confluence/pages/viewpage.action?pageId=688150
-Ram
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11755196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to interact with another android app in tamper-proof way I am developing an app, which is soft dependent on what a user does in another app. E.g. my app may allocate a reward to to a user who shares our image on Instagram.
What can be the best way for my app to verify that the user has done this action. Let's say no API is available for me to verify existence of such a post on Instagram.
a) Does android allow one app to programmatically interact with another. To what extent this depends on what the other app allows, vs certain general features of the platform which are always true irrespective of other app's intention of preventing such interaction?
b) Secondly, if I go the brute force way (provided user permits), can I simulate user actions and launch the other app and interact with it on behalf of the user, much like using the Win32 API and simulating a mouse click or keyboard input?
c) Basically, I just want a screen shot of the user showing me the post has been shared. My simplest goal is to verify that the screenshot is indeed from the other app, and not a static image or a fake app looking like the original?
Any guidance or general advice would be greatly appreciated.
Thanks
Asif
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68331876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Netbeans: Launch web application into PC host name and not localhost Anyone know if there's a way to have netbeans launch the website using url
http://mycomputer.domain.com:8080/mywebapp
instead of
http:// localhost :8080/mywebapp ?
I've tried editing the server.xml and other references to localhost but it doesn't work or i've missed something.
This is in Linux Mint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17336818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TextBoxes randomly disappearing I have developped an Outlook addin in order to transfer some mails to an external ERP and all was working fine until some months ago. Since then, on one of the dozens computers on which it works perfectly fine, three TextBoxes started to randomly disappear.
I've put some log, since it's impossible to reproduce within my debug environment, and today I've found something that could be the problem, but I have no idea on how to fix it:
When they fail, the CanFocus property value of those three components are false, while Enabled and Visible are both true and the Handle property is properly set. I've read here that those properties were mandatory to allow focusing on a component. Of course when all goes fine, the CanFocus value is true.
The fix I had already tried was simply executing the following code in the Form on Shown event :
txtField1.Show();
txtField2.Show();
txtField3.Show();
txtField1.Visible = true;
txtField2.Visible = true;
txtField3.Visible = true;
this.Refresh();
Where textFields are extended TextBoxes and this refers to the parent Form of those fields. This code is called when form is shown or when a dedicated button is clicked.
Strangest thing, we had the problem on Windows 7 with a 2016 Outlook, migrated it to Windows 10 hoping it would resolve it and finally even installed a brand new desktop with a fresh Windows 10 and Office 2016, and the bug is still there, only for this specific user...
Has someone an idea of what could go wrong ? or any methods to force the showing of thoses components ?
Thanks in advance !
EDIT : After Jimi's comment, I've added some logs to be sure that all the hierachy is Visible, Enabled and has an Handle. After analyzing the new logs, it appears that the whole hierarchy except for the three fields has all those three property in a valid state and the CanFocus property of each member is true.
Here is the logged hierarchy :
Logging object of Type Hermod2._0.clsCustomAutoCompleteTextbox : Hermod2._0.clsCustomAutoCompleteTextbox, Text:
Property AutoSize : True
Property CanFocus : False
Property ClientSize : {Width=281, Height=16}
Property Enabled : True
Property Handle : 3279192
Property Height : 20
Property Name : txtPartner
Property Parent : System.Windows.Forms.GroupBox, Text: Dossier détecté
|=> Logging object of Type System.Windows.Forms.GroupBox : System.Windows.Forms.GroupBox, Text: Dossier détecté
|=> Property AutoSize : False
|=> Property CanFocus : True
|=> Property ClientSize : {Width=458, Height=113}
|=> Property Enabled : True
|=> Property Handle : 2952070
|=> Property Height : 113
|=> Property Name : groupBox2
|=> Property Parent : System.Windows.Forms.Panel, BorderStyle: System.Windows.Forms.BorderStyle.None
|=> Logging object of Type System.Windows.Forms.Panel : System.Windows.Forms.Panel, BorderStyle: System.Windows.Forms.BorderStyle.None
|=> Property AutoSize : False
|=> Property CanFocus : True
|=> Property ClientSize : {Width=778, Height=399}
|=> Property Enabled : True
|=> Property Handle : 4130368
|=> Property Height : 399
|=> Property Name : panel1
|=> Property Parent : Hermod2._0.CaseSearch, Text: Recherche de dossier
|=> Logging object of Type Hermod2._0.CaseSearch : Hermod2._0.CaseSearch, Text: Recherche de dossier
|=> Property AutoSize : False
|=> Property ClientSize : {Width=783, Height=405}
|=> Property Size : {Width=799, Height=444}
|=> Property CanFocus : True
|=> Property Enabled : True
|=> Property Handle : 1379040
|=> Property Height : 444
|=> Property Name : CaseSearch
|=> Property Parent :
|=> Can't log object, it's null...
|=> Property Visible : True
|=> Property Width : 799
|=> Property PreferredSize : {Width=798, Height=442}
|=> Property Size : {Width=778, Height=399}
|=> Property Visible : True
|=> Property Width : 778
|=> Property PreferredSize : {Width=771, Height=358}
|=> Property Size : {Width=458, Height=113}
|=> Property Visible : True
|=> Property Width : 458
|=> Property PreferredSize : {Width=457, Height=115}
Property Size : {Width=285, Height=20}
Property Visible : True
Property Width : 285
Property PreferredSize : {Width=54, Height=20}
Here is a screenshot of the components when all goes right :
And here is the screenshot of the exact same zone where it goes wrong :
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61779478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twistd TAP change log verbosity I am currently writing an application that is meant to be started using Twisted's twistd script as a plugin.
However my code is currently very verbose logging quite a bit of information. When running my application a a twistd pluging is there any way that I can filter the log messages and offer different levels of log verbosity to the user?
Update
After digging through all the twisted logging documentation I've decided to reduce the verbosity by using global flags to disable log messages.
So to rephrase my question it would have to be how can I reduce the verbosity of twisted itself. Currently twisted tells you every time a factory is created or destroyed, along with a lot of detail. I would like to reduce this verbosity, and also change the way additional detail is displayed.
Also it would be nice if I could add logging levels to my code, instead of completely disabling log messages, but this is not necessary.
Hope this clears things up a little bit.
A: If you want a factory to not tell you when it builds a new protocol, you can just set its noisy to False. See http://twistedmatrix.com/trac/browser/tags/releases/twisted-11.0.0/twisted/internet/protocol.py#L35 -- I am not sure if this is what you were asking.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6190166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Adding Subject to Lync Chat from javascript using sip action I am able to open lync for a particular user on intranet which is perfectly working fine using :
sip:[email protected]
But i am looking if i can initiate the lync with some subject from javascript , anything like the following:
sip:[email protected]?subject='this is subject'
Is there anything that sip/lync support in this regard ?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50116489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jmeter not considering local domain in Server name or IP while test script recorder with Mozilla I am using Jmeter 4.0 for the first time and when I am trying for test recording with Mozilla linked to Jmeter, i am able to record .net and .com sites but I am unable to test my application deployed in the server and having the URL with server domain which is not a generic site like .net and .com.
Please let me know how I can test my server's domain URLs through Jmeter.
A: Sounds like this is a proxy issue, in order to isolate it, if possible and then host the application on the local box and then try to record it, it will work.!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51297796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CentOS7: copy file and preserve SELinux context In order to configure my CentOS system, I'd like to overwrite an arbitrary file preserving almost every attribute but timestamp and content.
As an example, I'll use /etc/phpMyAdmin/config.inc.php
Note: file being copied is in other filesystem
[root@localhost phpMyAdmin]# ls -laZ /etc/phpMyAdmin/
drwxr-x---. root apache system_u:object_r:etc_t:s0 .
drwxr-xr-x. root root system_u:object_r:etc_t:s0 ..
-rw-r-----. root apache system_u:object_r:etc_t:s0 config.inc.php
[root@localhost phpMyAdmin]# /bin/cp -frv --backup=numbered --preserve=mode,ownership,context,xattr config.inc.php /etc/phpMyAdmin/config.inc.php
«config.inc.php» -> «/etc/phpMyAdmin/config.inc.php» (respaldo: «/etc/phpMyAdmin/config.inc.php.~1~»)
[root@localhost phpMyAdmin]# ls -laZ /etc/phpMyAdmin/
drwxr-x---. root apache system_u:object_r:etc_t:s0 .
drwxr-xr-x. root root system_u:object_r:etc_t:s0 ..
-rw-r-----. root apache system_u:object_r:unlabeled_t:s0 config.inc.php
-rw-r-----. root apache system_u:object_r:etc_t:s0 config.inc.php.~1~
[root@localhost phpMyAdmin]# systemctl restart httpd
When I tried http://localhost/phpmyadmin, fist time I get a SELinux warning, and Apache can't access the file.
[root@localhost phpMyAdmin]# chcon --reference /etc/phpMyAdmin/config.inc.php.~1~ /etc/phpMyAdmin/config.inc.php
[root@localhost phpMyAdmin]# ls -laZ /etc/phpMyAdmin/
drwxr-x---. root apache system_u:object_r:etc_t:s0 .
drwxr-xr-x. root root system_u:object_r:etc_t:s0 ..
-rw-r-----. root apache system_u:object_r:etc_t:s0 config.inc.php
-rw-r-----. root apache system_u:object_r:etc_t:s0 config.inc.php.~1~
[root@localhost phpMyAdmin]# systemctl restart httpd
Now apache can read the file.
How can I make cp preserve the SELinux context of the original file?
A: according to the cp documentation, the switch "--preserve=context" allows to copy the Selinux context as well during the process.
Please have a look to this excellent documentation from redhat, it explains the topic wonderfully in an human language:
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security-Enhanced_Linux/sect-Security-Enhanced_Linux-Working_with_SELinux-Maintaining_SELinux_Labels_.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43867771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: select only one value in 1:N relation i want to have only one value in the result of the query which is the first value, or the last value, i tried many things but i coudnt resolve it, the query is too long but i picked for you only the part where i am stucked.
select eccev.extra_data , c.id,
case when (eccev.extra_data::json->'tns')::VARCHAR = 'false'
then 'NON'
else case when coalesce((eccev.extra_data::json->'tns')::VARCHAR, '') = '' then 'EMPTY VALUE' else 'OUI'
end end as tns
from endorsement_contract_covered_element_version eccev, endorsement_contract_covered_element ecce, endorsement_contract ec, contract c, endorsement e, party_party pp
WHERE ec.endorsement = e.id
and e.applicant = pp.id
and c.subscriber = pp.id
AND eccev.covered_element_endorsement = ecce.id
and ecce.contract_endorsement = ec.id
and c.contract_number = 'CT20200909112'
with this query i have the result
{"qualite":"non_etu","tns":false} 199479 NON
{"qualite":"non_etu","tns":false} 199479 NON
{"qualite":"non_etu","tns":false} 199479 NON
i want to have only the first or the last row so i dont have repetition on the other rows, i saw that we can use first_value(X over (XX)) but i couldnt make it.
if u guys can help me, i would be gratefull
Thanks
A: you can try this
select distinct on (eccev.extra_data , c.id) eccev.extra_data , c.id, case when ...
but your query seems not optimized as you cross join 6 tables all together ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69709231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Serialization detection? class MyClass implements Serializable{}
What must I write so that the Object knows when it is getting serialized and deserialized to do something before getting serialized and after getting deserialized?
A: You can use readObject and writeObject methods for this purpose. writeObject method will be executed when serializing your object reference.
Basically, you will do it like this:
public class MyClassToSerialize implements Serializable {
private int data;
/* ... methods ... */
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWrite(); //serialization of the current serializable fields
//add behavior here
}
}
More info on the usage of these methods: http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serialTOC.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32127487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image compresser webp in angular I am working on uploading images that are mostly taken from Hi-Res Cameras. But it is really increasing the upload time since the file sizes are 5-10MB
I am using angular & I want to compress the image without loss in quality. I came across WebP and thought of implementing a convertor.
I tried using the webp-converter but its not working with angular....so any idea or any other plugin that can help me to overcome this issue.
A: you can donwload a converter https://developers.google.com/speed/webp/download for the images, also you can use some online converter like https://cloudconvert.com/webp-converte
for me it doesn't make sense if you want to convert on your angular app the images(tecnically angular doesnt serve images it creates a small server cos angular is a front end framework), cos the computer cost of the convertion it's even heavier than serve heavy images, so the solution is =>
First, convert your images, and then use them on your angular project, from a cdn or serve it static replacing your static images...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70935723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Godaddy subdomain issue with htaccess I'm trying to understand what's wrong with my htaccess file. I'm placing my site under a subdomain in which the subdomain points to the www folder. The folder structure of the site is:
project
----app (controllers, models, etc)
----www (index.php, js, styles)
The htaccess is:
RewriteEngine On
RewriteRule ^(tmp)\/|\.ini$ - [R=404]
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA,E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
This works fine locally for development, but not on Godaddy. Any idea where I'm going wrong?
Thanks
A: Figured it out. I was missing RewriteBase /.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36463282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pickle in python, writing to files if group == 10G2:
file_name='10G2 Scores.txt'
fileObject = open(file_Name,'wb')
pickle.dump(+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
This is part of a maths quiz and I am trying to write scores to a text file. It says there is a syntax error on the 10G2?
All of the variables have been defined and I have imported pickle
Thanks in advance. BTW, I'm doing GCSE computing.
This is my whole code:
#Maths Quiz
noq=0
score=0
import math
import pickle
import random
import time
import pickle
def write(name, finalscore, totalquestions, score, file_Object):
pickle.dump ((str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,file_Object)
return
group=input("What mentor group are you in?: ")
name=input("What is your name?: ")
print ("Hello " + name + ". How many questions would you like to do?:")
totalquestions=int(input(" "))
for i in range (0,(totalquestions)):
noq=noq+1
print ("Question " +str(noq))
numberone=random.randint(1, 10)
numbertwo=random.randint(1, 10)
answer=int(numberone) + int(numbertwo)
print ("What is " +str(numberone) + "+" + str(numbertwo) + "?:")
uanswer=int(input(""))
if answer==uanswer:
print("That is correct!!!")
score=score +1
print ("Your score is.....")
time.sleep(0.5)
print("" +str(score) + " out of " + str(i+1))
time.sleep(1)
else:
print ("Sorry, that is wrong!!!")
score=score
print ("Your score is.....")
time.sleep(0.5)
print ("" +str(score) + " out of " + str(i+1))
time.sleep(1)
time.sleep(0.5)
print ("Your final score is.....")
finalscore=score/totalquestions
finalscore=finalscore*100
time.sleep(3)
print ("" +str(finalscore)+ " percent")
#file write###############################################################################
if group == 10G2:
file_name='10G2 Scores.txt'
fileObject= open(file_Name,'w')
pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
elif group == 10G1:
file_name='10G1 Scores.txt'
fileObject = open(file_Name,'w')
pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
elif group == 10G3:
file_name='10G3 Scores.txt'
fileObject = open(file_Name,'w')
pickle.dump((+str(name) + ' got ' + str(finalscore) + ' percent from ' + str(totalquestions) + ' question(s), this is ' + str(score) + ' out of ' + str(totalquestions) + '.') ,fileObject)
fileObject.close()
elif group == 10G4:
file_name='10G4 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
elif group == 10G5:
file_name='10G5 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
elif group == 10G6:
file_name='10G6 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
elif group == 10G7:
file-name='10G7 Scores.txt'
fileObject = open(file_Name,'w')
write ()
fileObject.close()
A: Try changing this line
if group == 10G2:
to:
if group == '10G2':
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33858690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Logging a literal message in NLog and/or Serilog UPDATE: This turned out to be a discrepancy that exists in Serilog (which I tunnel to), but does not exist in NLog, which treats a single argument as a verbatim string (as one (and specifically, I) might expect)
Using NLog, if I want to log something potentially containing embedded double braces: {{ without having them collapsed, what's the most efficient way?
e.g.:
NLog.LogManager.GetLogger("x").Warn("{{\"aaa}}")
emits in my custom serilog-target:
{"aaa}
And I want:
{{"aaa}}
Is
NLog.LogManager.GetLogger("x").Warn("{0}","{{\"aaa}}")
the best way or is there a more efficient way ?
UPDATE: no such tricks required:
NLog.LogManager.GetLogger("x").Warn("{{\"aaa}}")
... does indeed just work!
(This is not (just) me being pedantic, its a follow-on from a question regarding a high perf/throughput requirement)
A: Turns out the question is wrong. The code above works in NLog - a single string is not treated as a message template and is rendered verbatim.
I was tunneling it thru to Serilog per the linked question, and Serilog was doing the collapsing I show the effects of in the question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49678739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Proper use of Class Inheritance Javascript OOP There seems to be some problem on my syntax but I don't know what seems to be the problem.
I am using prototyping inheritance (if I'm not mistaken)
The program should be like this:
*
*The class must inherit the features of the parent, so when I call on the function it will display some text.
Here is what my code looks like:
function myFunction() {
var Property = function(dom,height,width){
this.dom = document.createElement("img");
this.height = height;
this.width = width;
};
Property.prototype.display = function() {
text("The image has: ", this.height+200, this.width+200);
};
Image.prototype = Object.create(Property.prototype)
var firstImage = function(dom,height,width){
Property.call(this, dom, height,width);
};
var image1 = new Image("image.jpg", 10 , 10);
image1.display();
}
A: (I think naomik's is the better approach, but if you are trying to just figure out what's happening, see the following:)
Apparently Image does not allow extension (at least in Firefox where I am testing) because it does work with another class.
If, after this line...
Image.prototype = Object.create(Property.prototype)
...you add:
alert(Image.prototype.display)
...you will see that it is undefined, whereas if you add:
function MyImage () {}
MyImage.prototype = Object.create(Property.prototype)
alert(MyImage.prototype.display); // Alerts the "display" function
I guess that is because you cannot replace the whole prototype. Try adding to the prototype instead (though this won't help with the constructor).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22265001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set SelectedValue in combobox that populated from Data Table in c#? I have a Combobox in my form. This Combobox is populated with values from a table(Faculty) in the database.
I need to set the SelectedValue of this Combobox based on the record in another table(student). Both tables are in the same database.
I tried to set SelectedValue using the value getting from student table
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
but it didn't work.
So far I was only able to populate the Combobox ,
// --- populate faculty cmb ---
MySqlCommand cmdCmb = new MySqlCommand("SELECT facultyname FROM faculty;", db.getConnection());
db.openConnection(); // open connection
using (var reader = cmdCmb.ExecuteReader())
{
while (reader.Read())
{
cmbfaculty.Items.Add(reader.GetString("facultyname"));
}
}
but unable to set SelectedValue.
string sQuery = "SELECT indexno,faculty FROM student WHERE indexno ='"+selected+"'";
MySqlCommand cmd = new MySqlCommand(sQuery, db.getConnection());
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
txtindex.Text = table.Rows[0][0].ToString();
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
Hoping to fix the issue.
EDIT:
Able to do that by finding the item that exactly matches the specified
string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;
Are there any other ways to archieve this.
A: Able to do that by finding the item that exactly matches the specified string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61358613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Xcode UIProgressBar does not increment I am trying to increment progress bar and show percentage on a label. However, both remains without changes when "incrementaProgres" function is called. IBOutlets are properly linked on xib and also tested that, when function is called, variables have proper value. Thanks
from delegate:
loadingViewController *theInstanceP = [[loadingViewController alloc] init];
[theInstanceP performSelectorOnMainThread:@selector(incrementaProgres:) withObject:[NSNumber numberWithFloat:0.15] waitUntilDone:YES];
loadingView class:
- (void)viewDidLoad
{
[super viewDidLoad];
[spinner startAnimating];
[progress setProgress:0.0];
}
- (void)incrementaProgres: (CGFloat)increment{
[progress setProgress:(progresInc + increment)];
carrega.text = [NSString stringWithFormat: @"%f", (progresInc + increment)];
}
A: Progress bar's progress value is between 0.0 and 1.0, your code sets it in the increments of 15.0, which is out of range. Your increment should be 0.15, not 15.0.
A: Progress is a value between 0.0 and 1.0.
Edit:
Did you try to call [myView setNeedsDisplay];?
2nd Edit:
Maybe there is one confusion: viewDidLoad is called right before you are presenting the view. Therefore in the code you have shown here incrementaProgres: is called before viewDidLoad.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10121715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Best way to deploy an application that comes with lots of data I'm working on an Android application that will come with lots of data. I'd have expected to just distribute the SQLite database, but it's clear from researching this that the database can be included, but must be copied from raw to data, which if there's a good few MB of data will take up space needlessly. For my app the data is all text/numeric/date, and in a relational database would normally take up four tables. So pretty simple, but having two copies of it seems v wasteful.
The options I see are:
*
*Tolerate the data being duplicated (it pains me)
*On installation the app downloads the data over HTTP (I'd then have a potential challenge with the load), probably Google App Engine.
Any other solutions worth considering?
A: If you package your data into your res/raw folder, it will indeed be duplicated and unfortunatley cannot be removed once the phone is done with it ie after first run.
You could experiment which is a smaller in size - packaging the data as a csv or xml file or as a precompiled DB in the res/raw folder and if acceptible go with the best.
If you went with the csv or xml file option, you could run a parser on first run and process the data into a DB.
Something I only found recently but the res/raw folder can only handle files of around 1mb, this is one solution I came across for packaging a large DB and moving it on first run, it doesn't get over the repition of data within the app:
Database Populating Solution
Here is an alternative from the android blogspot, the third one down maybe exactly what you are looking for:
The downloader activity runs at the
beginning of your application and
makes sure that a set of files have
been downloaded from a web server to
the phone's SD card. Downloader is
useful for applications that need more
local data than can fit into an .apk
file.
Downloader Blogspot
Possibly adapt this example - download the DB file from the server and then move it into your database folder.
A: I was confronted to the same kind of situation: I am writing an app which has to access - locally – a database containing mainly text and weighing more than 20MB (7MB zip compressed).
The best solution in my opinion for this kind of problem is to download the zipped compiled database on first execution of the app.
The advantages of this solution:
*
*The APK stays light. This is a good because:
*
*very large APKs may discourage some potential users
*testing is faster, as uploading a 7MB+ APK to an AVD (as I did initially) is pretty SLOW.
*
*There is no duplicate of your data (if you take care of deleting the ZIP archive after extracting it
*
*You don’t fill up your users phones internal memory. Indeed, your app should download the database directly to the SD CARD. Including big files in res/raw folders would cause much trouble to all users who run Android < 2.2, as they won’t be able to move the app to the SD CARD (I’ve seen several negative user comments due to this on some apps that use a few MBs on the internal memory).
One last thing: I don’t recommend including a CSV or XML and populate the database from it on first run. The reason being this would be very SLOW, and this kind of processing is not supposed to be done by every client.
A: Not a proper answer, but on the subject of option 1: remember an apk is a zip, so a text file, containing the same words over and over, would become a lot smaller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4010238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Create categorical variable from previous columns in R I have been trying to create a new categorical variable from previous binary variables. All the binary variables I'm trying to include (cough, fever, etc...) have values of either '1' or '0'.
This is the code I've been trying:
symptoms<-ifelse(cough==1,"cough",ifelse(fever==1,"fever",ifelse(diarrhea==1,"diarrhea",ifelse(dispnea==1,"dispnea",ifelse(neurologic==1,"neurologic",ifelse(otherSymp==1,"other symtomes", NA))))))
The problem is that the output results in only 4 categories, not 6.
I know this is a basic question, sorry and thank you in advance.
A: As mentioned in the comments, case_when is a helpful alternative to many nested ifelse calls:
library(dplyr)
# Create sample dataset
df <- data.frame(cough = c(1, 0, 0, 0, 0, 0, 0, 1),
fever = c(0, 1, 0, 0, 0, 0, 0, 1),
diarrhea = c(0, 0, 1, 0, 0, 0, 0, 1),
dyspnea = c(0, 0, 0, 1, 0, 0, 0, 1),
neurologic = c(0, 0, 0, 0, 1, 0, 0, 0),
otherSymp = c(0, 0, 0, 0, 0, 1, 0, 0))
# Create categorical variable
df |> mutate(symptom = case_when(cough == 1 ~ "cough",
fever == 1 ~ "fever",
diarrhea == 1 ~ "diarrhea",
dyspnea == 1 ~ "dyspnea",
neurologic == 1 ~ "neurologic",
otherSymp == 1 ~ "other",
TRUE ~ "none"))
Output
#> cough fever diarrhea dyspnea neurologic otherSymp symptom
#> 1 1 0 0 0 0 0 cough
#> 2 0 1 0 0 0 0 fever
#> 3 0 0 1 0 0 0 diarrhea
#> 4 0 0 0 1 0 0 dyspnea
#> 5 0 0 0 0 1 0 neurologic
#> 6 0 0 0 0 0 1 other
#> 7 0 0 0 0 0 0 none
#> 8 1 1 1 1 0 0 cough
Created on 2022-07-11 by the reprex package (v2.0.1)
However, this is a very basic solution, which assumes that you can't have more than one symptom (unreasonable) - if you have more than one, symptom will only mention the first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72666197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Keras time series can I predict next 6 month in one time I use keras for time series prediction. My code can predict next 6 months by predict next one month and then get it to be input for predict next month again untill complete 6 months. That means predict one month 6 times. Can I predict next 6 month in one time.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import LSTM
from pandas.tseries.offsets import MonthEnd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout
import keras.backend as K
from keras.layers import Bidirectional
from keras.layers import Embedding
from keras.layers import GRU
df = pd.read_csv('D://data.csv',
engine='python')
df['DATE_'] = pd.to_datetime(df['DATE_']) + MonthEnd(1)
df = df.set_index('DATE_')
df.head()
split_date = pd.Timestamp('03-01-2015')
train = df.loc[:split_date, ['data']]
test = df.loc[split_date:, ['data']]
sc = MinMaxScaler()
train_sc = sc.fit_transform(train)
test_sc = sc.transform(test)
X_train = train_sc[:-1]
y_train = train_sc[1:]
X_test = test_sc[:-1]
y_test = test_sc[1:]
K.clear_session()
model = Sequential()
model.add(Dense(12, input_dim=1, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.summary()
model.fit(X_train, y_train, epochs=200, batch_size=2)
y_pred = model.predict(X_test)
real_pred = sc.inverse_transform(y_pred)
real_test = sc.inverse_transform(y_test)
print("Predict Value")
print(real_pred)
print("Test Value")
print(real_test)
A: Yes, by changing your output layer (the last layer) from Dense(1) to Dense(6). Of course you also have to change your y_train and y_test to have shape (1,6) instead of (1,1).
Best of luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53252152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I filter a list of words (string) by if the list element contains a string at a specific index? Say I have a word list of thousands of words. But, they're all the same length. so say for example, all 5 letter words, and I want to find all the words that have 'o' as the middle letter (3rd position, 2nd in the index since it starts from 0).
How do I go about removing all the other words in the original list so we can prune it down from there?
I'll be doing this multiple times, up to 4 times in this case, since the words would all be 5 letters exactly.
So it's like original_list = ["house", "ghost", "there", "loose"] -- stuff like that. And my output should be original_list = ["ghost", "loose"]
Ideally instead of appending to a new list, I'd rather just remove items that don't match from the original list. That way I can keep pruning it down from there in each iteration.
A: Maybe try an iterative approach?
from typing import List
def remove_words(words: List[str]):
index = 0
while index < len(words):
if words[index][2] != 'o':
words.pop(index)
else:
index += 1
# return words -- OPTIONAL
if __name__ == "__main__":
original_list = ["house", "ghost", "there", "loose"]
remove_words(original_list)
print(original_list) # ['ghost', 'loose']
Note on Performance
While the solution above answers the OP, it is not the most performant nor is it a "pure function" since it mutates external scope state (https://en.wikipedia.org/wiki/Pure_function).
from timeit import timeit
def remove_words():
# defining the list here instead of global scope because this is an impure function
words = ["house", "ghost", "there", "loose"]
index = 0
while index < len(words):
if words[index][2] != 'o':
words.pop(index)
else:
index += 1
def remove_words_with_list_comprehension():
# defining the list here to ensure fairness when testing performance
words = ["house", "ghost", "there", "loose"]
return [word for word in words if word[2] == 'o']
if __name__ == "__main__":
t1 = timeit(lambda : remove_words_with_list_comprehension(), number=1000000)
t2 = timeit(lambda : remove_words(), number=1000000)
print(f"list comprehension: {t1}")
print(f"while loop: {t2}")
# OUTPUT
# list comprehension: 0.40656489999673795
# while loop: 0.5882093999971403
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74032096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Run scheduler using spring I have rest api. A starttime is passed to this rest api. I want to schedule a job after that particular time. This job will run only once. My application where I need to add this feature runs as windows service. I have written some code but that is never scheduled. Please advise.
@Component
@Path("/appcheck")
@Api(value = "/appcheck")
public class ApplicationCheckImpl extends RestEndpoint
implements ApplicationCheckApi {
@POST
@Path("/check")
@ApiOperation(value = "Check",notes = "Sample Check", response = java.lang.String.class)
@ApiResponses(value = {@ApiResponse(code = 400, message = "Bad values")})
public Response checkApp(
@ApiParam(value = "json", required = true)
String src,
@QueryParam("instances") Integer instances,
@QueryParam("scheduleTime") Integer scheduleTime,
@Context HttpServletRequest servletRequest) {
if (scheduleTime != null) {
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, scheduleTime);
Date startTime = now.getTime();
applicationCheckServiceApi.setStartTime(startTime);
applicationCheckServiceApi.setInstances(instances);
applicationCheckServiceApi.setScheduleTime(scheduleTime);
applicationCheckServiceApi.setServletRequest(servletRequest);
applicationCheckServiceApi.setSrc(src);
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ApplicationCheckConfiguration.class);
return applicationCheckServiceApi.getResponse();
}
ApplicationCheckConfiguration
@Configuration
@EnableScheduling
@ComponentScan(basePackages="com.abc")
public class ApplicationCheckConfiguration implements SchedulingConfigurer {
@Autowired
private ApplicationCheckServiceApi applicationCheckServiceApi;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler());
taskRegistrar.addTriggerTask(
new Runnable() {
public void run() {
myTask().work();
}
},
new Trigger() {
@Override public Date nextExecutionTime(TriggerContext triggerContext) {
return applicationCheckServiceApi.getStartTime();
}
}
);
}
@Bean(destroyMethod="shutdown")
public Executor taskScheduler() {
return Executors.newScheduledThreadPool(42);
}
@Bean
public MyTask myTask() {
return new MyTask();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24812634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Loss of precision in decimal display of double Why is there a discrepancy in the display of the following value?
double x = (double)988530483551494912L;
System.out.printf("%f%n", x); -> 988530483551494910.000000
System.out.println(Double.toString(x)); -> 9.8853048355149491E17
System.out.println(new BigDecimal(x)); -> 988530483551494912
As you can see, both toString() and the %f conversion lose the precision of the last digit. However, we can see that the last digit is actually precise, because the BigDecimal conversion preserves it.
A: Thanks to @user16320675's comment, I'm answering my own question. The reason is that the number 988530483551494912L has precision beyond the limit of the double type's precision, and Double.toString() (and similarly %f) will, as per documentation, only use the minimum number of significant digits required to distinguish a double number from adjacent numbers. Adjacent numbers are those that have the smallest representable difference from the original, on either side of it.
This can be demonstrated using Math.nextAfter to show the adjacent numbers:
import static java.lang.Math.nextAfter;
double x = (double)988530483551494912;
System.out.println(nextAfter(x, Double.MIN_VALUE)); ==> 9.8853048355149478E17
System.out.println(x); ==> 9.8853048355149491E17
System.out.println(nextAfter(x, Double.MAX_VALUE)); ==> 9.8853048355149504E17
So, as we can see, there is no point in adding any more significant figures because this string representation already has enough digits to distinguish the number from adjacent values.
However, a question still remains: it shows 17 significant figures, but 16 would be sufficient. I'm not sure why it issues an extra final digit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72393237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Catching return value from Tcl in batch This is my Tcl script
return 2
It is doing nothing, but just returning value 2. Now my batch script call this tcl file called foo.
tclsh foo.tcl
The return value can change from time to time and I need to get this value in the batch file. Is thr a way to do that. I am new to batch commands, so I dont have much idea about this. I tried if-else loop, but it gives syntax error. Any idea would be appreciated.
A: To get an external caller of Tcl to see a result code, you need exit and not return:
# In Tcl
exit 2
Then your caller can use the exit code handling built into it to detect. For example with bash (and most other Unix shells):
# Not Tcl, but rather bash
tclsh foo.tcl
echo "exit code was $?"
On Windows, I think it's something to do with ERRORLEVEL but it's a long time since I used that platform for that sort of thing. I just remember it being annoying…
A: It appears %ERRORLEVEL% is what you want:
C:\Users\glennj>tclsh
% exit 3
C:\Users\glennj>echo %ERRORLEVEL%
3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22701073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trying to upsert document in flask_MongoEngine I've currently got a model:
class Ticket(db.Document):
name = db.StringField #issue.key
project = db.StringField() #issue.fields.project.key
issue_type = db.StringField() #issue.fields.issuetype.name
summary = db.StringField() #issue.fields.summary
description = db.StringField() #issue.fields.description
created = db.DateTimeField() #issue.fields.created
updated = db.DateTimeField() #issue.fields.updated
And some code that attempts to upsert:
Ticket.objects(name=name).update(
upsert = True,
name = name,
project = project,
issue_type = issue_type,
summary = summary,
description = description,
created = created,
updated = updated
)
And I'm getting this error message:
mongoengine.errors.InvalidQueryError: Cannot resolve field "name"
With the relevant bit saying the error occurs in
updated = updated
So far I've tried re-naming the fields of my variables and my model, but the error message remains the same. Sorry for asking if there's an in my face answer I'm blind to.
Update: If I delete name = name from the update it works fine. I renamed name to title and re-added it and it does not work. I am thoroughly confused.
A: I'm a moron and left off parens on name in the model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45500147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress API works with VPN only? I'm working on a project on my localhost for sometime now, and i've recently tried to make it online. My project works perfectly on my localhost, and I can post new articles to wordpress blogs with no problem.
The problem is, after uploading my project to a online web server ( Hostgators Baby Plan ) , I tried to add a new post to one of my wordpress blogs and I got the following error :
faultCode 500 faultString You are not allowed to do that.
The thing is, I've searched everywhere in the past few days in-order to solve this problem and had no luck.
Do you guys think this problem is caused because i'm using a webserver and not a VPS? If you have any other solutions I'll be glad to hear them out.
A: It might be related to file permissions or something like that.
There is no need to use VPS. I manage my website on a shared server and I've tested WordPress on free hosting services too.
A: This is probably due to incorrect permissions either on the file structure or the mySQL DB user or something like that. Take a look at this article on the WP codex about file permissions.
Big services like Hostgater usually have an "auto-install" feature for common software like Wordpress (via Softaculous or something similar). I don't know how you migrated your site from your local version to the server but it may be worth installing a fresh Wordpress instance through Hostgator and then simply loading in the wp-content folder and your development database on top of that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14812900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL query to find maximum tax brackets I have a database table of tax brackets in a variety of locations with the fields: location, tax_bracket, and tax_rate.
I need to create a query that will return a list of countries, with their highest tax rate, that have at least one tax bracket with a tax rate over X.
How could I accomplish this?
A: Here is a sample to get you started, without knowing your schema:
Select
LocationName,
MaxTaxRate
FROM
(select
Max(tax_rate) as MaxTaxRate,
LocationName
from
MyLocations
group by
LocationName
) as MaxTable
You will have to join up with other information, but this is as far as I can go efficiently without more schema info.
A: select location, max(tax_rate) from tax_brackets where tax_rate > x group by location
the tax_rate > x should filter all tax_rates lower x, which means if the location has no tax_rates over x, they do not have at least one rate over x, which means they won't appear in the group by.
The group by should organize by location.
The select does location and max of those per location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7212793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: javax.servlet.http.Cookie vs javax.ws.rs.core.Cookie Being new to web development, I need some help in understanding what is the difference between the javax.servlet.http.Cookie and javax.ws.rs.core.Cookie.I assume that the latter can be used to set cookie into the response of a rest service. But can we also set the initial Cookie object into the HTTPServletResponse?
A: These are objects that represent the same underlying entity, namely an HTTP cookie as defined by the RFC. Both "do" the same thing, representing a cookie header in an HTTP response (a request cookie is a name=value pair only, whereas response cookies can have several additional attributes as described in the RFC). Where you use one vs the other is simply a matter of what you are coding. If you are writing a JAX-RS provider, then the JAX-RS apis will use javax.ws.core.Cookie. If you are writing an HttpServlet, then you use the javax.servlet.http.Cookie. JAX-RS implementations will also allow you to use context injection so that you can have direct access to the HttpServlet objects within your JAX-RS service provider
A: javax.servlet.http.Cookie is created and placed on the HTTP response object with the addCookie method.
Instead, the description for javax.ws.core.Cookie reads:
Represents the value of a HTTP cookie, transferred in a request
… so you'd expect the getCookies method on the HTTP request object to return an array of that type of cookies, but no, it returns an array of javax.servlet.http.Cookie. Apparently javax.ws.core.Cookie is used by some methods in the javax.ws.rs packages. So you use javax.ws.core.Cookie with jax-rs web services and javax.servlet.http.Cookie with HttpServlets and their request / response objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28565561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Running NPM install locally deletes required packages from my package-lock.json. This causes Git actions to fail when running NPM ci? When I run npm install, remove or add any package (or do anything that changes the local package.json) and commit to a PR branch, I get the following error in the github actions "run npm ci" build.
npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR!
npm ERR! Missing: [email protected] from lock file
npm ERR! Missing: @types/[email protected] from lock file
Things i've tried:
*
*Deleting node modules & package-lock.json & running npm i - DOESNT WORK
*Changing my github main.yml to npm ci --legacy-peer-deps - DOES FIX THIS BUG but causes other weird bugs about paths to other React components withing my project to not be found with a Type error: Cannot find module '../ etc" (they all work fine if the old package-lock is used)
*Pasting the old package-lock.json to overwrite my local copy and committing - WORKS? But I can never actually remove or add packages.
Running npm ci locally works perfectly fine.
In summary:
If I create a new branch from main > npm install a new package & push the updated package.json and package-lock.json to the branch > it fails the github actions check on npm ci with the above npm ERR because the package-lock.json does not match.
I'm stumped, any help would be greatly appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73815415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ code -calling a constructor of one class within a constructor of same class I am trying to compile this C++ code unfortunately, I failed to compile the code below. Can you help me by explaining why I am getting this error ?
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id)
{
strcpy(this->name,name); //string copy
this->id=id;
fee=0;
}
student(char name[10],int id,int fee)
{
student::student(name,id); //calling a constructor of one class
// within a constructor of same class
this->fee=fee;
}
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
Below is the error GCC is complaining about.:
main.cpp|20|error: cannot call constructor 'student::student' directly [-fpermissive]|
A: As rightly suggested by @sweenish, You must do the constructor delegation in the initialization section. Something like this:
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id)
{
strcpy(this->name,name); //string copy
this->id=id;
fee=0;
}
student(char name[10],int id,int fee): student(name, id) // constructor delegation
{
this->fee=fee;
}
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
Also, an advice for you. You may define the more specialized constructor and delegate the responsibility of less specialized constructors to more specialized ones.
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id, int fee): id{id}, fee{fee} // more specialized
{
strcpy(this->name,name); //string copy
}
student(char name[10],int id): student(name, id, 0) { } // less specialized calling the more specialized constructor
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
A: Here's your code with changes made to get it compiling; I marked the changes with comments.
#include <iostream>
// #include <cstring> // CHANGED: Prefer C++ ways when writing C++
#include <string> // CHANGED: The C++ way
// using namespace std; // CHANGED: Bad practice
class student {
private:
std::string name{}; // CHANGED: Move from C-string to std::string
int id = 0; // CHANGED: Default member initialization
int fee = 0;
public:
// CHANGED: Move from C-string to std::string
student(std::string name, int id)
: name(name),
id(id)
// CHANGED: ^^ Utilize initialization section
{
// CHANGED: Not needed anymore
// strcpy(this->name,name); //string copy
// this->id=id;
// fee=0;
}
student(std::string name, int id, int fee) : student(name, id) {
// CHANGED: Not needed anymore
// student::student(name,id); //calling a constructor of one class
// // within a constructor of same class
// NOTE: Inconsistency with other ctor w.r.t. this->
this->fee = fee;
}
void show() // print function
{
std::cout << "Name:" << name << '\n';
std::cout << "id:" << id << '\n';
std::cout << "fee:" << fee << "\n\n";
}
};
int main() {
student s1("DAVID", 123);
student s2("WILLIAM", 124, 5000);
s1.show();
s2.show();
return 0;
}
Here is the same code, but with the stuff I commented out removed to make it easier to read.
#include <iostream>
#include <string>
class student {
private:
std::string name{};
int id = 0;
int fee = 0;
public:
student(std::string name, int id) : name(name), id(id) {}
student(std::string name, int id, int fee) : student(name, id) {
this->fee = fee;
}
void show()
{
std::cout << "Name:" << name << '\n';
std::cout << "id:" << id << '\n';
std::cout << "fee:" << fee << "\n\n";
}
};
int main() {
student s1("DAVID", 123);
student s2("WILLIAM", 124, 5000);
s1.show();
s2.show();
return 0;
}
The initialization section follows the parameter list and is marked with :. You then initialize each member, in the order they are declared.
In the case of the constructor doing the delegating, you are unable to initialize fee in the initialization section. The error I receive is a delegating constructor cannot have other mem-initializers.
I don't like splitting my initialization like that, and if you insist on delegating constructor calls for this class, implement the most specific constructor and delegate to it with your less specific constructors. I prefer default member initialization as I think it leads to less confusion and written code overall.
The code then compiles and you get the expected output:
Name:DAVID
id:123
fee:0
Name:WILLIAM
id:124
fee:5000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67846046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.