text
stringlengths
15
59.8k
meta
dict
Q: Selenium.PhantomJS is invalid namespace I am really trying my best to find a way to web scrape a website using javascript to load the pages so I can scrape lets say my playlist for example. I have had no luck with chrome driver nor phantomjs. Please have a look below and see if you can help me with the error. using OpenQA.Selenium; //The type or namespace 'PhantomJS' does not exist in the namespace 'OpenQASelenium' using OpenQA.Selenium.PhantomJS; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MusicScaper { class TidalScraper { } } My packages.config file is as follows: <?xml version="1.0" encoding="utf-8"?> <packages> <package id="HtmlAgilityPack" version="1.8.7" targetFramework="net461" /> <package id="PhantomJS" version="2.1.1" targetFramework="net461" /> <package id="Selenium.Support" version="3.14.0" targetFramework="net461" /> <package id="Selenium.WebDriver" version="3.14.0" targetFramework="net461" /> </packages> A: So the simple answer to fix your issue is that when install the Selenium.WebDriver Nuget Package make sure its on version 3.11.2 as PhantomJS driver classes were removed in 3.14 (Had the exact same problem) as is no longer maintained. A: The .NET language bindings marked the PhantomJS driver classes deprecated in 3.11, and those classes were removed in 3.14. The PhantomJS project and its driver are no longer being maintained, and the driver code has not (and will not) be updated to support the W3C WebDriver Specification. The preferred β€œheadless” solution is to use Chrome or Firefox in headless mode, as both of those browsers and their drivers support such an operating mode. Alternatively, if you have your heart set on PhantomJS, and you don’t care about cross-browser execution, you can simply use the PhantomJS executable and automate it through its internal JavaScript API.
{ "language": "en", "url": "https://stackoverflow.com/questions/52442100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: float.TryParse not working I created program that calculates the currency exchange rate. The program has: * *ComboboxCurrencyName - which displays the currency name. *ComboCurrencyValue - which displays the value of a given currency. *txtYourValue - textbox which gets from user the amount of money *Button that calculates the rate of the given currency with the amount of money given from user. My code: public void EchangeRate(float x,float y) { label1.Text = (x * y).ToString(); } private void button1_Click(object sender, EventArgs e) { if(comboCurrencyName.SelectedIndex==comboCurrencyValue.SelectedIndex) { float currency; float inputValue; if(float.TryParse(comboCurrencyValue.SelectedItem.ToString(),out currency)&& float.TryParse(txtYourValue.Text,out inputValue)) { EchangeRate(currency,inputValue); } } else { MessageBox.Show("Not selected currency "); } } When I select a given currency with a combobox and I'm entering the value to convert, nothing happens when I press the button. I think this is a problem with converting combobox to float value. Previously I used float.Parse() I had the error: System.FormatException: 'Invalid input string format. Breakpoint A: Replace with: (float.TryParse(comboCurrencyValue.SelectedItem.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture,out currency)&& float.TryParse(txtYourValue.Text,out inputValue)) To explain: in Poland a comma is used instead of a decimal point, so you must specify that you want to use an invariant culture.
{ "language": "en", "url": "https://stackoverflow.com/questions/46207287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to import a single excel file/sheet with various Models (and sub-data/models) in Laravel? As per the title, I have a single excel file full of data (parent/child) in each row. The Laravel Excel site shows how to import, assuming a single model per row - but how does one import the child data? https://laravel-excel.maatwebsite.nl/3.1/imports/ eg 'pseudo' schema: Schema::create('students', function (Blueprint $table) { $table->increments('id')->unsigned()->index(); $table->string('student_code',16); $table->string('student_name',64); $table->string('student_surname',64); }); Schema::create('student_courses', function (Blueprint $table) { $table->increments('id')->unsigned()->index(); $table->integer('student_id')->unsigned()->index(); $table->string('course', 32); $table->date('start_date'); $table->date('end_date'); $table->timestamps(); }); Schema::create('student_contacts', function (Blueprint $table) { $table->increments('id')->unsigned()->index(); $table->integer('student_id')->unsigned()->index(); $table->string('contact_name', 32); $table->string('contact_number', 32); $table->timestamps(); }); Eg File: students.xlsx Student Code | Student Name | Student Surname | Course | Course Start Date | Course End Date | Contact Person | Contact Numbers ABC1 | Arnold | Clarp | C++ | 2019-01-01 | 2019-12-01 | Boogle | 555-111-222 DEF2 | Delta | Flork | English | 2019-01-02 | 2019-12-02 | Google | 555-111-333 GHI3 | Goblin | Clark | Science | 2019-01-03 | 2019-12-03 | Foogle | 555-111-444 Assuming my import code: class StudentsImport implements ToModel, WithStartRow { /** * @param array $row * * @return \Illuminate\Database\Eloquent\Model|null */ public function model(array $row) { return new Student([ 'student_code' => $row[1], 'student_name' => $row[2], 'student_surname' => $row[3], ]); } /** * @return int */ public function startRow(): int { return 2; } } Where would I actually go about plugging in the import of the "child" course/contact data? I'm guessing that instead of 'returning a new student' - I would actually first assign it to a variable, then import it then? Is this the correct way? eg: public function model(array $row) { $student = new Student([ 'student_code'=> $row[1], 'student_name'=> $row[2], 'student_surname'=> $row[3], ]) $student->courses()->create([ 'course'=>$row[4], 'start_date'=>$row[5], 'end_date'=>$row[6] ]); $student->contacts()->create([ 'contact_name'=>$row[7], 'contact_number'=>$row[8] ]); return $student; } //actual code as it stands, no longer 'pseudo': $student = new Student([ 'bursary_provider_id' => 1, 'bursary_provider_reference' => 'xxx', 'student_name' => $row[1], 'student_initials' => $row[3], 'student_surname' => $row[2], 'passport_number' => $row[7], 'passport_expiration' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[9]), 'country_id' => 7, 'id_number' => $row[6], 'status' => $status, 'notes' => $row[5] ]); if (isset($row[10])) { $student->visas()->create([ 'country_id' => 201, 'visa_reference_number' => $row[10], 'visa_expiration_date' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[11]) ]); Error (its not passing across the parent id) SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'student_id' cannot be null (SQL: insert into student_visas (country_id, visa_reference_number, visa_expiration_date, student_id, updated_at, created_at) values (201, ABCHFV4, 2019-12-31 00:00:00, , 2019-01-11 08:03:06, 2019-01-11 08:03:06)) A: You get the error because the student is not yet written to de database, so no id has been assigned to the new student instance. If you use collections the data is immediately written to the database. In the model function you can use $student=Student::Create(['bursary_provider_id' => 1, 'bursary_provider_reference' => 'xxx', 'student_name' => $row[1], 'student_initials' => $row[3], 'student_surname' => $row[2], 'passport_number' => $row[7], 'passport_expiration' => \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[9]), 'country_id' => 7, 'id_number' => $row[6], 'status' => $status, 'notes' => $row[5]]); This will write the student to the database and generate the neccessary id. I am not sure how this affects performance though. A: The answer, (and do not ask me why, because documentation is so poor at this stage) is to use collections. use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\ToCollection; and instead of ToModel: public function collection(Collection $rows) and it doesnt 'return' anything. Other than these changes, using the exact same code in OP works as intended.
{ "language": "en", "url": "https://stackoverflow.com/questions/54130017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why we need to use T-SQL over SQL when creating reports from Data Warehouse? Can someone tell me why we need to use T-SQL over SQL when creating reports from Data Warehouse? SQL also has functions and Joins but I see all of the online tutorials use T-SQL when creating reports from DW. Can it be done with SQL? If T-SQL is must, could you please explain why? In terms of what can T-SQL do that SQL cannot. Some useful tutorial links for T-SQL and creating reports would be great too! Thanks in advance~ A: Regardless the fact T-SQL has more functionality than plain SQL, in general data warehousing you have two main approaches: * *Put business logic closer to the data. This way you develop lots of T-SQL functions and apply many optimizations available there to improve performance of your ETL. Pros is greater performance of your ETL and reports. But cons are the cost of making changes to the code and migration cost. The usual case for growing DWH is migration to some of the MPP platforms. If you have lots of T-SQL code in MSSQL, you'll have to completely rewrite it, which will cost you pretty much money (sometimes even more than the cost of MPP solution + hardware for it) *Put business logic to the external ETL solution like Informatica, DataStage, Pentaho, etc. This way in database you operate with pure SQL and all the complex logic (if needed) is the responsibility of your ETL solution. Pros are simplicity of making changes (just move the transformation boxes and change their properties using GUI) and simplicity of changing the platform. The only con is the performance, which is usually up to 2-3x slower than in case of in-database implementation. This is why you can either find a tutorial on T-SQL, or tutorial on ETL/BI solution. SQL is very general tool (many ANSI standards for it) and it is the basic skill for any DWH specialist, also ANSI SQL is much simpler as it does not have any database-specific stuff
{ "language": "en", "url": "https://stackoverflow.com/questions/26672642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Swing Drawn Shapes Disappearing I'm making a game of Connect 4 in Java using Swing painted Graphics. The problem I'm having is that if I click a button under a designated column to add another tile to that column, the one underneath it disappears. Also, the color changes from red to yellow, but then stays yellow instead of changing back to red (supposed to be red on each odd click until 41 and yellow on every even click to 42). Here is a clip of the code: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.FlowLayout; public class Connect_4 extends JFrame { private JPanel contentPane; public int countClicks = 0; public boolean check = false; public boolean check2 = false; public boolean flag1; public boolean flag2; public boolean flag3; public boolean flag4; public boolean flag5; public boolean flag6; public boolean flag7; public int btn1Count = 0; public int btn2Count = 0; public int btn3Count = 0; public int btn4Count = 0; public int btn5Count = 0; public int btn6Count = 0; public int btn7Count = 0; public boolean flag; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Connect_4 frame = new Connect_4(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.red); Font font = new Font("Serif", Font.PLAIN, 20); g.setFont(font); g.drawString("C O N N E C T 4", 34, 47); g.setColor(Color.blue); g.fillRect(34, 50, 140, 120); g.setColor(Color.black); // ~~~~row 1~~~~ g.drawRect(34, 50, 20, 20); g.drawRect(54, 50, 20, 20); g.drawRect(74, 50, 20, 20); g.drawRect(94, 50, 20, 20); g.drawRect(114, 50, 20, 20); g.drawRect(134, 50, 20, 20); g.drawRect(154, 50, 20, 20); g.setColor(Color.white); g.fillOval(36, 52, 16, 16); g.fillOval(56, 52, 16, 16); g.fillOval(76, 52, 16, 16); g.fillOval(96, 52, 16, 16); g.fillOval(116, 52, 16, 16); g.fillOval(136, 52, 16, 16); g.fillOval(156, 52, 16, 16); g.setColor(Color.black); // ~~~~row 2~~~~ g.drawRect(34, 70, 20, 20); g.drawRect(54, 70, 20, 20); g.drawRect(74, 70, 20, 20); g.drawRect(94, 70, 20, 20); g.drawRect(114, 70, 20, 20); g.drawRect(134, 70, 20, 20); g.drawRect(154, 70, 20, 20); g.setColor(Color.white); g.fillOval(36, 72, 16, 16); g.fillOval(56, 72, 16, 16); g.fillOval(76, 72, 16, 16); g.fillOval(96, 72, 16, 16); g.fillOval(116, 72, 16, 16); g.fillOval(136, 72, 16, 16); g.fillOval(156, 72, 16, 16); g.setColor(Color.black); // ~~~~row 3~~~~ g.drawRect(34, 90, 20, 20); g.drawRect(54, 90, 20, 20); g.drawRect(74, 90, 20, 20); g.drawRect(94, 90, 20, 20); g.drawRect(114, 90, 20, 20); g.drawRect(134, 90, 20, 20); g.drawRect(154, 90, 20, 20); g.setColor(Color.white); g.fillOval(36, 92, 16, 16); g.fillOval(56, 92, 16, 16); g.fillOval(76, 92, 16, 16); g.fillOval(96, 92, 16, 16); g.fillOval(116, 92, 16, 16); g.fillOval(136, 92, 16, 16); g.fillOval(156, 92, 16, 16); g.setColor(Color.black); // ~~~~row 4~~~~ g.drawRect(34, 110, 20, 20); g.drawRect(54, 110, 20, 20); g.drawRect(74, 110, 20, 20); g.drawRect(94, 110, 20, 20); g.drawRect(114, 110, 20, 20); g.drawRect(134, 110, 20, 20); g.drawRect(154, 110, 20, 20); g.setColor(Color.white); g.fillOval(36, 112, 16, 16); g.fillOval(56, 112, 16, 16); g.fillOval(76, 112, 16, 16); g.fillOval(96, 112, 16, 16); g.fillOval(116, 112, 16, 16); g.fillOval(136, 112, 16, 16); g.fillOval(156, 112, 16, 16); g.setColor(Color.black); // ~~~~row 5~~~~ g.drawRect(34, 130, 20, 20); g.drawRect(54, 130, 20, 20); g.drawRect(74, 130, 20, 20); g.drawRect(94, 130, 20, 20); g.drawRect(114, 130, 20, 20); g.drawRect(134, 130, 20, 20); g.drawRect(154, 130, 20, 20); g.setColor(Color.white); g.fillOval(36, 132, 16, 16); g.fillOval(56, 132, 16, 16); g.fillOval(76, 132, 16, 16); g.fillOval(96, 132, 16, 16); g.fillOval(116, 132, 16, 16); g.fillOval(136, 132, 16, 16); g.fillOval(156, 132, 16, 16); g.setColor(Color.black); // ~~~~row 6~~~~ g.drawRect(34, 150, 20, 20); g.drawRect(54, 150, 20, 20); g.drawRect(74, 150, 20, 20); g.drawRect(94, 150, 20, 20); g.drawRect(114, 150, 20, 20); g.drawRect(134, 150, 20, 20); g.drawRect(154, 150, 20, 20); g.setColor(Color.white); g.fillOval(36, 152, 16, 16); g.fillOval(56, 152, 16, 16); g.fillOval(76, 152, 16, 16); g.fillOval(96, 152, 16, 16); g.fillOval(116, 152, 16, 16); g.fillOval(136, 152, 16, 16); g.fillOval(156, 152, 16, 16); g.setColor(Color.black); g.drawLine(174, 170, 174, 187); g.drawLine(34, 170, 34, 187); g.drawLine(164, 187, 184, 187); g.drawLine(24, 187, 44, 187); if (flag1 == true && check == true && btn1Count == 1) { g.setColor(Color.red); g.fillOval(36, 152, 16, 16); } if (flag1 == true && check2 == true && btn1Count == 1) { g.setColor(Color.yellow); g.fillOval(36, 152, 16, 16); } if (flag1 == true && check == true && btn1Count == 2) { g.setColor(Color.red); g.fillOval(36, 132, 16, 16); } if (flag1 == true && check2 == true && btn1Count == 2) { g.setColor(Color.yellow); g.fillOval(36, 132, 16, 16); } if (flag1 == true && check == true && btn1Count == 3) { g.setColor(Color.red); g.fillOval(36, 112, 16, 16); } if (flag1 == true && check2 == true && btn1Count == 3) { g.setColor(Color.yellow); g.fillOval(36, 112, 16, 16); } if (flag1 == true && check == true && btn1Count == 4) { g.setColor(Color.red); g.fillOval(36, 92, 16, 16); } if (flag1 == true && check2 == true && btn1Count == 4) { g.setColor(Color.yellow); g.fillOval(36, 92, 16, 16); } if (flag1 == true && check == true && btn1Count == 5) { g.setColor(Color.red); g.fillOval(36, 72, 16, 16); } if (flag1 == true && check2 == true && btn1Count == 5) { g.setColor(Color.yellow); g.fillOval(36, 72, 16, 16); } if (flag1 == true && check == true && btn1Count == 6) { g.setColor(Color.red); g.fillOval(36, 52, 16, 16); } if (flag1 == true && check2 == true && btn1Count == 6) { g.setColor(Color.yellow); g.fillOval(36, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (flag2 == true && check == true && btn2Count == 1) { g.setColor(Color.red); g.fillOval(56, 152, 16, 16); } if (flag2 == true && check2 == true && btn2Count == 1) { g.setColor(Color.yellow); g.fillOval(56, 152, 16, 16); } if (flag2 == true && check == true && btn2Count == 2) { g.setColor(Color.red); g.fillOval(56, 132, 16, 16); } if (flag2 == true && check2 == true && btn2Count == 2) { g.setColor(Color.yellow); g.fillOval(56, 132, 16, 16); } if (flag2 == true && check == true && btn2Count == 3) { g.setColor(Color.red); g.fillOval(56, 112, 16, 16); } if (flag2 == true && check2 == true && btn2Count == 3) { g.setColor(Color.yellow); g.fillOval(56, 112, 16, 16); } if (flag2 == true && check == true && btn2Count == 4) { g.setColor(Color.red); g.fillOval(56, 92, 16, 16); } if (flag2 == true && check2 == true && btn2Count == 4) { g.setColor(Color.yellow); g.fillOval(56, 92, 16, 16); } if (flag2 == true && check == true && btn2Count == 5) { g.setColor(Color.red); g.fillOval(56, 72, 16, 16); } if (flag2 == true && check2 == true && btn2Count == 5) { g.setColor(Color.yellow); g.fillOval(56, 72, 16, 16); } if (flag2 == true && check == true && btn2Count == 6) { g.setColor(Color.red); g.fillOval(56, 52, 16, 16); } if (flag2 == true && check2 == true && btn2Count == 6) { g.setColor(Color.yellow); g.fillOval(56, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (flag3 == true && check == true && btn3Count == 1) { g.setColor(Color.red); g.fillOval(76, 152, 16, 16); } if (flag3 == true && check2 == true && btn3Count == 1) { g.setColor(Color.yellow); g.fillOval(76, 152, 16, 16); } if (flag3 == true && check == true && btn3Count == 2) { g.setColor(Color.red); g.fillOval(76, 132, 16, 16); } if (flag3 == true && check2 == true && btn3Count == 2) { g.setColor(Color.yellow); g.fillOval(76, 132, 16, 16); } if (flag3 == true && check == true && btn3Count == 3) { g.setColor(Color.red); g.fillOval(76, 112, 16, 16); } if (flag3 == true && check2 == true && btn3Count == 3) { g.setColor(Color.yellow); g.fillOval(76, 112, 16, 16); } if (flag3 == true && check == true && btn3Count == 4) { g.setColor(Color.red); g.fillOval(76, 92, 16, 16); } if (flag3 == true && check2 == true && btn3Count == 4) { g.setColor(Color.yellow); g.fillOval(76, 92, 16, 16); } if (flag3 == true && check == true && btn3Count == 5) { g.setColor(Color.red); g.fillOval(76, 72, 16, 16); } if (flag3 == true && check2 == true && btn3Count == 5) { g.setColor(Color.yellow); g.fillOval(76, 72, 16, 16); } if (flag3 == true && check == true && btn3Count == 6) { g.setColor(Color.red); g.fillOval(76, 52, 16, 16); } if (flag3 == true && check2 == true && btn3Count == 6) { g.setColor(Color.yellow); g.fillOval(76, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (flag4 == true && check == true && btn4Count == 1) { g.setColor(Color.red); g.fillOval(96, 152, 16, 16); } if (flag4 == true && check2 == true && btn4Count == 1) { g.setColor(Color.yellow); g.fillOval(96, 152, 16, 16); } if (flag4 == true && check == true && btn4Count == 2) { g.setColor(Color.red); g.fillOval(96, 132, 16, 16); } if (flag4 == true && check2 == true && btn4Count == 2) { g.setColor(Color.yellow); g.fillOval(96, 132, 16, 16); } if (flag4 == true && check == true && btn4Count == 3) { g.setColor(Color.red); g.fillOval(96, 112, 16, 16); } if (flag4 == true && check2 == true && btn4Count == 3) { g.setColor(Color.yellow); g.fillOval(96, 112, 16, 16); } if (flag4 == true && check == true && btn4Count == 4) { g.setColor(Color.red); g.fillOval(96, 92, 16, 16); } if (flag4 == true && check2 == true && btn4Count == 4) { g.setColor(Color.yellow); g.fillOval(96, 92, 16, 16); } if (flag4 == true && check == true && btn4Count == 5) { g.setColor(Color.red); g.fillOval(96, 72, 16, 16); } if (flag4 == true && check2 == true && btn4Count == 5) { g.setColor(Color.yellow); g.fillOval(96, 72, 16, 16); } if (flag4 == true && check == true && btn4Count == 6) { g.setColor(Color.red); g.fillOval(96, 52, 16, 16); } if (flag4 == true && check2 == true && btn4Count == 6) { g.setColor(Color.yellow); g.fillOval(96, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (flag5 == true && check == true && btn5Count == 1) { g.setColor(Color.red); g.fillOval(116, 152, 16, 16); } if (flag5 == true && check2 == true && btn5Count == 1) { g.setColor(Color.yellow); g.fillOval(116, 152, 16, 16); } if (flag5 == true && check == true && btn5Count == 2) { g.setColor(Color.red); g.fillOval(116, 132, 16, 16); } if (flag5 == true && check2 == true && btn5Count == 2) { g.setColor(Color.yellow); g.fillOval(116, 132, 16, 16); } if (flag5 == true && check == true && btn5Count == 3) { g.setColor(Color.red); g.fillOval(116, 112, 16, 16); } if (flag5 == true && check2 == true && btn5Count == 3) { g.setColor(Color.yellow); g.fillOval(116, 112, 16, 16); } if (flag5 == true && check == true && btn5Count == 4) { g.setColor(Color.red); g.fillOval(116, 92, 16, 16); } if (flag5 == true && check2 == true && btn5Count == 4) { g.setColor(Color.yellow); g.fillOval(116, 92, 16, 16); } if (flag5 == true && check == true && btn5Count == 5) { g.setColor(Color.red); g.fillOval(116, 72, 16, 16); } if (flag5 == true && check2 == true && btn5Count == 5) { g.setColor(Color.yellow); g.fillOval(116, 72, 16, 16); } if (flag5 == true && check == true && btn5Count == 6) { g.setColor(Color.red); g.fillOval(116, 52, 16, 16); } if (flag5 == true && check2 == true && btn5Count == 6) { g.setColor(Color.yellow); g.fillOval(116, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (flag6 == true && check == true && btn6Count == 1) { g.setColor(Color.red); g.fillOval(136, 152, 16, 16); } if (flag6 == true && check2 == true && btn6Count == 1) { g.setColor(Color.yellow); g.fillOval(136, 152, 16, 16); } if (flag6 == true && check == true && btn6Count == 2) { g.setColor(Color.red); g.fillOval(136, 132, 16, 16); } if (flag6 == true && check2 == true && btn6Count == 2) { g.setColor(Color.yellow); g.fillOval(136, 132, 16, 16); } if (flag6 == true && check == true && btn6Count == 3) { g.setColor(Color.red); g.fillOval(136, 112, 16, 16); } if (flag6 == true && check2 == true && btn6Count == 3) { g.setColor(Color.yellow); g.fillOval(136, 112, 16, 16); } if (flag6 == true && check == true && btn6Count == 4) { g.setColor(Color.red); g.fillOval(136, 92, 16, 16); } if (flag6 == true && check2 == true && btn6Count == 4) { g.setColor(Color.yellow); g.fillOval(136, 92, 16, 16); } if (flag6 == true && check == true && btn6Count == 5) { g.setColor(Color.red); g.fillOval(136, 72, 16, 16); } if (flag6 == true && check2 == true && btn6Count == 5) { g.setColor(Color.yellow); g.fillOval(136, 72, 16, 16); } if (flag6 == true && check == true && btn6Count == 6) { g.setColor(Color.red); g.fillOval(136, 52, 16, 16); } if (flag6 == true && check2 == true && btn6Count == 6) { g.setColor(Color.yellow); g.fillOval(136, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (flag7 == true && check == true && btn7Count == 1) { g.setColor(Color.red); g.fillOval(156, 152, 16, 16); } if (flag7 == true && check2 == true && btn7Count == 1) { g.setColor(Color.yellow); g.fillOval(156, 152, 16, 16); } if (flag7 == true && check == true && btn7Count == 2) { g.setColor(Color.red); g.fillOval(156, 132, 16, 16); } if (flag7 == true && check2 == true && btn7Count == 2) { g.setColor(Color.yellow); g.fillOval(156, 132, 16, 16); } if (flag7 == true && check == true && btn7Count == 3) { g.setColor(Color.red); g.fillOval(156, 112, 16, 16); } if (flag7 == true && check2 == true && btn7Count == 3) { g.setColor(Color.yellow); g.fillOval(156, 112, 16, 16); } if (flag7 == true && check == true && btn7Count == 4) { g.setColor(Color.red); g.fillOval(156, 92, 16, 16); } if (flag7 == true && check2 == true && btn7Count == 4) { g.setColor(Color.yellow); g.fillOval(156, 92, 16, 16); } if (flag7 == true && check == true && btn7Count == 5) { g.setColor(Color.red); g.fillOval(156, 72, 16, 16); } if (flag7 == true && check2 == true && btn7Count == 5) { g.setColor(Color.yellow); g.fillOval(156, 72, 16, 16); } if (flag7 == true && check == true && btn7Count == 6) { g.setColor(Color.red); g.fillOval(156, 52, 16, 16); } if (flag7 == true && check2 == true && btn7Count == 6) { g.setColor(Color.yellow); g.fillOval(156, 52, 16, 16); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } public Connect_4() { setTitle("Connect 4"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 210, 220); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); // getContentPane().setBackground(Color.RED); setResizable(false); contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 137)); JPanel panel = new JPanel(); // panel.setBackground(Color.BLUE); contentPane.add(panel, BorderLayout.CENTER); JButton btn1 = new JButton(); btn1.setPreferredSize(new Dimension(15, 10)); panel.add(btn1); btn1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { countClicks++; btn1Count++; flag = true; flag1 = true; switch (countClicks) { case 1: case 3: case 5: case 7: case 9: case 11: case 13: case 15: case 17: case 19: case 21: case 23: case 25: case 27: case 29: case 31: case 33: case 35: case 37: case 39: case 41: check = true; repaint(); break; case 2: case 4: case 6: case 8: case 10: case 12: case 14: case 16: case 18: case 20: case 22: case 24: case 26: case 28: case 30: case 32: case 34: case 36: case 38: case 40: case 42: check2 = true; repaint(); break; } } }); I do not know why the previous tile in a column disappears nor how to make it stop. Is the problem repaint()? Is it the if statements in the paint method? Please help. A: Paint() - this method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead. repaint() - this method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not it's size ( like changing color, animating, etc. ) then call this method. validate() - This tells the component to lay itself out again and repaint itself. If you have done anything to change the size of the component or any of it's children(adding, removing, resizing children), you should call this method... I think that calling revalidate() is preferred to calling validate() in Swing, though... update() - This method is in charge of clearing the component and calling paint(). Again, you should call repaint() instead of calling this method directly... If you need to do fast updates in animation you should override this method to just call the paint() method... updateUI() - Call this method if you have changed the pluggable look & feel for a component after it has been made visible. Note: The way you have used switch case in your program is not a good implementation, use a variable(counter) and increment as user clicks and then use if/while condition for further implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/37517767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using separate scales for each group in a grouped and stacked barplots in Altair I'd like to use separate scales for each group in a grouped and stacked barplot using Altair in Python. So for example instead of the following I'd like something similar to the following. In this (Gimp-)edited picture I have the same scale for all the 4 groups A,B,C and D. But In my actual data, the orders of magnitude are different from a group to another. So each Group should have a different scale. Any ideas on how to do that? Here is an Minimum Example from HERE import pandas as pd import numpy as np import altair as alt df1=pd.DataFrame(10*np.random.rand(4,3),index=["A","B","C","D"],columns=["I","J","K"]) df2=pd.DataFrame(10*np.random.rand(4,3),index=["A","B","C","D"],columns=["I","J","K"]) df3=pd.DataFrame(10*np.random.rand(4,3),index=["A","B","C","D"],columns=["I","J","K"]) def prep_df(df, name): df = df.stack().reset_index() df.columns = ['c1', 'c2', 'values'] df['DF'] = name return df df1 = prep_df(df1, 'DF1') df2 = prep_df(df2, 'DF2') df3 = prep_df(df3, 'DF3') df = pd.concat([df1, df2, df3]) chart = alt.Chart(df).mark_bar().encode( x=alt.X('c2:N', title=None), y=alt.Y('sum(values):Q', axis=alt.Axis(grid=False, title=None)), column=alt.Column('c1:N', title=None), color=alt.Color('DF:N', scale=alt.Scale(range=['#96ceb4', '#ffcc5c','#ff6f69'])) ).configure_view( strokeOpacity=0 ) chart.save("Power.svg") A: You can have independent axes for the charts by adding resolve_scale(y='independent') Note that, by itself, this lets the y-domain limits for each facet adjust to the subset of the data within each facet; you can make them match by explicitly specifying domain limits. Put together, it looks like this: alt.Chart(df).mark_bar().encode( x=alt.X('c2:N', title=None), y=alt.Y('sum(values):Q', axis=alt.Axis(grid=False, title=None), scale=alt.Scale(domain=[0, 25])), column=alt.Column('c1:N', title=None), color=alt.Color('DF:N', scale=alt.Scale(range=['#96ceb4', '#ffcc5c','#ff6f69'])) ).configure_view( strokeOpacity=0 ).resolve_scale( y='independent' )
{ "language": "en", "url": "https://stackoverflow.com/questions/61492124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting just one row that has max datetime SELECT v.DoorNo,v.NewDoorNo, v.GarageName, c.VersionDate, v.OperatorName as Operator, v.OperatorId, c.DeviceId, c.VehicleId, c.ProgramVersionNo, c.ParameterFileVersionNo, c.TariffFileVersionNo, c.BlaclistFileVersionNo, c.LineNoFileVersionNo, c.ScreenProgramVersion, c.SoapProgramVersiyon FROM dbo.vValidator AS v RIGHT JOIN dbo.CDeviceVersion AS c with(nolock) ON (v.DoorNo = c.DoorNo or v.NewDoorNo=c.DoorNo where v.NewDoorNo='O1211' This query returns 2 rows, but I want to select just one row that has maximum versionDate. How can I select it? A: Is this what you want? SELECT TOP (1) v.DoorNo,v.NewDoorNo, v.GarageName, c.VersionDate, v.OperatorName as Operator, v.OperatorId, c.DeviceId, c.VehicleId, c.ProgramVersionNo, c.ParameterFileVersionNo, c.TariffFileVersionNo, c.BlaclistFileVersionNo, c.LineNoFileVersionNo, c.ScreenProgramVersion, c.SoapProgramVersiyon FROM dbo.vValidator AS v RIGHT JOIN dbo.CDeviceVersion AS c with(nolock) ON (v.DoorNo = c.DoorNo or v.NewDoorNo=c.DoorNo) where v.NewDoorNo='O1211' ORDER BY c.VersionDate
{ "language": "en", "url": "https://stackoverflow.com/questions/23006240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Good examples of implementing forms with client/server side validation in Django While Django makes it very easy to create simple HTML forms, I wonder if anyone could suggest good open-source Django projects with examples for implementing "modern-looking" forms with additional elements such as: * *disqus registration form *twitter registration form I have looked at several projects: * *django-uni-form *django-crispy-forms (seems to be a successor for previous one) *django-ajax-forms but I can't seem to find any good examples to learn from. Any suggestions are welcome. A: Have a look at Twitter Bootstrap. It integrates very well with django-crispy-forms and will let you produce very clean, modern looking forms quite easily, with very little work on the client side. It won't help you out with Ajax functionality, but will handle look and feel quite nicely.
{ "language": "en", "url": "https://stackoverflow.com/questions/9963370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How insert an image in footer of excel document with phpspreadsheet I'm trying to insert dinamically an image in the footer of an Xlsx document, using PHPSpreadsheet library. I tried to modify the sample of documentation, but nothing appears when I print the doc. $inputFileName = './tpl1.xlsx'; $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); $sheet = $spreadsheet->getActiveSheet(); $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setPath('./uploads/blu.png'); $drawing->setHeight(36); $sheet->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_FOOTER_CENTER); $sheet->getHeaderFooter()->setOddHeader('&C&G'); Some ideas? A: You must change the setOddHeader $sheet->getHeaderFooter()->setOddHeader('&C&G'); to $sheet->getHeaderFooter()->setOddFooter('&C&G'); The HeaderFooter::IMAGE_FOOTER_CENTER and &C&G must correspond each other. You should set a width e.g.: $drawing->setWidth(800); The fullcode should look like this: $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); $drawing->setName('PhpSpreadsheet logo'); $drawing->setPath('./uploads/blu.png'); $drawing->setWidth(800); $sheet->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_FOOTER_CENTER); $sheet->getHeaderFooter()->setOddFooter('&C&G');
{ "language": "en", "url": "https://stackoverflow.com/questions/56758044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create slanting text using paint in xamarin android? I want to implement a slanting text in repeat over an image.But I don't know how to implement it. I have attached the sample image.Can any one help me with this? A: You could create a custom view and draw the text on canvas. Here is a sample. Custom view: public class TextOverlay : View { protected TextOverlay(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public TextOverlay(Context context) : base(context) { } public TextOverlay(Context context, IAttributeSet attrs) : base(context, attrs) { } public TextOverlay(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public TextOverlay(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); // make the canvas Transparent canvas.DrawColor(Color.Transparent); canvas.Translate(100, 150); var paint = new Paint { Color = Color.Blue, TextSize = 18 }; paint.SetStyle(Paint.Style.Fill); canvas.Rotate(-45); canvas.DrawText("CANCELLED", 0, 0, paint); } } Add it to a relative layout on top of the image view: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main"> <ImageView android:src="@android:drawable/ic_menu_gallery" android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageView1" android:foregroundGravity="center" android:layout_alignParentStart="false" android:layout_alignParentTop="false" android:layout_alignParentRight="false" android:layout_alignParentLeft="false" android:layout_alignParentEnd="false" android:layout_alignParentBottom="false" android:layout_centerInParent="true" /> <viewoverlay.TextOverlay android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/textOverlay" android:foregroundGravity="center" android:layout_alignParentStart="false" android:layout_alignParentTop="false" android:layout_alignParentRight="false" android:layout_alignParentLeft="false" android:layout_alignParentEnd="false" android:layout_alignParentBottom="false" android:layout_centerInParent="true" /> </RelativeLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/52734679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom segue to a navigation controller I am using a custom segue to slide my views over. The custom subclass works fine whenever it moves from a view controller to a view controller, but it crashes when I try to move from a view controller to a navigation controller. (It carries over the previous navigation bar and when I try to click the screen it crashes.) This is the custom segue class FromRightSegue: UIStoryboardSegue { override func perform() { let src = self.source let dst = self.destination src.view.superview?.insertSubview(dst.view, aboveSubview: src.view) dst.view.transform = CGAffineTransform(translationX: src.view.frame.size.width, y: 0) UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: { dst.view.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: { finished in src.present(dst, animated: false, completion: nil) } ) } } When I use the built in segues like show the segue works fine, but there is no built in segue that moves from the right. Any suggestions?
{ "language": "en", "url": "https://stackoverflow.com/questions/50893641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Push Notification in Android App through GCM I am new to android app development. Right now I am developing a simple application in which user can upload the data to the MySQL server through PHP scripts. I am successfully able to do that. But I want that whenever a user uploaded some data to server from his app then all other app user should receive the notification (i.e. xyz user has added a new post.). I have found the way that I can achieve this using Google Cloud Messaging. But I am unable to implement it inside my application. I have successfully implemented the GCM notification from the web message through a PHP script on web server using the below PHP script. <?php //Generic php function to send GCM push notification function sendMessageThroughGCM($registatoin_ids, $message) { //Google cloud messaging GCM-API url $url = 'https://android.googleapis.com/gcm/send'; $fields = array( 'registration_ids' => $registatoin_ids, 'data' => $message, ); // Update your Google Cloud Messaging API Key define("GOOGLE_API_KEY", "AIzaSyCVQRSnEoulXoG21uKua1DTrOUvMkxbK-U"); $headers = array( 'Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); return $result; } ?> <?php //Post message to GCM when submitted $pushStatus = "GCM Status Message will appear here"; if(!empty($_GET["push"])) { $gcmRegID = file_get_contents("GCMRegId.txt"); $pushMessage = $_POST["message"]; if (isset($gcmRegID) && isset($pushMessage)) { $gcmRegIds = array($gcmRegID); $message = array("m" => $pushMessage); $pushStatus = sendMessageThroughGCM($gcmRegIds, $message); } } //Get Reg ID sent from Android App and store it in text file if(!empty($_GET["shareRegId"])) { $gcmRegID = $_POST["regId"]; file_put_contents("GCMRegId.txt",$gcmRegID); echo "Done!"; exit; } ?> <html> <head> <title>Google Cloud Messaging (GCM) in PHP</title> <style> div#formdiv, p#status{ text-align: center; background-color: #FFFFCC; border: 2px solid #FFCC00; padding: 10px; } textarea{ border: 2px solid #FFCC00; margin-bottom: 10px; text-align: center; padding: 10px; font-size: 25px; font-weight: bold; } input{ background-color: #FFCC00; border: 5px solid #fff; padding: 10px; cursor: pointer; color: #fff; font-weight: bold; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(function(){ $("textarea").val(""); }); function checkTextAreaLen(){ var msgLength = $.trim($("textarea").val()).length; if(msgLength == 0){ alert("Please enter message before hitting submit button"); return false; }else{ return true; } } </script> </head> <body> <div id="formdiv"> <h1>Google Cloud Messaging (GCM) in PHP</h1> <form method="post" action="/swach/gcm/gcm.php/?push=true" onsubmit="return checkTextAreaLen()"> <textarea rows="5" name="message" cols="45" placeholder="Message to send via GCM"></textarea> <br/> <input type="submit" value="Send Push Notification through GCM" /> </form> </div> <p id="status"> <?php echo $pushStatus; ?> </p> </body> </html> and successfully received the notification on my device. But I want to setup that app should automatically notify the GCM to send the message instead of using WEB scripts. And the notification should be received to all other app users. I have also gone through the GCM DownStream and UpStream messaging but didn't understood much, not able to implement successfully. I have tried to setup the Downstream using the below code but i didn't received the notification to my App public class AddNewMessage extends Activity{ private Integer msgId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_new_message); msgId = 1; } // OnClick Action to the button inside the Activity Layout public void sendNewMessage(View view) { final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); if (view == findViewById(R.id.send_message)) { new AsyncTask<Void,Void,String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action","SAY_HELLO"); String id = Integer.toString(msgId); gcm.send(ApplicationConstants.GOOGLE_PROJ_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { Toast.makeText(AddNewMessage.this, "send message failed: " + msg, Toast.LENGTH_LONG).show(); } }.execute(null, null, null); } } } Thanks for your time. A: Follow steps : 1. Get registration ID of app user's device and save it to your database. private String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.d(TAG, "Registration ID not found."); return ""; } int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.d(TAG, "App version changed."); return ""; } return registrationId; } 2.Use your php code.(remove HTML part) Note - use array of registration IDs 3.In response open this php script with registration ids. A: You can have a longer method where you send the information to a php script. This php script will select all the registration ids of the users and use a foreach loop to send the notifications. This means you need to store the registration ids in your mysql database
{ "language": "en", "url": "https://stackoverflow.com/questions/34563280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Navigate to a specific page in a specific tab Flutter I am quite new to flutter and I am trying to implement navigation between different tabs. I am using a CupertinoTabView because I need a parallel navigators and a specific history for each tab in my bottom bar. My question is whether it is possible to switch from a child page of Tab1 to a child page of Tab2, and if so in which way. In this image you can see my widget tree: Class MyApp.dart class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { TabItem _currentTab = TabItem.tab1; final Map<TabItem, GlobalKey<NavigatorState>> navigatorKeys = { TabItem.tab1: GlobalKey<NavigatorState>(), TabItem.tab1: GlobalKey<NavigatorState>(), }; Map<TabItem, WidgetBuilder> get widgetBuilders { return { TabItem.tab1: (_) => Tab1(), TabItem.tab2: Tab2(), }; } void _select(TabItem tabItem) { if (tabItem == _currentTab) { navigatorKeys[tabItem].currentState.popUntil((route) => route.isFirst); } else { setState(() => _currentTab = tabItem); } } @override Widget build(BuildContext context) { return CupertinoScaffold( currentTab: _currentTab, onSelectTab: _select, widgetBuilders: widgetBuilders, navigatorKeys: navigatorKeys, ); } } Class CupertinoScaffold.dart (contains CupertinoTabView) class CupertinoScaffold extends StatelessWidget { const CupertinoScaffold({ Key key, @required this.currentTab, @required this.onSelectTab, @required this.widgetBuilders, @required this.navigatorKeys, }) : super(key: key); final TabItem currentTab; final ValueChanged<TabItem> onSelectTab; final Map<TabItem, WidgetBuilder> widgetBuilders; final Map<TabItem, GlobalKey<NavigatorState>> navigatorKeys; @override Widget build(BuildContext context) { return CupertinoTabScaffold( tabBar: CupertinoTabBar( key: Key(Keys.tabBar), items: [ BottomNavigationBarItem(title: Text('Tab1')), BottomNavigationBarItem(title: Text('Tab2')) ], onTap: (index) => onSelectTab(TabItem.values[index]), ), tabBuilder: (context, index) { final item = TabItem.values[index]; return CupertinoTabView( navigatorKey: navigatorKeys[item], builder: (context) => widgetBuilders[item](context), onGenerateRoute: CupertinoTabViewRouter.generateRoute, ); }, ); } } Class Tab1.dart class Tab1 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Tab1')), body: Center( child: Button( child: Text( 'Open child tab1' ), onPressed: () => Navigator.of(context).pushNamed('/tab1-child'), ), ), ); } } Class CupertinoTabViewRouter.dart class CupertinoTabViewRouter { static Route generateRoute(RouteSettings settings) { switch (settings.name) { case '/tab1-child': return CupertinoPageRoute<dynamic>( builder: (_) => Tab1Child(), settings: settings, fullscreenDialog: true, ); case '/tab2-child': return CupertinoPageRoute<dynamic>( builder: (_) => Tab2Child(), settings: settings, fullscreenDialog: true, ); } return null; } } Class Tab1Child.dart class Tab1Child extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('ChildTab1')), body: Center( child: Button( child: Text( 'Open child tab2' ), onPressed: () => //TODO!, ), ), ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/62891947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jenkins job on two slaves? We need to be able to run a Jenkins job that consumes two slaves. (Or, two jobs, if we can guarantee that they run at the same time, and it's possible for at least one to know what the other is.) The situation is that we have a heavy weight application that we need to run tests against. The tests run on one machine, the application runs on another. It's not practical to have them on the same host. Right now, we have a Jenkins job that uses a script to kick a dedicated application server up, install the correct version, the correct data, and then run the tests against it. That means that I can't use the dedicated application server to run other tasks, when there aren't the heavy weight testing going on. It also pretty much limits us to one loop. Being able to assign the app server dynamically would allow more of them. There's clearly no way to do this in the core jenkins, but I'm hoping there's some plugin or hackery to make this possible. The current test build is a maven 2 job, but that's configurable, if we have to wrap it in something else. It's kicked off by the successful completion of another job, which could be changed to start two, or whatever else is required. A: I just learned from that the simultaneous allocation of multiple slaves can be done nicely in a pipeline job, by nesting node clauses: node('label1') { node('label2') { // your code here [...] } } See this question where Mateusz suggested that solution for a similar problem. A: Let me see if I understood the problem. * *You want to have dynamically choose a slave and start the App Server on it. *When the App server is running on a Slave you do not want it to run any other job. *But when the App server is not running, you want to use that Slave as any other Slave for other jobs. One way out will be to label the Slaves. And use "Restrict where this project can be run" to make the App Server and the Test Suite run on the machines with Slave label. Then in the slave nodes, put " # of executors" to 1. This will make sure that at anytime only one Job will run. Next step will be to create a job to start the App Server and then kick off the Test job once the App Server start job is successful.. If your test job needs to know the server details of the machine where your App server is running then it becomes interesting.
{ "language": "en", "url": "https://stackoverflow.com/questions/21418480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cast a Swift struct to UnsafeMutablePointer Is there a way to cast a Swift struct's address to a void UnsafeMutablePointer? I tried this without success: struct TheStruct { var a:Int = 0 } var myStruct = TheStruct() var address = UnsafeMutablePointer<Void>(&myStruct) Thanks! EDIT: the context I am actually trying to port to Swift the first example in Learning CoreAudio. This is what I have done until now: func myAQInputCallback(inUserData:UnsafeMutablePointer<Void>, inQueue:AudioQueueRef, inBuffer:AudioQueueBufferRef, inStartTime:UnsafePointer<AudioTimeStamp>, inNumPackets:UInt32, inPacketDesc:UnsafePointer<AudioStreamPacketDescription>) { } struct MyRecorder { var recordFile: AudioFileID = AudioFileID() var recordPacket: Int64 = 0 var running: Boolean = 0 } var queue:AudioQueueRef = AudioQueueRef() AudioQueueNewInput(&asbd, myAQInputCallback, &recorder, // <- this is where I *think* a void pointer is demanded nil, nil, UInt32(0), &queue) I am doing efforts to stay in Swift, but if this turns out to be more a problem than an advantage, I will end up linking to a C function. EDIT: bottome line If you came to this question because you are trying to use a CoreAudio's AudioQueue in Swift... don't. (read the comments for details) A: As far as I know, the shortest way is: var myStruct = TheStruct() var address = withUnsafeMutablePointer(&myStruct) {UnsafeMutablePointer<Void>($0)} But, why you need this? If you want pass it as a parameter, you can (and should): func foo(arg:UnsafeMutablePointer<Void>) { //... } var myStruct = TheStruct() foo(&myStruct) A: Most of the method prototypes have been changed as Swift evolved over the years. Here is the syntax for Swift 5: var struct = TheStruct() var unsafeMutablePtrToStruct = withUnsafeMutablePointer(to: &struct) { $0.withMemoryRebound(to: TheStruct.self, capacity: 1) { (unsafePointer: UnsafeMutablePointer<TheStruct>) in unsafePointer } }
{ "language": "en", "url": "https://stackoverflow.com/questions/29556610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: ngrok command not found and is already on /usr/local/bin I'm trying to install ngrok on my mac. Here is what I have done so far. * *Downloaded ngrok from here https://ngrok.com/download. *Unziped the file and copied the Unix Executable File into /usr/local/bin like many other questions and answers suggested. Now when I try to execute any command with ngrok in the current folder or in the project one the result of this is command not found but ngrok is there as you can see. By the way, here is the path: ramonmorcillo@Ramons-MacBook-Pro bin % echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin I may be missing something but I have been all morning searching for an answer and followed all other questions steps but it is still not working. Can anyone help me solve this? A: I finally solved it. I connected my account and it worked. ramonmorcillo@Ramons-MacBook-Pro bin % ./ngrok authtoken MY _AUTH_TOKEN Authtoken saved to configuration file: /Users/ramonmorcillo/.ngrok2/ngrok.yml ramonmorcillo@Ramons-MacBook-Pro bin % ./ngrok help NAME: ngrok - tunnel local ports to public URLs and inspect traffic DESCRIPTION: ngrok exposes local networked services behinds NATs and firewalls to the public internet over a secure tunnel. Share local websites, build/test webhook consumers and self-host personal services. ...
{ "language": "en", "url": "https://stackoverflow.com/questions/63299018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If statement to show toast or continue to next activity Not getting any errors im just stumped on this friggin if statement. I want the if statement to basically say if a check box is not checked and 3 EditTexts are empty then print a toast. Otherwise dont print the toast and continue to the next activity. First I turn the value of the checkbox into either t/f for true/false then execute my if statements as the following. CheckBox noPtD1 = (CheckBox) findViewById(R.id.noPTD1); String noPt_D1 = "f"; if (noPtD1.isChecked()) { noPt_D1 = "t"; } if (noPt_D1.equals("f") && day1_inst.equals("") || day1_uniform.equals("") || day1_location.equals("")) { Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY checkbox!", Toast.LENGTH_LONG).show(); } if(noPt_D1.equals("t") || !day1_inst.equals("") && !day1_uniform.equals("") && !day1_location.equals("")) { //PASS VARIABLES WITH INTENT Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class); //PASS VARIABLES FOR DAY 1 intent.putExtra("noPt_D1", noPt_D1); intent.putExtra("day1_inst", day1_inst); intent.putExtra("day1_uniform", day1_uniform); intent.putExtra("day1_location", day1_location); intent.putExtra("d1hours", d1hours); intent.putExtra("d1min", d1min); intent.putExtra("d1x1", d1x1); intent.putExtra("d1x2", d1x2); intent.putExtra("d1x3", d1x3); intent.putExtra("d1x4", d1x4); startActivity(intent); } This is working except for then I check the checkbox and and start the next activity with a button the next activity pops up like it is supposed to but the toast still appears. What did I mess up? I got it I posted my answer below. But to rephrase exactly what my intent was: If the user DOES NOT check the checkbox and leaves all 3 inputtexts blank show the toast and dont continue to next activity. If the user DOES check the checkbox then DONT show the toast and continue to next activity. A: Use brackets inside if statement if (noPt_D1.equals("f") && (day1_inst.equals("") || day1_uniform.equals("") || day1_location.equals(""))) { } if(noPt_D1.equals("t") || (!day1_inst.equals("") && !day1_uniform.equals("") && !day1_location.equals(""))) { } A: You are making minor mistake in condition PLUS you need to use if - else block instead of 2 if blocks //surround all && conditions inside separate braces if (noPt_D1.equals("f") && (day1_inst.equals("") || day1_uniform.equals("") || day1_location.equals(""))) { //show toast } else if(noPt_D1.equals("t") || (!day1_inst.equals("") && !day1_uniform.equals("") && !day1_location.equals(""))) { //start activity } Hope this helps. A: also try this. and its better to avoid including special characters for ur class name if ("f".equals(noPt_D1) && "".equals(day1_inst) || "".equals(day1_uniform) || "".equals(day1_location)) { Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY checkbox!", Toast.LENGTH_LONG).show(); } if("t".equals(noPt_D1) || !"".equals(day1_inst) && !"".equals(day1_uniform) && !"".equals(day1_location)) { //PASS VARIABLES WITH INTENT Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class); //PASS VARIABLES FOR DAY 1 intent.putExtra("noPt_D1", noPt_D1); intent.putExtra("day1_inst", day1_inst); intent.putExtra("day1_uniform", day1_uniform); intent.putExtra("day1_location", day1_location); intent.putExtra("d1hours", d1hours); intent.putExtra("d1min", d1min); intent.putExtra("d1x1", d1x1); intent.putExtra("d1x2", d1x2); intent.putExtra("d1x3", d1x3); intent.putExtra("d1x4", d1x4); startActivity(intent); } A: Try to check EditText values via length() of String value. Secondly put && operator in if statement because you said in your question: if a check box is not checked and 3 EditTexts are empty then print a toast. Otherwise dont print the toast and continue to the next activity. if (noPt_D1.equals("f") && day1_inst.trim().length() == 0 && day1_uniform.trim().length() == 0 && day1_location.trim().length() == 0) { Toast.makeText(getApplicationContext(), "Please Enter All Data", Toast.LENGTH_LONG).show(); } else { Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class); intent.putExtra("noPt_D1", noPt_D1); intent.putExtra("day1_inst", day1_inst); intent.putExtra("day1_uniform", day1_uniform); intent.putExtra("day1_location", day1_location); intent.putExtra("d1hours", d1hours); intent.putExtra("d1min", d1min); intent.putExtra("d1x1", d1x1); intent.putExtra("d1x2", d1x2); intent.putExtra("d1x3", d1x3); intent.putExtra("d1x4", d1x4); startActivity(intent); } EDIT: Make sure you should declare your Strings which I am assuming are: String day1_inst = your_editText_inst.getText().toString(); String day1_uniform = your_editText_uniform.getText().toString(); String day1_location = your_editText_location.getText().toString(); String noPt_D1 = "f"; if(your_check_box.isChecked()) { noPt_D1 = "t"; } else { noPt_D1 = "f"; } A: Try using an OnCheckedChangeListener Listener, like whats shown below : CheckBox noPtD1 = (CheckBox) findViewById(R.id.noPTD1); String noPt_D1 = "f"; noPtD1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { noPt_D1 = "t"; } else { noPt_D1 = "f"; } } }); A: Replace getApplicationContext() with this if you are in activity. getActivity() if you're in fragment. A: Just figured it out thanks to M S Gadag =) Basically I took the if statements and put the startActivity if statement on top. Then I added a variable to show that that statement had already been executed. Then I used that variable to start another if statement to decide whether or not to show the toast. int showToast = 0; if("t".equals(noPt_D1) || !"".equals(day1_inst) && !"".equals(day1_uniform) && !"".equals(day1_location)) { //PASS VARIABLES WITH INTENT Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class); //PASS VARIABLES FOR DAY 1 intent.putExtra("noPt_D1", noPt_D1); intent.putExtra("day1_inst", day1_inst); intent.putExtra("day1_uniform", day1_uniform); intent.putExtra("day1_location", day1_location); intent.putExtra("d1hours", d1hours); intent.putExtra("d1min", d1min); intent.putExtra("d1x1", d1x1); intent.putExtra("d1x2", d1x2); intent.putExtra("d1x3", d1x3); intent.putExtra("d1x4", d1x4); startActivity(intent); showToast = 1; } if ("f".equals(noPt_D1) && "".equals(day1_inst) || "".equals(day1_uniform) || "".equals(day1_location)) { if (showToast !=1) { Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY checkbox!", Toast.LENGTH_LONG).show(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/27118831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is wrong in this 2 query's please This is a query I want to do in Swift with Firestore Database. I spend a lot of time to make this code work. In debugger when it arrived in the first db.collection line the debugger jump to the second db.collection line without process the code between. After processing the 2. db.collection line he go back to the first and process the code. func readAirplanes() { var airplaneArray = [String]() var arrayPosition = 1 db.collection("airplane").whereField("Userid", isEqualTo: userID).getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") return } else { self.lbNext.isHidden = false self.btEdit.isUserInteractionEnabled = true self.btDelete.isUserInteractionEnabled = true for document in querySnapshot!.documents { airplaneArray.append(document.documentID) } } } db.collection("airplane").document(airplaneArray[arrayPosition]).getDocument() { (document, error) in if let document = document, document.exists { self.tfPrefix.text = document.get("Prefix") as? String self.tfIcao.text = document.get("Icao") as? String self.tfModel.text = document.get("Model") as? String self.tfSerial.text = document.get("Serial") as? String self.tfManifacture.text = document.get("Manifacture") as? String self.tfYear.text = document.get("Year") as? String self.tfRules.text = document.get("Rules") as? String self.tfOperator.text = document.get("Operator") as? String self.tfCVA.text = document.get("CVA") as? String } else { print("Document does not exist") } } } any help please A: Firestore`s queries run asyncronously, not one after another. So the second query may start earlier than the first is completed. If you want to run them one by one you need to put 2nd query into 1st. Try this: func readAirplanes() { var airplaneArray = [String]() var arrayPosition = 1 db.collection("airplane").whereField("Userid", isEqualTo: userID).getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") return } else { self.lbNext.isHidden = false self.btEdit.isUserInteractionEnabled = true self.btDelete.isUserInteractionEnabled = true for document in querySnapshot!.documents { airplaneArray.append(document.documentID) } db.collection("airplane").document(airplaneArray[arrayPosition]).getDocument() { (document, error) in if let document = document, document.exists { self.tfPrefix.text = document.get("Prefix") as? String self.tfIcao.text = document.get("Icao") as? String self.tfModel.text = document.get("Model") as? String self.tfSerial.text = document.get("Serial") as? String self.tfManifacture.text = document.get("Manifacture") as? String self.tfYear.text = document.get("Year") as? String self.tfRules.text = document.get("Rules") as? String self.tfOperator.text = document.get("Operator") as? String self.tfCVA.text = document.get("CVA") as? String } else { print("Document does not exist") } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/64285676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get access to StateNotifier state in HookWidget? We can create a StateNotifierProvider like this: final provider = StateNotifierProvider((ref) => CounterNotifier()); To access provider in HookWidget, we can use useProvider like this: final counterModel = useProvider(provider); But how to get state? The below code used to work till last year but does not work now: final counterModel = useProvider(provider.state); Now it says the getter state isn't defined. So how to get access to the state? A: As of Riverpod 0.14.0, the way we work with StateNotifier is a bit different. Now, state is the default property exposed, so to listen to the state, simply: final counterModel = useProvider(provider); To access any functions, etc. on your StateNotifier, access the notifier: final counterModel = useProvider(provider.notifier); And now when we create StateNotifierProviders, we include the type of the state of the StateNotifier: final provider = StateNotifierProvider<CounterNotifier, CounterModel>((ref) => CounterNotifier()); See more on the changes from 0.13.0 -> 0.14.0 here.
{ "language": "en", "url": "https://stackoverflow.com/questions/67152281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building a Chat application using Server sent Event and node.js I am new to node.js and SSE. I want to create a chat application using SSE and node.js. can any one guide which is better SSE or websocket? Is there any polyfill for IE using js not php for IE7+ Please suggest. Thanks in advance. A: If the client will never make requests to the server and the server will be doing all the pushing, then you should use server-sent events. However, for a chat application, because clients need to constantly send requests to the server, the WebSocket API is the natural choice. The "polyfills" for the WebSocket API are other technologies that mimic a socket connection in a much less efficient manner, like, for example, Ajax long polling. WebSocket libraries like Socket.IO are designed to use the WebSocket API when available and fall back to other technologies like Ajax long polling when the WebSocket API is not available. Certain server side languages also handle resources differently. For example, PHP will require 1 process per socket connection, which can fill a thread limit quickly, whereas NodeJS (IIRC) can loop through the connections and handle them all on 1 thread. So how the language handles resources given your chosen solution should be considered as well. A: First of all think about compatibility. SSE: http://caniuse.com/#feat=eventsource IE: no support Firefox: Version 6+ Opera: Version 11+ Chrome: Unknown version + Safari: Version 5.1+ WebSocket: (protocol 13) http://caniuse.com/#feat=websockets IE: Version 10+ Firefox: Version 11+ Opera: Version 12.1+ Chrome: Version 16+ Safari: Version 6+ I know a lot of modules that works with WebSockets (including one made by me simpleS, I made a simple demo chat to show how should the connections be organized in channels, give it a try), and a bit lesser those which works with SSE, I guess that the last ones are less tested and you cannot rely to much on them in comparison with modules that works with WebSockets. You can find mode information about the WebSockets and SSE here: WebSockets vs. Server-Sent events/EventSource A: there is a polyfill - https://github.com/Yaffle/EventSource (IE8+) and example of chat - https://github.com/Yaffle/EventSource/blob/master/tests/server.js
{ "language": "en", "url": "https://stackoverflow.com/questions/14555837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tomcat error when referencing component link: attribute pageURI is mandatory Currently my pages are returning errors since I've begun implementing XPM into are JSP environment. The component links seems to be the problem here. It was working fine several days ago, now we continiously get these Tomcat errors: SEVERE: Servlet.service() for servlet [jsp] in context with path [/JSPStaging] threw exception [/en_nl/system/footer.jsp (line: 10, column: 8) According to the TLD or the tag file, attribute pageURI is mandatory for tag ComponentLink] with root cause org.apache.jasper.JasperException: /en_nl/system/footer.jsp (line: 10, column: 8) According to the TLD or the tag file, attribute pageURI is mandatory for tag ComponentLink at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42) at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:408) at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:237) at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:858) at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1539) at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376) at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428) at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2434) at org.apache.jasper.compiler.Node$Root.accept(Node.java:475) at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376) at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1795) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:217) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:373) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:353) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544) at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:954) at org.apache.jsp.en_005fnl.index2_jsp._jspService(index2_jsp.java:137) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.tridion.preview.web.BinaryContentFilter.doFilter(BinaryContentFilter.java:55) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.tridion.preview.web.PageContentFilter.doFilter(PageContentFilter.java:75) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.tridion.ambientdata.web.AmbientDataServletFilter.doFilter(AmbientDataServletFilter.java:255) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) 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:662) Weirdly enough, the componentlinks on the plain JSP file are there, including the PageURI.: <tridion:ComponentLink runat="server" PageURI="tcm:17-480-64" ComponentURI="tcm:17-795" TemplateURI="tcm:0-0-0" AddAnchor="false" LinkText="&lt;img src=&#34;/Images/women_edfd8f3453414ade82b7becaa0790386.jpg&#34; alt=&#34;Woman #1&#34;&gt;" LinkAttributes="" TextOnFail="true"/> as well as properly including the cd_tags lib into every seperate page template, along with the proper core references: <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <%@ taglib uri="cd_tags" prefix="tridion" %> I've tried searching for the error, but there's no Tridion context-specific solution. I'm currently looking into resetting/reconfiguring component linking, but I'm not entirely sure if there's anything wrong in the configs in the first place. Any ideas would be fantastic. A: That link is for the .NET control -- not the JSP tag library. Maybe someone changed the Target Language on the Publication Target you are using (or it's published to the wrong target)? Another possibility is that it is hard-coded in the template instead of using TCDL. A: Thanks to Peter Kjaer pointing me in the direction, this issue is now solved. It is not, however, due to publication targets and language (since they were set correctly - but I wouldn't completely rule out the possibilty of pubtargets conflicting). The issue turned out to be the deployer_conf xml file on the HTTP upload server role, with its (default) lines within the TCDLEngine node - Properties. <!--<Property Name="tcdl.dotnet.style" Value="controls"/>--> <Property Name="tcdl.jsp.style" Value="tags"/> As you can see, I commented the dotnet line. It will now properly resolve links, as well as componentlinks not including 'runat's anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/14810369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to replace multiple identical lines in a file using Ansible I have a log rotate: /var/log/pgsql/*.csv { missingok copytruncate notifempty rotate 1 compress hourly size 25M create 0644 postgres postgres } /var/log/pgsql/*.log { missingok copytruncate notifempty rotate 1 compress hourly size 25M create 0644 postgres postgres } Using ansible lineinfile: - name "change postgres logrotate config" become: yes become_user: root lineinfile: path: /etc/logrotate.d/postgresql regexp: 'size *' line:' size 10M' backrefs: yes I'm able to change only the last matching line. How can I replace both identical lines (size 25M), with the new line (size 10M)
{ "language": "en", "url": "https://stackoverflow.com/questions/67660019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to change the value of dictionary during looping How do I modify a value in Dictionary? I want to reassign a value to a value in my dictionary while looping on my dictionary like this: for (int i = 0; i < dtParams.Count; i++) { dtParams.Values.ElementAt(i).Replace("'", "''"); } where dtParams is my Dictionary I want to do some thing like this: string a = "car"; a = a.Replace("r","t"); A: The string Replace function returns a new modified string, so you'd have to do something like: foreach (var key in dtParams.Keys.ToArray()) { dtParams[key] = dtParams[key].Replace("'", "''"); } EDIT: Addressed the collection is modified issue (which I didn't think would occur if you access a key that already exists...) A: when you use replace , it will return a new string instance , you need to assign the value in the dictionary after replace becaue string is immutable in nature A: You can't do this directly; you cannot modify a collection while you're enumerating it (also, avoid using ElementAt here; this is a LINQ to Objects extension method and is inefficient for iterating over an entire list). You'll have to make a copy of the keys and iterate over that: foreach(var key in dtParams.Keys.ToList()) // Calling ToList duplicates the list { dtParams[key] = dtParams[key].Replace("'", "''"); } A: A little lambda will go a long way. ;) I dropped this into LINQPad and tested it out for you. All the collections have .To[xxx] methods so you can do this quite easily in 1 line. var dtParams = new Dictionary<string, string>(); dtParams.Add("1", "'"); dtParams.Add("a", "a"); dtParams.Add("b", "b"); dtParams.Add("2", "'"); dtParams.Add("c", "c"); dtParams.Add("d", "d"); dtParams.Add("e", "e"); dtParams.Add("3", "'"); var stuff = dtParams.ToDictionary(o => o.Key, o => o.Value.Replace("'", "''")); stuff.Dump();
{ "language": "en", "url": "https://stackoverflow.com/questions/4388396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: NServiceBus : Identity context in outgoing message mutators NServiceBus 4.4.0 Hi ! I use message mutators for impersonification purpose. Basicaly, I serialize the ClaimsPrincipal.Identity in a JWT token in the outgoing mutator and deserialize it in the incoming mutator to add it to the principal of the NServiceBus host app. (based on this article : http://beingabstract.com/2014/10/serializing-the-claimsidentity/). The problem is that when we're in the outgoing mutator (IMutateOutgoingTransportMessages) the ClaimsPrincipal.Identity doesn't contain all the claims. Only the name. But if I'm looking just before the "Bus.Send" command, I have the correct claims (groups, permissions, etc.). The outgoing message mutator resides in an outside class, which is referenced by my main project. Here's the code from the outgoing mutator : public class OutgoingAccessMutator : IMutateOutgoingTransportMessages, INeedInitialization { public IBus Bus { get; set; } public void Init() { Configure.Instance.Configurer.ConfigureComponent<OutgoingAccessMutator>(DependencyLifecycle.InstancePerCall); } public void MutateOutgoing(object[] messages, TransportMessage transportMessage) { if (!transportMessage.Headers.ContainsKey(Common.Constants.Securite.AuthenticationTokenID)) { transportMessage.Headers[Common.Constants.Securite.AuthenticationTokenID] = TokenHelper.GenerateToken(ClaimsPrincipal.Current.IdentitePrincipale() as ClaimsIdentity); } } } The GenerateToken is in a static helper class in the mutator dll : public static string GenerateToken(ClaimsIdentity identity) { var now = DateTime.UtcNow; var tokenHandler = new JwtSecurityTokenHandler(); var securityKey = System.Text.Encoding.Unicode.GetBytes(Common.Constants.Securite.NServiceBusMessageTokenSymetricKey); var inMemorySymmetricSecurityKey = new InMemorySymmetricSecurityKey(securityKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = identity, TokenIssuerName = Common.Constants.Securite.NServiceBusMessageTokenIssuer, AppliesToAddress = Common.Constants.Securite.NServiceBusMessageTokenScope, Lifetime = new Lifetime(now, now.AddMinutes(5)), SigningCredentials = new SigningCredentials(inMemorySymmetricSecurityKey, Common.Constants.Securite.SignatureAlgorithm, Common.Constants.Securite.DigestAlgorithm) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return tokenString; } Then in the incoming message mutator which lives in another process (windows service executable host), I deserialize it : public class IncomingAccessTokenMutator : IMutateIncomingTransportMessages, INeedInitialization { public IBus Bus { get; set; } public void Init() { Configure.Instance.Configurer.ConfigureComponent<IncomingAccessTokenMutator>(DependencyLifecycle.InstancePerCall); } public void MutateIncoming(TransportMessage transportMessage) { if (transportMessage.Headers.ContainsKey(Common.Constants.Securite.AuthenticationTokenID)) { try { var token = transportMessage.Headers[Common.Constants.Securite.AuthenticationTokenID]; var identity = TokenHelper.ReadToken(token); if (identity != null) { identity.Label = Common.Constants.Securite.NomIdentitePrincipale; ClaimsPrincipal.Current.AddIdentity(identity); } } catch (Exception) { Bus.DoNotContinueDispatchingCurrentMessageToHandlers(); throw; } } } } Does anyone have any idea why the identity context is not the same inside the mutator and in the service that sends the message ?
{ "language": "en", "url": "https://stackoverflow.com/questions/32464173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MapView not showing Blue Dot Current Location In my iphone app I am using MKMapview to show locations,for the first time it showing current location with a blue dot.But if drag away in map and click the current location button it doesnt show the blue dot(but I am able to return the current location region) -(IBAction)currntLctnClick:(id)sender{ [map setCenterCoordinate:map.userLocation.location.coordinate animated:YES]; } A: Considering you said that you can see the user location on first load, it's safe to assume you have setShowsUserLocation: set to YES. Have you implemented - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation in your view controller? If so, be sure to avoid providing an annotation view for the built in user location marker. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { //check annotation is not user location if([annotation isEqual:[mapView userLocation]]) { //bail return nil; } static NSString *annotationViewReuseIdentifer = @"map_view_annotation"; //dequeue annotation view MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifer]; if(!annotationView) { annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifer]; } //set annotation view properties [annotationView setAnnotation:annotation]; return annotationView; } A: Have you implemented the viewForAnnotation function? are you checking that you're not drawing (or failing to draw) a different sort of pin for the MKUserLocation? A: To show your current location with blue dot - (void)viewDidLoad { yourMapView.showsUserLocation=YES; } Navigate to your current location on button click -(IBAction)currntLctnClick:(id)sender { MKCoordinateRegion location = MKCoordinateRegionMakeWithDistance(yourMapView.userLocation.coordinate, 10000.0, 10000.0); [yourMapView setRegion:location animated:YES]; } EDIT Or if still your blue dot is not visible then just remove your MapView from xib and drag and drop it again. A: For all those who came here by searching for GoogleMaps solution - This is the property you need to set true. Swift 3.0 self.mapView.isMyLocationEnabled=true A: [map setShowsUserLocation:YES]; A: Just check that annotation is MKUserLocation while iterating in viewForAnnotation method and return nil if it is true. It works that way because MKUserLocation is also part of mapView.annotations array and you just need to pass it through without any modification. func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { guard !(annotation is MKUserLocation) else { return nil } // your viewForAnnotation code... } A: Just to add, if you are using Interface Builder, select the Map View and in the Attributes section, make sure User Location is checked: Map View Attributes
{ "language": "en", "url": "https://stackoverflow.com/questions/14979879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Merging two PySpark DataFrame's gives unexpected results I have two PySpark DataFrames (NOT pandas): df1 = +----------+--------------+-----------+---------+ |pk |num_id |num_pk |qty_users| +----------+--------------+-----------+---------+ | 63479840| 12556940| 298620| 13| | 63480030| 12557110| 298620| 9| | 63835520| 12627890| 299750| 8| df2 = +----------+--------------+-----------+----------+ |pk2 |num_id2 |num_pk2 |qty_users2| +----------+--------------+-----------+----------+ | 63479800| 11156940| 298620| 10 | | 63480030| 12557110| 298620| 1 | | 63835520| 12627890| 299750| 2 | I want to join both DataFrames in order to get one DataFrame df: +----------+--------------+-----------+---------+ |pk |num_id |num_pk |total | +----------+--------------+-----------+---------+ | 63479840| 12556940| 298620| 13| | 63479800| 11156940| 298620| 10| | 63480030| 12557110| 298620| 10| | 63835520| 12627890| 299750| 10| The only condition for merging is that I want to sum up the values of qty_users for those rows that have the same values of < pk, num_id, num_pk > in df1 and df2. Just as I showed in the above example. How can I do it? UPDATE: This is what I did: newdf = df1.join(df2,(df1.pk==df2.pk2) & (df1.num_pk==df2.num_pk2) & (df1.num_id==df2.num_id2),'outer') newdf = newdf.withColumn('total', sum(newdf[col] for col in ["qty_users","qty_users2"])) But it gives me 9 columns instead of 4 columns. How to solve this issue? A: The outer join will return all columns from both tables.Also,we got to fill null values in qty_users as sum will also return null. Finally, we can select using coalsece function, from pyspark.sql import functions as F newdf = df1.join(df2,(df1.pk==df2.pk2) & (df1.num_pk==df2.num_pk2) & (df1.num_id==df2.num_id2),'outer').fillna(0,subset=["qty_users","qty_users2"]) newdf = newdf.withColumn('total', sum(newdf[col] for col in ["qty_users","qty_users2"])) newdf.select(*[F.coalesce(c1,c2).alias(c1) for c1,c2 in zip(df1.columns,df2.columns)][:-1]+['total']).show() +--------+--------+------+-----+ | pk| num_id|num_pk|total| +--------+--------+------+-----+ |63479840|12556940|298620| 13| |63480030|12557110|298620| 10| |63835520|12627890|299750| 10| |63479800|11156940|298620| 10| +--------+--------+------+-----+ Hope this helps.! A: Does this output what you want? df3 = pd.concat([df1, df2], as_index=False).groupby(['pk','num_id','num_pk'])['qty_users'].sum() The merging of your 2 dataframes is achieved via pd.concat([df1, df2], as_index=False) Finding the sum of the qty_users columns when all other columns are the same first requires grouping by those columns groupby(['pk','num_id','num_pk']) and then finding the grouped sum of qty_users ['qty_users'].sum()
{ "language": "en", "url": "https://stackoverflow.com/questions/46980635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: read file descriptor multiple times I just dont understand what is wrong with my code, The goal is to encrypt one file using other file as a key using bitwise xor. It works, the problem is that the while is executed only one time and thats not enough. The if statement in the while is in case the key is shorter than the input file. fd_in,fd_key and fd_out are the file descriptors. while ((numOfBytes = read(fd_in, buf, 4096))!=0){ numOfBytes_key=read(fd_key, buf_key, numOfBytes); if (numOfBytes>numOfBytes_key){ lseek(fd_in, -(numOfBytes - numOfBytes_key), SEEK_CUR); lseek(fd_key, 0, SEEK_SET); } for (i = 0; i < numOfBytes_key; i++){ buf_out[i] = buf[i] ^ buf_key[i]; } write(fd_out, buf_out, numOfBytes_key); } A: I guess that read functions can mess things up, since reading from empty, non existing ect file will return -1.Thus, rest of computations will fall. Try to avoid that by including if firective: while ((numOfBytes = read(fd_in, buf, 4096))!=0) { numOfBytes_key=read(fd_key, buf_key, numOfBytes); if (numOfBytes>numOfBytes_key && (numOfBytes >= 0) &&(numOfBytes_key >= 0 )) { lseek(fd_in, -(numOfBytes - numOfBytes_key), SEEK_CUR); lseek(fd_key, 0, SEEK_SET); } for (i = 0; i < numOfBytes_key; i++){ buf_out[i] = buf[i] ^ buf_key[i]; } write(fd_out, buf_out, numOfBytes_key); }
{ "language": "en", "url": "https://stackoverflow.com/questions/22156853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wordpress Single Sign On Client free plugin to authenticate users against external OAuth2 server I'm working on a project for a client who has their own OAuth2 SSO authentication server they use on multiple different apps. Previously their Wordpress website was password-protected (in order to access it they used the Password Protected plugin which hid everything on the website until the user input one specific shared password. Now they want their Wordpress website to: * *Immediately redirect to their (non-wordpress) SSO login website *After logging in (or detecting that the user is already logged in) redirect back to the Wordpress site. I already have all the requirements - client ID, realm, secret, I am on the whitelist of the SSO server *There are no requirements to sign REST requests or anything. All the SSO needs is to restrict the data on the wordpress site unless the user is already logged in on their server, or redirect them to the server if they are not logged in and after logging in redirect them back with the redirect-uri parameter. However, I am having trouble finding the right plugin,since there is no budget fora paid plugin. I have tried miniOrange but in order to restrict all access to users who are not logged in I'd have to use the paid version. Oauth0 is also paid. Is there any other plugin or a set of plugins that would help me? A: In case anyone discovered this post, I managed to finish it myself. I used this plugin but had to manually rewrite it quite a lot, changing the conditions on when to call the authentication endpoint (call it on init rather than on url route parameter change), had to write new code for calling reshresh token endpoint and logout endpoint and all sorts of other stuff. Sadly, i can't publish the newly edited plugin, since my client wouldn't allow it. The takeaway from this is that if you want SSO against an external identity provider in such a way that without being logged in through your SSO you can't view the page, it's difficult and you'd either have to pay money for an expensive plugin or extend an existing plugin, spending days figuring out how to do it. A: Was working on something similar way back. It is true that for most of the plugins we need to pay. I too have tried miniorange and the other plugin you have mentioned. The use case which you are referring to, I have done some manual changes from my side to achieve it and never got the solution I was looking for. After some research, I found out that this Page and Post restriction plugin by miniorange itself along with the SSO plugin can be used to restrict all access to users who are not logged in if I am not wrong about it, you can give it a try yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/65735182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building Sencha Touch 2 login system I am trying to build a multi log in system using Sencha Touch 2, were the user have to select if he is an AGENT OR FOLLOWER. so far i have been able to come up with a simple log in form. with no function. my code is just like this: Ext.define("ikhlas.view.login", { extend: 'Ext.Panel', xtype: 'loginpanel', config:{ title: 'Login', iconCls: 'more', styleHtmlContent: true, layout:{ type: 'vbox', }, items: [ { xtype: 'fieldset', iconCls: 'add', items: [ { xtype: 'emailfield', name: 'email', placeHolder: 'Username' }, { xtype: 'passwordfield', name: 'password', placeHolder: 'Password' }, { xtype: 'selectfield', label: 'User Type', options: [ {text: 'Agent', value: '0'}, {text: 'Follower', value: '1'} ] } ]}, { xtype: 'button', text: 'LogIn', ui: 'confirm', width: '40%', height: '7%', flex: 1, left: '55%', action: 'submitContact' }, { xtype: 'button', text: 'Forgot Username', ui: 'confirm', width: '41%', height: '4%', top: '90%', flex: 1, action: 'ForgotUsername' }, { xtype: 'button', text: 'Forgot Password', ui: 'confirm', width: '40%', height: '4%', top: '90%', flex: 1, left: '47%', action: 'ForgotPassword' }, ]} }); Now i will like to know how do i validate the user information (user name and password) from an API(a url will be given) so as to confirm the login username and password are correct before they can be allowed to access the application. Secondly i will like to throw an error message if the username or password is incorrect. A: It's obvious that you have to authenticate server-side. Assuming that you've already had one, so the remaining is not very difficult. The most simple way is just send an Ext.Ajax.request: Ext.Ajax.request({ url: your_API_url, params: { username: your_username_from_formpanel, password: your_password_from_formpanel }, timeout: 10000, // time out for your request success: function(result) { // here, base on your response, provide suitable messages // and further processes for your users }, failure: function(){ Ext.Msg.alert("Could not connect to server."); } }); Note: for security reasons, you should encrypt your user's password before sending it to server.
{ "language": "en", "url": "https://stackoverflow.com/questions/10699071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a progressbar timeline for an online course I'm creating an online course and I would like to create a horizontal progressbar-style timeline, that monitors the progress of the course and automatically displays the progress based on the current date. Let's say for example that the course has the following events: * *Course starts, 1.2.2015 17:30 *Assignment number 1 deadline, 10.2.2015 23:59 *Peer review deadline for assignment 1, 20.2.20.15 23:59 *Assignment number 2 deadline, 1.3.2015 23:59 *Course ends, 10.3.2015 23:59 What would be a smart way to approach this? I have googled around and found several javascript plugins related to timelines, but typically they seem to be for creating timelines of historic events. Is there something that is suitable for such a course progressbar?
{ "language": "en", "url": "https://stackoverflow.com/questions/28011913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON Parse error: Unrecognized token '<' React native Code so far : fetch('http:/example.com',{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ Id: this.state.TextInputId }) }).then((response) => response.json()) .then((responseJson) => { Snackbar.show({ title: responseJson, duration: Snackbar.LENGTH_SHORT, }); }).catch((error) => { console.error(error); }) this.props.navigation.navigate('Home') Produces the error: Parse error: Unrecognized token '<' React native A: This is not a issue related to react-native but related to your response. You're getting something like '<' in response which cannot be converted to JSON. Try with response.text()
{ "language": "en", "url": "https://stackoverflow.com/questions/55020034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Limit filter inside scope of include filter not working in loopback I have two tables, 'categoryinfo' and 'accounttag'. The two tales have the following relation: categoryinfo hasMany accounttag accounttag belongsTo categoryinfo I want to apply limit on: * *the number of categories (set to 5) and *number of accounttags fetched from the relation for each category (set to 10) However, the limit filter inside the scope of the include filter is not working properly and is fetching less results than the set limit for each category but the database contains more valid entries than the limit value. categoryinfo.find( { where: { valid: 1 }, include: [ { relation: 'accounttag', scope: { where: { valid: 1 }, order: 'rank ASC', limit: 10, } } ], order: 'modifiedon DESC', limit: 5 } ) Is there any way to achieve the required result using the same filters? A: With the current stable Version of Loopback you cannot filter on Level 2 properties for Relational Databases. These are some of the Issues raised on the same in Loopback https://github.com/strongloop/loopback/issues/517 https://github.com/strongloop/loopback/issues/683 As a matter of fact you might want to look into native sql queries in loopback and do the filtering there, or might need to use native javascript array methods for filtering
{ "language": "en", "url": "https://stackoverflow.com/questions/47653295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write TypeScript and CoffeeScript in Brackets? I want to write TypeScript and CoffeeScript in the Brackets code editor, but I am having difficulties. How do I compile it to vanilla js? How to refer it in the html page? A: For TypeScript intellisence / syntax highlighting / live error checking You need the brackets-typescript plugin : https://github.com/fdecampredon/brackets-typescript Compile to vanilla JS You can use grunt to do that for you : https://github.com/grunt-ts/grunt-ts. It can compile your project whenever you save a file in brackets (or any other editor). The output is JavaScript How to refer it in the html page You point to the generated JS with a normal script tag as you do if you were just using JavaScript to begin with. Alternatively you can use something like RequireJS http://requirejs.org/
{ "language": "en", "url": "https://stackoverflow.com/questions/24507965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PHP Session - Values Randomly NOT Being Written I am building a site that combines ajax and PHP to create dynamic forms that load/validate/submit in-page. I am using a combination of PHP session variables with custom handlers, $.post, and $().load to accomplish this. I build my forms in individual php pages (they are very large) and then load them into a section of my main page. At the top of my main page I start a session like so: <?php require("inc/SecureSession.php"); // Custom handlers session_save_path($_SERVER['TEMP']); session_start(); ?> Then in each form page I start a session and generate a token variable, like so: <?php require("inc/SecureSession.php"); // Custom handlers session_save_path($_SERVER['TEMP']); session_start(); $_SESSION['token'] = rand(); ?> This token variable gets inserted as a hidden field at the bottom of the form page, and should write to the session. However, I've found that session variables set in dynamically loaded (or posted) pages do not seem to consistently stay set. They work within the scope of the form page but then do not always carry over back to the main page. I thought this might be because they were not actually accessing the right session, but it seems all session variables outside the form page can be accessed within the form page. So I am stumped. The PHP handler I am using is the one here: http://www.zimuel.it/en/encrypt-php-session-data/ Edit: When I load one of the form-pages directly, it writes 100% of the time. It is only when I load a form via jQuery that it gets wonky. Edit2: The issue wasn't that I was declaring the code in the wrong order. I did some research and found that I am supposed to declare the save path and handler functions before I start the session. The issue appears to have been either that I opened php with "
{ "language": "en", "url": "https://stackoverflow.com/questions/12576886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacing Strings in Oracle 8i Query I've got a table like this in ORACLE 8i Value | Timestamp KKQ | 10:00 KVKK | 11:00 KMPE | 12:00 PPKKPE | 13:00 and I need to replace KV for V, KM for M, PE for R ,PP for N and P for L when querying these values. What's the best way to do it? The problem I see is that we can have ANY combination of the strings in Value column... the values we can have there are: KK, Q, KV, V, KM, M, PE, R, PP, N, P, L. A: select replace( replace( replace( replace(<input>, 'KV', 'V'), 'KM', 'M'), 'PE', 'R'), 'PP', 'N') from .... A: This cannot be solved by SQL, say with several REPLACE functions. The reason for this is that for instance PPP can mean PP-P or P-PP and thus be substituted either by PN or NP. Same for xxxKVxxx; is this KV or is it a trailing K and a leading V? You will have to write a database function (PL/SQL) that loops through the string and replaces part by part. You will certainly know how to interpret PPP :-) (BTW: Seems like a bad idea to store the classifications as a concatenated string of letters rather than in a separate table. You are using a relational database system without making use of the relational part. Hence the problem now.)
{ "language": "en", "url": "https://stackoverflow.com/questions/22531023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting ANR dialog while starting a service in Android Lollipop I'm using a service to to play radio, when the app is running in the background. My app contains 4 radio channels. So I have used a viewpager. When i swipe slowly, my app responds properly. But when I swipe quickly, my app is not responding & I'm getting a ANR dialog. As per the documentaion, a service runs as a separate thread. So it should not block my app. But to be on safer side, I added service inside async task. But still the same problem. I tested it on Nexus 5 device. But When I run the app on emulator(Nexus 5-Lollipop). It works perfectly. Then what might be the problem? Is anyone facing a similar problem. This is how I start my service: private void playRadio() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { if (getUserVisibleHint()) { if (PreferencesManager.getInstance(getActivity()).isLiveRadioPlaying()) stopRadio(); Log.d("Visible", ""); Intent intent = new Intent(getActivity(), LiveRadioService.class); intent.setAction(ACTION_START); intent.putExtra(RADIO_URL, mRadioUrl); intent.putExtra(RADIO_TITLE, mSectionTitle); intent.putExtra(LIVE_RADIO_SECTION_POSITION, mSectionPos); getActivity().startService(intent); } return null; } }.execute(); } Preparing the media player inside asynctask: private void playRadio() { new AsyncTask<Void,Void,Void>(){ @Override protected Void doInBackground(Void... voids) { try { cancelNotification(); mMediaPlayer.stop(); mMediaPlayer.reset(); mMediaPlayer.setDataSource(mUrl); mMediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(); } A: As per the documentaion, a service runs as a separate thread. Not True Because Service always run in same process of Application but worker thread is used by IntentService to process received the Intents. I'm getting a ANR dialog Probably Service doing some network related work or Api calls on Main Thread. To prevent ANR dialog launch separate Thread or use AsyncTask, IntentService to do intensive or blocking operations in Service
{ "language": "en", "url": "https://stackoverflow.com/questions/28402717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CommandBinding: CustomCommand-Class is not found I am about to learn CommandBindings in WPF, but somehow I cannot create custom commands. Following error is shown: (XDG0008) The name "CustomCommands" does not exist in the namespace "clr-namespace:CommandBindingWPF" <Window.CommandBindings> <CommandBinding Command="local:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" /> </Window.CommandBindings> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = viewmodel; } //more code but not relevant for question private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e) { Application.Current.Shutdown(); } } public static class CustomCommands { public static readonly RoutedUICommand Exit = new RoutedUICommand ( "Exit", "Exit", typeof(CustomCommands) ); //Define more commands here, just like the one above } I even tried to copy-paste it from https://wpf-tutorial.com/commands/implementing-custom-commands/ and paste the CanExecute and Executed just for testing in MainWindow-class (and of course i changed the xmlns:self), but it still does not work. Can someone help me out? It is making me crazy. A: The XAML designer in Studio takes information about types not from projects, but from their assemblies. Therefore, if you made a change to the project, then the Designer will not see them until you make a new assembly of the project. You do not need to close / open the Studio for this. Go to the "Project" menu, select "Build" there. Or the same can be done in the "Solution Explorer" in the context menu of the Project. Also, if you made changes to the project, a new build will be performed automatically when the Solution is launched for execution. In very rare cases (usually after some bugs, incorrect closing of the Studio), before building, you still need to perform a "Cleanup" of the Project or Solution. P.S. Due to this peculiarity of the XAML Designer, in order not to constantly stumble upon such errors (and in some cases they can be very confusing and even lead to compilation errors), it is recommended to create all types used in XAML in other projects. This makes it much easier to understand the source of the XAML Designer and Compiler errors and warnings. A: I fixed it by myself! I closed VS, rebuilt the project and the error did not pop up again (WPF designer issues : XDG0008 The name "NumericTextBoxConvertor" does not exist in the namespace "clr-namespace:PulserTester.Convertors"). I hate VS.
{ "language": "en", "url": "https://stackoverflow.com/questions/69129705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Psycopg2: cursor.execute is not working properly So, I have the following code that inserts the data of an old database to a new one: ... cur_old.execute("""SELECT DISTINCT module FROM all_students_users_log_course266""") module_rows = cur_old.fetchall() for row in module_rows: cur_new.execute("""INSERT INTO modules(label) SELECT %s WHERE NOT EXISTS (SELECT 1 FROM modules WHERE label=%s)""", (row[0], row[0])) ... The last line executes a query where labels are inserted into the new database table. I tested this query on pgAdmin and it works as I want. However, when execute the script, nothing is inserted on the modules table. (Actually the sequences are updated, but none data is stored on the table). Do I need to do anything else after I call the execute method from the cursor? (Ps. The script is running till the end without any errors) A: As Evert said, the commit() was missing. An alternative to always specifying it in your code is using the autocommit feature. http://initd.org/psycopg/docs/connection.html#connection.autocommit For example like this: with psycopg2.connect("...") as dbconn: dbconn.autocommit=True A: You forgot to do connection.commit(). Any alteration in the database has to be followed by a commit on the connection. For example, the sqlite3 documentation states it clearly in the first example: # Save (commit) the changes. conn.commit() And the first example in the psycopg2 documentation does the same: # Make the changes to the database persistent >>> conn.commit()
{ "language": "en", "url": "https://stackoverflow.com/questions/36464592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Hibernate C3P0 pool mechanism I am using Hibernate with my web application. And used C3P0 connection pooling mechanism for it. My configuration is as bellow, To check if it's working properly or not, I put max_size and min_size to 0. I think ideally if it's 0 then it should not give me any connection and should throw error/exception. But it doesn't do any thing like this. It's working as normal it should. So, how can I be sure that the given C3P0 related configuration is perfect one? <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/reg</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="connection.autocommit">false</property> <!-- Connection pooling configuration --> <property name="c3p0.acquire_increment">1</property> <property name="c3p0.idle_test_period">1</property> <!-- seconds --> <property name="c3p0.max_size">0</property> <property name="c3p0.max_statements">0</property> <property name="c3p0.min_size">0</property> <property name="c3p0.timeout">200</property> <!-- seconds --> <property name="hibernate.show_sql">false</property> A: It depends on the app you are building. Database connection pools are used because of following reasons: * *Acquiring DB connection is costly operation. *You have limited resources and hence at a time can have only finite number of DB connections open. *Not all the user requests being processed by your server are doing DB operations, so you can reuse DB connections between requests. Since acquiring new connections are costly, you should keep min_size to be non-zero. Based on what is load during light usage of your app, you can use a good guess here. Typically, 5 is specified in most examples. acquire_increment depends on how the fast the number of users that are using your app increases. So, imagine if you ask 1 new connection every time you needed an extra connection, your app may perform badly. So, anticipating user burst, you may want to increment in larger chunks, say 5 or 10 or more. Typically, max. number of DB connections you have can be lesser than the number of concurrent users that are using your app. However, if you are application is database-heavy, then, you may have to configure max_size to match the number of concurrent users you have. There will be a point when you may not be able to deal with so many users even after configuring max_size to be very high. That's when you will have to think about re-designing your app to avoid load on database. This is typically done by offloading read operations to alternate DB instance that serves only read operations. Also, one employs caching of such data which do not change often but are read very often. Similar justification can be applied for other fields as well
{ "language": "en", "url": "https://stackoverflow.com/questions/17319868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creat matrix numbers from 1 to 64 with only one loop how can I do that? I want to create a method with signature: void InitMatrixLinear(int[,] matrix) but with only one loop I don't wanna create the same photo with two loops I need to make the same photo with only one loop how can I create this? Like this I want to create: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 A: Assuming the matrix passed in is 8x8 (since we want [1,2,...,64] as the elements): for (int i = 0; i < 64; i++){ matrix[i%8,i/8] = i+1; } or for (int i = 0; i < 64; i++){ matrix[i/8,i%8] = i+1; } Depending on the desired orientation of the matrix
{ "language": "en", "url": "https://stackoverflow.com/questions/60179066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the contourf handler from matplotlib? I was wondering how to get the contourf handler from an axes within matplotlib. From the codes and outputs below you can easily find that im is matplotlib.contour.QuadContourSet but no such kind of thing in ax.get_children(). I know I can obtain im by assigning operations but sometimes using ax.get_children() can make life much easier when I just want to use im in another place once. Codes import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = plt.axes() im = ax.contourf(np.random.random((10,10))) im, ax.get_children() Output (<matplotlib.contour.QuadContourSet at 0x2abd4a3243c8>, [<matplotlib.collections.PathCollection at 0x2abd4a35b080>, <matplotlib.collections.PathCollection at 0x2abd4a35b4e0>, <matplotlib.collections.PathCollection at 0x2abd4a35ba58>, <matplotlib.collections.PathCollection at 0x2abd4a35be48>, <matplotlib.collections.PathCollection at 0x2abd4a365240>, <matplotlib.collections.PathCollection at 0x2abd4a365710>, <matplotlib.collections.PathCollection at 0x2abd4a365c18>, <matplotlib.spines.Spine at 0x2abd4a282a90>, <matplotlib.spines.Spine at 0x2abd4a282b38>, <matplotlib.spines.Spine at 0x2abd4a2f7320>, <matplotlib.spines.Spine at 0x2abd4a294d68>, <matplotlib.axis.XAxis at 0x2abd4a29a4a8>, <matplotlib.axis.YAxis at 0x2abd4a317748>, Text(0.5, 1.0, ''), Text(0.0, 1.0, ''), Text(1.0, 1.0, ''), <matplotlib.patches.Rectangle at 0x2abd4a33ca58>])
{ "language": "en", "url": "https://stackoverflow.com/questions/60284637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring Cloud Config Server Not Refreshing I'm setting up a Spring cloud server to read of an internal Stash directory. The server loads up ok the first time, but if I update properties in git, they don't get reflected until I restart cloud server (I try POST to /refresh endpoint). I'm on Windows and I see a few bugs related to server on Windows but I don't see any specific mention of my bug. A: see org.springframework.cloud.bootstrap.config.RefreshEndpoint code here: public synchronized String[] refresh() { Map<String, Object> before = extract(context.getEnvironment() .getPropertySources()); addConfigFilesToEnvironment(); Set<String> keys = changes(before, extract(context.getEnvironment().getPropertySources())).keySet(); scope.refreshAll(); if (keys.isEmpty()) { return new String[0]; } context.publishEvent(new EnvironmentChangeEvent(keys)); return keys.toArray(new String[keys.size()]); } that means /refresh endpoint pull git first and then refresh catch,and public a environmentChangeEvent,so we can customer the code like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/32364240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot log in with Keycloak using OIDC Plugin for Moodle I'm trying to improve the moodle login through Keycloak service. I installed this plugin (https://moodle.org/plugins/auth_oidc) on my local instance and after the installation I started to compile all the fields. The plugin provides a button in the login page that, on click, redirects to my keycloak login page. When I press "login" on keycloak what I expect is to return on moodle in a page like "registration page" where a user can add himself, but what I get is that I'm not logged and this error is displayed: Debug info: Error code: erroroidccall Γ—Stack trace: line 47 of /auth/oidc/classes/utils.php: moodle_exception thrown line 252 of /auth/oidc/classes/oidcclient.php: call to auth_oidc\utils::process_json_response() line 177 of /auth/oidc/classes/loginflow/authcode.php: call to auth_oidc\oidcclient->tokenrequest() line 84 of /auth/oidc/classes/loginflow/authcode.php: call to auth_oidc\loginflow\authcode->handleauthresponse() line 105 of /auth/oidc/auth.php: call to auth_oidc\loginflow\authcode->handleredirect() line 29 of /auth/oidc/index.php: call to auth_plugin_oidc->handleredirect() This error isn't explained in moodle docs. I saw the php but I didn't find anything helpful. In the code of the plugin I tryed to search the handleredirect() method but I didn't find it. Is there someone who fixed this error using keycloak (or other third-part oidc services)? A: I'm on the same problem with my keycloak and Moodle config. If you aren't an expert in PHP, you can edit the file of (Moodle Installation path) /auth/oidc/classes/oidcclient.php in the 252 line, and edit as follows: Then retry the login in your Moodle page and the result will be like this: Here you can view the error detail, in my case is a DNS problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/49492917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sync Hub and Spoke model with SQL Server Express on server and clients I have been researching on how to sync clients SQL Server Express to a central SQL Server Express. At first I looked at Replication but the only issue is that replication is not supported if the central server is SQL Server 2008 Express. I had to find another solution; I looked at the sync framework with WCF. At first it looked promising but the more I researched it the more I realized that documentation was extremely poor as well there were no samples for syncing SQL Server 2008 to SQL Server 2008 using Visual Studio 2010 project. I did find a few samples on blogs but could never get them to work. I am coming to the conclusion that sync framework is not the way to go because of the lack of support and samples for the product. I am now looking into a custom solution which will require a great deal more coding and testing. I was just wondering if anyone has had to sync production server SQL Server Express with clients also running SQL Server Express. How did you accomplish this and what technology did you use? I'm stuck, any help would be greatly appreciated. Thank You A: if you're referring to the VS Local Database Cache project item, yes, it doesnt support SQL Express as a client. if you're willing to hand code, the docs has a tutorial, see: Tutorial: Synchronizing SQL Server and SQL Express other samples you can take a look at: Database Sync:SQL Server and SQL Express 2-Tier Database Sync:SQL Server and SQL Express N-Tier with WCF
{ "language": "en", "url": "https://stackoverflow.com/questions/11703665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read an image file asynchronously I would like to read an image file asynchronously and Im trying to achieve that using async/await from C#. However, I still notice a significant lag with this implementation. Using the profiler I'm pretty confident it is it the FileStream.ReadAsync() method that takes ages to complete, rather than doing it asynchronously and stops the game from updating. I notice more lag this way than just using File.ReadAllBytes which is odd. I can't use that method that still causes some lag and I would like to not have a stop in frame rate. Here's some code. // Static class for reading the image. class AsyncImageReader { public static async Task<byte[]> ReadImageAsync(string filePath) { byte[] imageBytes; didFinishReading = false; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) { imageBytes = new byte[fileStream.Length]; await fileStream.ReadAsync(imageBytes, 0, (int) fileStream.Length); } didFinishReading = true; return imageBytes; } } // Calling function that is called by the OnCapturedPhotoToDisk event. When this is called the game stops updating completely rather than public void AddImage(string filePath) { Task<byte[]> readImageTask = AsyncImageReader.ReadImageAsync(filePath); byte [] imageBytes = await readImageTask; // other things that use the bytes.... } A: You don't need Task to load image asynchronously. You can use Unity's UnityWebRequest and DownloadHandlerTexture API to load. The UnityWebRequestTexture.GetTexture simplifies this since it setups up DownloadHandlerTexture for you automatically. This is done in another thread under the hood but you use coroutine to control it. public RawImage image; void Start() { StartCoroutine(LoadTexture()); } IEnumerator LoadTexture() { string filePath = "";//..... UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(filePath); yield return uwr.SendWebRequest(); if (uwr.isNetworkError || uwr.isHttpError) { Debug.Log(uwr.error); } else { Texture texture = ((DownloadHandlerTexture)uwr.downloadHandler).texture; image.texture = texture; } } You can also load the file in another Thread with the Thread API. Even better, use the ThreadPool API. Any of them should work. Once you load the image byte array, to load the byte array into Texture2D, you must do it in the main Thread since you can't use Unity's API in the main Thread. To use Unity's API from another Thread when you are done loading the image bytes, you would need a wrapper to do so. The example below is done with C# ThreadPool and my UnityThread API that simplifies using Unity's API from another thread. You can grab UnityThread from here. public RawImage image; void Awake() { //Enable Callback on the main Thread UnityThread.initUnityThread(); } void ReadImageAsync() { string filePath = "";//..... //Use ThreadPool to avoid freezing ThreadPool.QueueUserWorkItem(delegate { bool success = false; byte[] imageBytes; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); try { int length = (int)fileStream.Length; imageBytes = new byte[length]; int count; int sum = 0; // read until Read method returns 0 while ((count = fileStream.Read(imageBytes, sum, length - sum)) > 0) sum += count; success = true; } finally { fileStream.Close(); } //Create Texture2D from the imageBytes in the main Thread if file was read successfully if (success) { UnityThread.executeInUpdate(() => { Texture2D tex = new Texture2D(2, 2); tex.LoadImage(imageBytes); }); } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/52357990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript (JQuery) does not fill content into the textarea when form submitting Possible Duplicate: Textarea content is not included in $_POST array sometimes, but is at other times. I have a form which is sent by POST, in it I have a textarea. Here is the code <textarea name="content" id="default" class="admintableinput" cols="80" rows="20"></textarea> I have used the markItUp plugin for text editing. When the plugin is used on the textarea it doesn't enter any content into the $_POST array. I then tried a var_dump($_POST) and got this when the plugin was used: Array ( [title] => title [author] => author [summary] => summary [Category1] => 3 [image] => image [action] => Save Article ) When the plugin isn't used var_dump produces this: Array ( [title] => title [author] => author [summary] => summary [content] => content [Category1] => 4 [image] => image [action] => Save Article ) So any content entered into the textarea is only submitted without the plugin. But I have no idea why in the var_dump it doesn't even know there is a textarea there. It must be a Javascript issue, I'm using the JQuery library. Does anyone have any suggestions? Thanks in advance. A: I think that your plugin doesn`t set value for your textarea. Check for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/12248033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: calling out to rbenv gemset On a server I want to install a series of gems that got uploaded into a newly created gemset. This installation should be done from a resque worker. The purpose of creating the gemset is to execute some of the gems that got uploaded in an environment similar to the users machine. I don't understand 100% how rbenv works and that is really causing some headaches. Any ideas on how I can solve this problem would be great! A: You should checkout chgems. chgems is like chroot for RubyGems. chgems can spawn a sub-shell or run a command with PATH, GEM_HOME, GEM_PATH set to install gems into $directory/.gem/$ruby/$version/. $ chgems $directory gem install $user_gem $ chgems $directory $user_command
{ "language": "en", "url": "https://stackoverflow.com/questions/12042553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automate some web site steps I am looking into the automation of a specific procedure. The purpose of the procedure is to update Microsoft Ads IP exclusion rules from data on another website. At the high level it involves the following steps: * *Browse to a website (Clickcease.com) *Login to the webiste *A couple of navigation steps. *Click a button, which downloads a CSV file. Note: there is no URL available in the source code; it is like a javascript function of the site. I have already asked the site owner if there is some URL that could be used, and there is not. *Massage the downloaded file. This could be done via a callable script, so the automation method only needs to call this external script. *Browse to a second website (Microsoft Ads). *Navigate in that website. *Click on a control and change a setting. *Paste in into a field a column from the CSV file. *Click a control to commit the data. I have looked at macOS Automator and it seems to lack many of the functions. Also found Selenium WebDriver, but not sure that could do this task.
{ "language": "en", "url": "https://stackoverflow.com/questions/74368269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring (Websockets / REST / Security), JWT and Sockjs (Stomp) integration I'm developing a project and trying to integrate: * *Spring Security *Spring Websockets *Spring REST *Sockjs & Stomp (Angular2) I tried through google/spring docs/jwt examples and I cannot find anywhere a nicely explained and working (most importantly) example. Does anyone have example where mentioned are integrated (it does not have to be angular2, Sockjs & Stomp & Spring will do). Important part here is security that can work for both websockets & REST with JWT. Please help it's just driving my crazy. A: All you need is define custom bearerTokenResolver method in SecurityConfig and put access token into cookies or parameter. @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**") .hasAuthority("SCOPE_read") .antMatchers(HttpMethod.POST, "/api/foos") .hasAuthority("SCOPE_write") .anyRequest() .authenticated() .and() .oauth2ResourceServer() .jwt().and().bearerTokenResolver(this::tokenExtractor); } ... } public String tokenExtractor(HttpServletRequest request) { String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header != null) return header.replace("Bearer ", ""); Cookie cookie = WebUtils.getCookie(request, "access_token"); if (cookie != null) return cookie.getValue(); return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/43104475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find a pattern among several different lines using python I have three lines like below - what I want to do is to print found if at least 5 characters of the last 15 characters in the upper line have | character under themselves (meaning these characters bind to the characters in the third line) 5' TCAGATGTGTATAAGAGACAGTGCGTATTCTCAGTCAGTTGAAGTGATACAGAA :: ::: :: : : : ||||| : 3' ATTCAGCCTGCACTCGTTACCGAGGCATGACAGAGAATTCACGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG So far I have ended up with this script that can find specific patterns but I have not been able to expand it to find what I just mentioned in the question - it would be great if someone could help me to expand the code below - thank you. import re in_str = ''' 5' TCAGATGTGTATAAGAGACAGTGCGTATTCTCAGTCAGTTGAAGTGATACAGAA :: ::: :: : : : ||||| : 3' ATTCAGCCTGCACTCGTTACCGAGGCATGACAGAGAATTCACGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG''' in_str = re.sub(r'^\s*', "", in_str) lst = re.split(r'\n', in_str) acgt = set(['A', 'C', 'G', 'T']) for idx in range(min([len(s) for s in lst])): if lst[0][idx] in acgt and lst[1][idx] == '|' and lst[2][idx] in acgt: print('found!') break Based on the structure of the three lines the output of the script should be found since the 5 characters (from the last 15 characters of the upper string) has | under themselves. A: You can use the collections.Counter class to help with counting: from collections import Counter in_str = '''5' TCAGATGTGTATAAGAGACAGTGCGTATTCTCAGTCAGTTGAAGTGATACAGAA :: ::: :: : : : ||||| : 3' ATTCAGCCTGCACTCGTTACCGAGGCATGACAGAGAATTCACGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG''' # split string into lines: strs = in_str.split('\n') line1 = strs[0] line2 = strs[1] length1 = len(line1) assert length1 >= 15 # we assume this # last 15 characters of the first line suffix1 = line1[length1-15:length1] # or line1[-15:] # the 15 characters of the second line that are under the above characters suffix2 = line2[length1-15:length1] # count occurrences of each characters: c = Counter(suffix2) found = c.get('|', 0) >= 5 print(found) Prints: True A: How about something like this. First slice the second line based on the length of first line and then count the occurrence of | in that slice. in_str = ''' 5' TCAGATGTGTATAAGAGACAGTGCGTATTCTCAGTCAGTTGAAGTGATACAGAA :: ::: :: : : : ||||| : 3' ATTCAGCCTGCACTCGTTACCGAGGCATGACAGAGAATTCACGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG''' lines = in_str.strip().split("\n") first_line_length = len(lines[0]) # 62 valid_char_start_index = (first_line_length - 15 if first_line_length > 15 else 1) - 1 # 46 required_slice = lines[1][valid_char_start_index:first_line_length] # : ||||| : # occurrence_of_pipe_in_slice = required_slice.count("|") # 5 if occurrence_of_pipe_in_slice >= 5: print("found") In case the mapping is done in the beginning as mentioned in the comment, we can do something like this: import re in_str = ''' 5' TCAGATGTGTATAAGAGACAGGTGTAATCGTTCCGCTTGAATGTACGTCATGAA ||||| :: : :: :: : : :: 3' ATTTGCAGTACACTCGTTACCGAGGCATGACAGAGAATATGTGTAGAGGCGAGCTAAGGTACTTGAAAGGGTGTATTAGAG''' lines = in_str.strip().split("\n") first_line_prefix = re.match(r"\d\'\s+", lines[0]).group() # "5' " third_line_prefix = re.match(r"\d\'\s+",lines[2]).group() # "3' " if len(first_line_prefix) < len(third_line_prefix): # To make sure that which ever line starts first we are picking correct index valid_char_start_index = len(first_line_prefix) else: valid_char_start_index = len(third_line_prefix) # valid_char_start_index = 3 try: required_slice = lines[1][valid_char_start_index:valid_char_start_index+15] # ' ||||| ' except IndexError: required_slice = lines[1][valid_char_start_index:] # in case the second line is smaller than the required slice it # will consider to the end of the line occurrence_of_pipe_in_slice = required_slice.count("|") # 5 if occurrence_of_pipe_in_slice >= 5: print("found") To Summarise we can create a function where can take input parameter as where we want to look for the mapping beginning or in the end. And then determine start and end indices accordingly. From there in both cases rest of the process is same.
{ "language": "en", "url": "https://stackoverflow.com/questions/67557034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Object matching query does not exist i have a problem: DoesNotExist at /products// Product matching query does not exist. Request Method: GET Django Version: 1.4 Exception Type: DoesNotExist Exception Value: Product matching query does not exist. Exception Location: /Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/db/models/query.py in get, line 366 Python Executable: /usr/bin/python Python Version: 2.7.1 vews.py def SpecificProduct(request, productslug): product = Product.objects.get(slug=productslug) context = {'product': product} return render_to_response('singleproduct.html', context, context_instance=RequestContext(request)) singleproduct.html {% extends "base.html" %} {% block content %} <div id = "singleproduct"> <p>Name: {{ product }}</p> <p>Description: {{ product.en_description }}</p> <p>Description: {{ product.sp_description }}</p> </div> {% endblock %} url.py (r'^products/(?P<productslug>.*)/$', 'zakai.views.SpecificProduct'), models.py class Product(models.Model): en_name = models.CharField(max_length=100) sp_name = models.CharField(max_length=100) slug = models.SlugField(max_length=80) en_description = models.TextField(blank=True, help_text="Describe product in english") sp_description = models.TextField(blank=True, help_text="Describe product in spanish") photo = ThumbnailerImageField(upload_to="product_pic", blank=True) def __unicode__(self): return self.en_name A: You are visiting the URL /products// so there is no value for the parameter productslug in the URL. That means your Product query fails: product = Product.objects.get(slug=productslug) because it has no (correct) value for productslug. To fix it, change your URL pattern to: (r'^products/(?P<productslug>.+)/$', 'zakai.views.SpecificProduct'), which requires at least one character for the productslug parameter. To improve it furhter you can use the following regex which only accepts - and characters (which is what a slug consists of): (r'^products/(?P<productslug>[-\w]+)/$', 'zakai.views.SpecificProduct'),
{ "language": "en", "url": "https://stackoverflow.com/questions/11519938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Kubernetes - Use secrets on pre-install job On my helm chart I have a job with the pre-install hook where I need to use a property from my secrets. However when I try to install my helm chart I get the following error on my pre-install job: Error: secret "SecretsFileName" not found Secrets aren't created before the pods execution? What's the problem here? How can I solve this? Notes: * *I want to use secrets to have the properties encrypted. I don't want to use the decrypted value directly on my pod; *I already read Helm install in certain order but I still not understanding the reason of this error; *I already tried to use "helm.sh/hook": pre-install,post-delete and "helm.sh/hook-weight": "1" on secrets, and "helm.sh/hook-weight": "2" on my pod but the problem remains. My pre-install job: apiVersion: batch/v1 kind: Job metadata: name: "MyPodName" annotations: "helm.sh/hook": pre-install "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded #some more code spec: template: #some more code spec: dnsPolicy: {{ .Values.specPolicy.dnsPolicy }} restartPolicy: {{ .Values.specPolicy.restartPolicy }} volumes: - name: {{ .Values.volume.name }} persistentVolumeClaim: claimName: {{ .Values.volume.claimName }} securityContext: {{- toYaml .Values.securityContext | nindent 8 }} containers: - name: "MyContainerName" #some more code env: - name: SECRET_TO_USE valueFrom: secretKeyRef: name: SecretsFileName key: PROP_FROM_SCRETS #some more code My secrets file: apiVersion: v1 kind: Secret metadata: name: "SecretsFileName" labels: app: "MyAppName" #some more code type: Opaque data: PROP_FROM_SCRETS: eHB0bw== A: While Helm hooks are typically Jobs, there's no requirement that they are, and Helm doesn't do any analysis on the contents of a hook object to see what else it might depend on. If you read through the installation sequence described there, it is (7) install things tagged as hooks, (8) wait for those to be ready, then (9) install everything else; it waits for the Job to finish before it installs the Secret it depends on. The first answer, then, is that you also need to tag your Secret as a hook for it to be installed during the pre-install phase, with a modified weight so that it gets installed before the main Job (smaller weight numbers happen sooner): apiVersion: v1 kind: Secret annotations: "helm.sh/hook": pre-install "helm.sh/hook-weight": "-5" The next question is when this Secret gets deleted. The documentation notes that helm uninstall won't delete hook resources; you need to add a separate helm.sh/hook-delete-policy annotation, or else it will stick around until the next time the hook is scheduled to be run. This reads to me as saying that if you modify the Secret (or the values that make it up) and upgrade (not delete and reinstall) the chart, the Secret won't get updated. I'd probably just create two copies of the Secret, one that's useful at pre-install time and one that's useful for the primary chart lifecycle. You could create a template to render the Secret body and then call that twice: {{- define "secret.content" -}} type: Opaque data: PROP_FROM_SCRETS: eHB0bw== {{- end -}} --- apiVersion: v1 kind: Secret metadata: name: "SecretsFileName" labels: app: "MyAppName" {{ include "secret.content" . }} --- apiVersion: v1 kind: Secret metadata: name: "SecretsFileName-preinst" labels: app: "MyAppName" annotations: "helm.sh/hook": pre-install "helm.sh/hook-weight": "-5" "helm.sh/hook-delete-policy": hook-succeeded {{ include "secret.content" . }} A: According to the docs: pre-install: Executes after templates are rendered, but before any resources are created in Kubernetes
{ "language": "en", "url": "https://stackoverflow.com/questions/59423084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: query to fetch multiple row data in Columns format - postgresql I have table structure like this: Table - contact_details role email userId Primary Contact [email protected] 1 Secondary Contact [email protected] 1 End User [email protected] 1 Primary Contact [email protected] 2 Secondary Contact [email protected] 2 Result data should be: Primary Contact Secondary Contact End User UserId [email protected] [email protected] [email protected] 1 [email protected] [email protected] null 2 I am not able to retrieve End User as "null" for userId -2, what is happening is either the entire row comes if data exists for all three roles OR if any role is missing entire row missed. Can any one suggest the approach please? -- Postgres version - 12 A: You can try with this (conditional aggregation) select max(case when role = 'Primary Contact' then email else null end) as PrimaryContact, max(case when role = 'Secondary Contact' then email else null end) as SecondaryContact, max(case when role = 'End User' then email else null end) as EndUser, userId from contact_details group by userId
{ "language": "en", "url": "https://stackoverflow.com/questions/67916734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to fix PDF form displaying as unfilled in preview but filled when opened I am attempting to fill PDF forms programmatically with PDFSharp but am running into an odd problem. After filling the fields in the document replacing their default values I save and email the PDF. When I view the PDF as a preview like in Outlook, the form fields show their default values, but when I download and open the PDF the correct values are shown. This is how i generate the PDF files. Open the template, fill the fields and then save to new location. PdfDocument doc = PdfReader.Open(_pdfPath, PdfDocumentOpenMode.Modify); if (doc.AcroForm.Elements.ContainsKey("/NeedAppearances") == false) { doc.AcroForm.Elements.Add("/NeedAppearances", new PdfBoolean(true)); } else { doc.AcroForm.Elements["/NeedAppearances"] = new PdfBoolean(true); } PdfAcroField field = doc.AcroForm.Fields[key]; field.ReadOnly = false; field.Value = new PdfString(row[Layout[key]].ToString()); field.ReadOnly = true; doc.Save(newFilePath); Why would it display differently depending on the viewer? how can i fix this, or is there a workaround? I appreciate any assistance. EDIT If i open the filled in PDF (in Acrobat) and close it again I'm asked to save changes even though I haven't made any, and after saving the filled form data shows in the preview.
{ "language": "en", "url": "https://stackoverflow.com/questions/62796160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get column names from PDOStatement? I've recently built a class for automatic paging and ordering of query results, that works with PDO. Here's how I retrieve the data from a MySQL table: $this->query = "SELECT _id, name, price, creationDate, isPublished FROM fruits"; $this->fetch_type = PDO::FETCH_ASSOC; $this->result = $db->query($this->query); $this->rows = $this->result->fetchAll($this->fetch_type); $this->columns = empty($this->rows) ? array() : array_keys($this->rows[0]); This way I can easily store the column names inside an array (that's exactly what I need): var_dump($this->columns): array 0 => string '_id' (length=3) 1 => string 'name' (length=4) 2 => string 'price' (length=5) 3 => string 'creationDate' (length=12) 4 => string 'isPublished' (length=11) However, my method doesn't work if the fetch type is PDO::FETCH_OBJ, since I'm no more working with 2D arrays, but with objects inside arrays: var_dump($this->rows): array 0 => object(stdClass)[11] public '_id' => string '1' (length=1) public 'name' => string 'apple' (length=5) public 'price' => string '26.00' (length=5) public 'creationDate' => string '0000-00-00 00:00:00' (length=19) public 'isPublished' => string '1' (length=1) 1 => object(stdClass)[12] public '_id' => string '2' (length=1) public 'name' => string 'banana' (length=11) public 'price' => string '15.00' (length=5) public 'creationDate' => string '0000-00-00 00:00:00' (length=19) public 'isPublished' => string '1' (length=1) 2 => object(stdClass)[13] public '_id' => string '3' (length=1) public 'name' => string 'orange' (length=6) public 'price' => string '12.12' (length=5) public 'creationDate' => string '0000-00-00 00:00:00' (length=19) public 'isPublished' => string '1' (length=1) etc... So, how can I get column names from a result like this above? A: The simple answer to this is to cast the item that you pass to array_keys() to an explicit (array) - that way, arrays are unaffected but objects become the correct type: $this->columns = empty($this->rows) ? array() : array_keys((array) $this->rows[0]); A: getColumnMeta can retrieve the name of a column, it returns an associative array containing amongst others the obvious "name" key. so $meta = $this->result->getColumnMeta(0); // 0 indexed so 0 would be first column $name = $meta['name'];
{ "language": "en", "url": "https://stackoverflow.com/questions/10799062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Durandal - hide section of page depending on url or route In my durandal app every page except the home page has a left navbar. This left navbar should be update on refresh, though it should reside on shell.html. The problem is that i'm not being able to hide it properly on the home page. I can use jquery hide() method to hide the leftnav div when i'm on the home page, but the problem is that i can only use jquery code after data-bindind, and until there i can see the navbar. I tried to use durandal composition, but i'm not sure how can I hide the navbar only in the home page since i don't know how to know if i'm on the home page or not inside shell.js. Any ideias? A: In your view model, you'll want to hook into your router by creating a computed that listens to the value of the current instruction: var ko = require('knockout'); var router = require('plugins/router'); function viewModel() { this.currentRoute = ko.computed(function() { return router.activeInstruction().fragment; }); } Then you can reference this variable using the visible binding in your view. <!-- home route only --> <div data-bind="visible: currentRoute() == 'home'></div> <!-- non-home routes --> <div data-bind="visible: currentRoute() != 'home'></div> If you need more complicated logic, you can create a special computed function that does specific testing against the current route and reference that variable instead. For example: this.isSpecialRoute = ko.computed(function() { var re = /matchspecialroute/; return re.test(this.currentRoute()); }, this);
{ "language": "en", "url": "https://stackoverflow.com/questions/28727478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Overloaded method filter I have an exercise where I have to find first >=0 element which IS NOT in the Set. My plan was to firstly: filter the negative numbers from the set, then to make pairs by sliding, then to add the difference to the tuple (if it's 1, I know that there isn't any Int element which is not in Set between them). Then I wanted to filter out ones, that difference is not 1 - so I know that the element that I'm searching for is e.g. Having Set(-3,0,1,2,4), I have tuples (0,1),(1,2),(2,4) --> filtered out in the end is only (2,4, 2 (difference)), so my element is 2+1 = 3. When I'm trying to filter out the ones with the difference != 1, it says that it couldn't resolve overloaded method filter def minNotContained(set: Set[Int]): Int = { val positive = set.filter(_ >= 0) val pairs = positive.sliding(2).toList.map(_.toList) val pairsWithDifference = pairs.map{case List(a: Int,b: Int) => List((a,b,b-a))}.filter((x,y,z) => z!=1) } A: Use dropWhile() as your filter. val setOfInts = Set(....) val result = LazyList.from(0).dropWhile(setOfInts).head A: I managed to do it like this, but it's not the case.... I need to do that exercise using operations on collections, sorry for answering my question, but I wanted to my solution to be visible better. def minNotContained(set: Set[Int]): Int = { val positive = set.filter(_ >= 0) @tailrec def isInSet(collection: Set[Int], number: Int): Int = { if (collection.contains(number)) isInSet(collection, number+1) else number } isInSet(set,0) } println(minNotContained(Set(-3,0,1,2,4,5,6)))
{ "language": "en", "url": "https://stackoverflow.com/questions/67246432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dynamically set params are not posted using httpClient in angular 5 I am using angular 5 and am trying to post some data to an api. Following is what I have done so far: This code works perfectly: var params = new HttpParams() .set('addresses[0][latitude]', 90.64318211857652) .set('addresses[0][longitude]', 30.86662599723718) .set('addresses[1][latitude]', 90.622619801960056) .set('addresses[1][longitude]', 30.91368305099104) .set('transport_type', 'motorbike') .set('has_return', 0) .set('delay', 0); return this.http.post(url, params, {headers: headers}); but since I need to get them dynamically from a form I need to do the following which posts nothing to the server: var params = new HttpParams(); for(let address of p.addresses){ params.set(address.addLatLng, address.val); } params.set('transport_type', p.transport_type); params.set('has_return', p.has_return); params.set('delay', p.delay); return this.http.post(url, params, {headers: headers}); This is the result of console.log(p): addresses: Array(4) 0: {addLatLng: "addresses[0][latitude]", val: 90.67102482549417} 1: {addLatLng: "addresses[0][longitude]", val: 30.84517466245563} 2: {addLatLng: "addresses[1][latitude]", val: 90.58590327086768} 3: {addLatLng: "addresses[1][longitude]", val: 30.92026791653143} length: 4 __proto__: Array(0) delay: 0 has_return 0 transport_type: "motorbike" A: Https Params are immutable. Try that var params = new HttpParams(); for(let address of p.addresses){ params = params.set(address.addLatLng, address.val); } params = params.set('transport_type', p.transport_type) .set('has_return', p.has_return) .set('delay', p.delay); return this.http.post(url, params, {headers: headers}); A: Why use HttpParams?, the sintax for httpClient.post is httpClient.post(url,body,[options]). where body is a object. NOT confussed with params. the httpParams, see https://angular.io/guide/http#url-parameters is used to change the url. Your solucion works because you don't use httpParams in the form of this.http.post(url, params, { headers: headers, params:params }); you can do //A simple object var data= { 'addresses0latitude': 90.64318211857652, 'addresses0longitude': 30.86662599723718, 'addresses1latitude': 90.622619801960056, 'addresses1longitude': 30.91368305099104, 'transport_type', 'motorbike', 'has_return': 0, 'delay': 0 } return this.http.post(url, data, {headers: headers});
{ "language": "en", "url": "https://stackoverflow.com/questions/48802947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to perform model.objects.get(**kwargs) with case insensitive I would like to get an instance of one of my Django models by using dictionary in an insensitive case way. For the moment I'm using: my_model.objects.get(**dictionary) But I don't get the instance if there is a difference of lower / upper case between what there is in my dictionary and the fields of the instance. Do you think there is a clean way to perform this operation ? A: Django takes the WHERE filter to load the object entirely from the keys of the dictionary you provide. It is up to you to provide field lookups; you can use the iexact field lookup type, but you do need to use this on textual fields. So if you wanted to match a specific string field, case insensitively, add __iexact to the key in dictionary; e.g. {'foo': 'bar'} becomes {'foo__iexact': 'bar'}.
{ "language": "en", "url": "https://stackoverflow.com/questions/54485812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read InputStream and Write to a File This is related to my previous question - DataInputStream giving java.io.EOFException In that Client-Server app there is method to retrieve file sent from server and save to a file. Client.java - public void receiveFile(InputStream is, String fileName) throws Exception { int filesize = 6022386; int bytesRead; int current = 0; byte[] mybytearray = new byte[filesize]; System.out.println("Receving File!"); FileOutputStream fos = new FileOutputStream("RECEIVED_"+fileName); BufferedOutputStream bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray, 0, mybytearray.length); current = bytesRead; System.out.println(bytesRead); do { bytesRead = is.read(mybytearray, current, (mybytearray.length - current)); System.out.println(bytesRead); if (bytesRead >= 0) current += bytesRead; } while (bytesRead > -1); System.out.println("Loop done"); bos.write(mybytearray, 0, current); bos.flush(); bos.close(); } } Server.Java public void sendFile(OutputStream os, String fileName) throws Exception { File myFile = new File(fileName); byte[] mybytearray = new byte[(int) myFile.length() + 1]; FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(mybytearray, 0, mybytearray.length); System.out.println("Sending File!"); os.write(mybytearray, 0, mybytearray.length); os.flush(); bis.close(); } As you can see there are several stranded outs in client's receiveFile method. here is the output i received. The issue is that method don't complete its task and never reached to System.out.println("Loop done"); What's the issue ? A: I'll come to the loop error later. There is one little byte too much at the source: public void sendFile(OutputStream os, String fileName) throws Exception { File myFile = new File(fileName); if (myFile.length() > Integer.MAX_VALUE) { throw new IllegalStateException(); } Either byte[] mybytearray = Files.readAllBytes(myFile.toPath()); Or byte[] mybytearray = new byte[(int) myFile.length()]; // No +1. // BufferedInputStream here not needed. try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(myFile))) { bis.read(mybytearray); } // Always closed. and then System.out.println("Sending File!"); os.write(mybytearray); os.flush(); } Alternatively I have added the java 7 Files.readAllBytes. It could even be simpler using Files.copy. I just see the main error is mentioned already. Basically there is a misconception: you may read a byte array in its entirety. It will block till the end is read. If there is less to read ("end-of-file" reached), then the number of bytes is returned. So to all purposes you might read it in a whole. One often sees similar code to read a fixed size (power of 2) block (say 4096) repeated and written to the output stream. Again java 7 Files simplifies all: Files.copy(is, Paths.get("RECEIVED_" + fileName)); In Short: public void receiveFile(InputStream is, String fileName) throws Exception { Files.copy(is, Paths.get("RECEIVED_" + fileName), StandardCopyOption.REPLACE_EXISTING); } public void sendFile(OutputStream os, String fileName) throws Exception { Files.copy(Paths.get(fileName), os); } A: You probably want your condition to read: } while (bytesRead > -1 && current < mybytearray.length); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ At the moment, when you have read the entire file, your read statement keeps reading zero bytes (mybytearray.length - current) which succeeds and returns zero, so your loop never terminates. A: It would be much simpler to not keep appending to the input buffer public void receiveFile(InputStream istream, String fileName) throws Exception { System.err.println("Receving File!"); try (BufferedOutputStream ostream = new BufferedOutputStream( new FileOutputStream("RECEIVED_" + fileName))) { int bytesRead; byte[] mybytearray = new byte[1024]; do { bytesRead = istream.read(mybytearray); if (bytesRead > 0) { ostream.write(mybytearray, 0, bytesRead); } } while (bytesRead != -1); System.err.println("Loop done"); ostream.flush(); } } If you can use Guava, you can use ByteStreams.copy(java.io.InputStream, java.io.OutputStream) (Javadoc)
{ "language": "en", "url": "https://stackoverflow.com/questions/23184166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Underscorejs removing unwanted spaces for logic part I have an Underscore template which has if/else conditions PROBLEM : Underscore is inserting unwanted spaces for the logic part. The result of the generated HTML when else condition is satisfied is <a>NAME</a> <a class="name" href="/kkk/213">kkkkkkkk</a>Sir but I want an output of <a>NAME</a><a class="name" href="/kkk/213">kkkkkkkk</a>Sir I want to remove the line feed/space that is being inserted in the template.... Is there any solution to do this? A: Underscore's _.template doesn't do anything to whitespace so you have to arrange the whitespace in your template to match the output you need. Something like this: <a>NAME</a><% if(some_condition) { %> yours <% } else { %> <a class="name" href="/kkk/<%- ID %>"><%= NAME %></a> <% }%> Demo (look in your console): http://jsfiddle.net/ambiguous/gbx3M/ Or the more readable: <a>NAME</a><% if(some_condition) { %> yours <% } else { %> <a class="name" href="/kkk/<%- ID %>"><%= NAME %></a> <% } %> Demo (look in your console): http://jsfiddle.net/ambiguous/xuxLQ/ If you really need no space between the tags at all then I think you're stuck with this: <% if(some_condition) { %><a>NAME</a>yours<% } else { %><a>NAME<a class="name" href="/kkk/<%- ID %>"><%= NAME %></a><% } %> and manually stripping off leading/trailing whitespace: http://jsfiddle.net/ambiguous/LN7eU/ Another option is to use CSS to float and position the elements so that the whitespace becomes irrelevant. If none of those options are good enough then Underscore's (intentionally) simple and minimal templates might not be for you. A: I also found that you can get rid of this unwanted whitespace by tweaking the regular expression that Underscore uses to evaluate javascript code. _.templateSettings.evaluate = /(?:\n\s*<%|<%)([\s\S]+?)%>/g A: I succeeded it by using a forked version of tpl.js: https://github.com/ZeeAgency/requirejs-tpl You can find my version here: https://github.com/GuillaumeCisco/requirejs-tpl/ Basically I add a .replace(/\s\s+/g, '') when I receive the data, allowing me to trim spaces between tags by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/13169885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Import OpenLDAP directory into OSX Open Directory We run a bunch of Macbook Pros and Airs at work, as well as a few Windows 7 boxes and some Ubuntu workstations. We use OpenLDAP for the Linux and Windows boxes, but all the Apple users have local accounts on their individual machines. I've been mucking about with Open Directory on the OSX Server we use for Net Installs, and I've got a test user set up and I've been able to login over the network from another Mac. I was wondering if it is possible to be able to sync Open Directory with the OpenLDAP server, which runs on Debian I think, so when a new user is added, it will add them as a user on the Open Directory as well, hence all users can log on to all machines and it's a massive win. I'm not really that familiar with how LDAP works, so I'm totally winging it. Any pointers would be great Cheers :) A: It might be easier to use the OpenDirectory for the windows boxes but thats not the question. You can use OpenLDAP as backend for your Macs. But the OpenLDAP has to implement the schema of the OpenDirectory (which in itself uses OpenLDAP as backend). Those schema-files are lokated in different places depending on the MacOSVersion you are using. you have to place those files inside the OpenLDAPs schema folder and restart the ldap. After that you can extend the users to make use of that Information. But you will have to adapt the mapping of Information on the Mac-clients so that all relevant information from the LDAP ends up in the right places. Not an easy task. I'd think twice wheter it makes sense for a handfull or two of macBoxes. We've implemented for 150 Macs and it was a pain to get everything right. And AFAIK there is no easy way of bringing an OpenLDAP and an OpenDirectoy in synch eith one another due to the schema extension apple used. Depending on the frontend you use you might be able to implement a mechanism that adds a user to two LDAPs when the are created but what about changing passwords? Or changing a users name? you will have to do a lot of manual adaptions to make that possible. So In my opinion not an easy task especially when you have to catch up on some LDAP stuff and the LDAP documentation of Apple is rather sparse... A: Your question title says "Import OpenLDAP directory into OSX Open Directory". Which you certainly can. LDAP is a wire protocol. Check out PORTABLE HOME DIRECTORIES WITH OPENLDAP You then ask "is it possible to be able to sync Open Directory with the OpenLDAP server". Yes, there are many IDM products out there that will allow sync two LDAP directories. NetIQ IDM, http://forgerock.com/, and many others. But, probably more than you want to deal with. (I think they are best for 1000+ Users) A: Use below listed function and export that schema to LDIF format. ldapmodify If possible then use ldap admin tool phpldapadmin,ldap admin etc Export whole shema or branch in ldif and .xml(dsml) type. Then Inport it to desired directory server by using admin tool else commandline function ldapadd
{ "language": "en", "url": "https://stackoverflow.com/questions/23414822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using GQuery in GWT widgets I am using the GWT application widget library and want to validate the controls in the button click event.The code I am writing GQuery input = $(e).filter("input[type='password']").widgets(); but its is giving me compile time error.Please tell me or refer me any tutorial for validating the widget library controls. A: the widgets() method returns a list of widget and not a GQuery object List<Widget> myPasswordInputs = $(e).filter("input[type='password']").widgets(); If you are only one input of type password you can maybe use directly widget() method : PasswordTextBox myPasswordInput = $(e).filter("input[type='password']").widget(); Question: are you sure of your '$(e).filter("input[type='password']")' ? Because it means : "Create a GQuery object containing my element 'e' and keep it only if 'e' is an input of type password" If you want to retrieve all password inputs present within an element e, you have to use : List<Widget> myPasswordInputs = $("input[type='password']",e).widgets(); Julien A: Try: GQuery input = GQuery.$(e).filter("input[type='password']").widgets(); You need to do a static import to use $ directly: import static com.google.gwt.query.client.GQuery.*; import static com.google.gwt.query.client.css.CSS.*;
{ "language": "en", "url": "https://stackoverflow.com/questions/6147791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nokia Asha SDK: Glitch in List component when used with TextField on the same Form I'm a bit stuck with strange behaviour of List component in Asha SDK. What I'm doing is using TextField and List on the same form. Just a TextField and a List on BoxLayout, with no relationship. The problem is - focusing on TextField seems to trigger creation of another List component which is exact copy of original one, but displays just one item. You can see it in * *large green border marks 2 horizontal row delimiters - first one belongs to original List, second one seems to belong to that new fake List *small green border marks little vertical scroll bar which works for new fake List. Original List uses big scroll bar, you can see it on the right. *'Item 9' on provided image belongs to fake List, 'Item 8' - to original one. And this image shows how List is rendered when TextField is non-focused. Everything there seems to be correct: Could you please advise is there any way to solve this glitch? Is it possible to tweak it somehow with LookAndFeel? I really don't need that fake List. By the way, on Nokia SDK 2 (S40) there is no such glitch, everything works as expected. P.S. What I'm trying to implement is Autocomplete TextField. I'm using this article for that. If there is any other way to do so for Asha SDK, please share.
{ "language": "en", "url": "https://stackoverflow.com/questions/19836630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: StringByAppendingPathComponent() and WriteToFile() I'm trying to learn Swift 3 with translating a code from Swift 2. In swift 2, I see the code like this: return fullPath.stringByAppendingPathComponent(name) But, when I try in Swift 3, I've got similiar code, but like this: return fullPath.strings(byAppendingPaths: [name]) The issue is, return type in the 1st code is String (and that's the output I need from the lesson I learn), but return type in 2nd code should be [String]. The other issue is, in Swift 2 the code should be: imgData?.WriteToFile(fullPath, atomicaly:Bool) But in Swift 3, I only can input code like this: imgData.Write(to: URL , option: WritingOption) throws But in some examples, there's .Write(toFile: , atomically:) but I can't find it in Xcode. Am I translating incorrectly or using both Swift 2 and Swift 3 incorrectly? A: Regarding the first part of your question, as dan stated in the comments you should be using fullPath.appendingPathComponent(name) instead. Regarding your second question: The main difference between writeToFile and write(to: is the fact that the first is for Strings and the seconds is for NSData. Somewhat related: According to the NSData Class Reference In iOS 2.0+ you have: write(to:atomically:) and write(toFile:atomically:) Given: Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:atomically:, except for the type of the first argument. None of this has changed in Swift 3 according to the Swift Changelog.
{ "language": "en", "url": "https://stackoverflow.com/questions/38231281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bluetooth LE active scanning causes connection problems on other machine I am having a problem where BLE active scanning on one machine causes connection problems on another machine. I was wounder if anyone could explain why, and offer any suggestions on how to fix. I have broken down a rough version of my what my code does into simple scripts. on machine 1: sudo stdbuf -oL hcidump -X |tee hci.log & sudo hcitool lewlclr sudo hcitool lewladd 68:C9:0B:xx:xx:01 sudo hcitool lewladd 68:C9:0B:xx:xx:02 sudo hcitool lewladd 68:C9:0B:xx:xx:03 sudo hcitool lewladd 68:C9:0B:xx:xx:04 sudo hcitool lewladd 68:C9:0B:xx:xx:05 sudo hcitool lewladd 68:C9:0B:xx:xx:06 while true; do sudo hcitool lecc --whitelist; if [ $? == 1 ] ; then sleep 20; else sleep 1; sudo hcitool ledc 64 ; fi; done The above will run with no problems However after running the following on a different machine I get connection issues. sudo hcitool lescan --duplicates from the hci logs a normal connecition looks like: < HCI Command: LE Create Connection (0x08|0x000d) plen 25 bdaddr 00:00:00:00:00:00 type 0 interval 4 window 4 initiator_filter 1 own_bdaddr_type 0 min_interval 15 max_interval 15 latency 0 supervision_to 3200 min_ce 1 max_ce 1 > HCI Event: Command Status (0x0f) plen 4 LE Create Connection (0x08|0x000d) status 0x00 ncmd 1 > HCI Event: LE Meta Event (0x3e) plen 19 LE Connection Complete status 0x00 handle 64, role master bdaddr 68:C9:0B:xx:xx:xx (Public) < HCI Command: Disconnect (0x01|0x0006) plen 3 handle 64 reason 0x13 Reason: Remote User Terminated Connection > HCI Event: Command Status (0x0f) plen 4 Disconnect (0x01|0x0006) status 0x00 ncmd 1 > HCI Event: Disconn Complete (0x05) plen 4 status 0x00 handle 64 reason 0x16 Reason: Connection Terminated by Local Host and a bad connection is as follows: < HCI Command: LE Create Connection (0x08|0x000d) plen 25 bdaddr 00:00:00:00:00:00 type 0 interval 4 window 4 initiator_filter 1 own_bdaddr_type 0 min_interval 15 max_interval 15 latency 0 supervision_to 3200 min_ce 1 max_ce 1 > HCI Event: Command Status (0x0f) plen 4 LE Create Connection (0x08|0x000d) status 0x00 ncmd 1 > HCI Event: LE Meta Event (0x3e) plen 19 LE Connection Complete status 0x00 handle 64, role master bdaddr 68:C9:0B:xx:xx:xx (Public) > HCI Event: Disconn Complete (0x05) plen 4 status 0x00 handle 64 reason 0x3e Reason: Connection Failed to be Established < HCI Command: Disconnect (0x01|0x0006) plen 3 handle 64 reason 0x13 Reason: Remote User Terminated Connection > HCI Event: Command Status (0x0f) plen 4 Disconnect (0x01|0x0006) status 0x12 ncmd 1 Error: Invalid HCI Command Parameters Note: the last two entries (Invalid HCI Command Parameters) are because of the crudeness of the script, and only occur because of the failed connection. Of note, it looks like the connection is made, then it says in couldn't (Connection Failed to be Established). This seems a bit confusing to me. I have tried this on different machines. (desktop PC and RPi3) A: Peripheral is advertising. That means it periodically sends an avertisement (ADV_IND) packet on some advertisement channel. In response to this packet, a central may either (Core_v4.2, 6.B.4.4.2.3): * *do nothing, *send a scan request (SCAN_REQ) packet (Figure 4.3), peripheral should respond with a scan response (SCAN_RSP), *send a connection request (CONN_REQ) packet (Figure 4.5). Here, you have two centrals trying to reach the same peripheral at the same time. One is doing active scanning (#2 above), the other is initiating (#3 above). Unfortunately, both must send their packet at the exact same time, receiver gets jammed, and both scan request and connection request packets get lost. There is no acknowledgement for connection requests. Initiator must to assume the advertiser received and accepted the connection request, create the connection speculatively, and possibly time out afterwards. That's why the fast termination feature pointed by bare_metal exists. In case the peripheral does not take the connection request, central should not wait forever. LE Connection Complete event in your dumps just tell a Connection Request packet got sent, it does not tell it actually got received, processed or accepted by target. A: on the confusion of connection created vs connection established please see the vol 6, Part B,section 4.5 from low energy specification (core 4.2). so it seems in the second instance the remote device didn't send any data channel packet after CONNECT_REQ PDU. and in the second case if a disconnect is tried on a link which is not established , the controller will complain about invalid handle ( as there is no valid connection exist). To debug further you could enable Timing in hcidump which will confirm the failed to establish event is received by the host after Supervision Timeout. "The Link Layer enters the Connection State when an initiator sends a CONNECT_REQ PDU to an advertiser or an advertiser receives a CONNECT_REQ PDU from an initiator. After entering the Connection State, the connection is considered to be created. The connection is not considered to be established at this point. A connection is only considered to be established once a data channel packet has been received from the peer device. The only difference between A connection that is created and a connection that is established is the Link Layer connection supervision timeout value that is used" "If the Link Layer connection supervision timer reaches 6 * connInterval before the connection is established (see Section 4.5), the connection shall be considered lost. This enables fast termination of connections that fail to establish"
{ "language": "en", "url": "https://stackoverflow.com/questions/36699551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add Dynamic table rows to table layout in android together with textwatcher I try to Add new Table rows into TableLayout in my android app. I successfully added new table rows with multiple edittexts, by following an android tutorial. Now what I try to do is, I need to get user values for those edittexts using TextWatcher. I searched a lot of tutorials and tried a lot, but i was failed. This is how my app looks like before I add a button to this. What I need is to Open Second row by clicking a button If user wants, and if user enters values to edittext fields they need to use and , final Result should display accordingly. This is my previous code, I posted with a question and solved it in here . Using Android TextWatcher with multiple user input values and Update thses values If someone could help me, I highly appreciate your help. Thanks in advance. Now this is my new XML code <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:text="Add Line" /> <ScrollView android:id="@+id/scrollView2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/Button1" android:layout_marginTop="97dp"> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <TableLayout android:id="@+id/TableLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="?android:attr/dividerHorizontal" android:showDividers="middle"> <TableRow android:id="@+id/TableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content"> <EditText android:id="@+id/editText1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="4" android:padding="2dp" /> <EditText android:id="@+id/editText2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="4" android:padding="2dp" /> <EditText android:id="@+id/editText3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="4" android:padding="2dp" /> <TextView android:id="@+id/TextViewsub1" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:hint="$ 0.00" android:textSize="18dip" /> </TableRow> <TableRow android:id="@+id/TableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content"> <EditText android:id="@+id/editText4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="4" android:padding="2dp" /> <EditText android:id="@+id/editText5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="4" android:padding="2dp" /> <EditText android:id="@+id/editText6" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="4" android:padding="2dp" /> <TextView android:id="@+id/TextViewsub2" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:hint="$ 0.00" android:textSize="18dip" /> </TableRow> </TableLayout> </RelativeLayout> </ScrollView> <TextView android:id="@+id/textView12" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/scrollView2" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_marginEnd="87dp" android:layout_marginRight="87dp" android:hint="Rs: 0.00" /> <TextView android:id="@+id/textView13" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/textView12" android:layout_marginEnd="86dp" android:layout_marginRight="86dp" android:layout_toLeftOf="@+id/textView12" android:layout_toStartOf="@+id/textView12" android:text="Total Value" /> </RelativeLayout> This is now How my Java File looks like public class NewClass extends AppCompatActivity implements View.OnClickListener { Button btnAdd; int counter = 0; EditText edit1, edit2, edit3; TextView textViewSub1, textViewResult; @Override protected void onCreate(Bundle savedInstanceState) { /*First row variables*/ edit1 = (EditText) findViewById(R.id.editText1); edit2 = (EditText) findViewById(R.id.editText2); edit3 = (EditText) findViewById(R.id.editText3); textViewSub1 = (TextView) findViewById(R.id.TextViewsub1); textViewResult = (TextView) findViewById(R.id.textView12); super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_class); //add line button btnAdd = (Button) findViewById(R.id.Button1); btnAdd.setOnClickListener(this); edit1.addTextChangedListener(new LashCustomTextWatcher1()); edit2.addTextChangedListener(new LashCustomTextWatcher1()); edit3.addTextChangedListener(new LashCustomTextWatcher1()); } public class LashCustomTextWatcher1 implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { textViewResult.setText(lashCalculate()); } } public void onClick(View view) { TableLayout tl = (TableLayout) findViewById(R.id.TableLayout1); TableRow tr = new TableRow(this); //TextView tv = new TextView(this); //tv.setText("text "); edit1 = new EditText(this); //edit1.setText("Hello " + counter++); edit2 = new EditText(this); //edit2.setText("Item no " + counter++); edit3 = new EditText(this); //edit3.setText("Qty no " + counter++); textViewSub1 = new TextView(this); tr.addView(edit1); tr.addView(edit2); tr.addView(edit3); tr.addView(textViewSub1); //tr.addView(cb); tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT)); } public String lashCalculate() { //declaring variables double row1_value = 0; DecimalFormat df = new DecimalFormat("0.00"); //calculate first row if (!edit1.getText().toString().equals("") && !edit2.getText().toString().equals("")) { double num1 = Double.parseDouble((edit1.getText().toString())); double num2 = Double.parseDouble((edit2.getText().toString())); row1_value = num1 * num2; double num3 = 0; if (!edit3.getText().toString().equals("")) { num3 = Double.parseDouble((edit3.getText().toString())); row1_value = (((100 - num3) * num2) * num1) / 100; } textViewSub1.setText(df.format(row1_value)); } return df.format(row1_value); } } A: 1) First of all in parent layout xml put linearlayot as below: <LinearLayout android:id="@+id/parent_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"></LinearLayout> 2) Than Make a layout that is want to add in every click. 3) You can now add your view in parent like below : LinearLayout parent_layout = (LinearLayout)findViewById(R.id.parent_layout); for(i=0;i<3;i++) { parentlayout.addView(myViewReview(data.get(i))); } public View myViewReview() { View v; // Creating an instance for View Object LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.row_facility_review, null); TextView row_reviewer_name = (TextView) v.findViewById(R.id.row_reviewer_name); TextView row_review_text = (TextView) v.findViewById(R.id.row_review_text); return v; }
{ "language": "en", "url": "https://stackoverflow.com/questions/46196784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby on Rails - Why is Materialize.updateTextFields not a function? I have a Ruby on Rails project that uses the material-saas gem. I recently noticed that text field animations have stopped working. More specifically, when a text field is active, the label does not move up on the page and whatever the user types in the input field writes over the label text and looks awful. Here (https://github.com/Dogfalo/materialize/issues/682) is an example of the style issue I'm encountering. In addition to the label text not moving correctly, the form also has a file field that is not working. When a user selects a file to upload, the file name does not appear in the form, which is the intended behavior. I recently ran rake assets:clobber and rake assets:precompile and I wonder if that has something to do with this issue. I did some research and in the Material CSS docs they say: You can also call the function Materialize.updateTextFields(); to reinitialize all the Materialize labels on the page if you are dynamically adding inputs. I attempted this fix, but I get Uncaught TypeError: Materialize.updateTextFields is not a function in my console when I load the page. Here is my form view: <%= render 'shared/header' %> <div class="container"> <h3>New Photo of the Day</h3> <div class="row"> <%= form_for @photo, multiple: true do |f| %> <div class="input-field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="input-field"> <%= f.label :caption %> <%= f.text_area :caption, class: "materialize-textarea" %> </div> <%= f.label :date %> <%= f.date_field :date, class: "datepicker"%> <div class="file-field input-field"> <div class="btn waves-effect waves-light yellow accent-4 white-text"> <span>File</span> <%= f.file_field :image %> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text"> </div> </div> <div class="input-field center-align"> <%= f.submit "Upload", class: "btn-large waves-effect waves-light" %> </div> <% end %> Here is my assets/application.js //= require jquery //= require materialize-sprockets //= require jquery_ujs //= require react //= require react_ujs //= require components //= require_tree . Here is my assets/custom.js $(document).ready(function() { Materialize.updateTextFields(); }); This is all really strange because I know the form style animations were working. I did not change the code for my form. The only thing I can think of is the clobber / precompile command, which I needed to run to get some ui improvements up onto production. Thanks for taking the time to look this one over and I appreciate the assistance! A: You are using jQuery 1.x. Try using jQuery 2.x or 3.x. Source: https://github.com/Dogfalo/materialize/issues/4593 E: The way to do this in your setup would be to change the line //= require jquery to //= require jquery2. A: Looks like a few issues to me: Rails is magic, and it does something called "turbolinks." Basically, pages are dynamically replaced instead of actually changing pages. It makes your site faster, but doesn't always issue the same Javascript events. You'll also need JQuery 2 (I've updated my answer after advice from Dmitry). Change the first few lines of your application JS to: //= require jquery2 //= require turbolinks //= require materialize-sprockets Secondly, I found a second bug that exists in the materialize library. Basically, it wouldn't define updateTextFields() until turbo links loaded a page. To fix this, I've submitted a PR, but in the meantime, I would money-patch this by copy/pasting the method from the source to your code (inside $(document).ready). Use something like this to let your code get updated once they fix the bug (pretty much a polyfill). Materialize.updateTextFields = Materialize.updateTextFields || // code from forms.js
{ "language": "en", "url": "https://stackoverflow.com/questions/43302732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use a php code both for ajax and http requests? I have some classes and methods which are containing some php codes. Now I want to use those PHPcodes both for ajax and http requests. How? Should I write all my PHP codes twice? onetime for ajax requests and one time for http request? Here is my currect structure: /********************************************** Search.php ****/ ... // some html codes <div id="content"> <?php if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest") { $type = true; // true means ajax request } else { $type = false; // false means http request } $obj = new classname; $results = obj->func($type); echo $results; ?> </div> ... // some html codes /********************************************** Classname.php ****/ class classname { public function func($type){ $arr = ('key1'=>'some', 'kay2'=>'data'); if ($type){ echo json_encode($arr); } else { return $arr; } } } Now I want to know, this is standard? Actually I want to use it also for a request which came from a mobile app (something like an API). I think the above code has two problem: * *there will be a lot of IF-statement just for detecting type of requests (in the every methods) *there is just one file (class.php) for both ajax and http requests. And when I send a ajax request by for example mobile, it will process some codes which doesn't need to them at all Well, is there any point that I need to know? A: This is more about the design of your software then simplifying it. Often you would have a structure with classes that you use and separate PHP files for types of responses. For example: You could have the documents: classes.php, index.php and ajax.php. The classes would contain generic classes that can both be shown as JSON or as HTML. PS:Simplified could mean: /********************************************** Search.php ****/ ... // some html codes <div id="content"> <?php $obj = new classname; $results = obj->func($_SERVER["HTTP_X_REQUESTED_WITH"]); echo $results; ?> </div> ... // some html codes /********************************************** Classname.php ****/ class classname { public function func($type){ $arr = ('key1'=>'some', 'kay2'=>'data'); if(!empty($type["HTTP_X_REQUESTED_WITH"]) && strtolower($type["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest"){ echo json_encode($arr); } else { return $arr; } } } A: You can write a single code, and you should use only partials to load AJAX data. The main reason we are using AJAX is to minimize data transfer. You should not load a full page HTML in an AJAX call, although it is perfectly valid. I would suggest from my experience is, have a single file: <?php if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { /* special ajax here */ die(json_encode($data)); } else { ?> Regular Flow of Content <?php } ?> A: I would first do all the business logic, calling on your classes, without any dependency on whether you are in an ajax call or not. When all is ready for output, make the switch: Search.php: <?php // first do your business logic without view dependency. $obj = new classname; $results = obj->func(); // no type is passed. if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest") { // ajax request echo json_encode($results); exit(); } // http request ?> ... // some html codes <div id="content"> <?=$results?> </div> ... // some html codes Classname.php: <?php class classname { public function func(){ $arr = ('key1'=>'some', 'kay2'=>'data'); return $arr; } } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/34245711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GLFW triangle will not change color I've been following a short youtube tutorial on how to make basic graphics with glfw. I cannot get my triangle to change color help me. main code: #include <stdio.h> #include <stdlib.h> #include <string> #include <fstream> #include <GL/glew.h> #include <GLFW/glfw3.h> std::string LoadFileToString(const char* filepath) { std::string fileData; std::ifstream stream(filepath, std::ios::in); if (stream.is_open()) { std::string line = ""; while (getline(stream, line)) { fileData += "\n" + line; } stream.close(); } return fileData; } GLuint LoadShaders(const char* vertShaderPath, const char* fragShaderPath) { GLuint vertShader = glCreateShader(GL_VERTEX_SHADER); GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER); std::string vertShaderSource = LoadFileToString(vertShaderPath); std::string fragShaderSource = LoadFileToString(vertShaderPath); const char* rawVertShaderSource = vertShaderSource.c_str(); const char* rawFragShaderSource = fragShaderSource.c_str(); glShaderSource(vertShader, 1, &rawVertShaderSource, NULL); glShaderSource(fragShader, 1, &rawFragShaderSource, NULL); glCompileShader(vertShader); glCompileShader(fragShader); GLuint program = glCreateProgram(); glAttachShader(program, vertShader); glAttachShader(program, fragShader); glLinkProgram(program); return program; } int main() { if (glfwInit() == false) { //did not succeed fprintf(stderr, "GLFW failed to initialise."); return -1; } //4 AA glfwWindowHint(GLFW_SAMPLES, 4); //tells glfw to set opengl to 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window; window = glfwCreateWindow(640, 480, "DJ KELLER KEEMSTAR", NULL, NULL); if (!window) { fprintf(stderr, "Window failed to create"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "Glew failed to initialise"); glfwTerminate(); return -1; } //generate VAO GLuint vaoID; glGenVertexArrays(1, &vaoID); glBindVertexArray(vaoID); static const GLfloat verts[] = { //X, Y, Z -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; GLuint program = LoadShaders("shader.vertshader", "shader.fragshader"); //generate VBO GLuint vboID; glGenBuffers(1, &vboID); glBindBuffer(GL_ARRAY_BUFFER, vboID); glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glClearColor(0.0f, 0.0f, 1.0f, 1.0f); do { glClear(GL_COLOR_BUFFER_BIT); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vboID); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glUseProgram(program); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); glfwSwapBuffers(window); glfwPollEvents(); } while (glfwWindowShouldClose(window) == false); return 0; } fragshader: #version 330 core out vec3 color; void main() { color = vec3(1,0,0); } vertshader: #version 330 core layout(location = 0) in vec3 in_pos; void main() { gl_Position.xyz = in_pos; gl_Position.w = 1; } The triangle is supposed to be red: A: std::string vertShaderSource = LoadFileToString(vertShaderPath); std::string fragShaderSource = LoadFileToString(vertShaderPath); ^^^^^^^^^^^^^^ wat Don't try to use a vertex shader as a fragment shader. Recommend querying the compilation and link status/logs while assembling the shader: #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <cstdarg> struct Program { static GLuint Load( const char* shader, ... ) { GLuint prog = glCreateProgram(); va_list args; va_start( args, shader ); while( shader ) { const GLenum type = va_arg( args, GLenum ); AttachShader( prog, type, shader ); shader = va_arg( args, const char* ); } va_end( args ); glLinkProgram( prog ); CheckStatus( prog ); return prog; } private: static void CheckStatus( GLuint obj ) { GLint status = GL_FALSE; if( glIsShader(obj) ) glGetShaderiv( obj, GL_COMPILE_STATUS, &status ); if( glIsProgram(obj) ) glGetProgramiv( obj, GL_LINK_STATUS, &status ); if( status == GL_TRUE ) return; GLchar log[ 1 << 15 ] = { 0 }; if( glIsShader(obj) ) glGetShaderInfoLog( obj, sizeof(log), NULL, log ); if( glIsProgram(obj) ) glGetProgramInfoLog( obj, sizeof(log), NULL, log ); std::cerr << log << std::endl; exit( EXIT_FAILURE ); } static void AttachShader( GLuint program, GLenum type, const char* src ) { GLuint shader = glCreateShader( type ); glShaderSource( shader, 1, &src, NULL ); glCompileShader( shader ); CheckStatus( shader ); glAttachShader( program, shader ); glDeleteShader( shader ); } }; #define GLSL(version, shader) "#version " #version "\n" #shader const char* vert = GLSL ( 330 core, layout( location = 0 ) in vec3 in_pos; void main() { gl_Position.xyz = in_pos; gl_Position.w = 1; } ); const char* frag = GLSL ( 330 core, out vec3 color; void main() { color = vec3(1,0,0); } ); int main() { if (glfwInit() == false) { //did not succeed fprintf(stderr, "GLFW failed to initialise."); return -1; } //4 AA glfwWindowHint(GLFW_SAMPLES, 4); //tells glfw to set opengl to 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(640, 480, "DJ KELLER KEEMSTAR", NULL, NULL); if (!window) { fprintf(stderr, "Window failed to create"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "Glew failed to initialise"); glfwTerminate(); return -1; } //generate VAO GLuint vaoID; glGenVertexArrays(1, &vaoID); glBindVertexArray(vaoID); static const GLfloat verts[] = { //X, Y, Z -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; GLuint program = Program::Load ( vert, GL_VERTEX_SHADER, frag, GL_FRAGMENT_SHADER, NULL ); //generate VBO GLuint vboID; glGenBuffers(1, &vboID); glBindBuffer(GL_ARRAY_BUFFER, vboID); glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW); glClearColor(0.0f, 0.0f, 1.0f, 1.0f); do { glClear(GL_COLOR_BUFFER_BIT); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vboID); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glUseProgram(program); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); glfwSwapBuffers(window); glfwPollEvents(); } while (glfwWindowShouldClose(window) == false); return 0; } That way if you try something like: GLuint program = Program::Load ( vert, GL_VERTEX_SHADER, vert, GL_VERTEX_SHADER, NULL ); ...it will bail out early and give you a better indication of what went wrong: Vertex shader(s) failed to link. Vertex link error: INVALID_OPERATION. ERROR: 0:2: error(#248) Function already has a body: main ERROR: error(#273) 1 compilation errors. No code generated
{ "language": "en", "url": "https://stackoverflow.com/questions/38583762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Minimalist Sphere Impostor -- computing sphere radius in zdepth I'm trying to code up a fast and minimalist sphere impostor-- the sphere doesn't need to be shaded or do anything but correct gl_FragDepth. I have some code that's very close to working... cutting out everything but the key code: vertex shader: out_XYZ=float4(sphereCenter.xyz,1.)*sceneComboMatrix; switch(gl_VertexID) { case 0: out_XYZ.xy+=vec2(radius,-radius); out_UV=float2(1.,-1.); break; case 1: out_XYZ.xy+=vec2(-radius,-radius); out_UV=float2(-1.,-1.); break; case 2: out_XYZ.xy+=vec2(radius,radius); out_UV=float2(1.,1.); break; case 3: out_XYZ.xy+=vec2(-radius,radius); out_UV=float2(-1.,1.); break; } fragment shader: float aLen2=dot(in_UV,in_UV); float aL=inversesqrt(aLen2); if (aL<1.) discard; out_Color=float4(1.,0.,0.,1.); float magicNumber=.0031f; gl_FragDepth=gl_FragCoord.z-(sin(1.-(1./aL))*(3.14/2.)*magicNumber); This produces the following: Not TOO bad... it works as a proof of concept. The issue is, my variable magicNumber above, which I simply fiddled around with, should be replaced with the radius of the sphere in zdepth. How can I compute the size of the sphere's radius in terms of zdepth? (A note: I don't need this to be hyperaccurate-- it's being used for some particles that can clip slightly wrong... but it does need to be more accurate than my screenshot above) (EDIT----------) Using resources from Nicol Bolas, I wrote some code to attempt to get the difference in zdepth between the sphere's maximally close point ot the camera and the sphere's center. However, the result pushes the sphere VERY FAR toward the camera. Why doesn't this code give me the length of the sphere's radius in z-space (i.e. the difference in Z between the sphere's center and another point closer to the camera?) vec4 aSPos=vec4(spherePos.xyz,1.)*sceneComboMatrix; float aD1=aSPos.z/aSPos.w; aSPos=vec4(spherePos.xyz+(normalTowardCamera.xyz*sphereRadius),1.)*sceneComboMatrix; float aD2=aSPos.z/aSPos.w; radiusLengthInZ=((gl_DepthRange.diff*(aD1-aD2))+gl_DepthRange.near+gl_DepthRange.far)/2.0;
{ "language": "en", "url": "https://stackoverflow.com/questions/74210329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Firefox profile is throwing a Selenium WebDriverException since I updated to Firefox 63 I have been using the following Selenium code to open a fresh Firefox profile. FirefoxProfile profile = new FirefoxProfile(new File("profile file path")); FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setProfile(profile); driver = new FirefoxDriver(firefoxOptions); driver.get("application Url"); It was working fine until I updated to Firefox 63 and now I am getting the following error. 1540496896005 Marionette DEBUG Accepted connection 0 from 127.0.0.1:53310 1540496896006 Marionette TRACE 0 -> [0,1,"newSession",{"acceptInsecureCerts":true,"browserName":"firefox","capabilities":{"desiredCapabilities":{"acceptInsecureCerts":true,"browserName":"firefox"}}}] 1540496896006 Marionette TRACE 0 <- [1,1,{"error":"unknown command","message":"newSession","stacktrace":"WebDriverError@chrome://marionette/content/error.js:178: ... et@chrome://marionette/content/server.js:245:8\n_onJSONObjectReady/<@chrome://marionette/content/transport.js:490:9\n"},null] Oct 25, 2018 2:48:16 PM org.openqa.selenium.remote.ErrorCodes toStatus INFO: HTTP Status: '404' -> incorrect JSON status mapping for 'unknown error' (500 expected) Exception in thread "main" org.openqa.selenium.WebDriverException: newSession Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:05:20.749Z' System info: host: 'NRIJCTDU8047923', ip: '10.241.10.83', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0' Driver info: driver.version: FirefoxDriver remote stacktrace: stack backtrace: 0: 0x4bb74f - <no info> 1: 0x4bbea9 - <no info> 2: 0x43ce8d - <no info> 3: 0x44ce14 - <no info> 4: 0x44944a - <no info> 5: 0x4203e1 - <no info> 6: 0x407dc7 - <no info> 7: 0x6d95b9 - <no info> 8: 0x4173a7 - <no info> 9: 0x6d38b3 - <no info> 10: 0x770b59cd - BaseThreadInitThunk at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:83) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57) at java.lang.reflect.Constructor.newInstance(Constructor.java:437) at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57) at org.openqa.selenium.remote.W3CHandshakeResponse$$Lambda$200.0000000013211B00.apply(Unknown Source) at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104) at org.openqa.selenium.remote.W3CHandshakeResponse$$Lambda$202.0000000011F857C0.apply(Unknown Source) at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122) at org.openqa.selenium.remote.ProtocolHandshake$$Lambda$203.0000000012223A00.apply(Unknown Source) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:204) at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:969) at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:137) at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:540) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:527) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:513) at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:163) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:245) at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:475) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212) at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:125) at selenium.utilities.SeleniumUtilities.OpenApplicationWelcomePage(SeleniumUtilities.java:35) at selenium.mogems.MoGemsMainPondek.main(MoGemsMainPondek.java:14) I have tried creating a new profile and also tried the following code. ProfilesIni profile = new ProfilesIni(); FirefoxProfile myprofile = profile.getProfile("Selenium2"); FirefoxOptions firefoxOptions = new FirefoxOptions(); firefoxOptions.setProfile(myprofile); driver = new FirefoxDriver(firefoxOptions); A: I just needed to update to the latest geckoDriver. A: It might be useful to someone else, since I didn't immediately have success from just updating to the latest gecko driver (I was running an older version of selenium stand alone server, 3.6). I am using facebook/php-webdriver. After updating to Firefox 63, the combination of Selenium standalone server v3.8.1 and geckodriver 0.23 stopped the error occurring. A: I am Case I Update my Gecko Driver its Working Fine Now.Always Try New Gecko Driver . https://www.seleniumhq.org/download/.
{ "language": "en", "url": "https://stackoverflow.com/questions/52997403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NoClassDefFoundError for aurora.jar I am trying to execute next: C:\dev\sources\boSchedules\loadJavaLibs>java -cp aurora.jar; ojdbc6.jar oracle.aurora.server.tools.loadjava.LoadJavaMain -thin -user login/pass@myserv:mysid %BOS_SRC%/credit/card/api/ScheduleCardApi And I get next: Exception in thread "main" java.lang.NoClassDefFoundError: ojdbc6/jar Caused by: java.lang.ClassNotFoundException: ojdbc6.jar at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Could not find the main class: ojdbc6.jar. Program will exit. Why am I getting this error? A: Take a look at the Java Application Launcher man page. java -cp aurora.jar; ojdbc6.jar oracle.aurora.server.tools.loadjava.LoadJavaMain -thin -user sched/sched@teach:prod %BOS_SRC%/credit/card/api/ScheduleCardApi You have a space between your classpath entries aurora.jar; ojdbc6.jar. The launcher thinks the first jar is the only classpath entry and the ojdbc6.jar is your class containing the main(String[] args) method. It also considers everything after that as arguments to pass to the main(String[] args) method. Remove that space. A: Remove the space between the aurora.jar; and the ojdbc6.jar A: Spaces delimit the parameters each other. The JVM interprets the command as if you run "ojdbc6.jar" class: "jar" as a classname and "ojdbc6" as a package. To concat the names of libraries you want to place into classpath for a specific class run please use semicolon with no spaces as "lib1;lib2" P.S.: Could you please ask your colleagues if you may paste some of our credentials to the SO? :)
{ "language": "en", "url": "https://stackoverflow.com/questions/15683790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can phone use host network when debugging on device via Eclipse/ADB? I have a Android phone connected with host computer with USB cable. ADB runs well and I can debug application on phone. The only problem is that the App requires special network setup which I can reach on host but not mobile. Is there a way to let the device send all network operations through ADB and Host network? A: What you're looking for is known as reverse tethering. See https://android.stackexchange.com/questions/2298/how-to-set-up-reverse-tethering-over-usb for a solution. A: Have you tried sharing your internet connection on your laptop, and connect your phone through it?. Make sure you disable data connection on your phone to assure you are connected through WiFi
{ "language": "en", "url": "https://stackoverflow.com/questions/3192921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Reactive redirection using go_router and flutter_bloc What would be the best way to somehow implement a reactive redirection using bloc states? Currently I'm doing redirection like this: router.dart final router = GoRouter( routes: [ GoRoute( name: OnBoardingPage.name, path: '/', builder: (context, state) => OnBoardingPage(), redirect: (context, state) async { final homeLocation = '/login'; if (isMobilePlatform) { final onBoardingCubit = context.read<OnBoardingCubit>(); await onBoardingCubit.init(); if (onBoardingCubit.state is DoNotShowOnBoarding) return homeLocation; return null; } return homeLocation; }, ), GoRoute( name: 'login', path: '/login', builder: (context, state) => HomePage(), ), ], ); onboardingpage.dart class OnBoardingPage extends StatelessWidget { static String name = 'oboarding'; const OnBoardingPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocListener<OnBoardingCubit, OnBoardingState>( listener: (context, state) { if (state is DoNotShowOnBoarding) { GoRouter.of(context).refresh(); } }, child: IntroductionScreen( rawPages: introductionPages(context), onDone: () => context.read<OnBoardingCubit>()..onBoardingIsCompleted(), next: Icon(Icons.arrow_forward), done: Text('done'.tr()), curve: Curves.easeInQuad, controlsMargin: const EdgeInsets.all(16), dotsDecorator: DotsDecorator( size: const Size.square(10.0), activeSize: const Size(20.0, 10.0), activeColor: Theme.of(context).colorScheme.primary, spacing: const EdgeInsets.symmetric(horizontal: 3.0), activeShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ), ), ), ); } } However I do not like the fact hat I have to call GoRouter.of(context).refresh() in the bloc listener to trigger the redirection again. Is there a more professional way to work with flutter_bloc ?
{ "language": "en", "url": "https://stackoverflow.com/questions/75522668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to receive response from an HTTPS site (PYTHON) I would like to know how do I connect and receive a response from a website that uses HTTPS I believe I have to use ssl but I do not know how? import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(("www.netflix.com", 443)) client.send("GET / HTTP/1.1\r\nHost: www.netflix.com\r\n\r\n") print client.recv(1024)
{ "language": "en", "url": "https://stackoverflow.com/questions/49185784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: convert mysql dump file to access db I have mysql dump file and I need to convert it to ms access, I have no access to phpmyadmin so I can't use the programs that connect to the mysql db, so I need for a software to convert mysql dump file to ms access db. just i have this dump file in hand thanks if you can help
{ "language": "en", "url": "https://stackoverflow.com/questions/7620566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to share a branch to anyone else in the team without committing it in GIT ? Consider that i am working on a branch and made some changes and need some help from my friend and want to send the branch to him without committing it. is it possible? Considering that i am working on the main development branch A: Of course you can send patches to anyone (git diff >file). However, branches contain commits (really, they're just a name for one commit and its ancestors come along for the ride), so it's meaningless to talk about sharing a branch without having committed anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/46335852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to determine if a user purchased an App I was wondering how can I determine though code, if a user did buy our App through the Windows Store. Because we have a payed App, and I found it for download on eg. FileDir as an .xap file. Fully working. We are not working with in-app purchases or trial version, you have to pay for it. A: If you are not the original developer (logged in with the same account) XAP installation through SD Card or download will still require you buy the application. If you have already bought it in the past it will not ask again as it will verify that with the Windows Phone Store. Is that your question? If you are asking how to check from one app if another one has been bought the best option is to check the list of installed apps: InstallationManager.FindPackagesForCurrentPublisher method To check if license is still active you can check in the code: bool hasBeenBought = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.IsActive;
{ "language": "en", "url": "https://stackoverflow.com/questions/22806113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Syntax errors in if/else statement I am very new to c# and while working on a basic program I am receiving this error(Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement) and cannot figure out why it is appearing. if (pizzaDiameter >= 12 && pizzaDiameter < 16)// begin nested if statement { Console.WriteLine("A" + pizzaDiameter + "will yield 8 slices."); } else if (pizzaDiameter >= 16 && pizzaDiameter < 24)//Second pizza diameter range { Console.WriteLine("A" + pizzaDiameter + "will yield 12 slices."); } else if (pizzaDiameter >= 24 && pizzaDiameter < 30) { Console.WriteLine("A" + pizzaDiameter + "will yield 16 slices."); } else (pizzaDiameter >= 24 && pizzaDiameter <= 30) { Console.WriteLine("A" + pizzaDiameter + "will yield 24 slices."); } else // pizza diameter was not a whole number { Console.WriteLine("Pizza diameter must be between 12-36 inclusive.");// Error appears here. } else //pizza diameter must be between 12-36 { Console.WriteLine("Pizza diameter must be a whole number."); } A: There's something wrong with your control structure, i.e. you've got only one if(), but three times else. Also, try to think about the problem and you'll notice that you can simplify the whole structure significantly (and also skip many checks): if (pizzaDiameter < 12) // All diameters below 12 will use this branch. Console.WriteLine("Your pizza seems to be too small."); else if (pizzaDiameter < 16) // You don't have to ensure it's bigger than 12, since those smaller already picked the branch above. Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 8 slices"); else if (pizzaDiameter < 24) // Again you won't have to care for less than 16. Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 12 slices"); // ... else Console.WriteLine("Your pizza seems to be too big.");
{ "language": "en", "url": "https://stackoverflow.com/questions/26205619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does LockBits/UnlockBits do in c#? I have a method in c# that the only thing it does its LockBits, and then UnlockBits, and the images(input/output, transformed to byte arrays) are different. The one from output has less 100 and something bytes than the one from the input. This happens only with .jpg files. And checking the files in HxD I came to the understanding that itΒ΄s removing a part of the header, the exif signature to be exact. But I don't know how and why. Does someone know what this is doing? Here's the code: public Image Validate (image){ BitmapData original = null; Bitmap originalBMP = null; try{ originalBMP = image as Bitmap; original = originalBMP.LockBits(new Rectangle(0, 0, originalBMP.Width, originalBMP.Height), ImageLockMode.ReadWrite, originalBMP.PixelFormat); originalBMP.UnlockBits(original); }catch{} return image; } A: Calling Bitmap.LockBits() followed by Bitmap.UnlockBits() does nothing. The behavior you observe is because of loading a JPEG image, and then saving it again. JPEG uses a lossy algorithm. So what happens: * *You load the JPEG from disk *The JPEG data gets decoded into individual pixels with color information, i.e. a bitmap *You save the bitmap again in the JPEG format, resulting in a different file than #1 You also potentially lose metadata that was present in the JPEG file in doing so. So yes, the file is different and probably smaller, because every time you do this, you lose some pixel data or metadata. Lockbits/Unlockbits are used to allow the program to manipulate the image data in memory. Nothing more, nothing less. See also the documentation for those methods. A: Use the LockBits method to lock an existing bitmap in system memory so that it can be changed programmatically. You can change the color of an image with the SetPixel method, although the LockBits method offers better performance for large-scale changes. A Rectangle structure that specifies the portion of the Bitmap to lock. Example: private void LockUnlockBitsExample(PaintEventArgs e) { // Create a new bitmap. Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg"); // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Set every third value to 255. A 24bpp bitmap will look red. for (int counter = 2; counter < rgbValues.Length; counter += 3) rgbValues[counter] = 255; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 150); }
{ "language": "en", "url": "https://stackoverflow.com/questions/59842615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: While generating Controller, "View Model "requires a primary key" error I have 3 tables, 1 has master data of students, 1 is a lookup table that links address and third is a table of family members names. I wanted to create a page to input student details, their address and family members. So I created a View model class. When I generate the Controller for that view model class, The Entity type "ViewModelClassName" requires a primary key error pops up. I am new to web development. I am in a situation where there is no one to ask anything. Please help. Thanks. public StudentMaster StudentMaster { get; set; } public StudentAddresses StudentAddresses { get; set; } public StudentFamilyMembers StudentFamilyMembers { get; set; } A: ASP.NET Scaffolding is expecting Entity Framework based Data Model classes in order to help you creating views/controllers . But you are using View Model ,view model doesn't been persist in a database and also it doesn't have any primary key field, hence it cannot be scaffolded. And also when using scaffold wizard you always need to choose data context . But a view model has no relationship with your data context. You should use your actual data model instead of a viewmodel to perform scaffolding , then modify the codes to use view model to transfer data between views and controllers Inside your controller action that you could map the view model back to your data model that will be persisted using EF. You could use AutoMapper to map between your view models and data models.
{ "language": "en", "url": "https://stackoverflow.com/questions/54295826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to create file association with two program and making one default if both present? I have to create file association for an extension with two programmes and if both programmes A and B are present then choose program A to open the file. If only B is present then choose program B to open the file. If you can give the wix code or else you can provide me with registry details. A: Create a wrapper (just a simple batch script) that calls the appropriate program. Set the file type association to use the wrapper. A: I would suggest you to use registry entry. Call a CustomAction in WIX to check for the registry entry. The check can be as simple as if...else IF (Regitry_A != null && Registry_B != null) { //Choose program A } ELSE IF (Regitry_A != null) { //Choose Program A } ELSE { //Choose Program B }
{ "language": "en", "url": "https://stackoverflow.com/questions/2598830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Playframework - internationalization and routes I need two language versions of my web site which will be located in domainname/lang1/somecontroller and domainname/lang2/somecontroller urls. What architecture of routes file allow me to avoid of duplicating controllers declaration for every language? A: * /{language}/MyController Application.MyController should allow you to access both languages, and you then have access to the language passed in, in the controller, if you wish.
{ "language": "en", "url": "https://stackoverflow.com/questions/12076476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I recently installed tensorflow on python 3.7.5 on my system without any problem but I couldn't import it. Below is the error that it gives me import tensorflow Traceback (most recent call last): File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 242, in load_module return load_dynamic(name, filename, file) File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 342, in load_dynamic return _load(spec) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow\__init__.py", line 98, in <module> from tensorflow_core import * File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module> from tensorflow.python.tools import module_util as _module_util File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__ module = self._load() File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow\__init__.py", line 44, in _load module = _importlib.import_module(self.__name__) File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module> from tensorflow.python import pywrap_tensorflow File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 242, in load_module return load_dynamic(name, filename, file) File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 342, in load_dynamic return _load(spec) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. Failed to load the native TensorFlow runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/59042324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Property.ValueChangeListener - Cannot be resolved to a variable (Vaadin) I'm trying the tutorial available on vaadin's website and when I was setting the item selection on a table's row the tutorial suggests that I should add the following line to my table class. addListener((Property.ValueChangeListener), app); Being app a reference to my controller. However eclipse points an error to Property.ValueChangeListener "Property.ValueChangeListener cannot be resolved to a variable". What exactly am I doing wrong here ? PS: My believe my imports are correct since eclipse's auto-complete was working just fine to identify .ValueChangeListener PersonList Class: package com.example.simpleaddressbook2; import com.vaadin.data.Property; import com.vaadin.ui.Table; public class PersonList extends Table { public PersonList(Simpleaddressbook2Application app){ setSizeFull(); setContainerDataSource(app.getDataSource()); setVisibleColumns(PersonContainer.NATURAL_COL_ORDER); setColumnHeaders(PersonContainer.COL_HEADERS_ENGLISH); setSelectable(true); setImmediate(true); addListener((Property.ValueChangeListener), app); setNullSelectionAllowed(false); } } A: Found what was wrong, the correct code is : addListener((Property.ValueChangeListener) app); and not addListener((Property.ValueChangeListener), app); Damn comma !
{ "language": "en", "url": "https://stackoverflow.com/questions/13252526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a method to remove ArrayList elements from index x to index y As the title says, if I'm creating a method to remove a section of an ArrayList, how would I go about this. If I have ArrayList<Character> se = {'a','b','c','d','e','f','g'} and want to return only "abg" I would call this method as such: remove(2,5); How could I create this method to remove not only the arg indexes but also everything in between? A: list.subList(2, 6).clear() does the job in one step. A: Create a loop counting backward from 5 to 2 and remove the elements. for(int i = 5; i >= 2; i--) ... A: void method(int startindex , int endindex) { for(int i = 0 ; i < endindex - startindex ; i++)//in your example startindex = 2 end.. = 6 { list.remove(startindex); } } modify your code accordingly.Hope this may solve your problem. A: Create a loop at same position, removing elements a certain number of times. For example, if you wanted to call list.remove(a,b) Your code would be: for (int i = 0; i <= b - a; i++) { list.remove(a); }
{ "language": "en", "url": "https://stackoverflow.com/questions/36109503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: bash get the number of files and pass it to for loop I am trying to get the number of files with a certain pattern in a directory and then do a for loop starting from zero to that number. number=`ls -d *pattern_* | wc -l`%3d for i in {001.."$number"};do # do something with $i done the problem is that my numbers are three digits, so that is why i added %3d to the end of my number variable, but it is not working. so if I have 20 files, the number variable in the for loop should get a leading zero 020. A: You really shouldn't rely on the output of ls in this way, since you can have filenames with embedded spaces, newlines and so on. Thankfully there's a way to do this in a more reliable manner: ((i == 0)) for fspec in *pattern_* ; do ((i = i + 1)) doSomethingWith "$(printf "%03d" $i)" done This loop will run the exact number of times related to the file count regardless of the weirdness of said files. It will also use the correctly formatted (three-digit) argument as requested.
{ "language": "en", "url": "https://stackoverflow.com/questions/43136464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: [email protected] requires a peer of [email protected] but none was installed I would like too install redux package. When i am using "npm install redux" i have warrning like this. ─ UNMET PEER DEPENDENCY [email protected] extraneous β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] extraneous β”œβ”€β”€ [email protected] extraneous └── [email protected] extraneous [email protected] requires a peer of [email protected] but none was installed. How too fix it? A: there are some solutions * *npm install [email protected] *npm audit fix (this one requires you to have a package.json file [get that by npm init]) tell me if one works OR list the problems that you face A: Now when i am using npm install redux everythink looks fine but, this is my package.json and i dont have 'redux' in dependencies. When i wanna use import { createStore } from 'redux'; my Webstorm dont see redux package. { "name": "my-app", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.13.1", "react-dom": "^16.13.1", "react-redux": "^7.2.1", "react-scripts": "0.9.5" }, "devDependencies": { "gulp": "^4.0.2" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "description": "This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).", "main": "index.js", "author": "", "license": "ISC" }
{ "language": "en", "url": "https://stackoverflow.com/questions/63339060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PhpStorm highlighting Laravel blade incorrectly on Mac? Was ok on old PC tl;dr - My PhpStorm 10 is highlighting my blade code incorrectly: (see screenshot) Screenshot sample of incorrect highlighting: Please help me fix this? I recently switched away from PC (PhpStorm 9) to Mac (PhpStorm 10.0.2). I git cloned to the new mac (a Laravel 5.1 project), setup homestead, ok. But PhpStorm highlights this code as if I've missed an ending semicolon. (see screenshot above - the below is the code that gets highlighted strangely). @yield('content') <!--also the following--> @if (Session::has('flash_message')) <div>{{ Session::get('flash_message') }}</div> @endif This was not an issue on my old PC setup. AFAIK Laravel's @yield and @if @endif don't need a semicolon, based on this. I've run this code for 4 months from my old PC without issues, and it runs normally on my Mac's Laravel Homestead installation. I've tried these: 1. exported and imported all settings from my old PC's phpstorm to the Mac - it imported my text colors but still highlights wrong on Mac. 2. downloaded the Laravel plugin and restarted phpstorm - no change 3. confirmed the blade plugin is activated in phpstorm 4. tested the same file on my old PC - no issues there in phpstorm 9. What could be causing this highlighting? What have I missed? A: Tinkered around and a solution: Go to Phpstorm Preferences (on Mac, 'Settings' on PC) > Editor > Colors & Fonts > PHP > PHP Code > Background On my Mac the background color was set incorrectly to white (inherited). I then unchecked "Use Inherited Attributes" and set it to black. Problem fixed. I don't know why this was set to white as on my PC it is set to black. I had done a phpstorm full settings export from pc, and imported to mac, using the generated settings.jar file so I can't say why this did not import properly. Don't know if something changed between versions 9.0 and 10.0 or whether it got skipped somehow during import.
{ "language": "en", "url": "https://stackoverflow.com/questions/34487650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieving viewport height of screen in mobile browsers with jquery I'm attempting to get the viewport height in mobile browsers WITHOUT the height of the browser bar but all of the solutions I've attempted have come up short. What others have suggested is using the below, however it does not work for me. I still get a blank white bar at the bottom of the window when scrolling var screenHeight = window.innerHeight; $('.mobile-nav-wrapper').height(screenHeight) A: Solution 1: I don't have an answer using jQuery. But using a plain/vanilla JavaScript wouldn't cause any issue :). Following script allows you to detect the Viewport size (height and width) reliably. https://github.com/tysonmatanich/viewportSize Sample usage: <script type="text/javascript"> var width = viewportSize.getWidth(); var height = viewportSize.getHeight(); </script> I have used it in couple of projects, were i have to re-initialize some widgets based on current Viewport width/height rather than using window width/height (Window width/height calculation isn't consistent in all browsers - some include scroll bar size 16px as a part of window width and some doesn't). Sample Test page: http://tysonmatanich.github.io/viewportSize/ Solution 2: (Just for reference - Not an answer to OP's question, though it is related so I thought that it can remain) Well modernizr has a very good addition Modernizr.Mq. Through which you can cross check which break point range you are in... if(Modernizr.mq("(min-width:320px)")){ //Do job 1 } else if (Modernizr.mq("(min-width:768px)")){ //Do job 2 } or based on height Modernizr.mq("(min-height: 800px)") http://tysonmatanich.github.io/viewportSize/ A: I believe what you are looking for is scrollHeight The scrollHeight property returns the entire height of an element in pixels, including padding, but not the border, scrollbar or margin. You can try this: document.body.scrollHeight
{ "language": "en", "url": "https://stackoverflow.com/questions/38665496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select box options to write to new row in database - MySQL and PHP I have a form which currently has the following fields: Name, Size, Template There are two select boxes in this form for the fields 'Size' and 'Template'. I want the form to insert a new row if a user selects more than one option on the select box. I have managed to do this for 'Template' but I can not figure out how to use the foreach construct twice so that it also inserts a new row when multiple options are selected from the Size field. Here is my code which works for inserting a new row for multiple 'Template' selected options: $template = $_POST['Template']; $size = $_POST['Size']; foreach( $template as $temp ) { switch( $temp ) { case '1': $template; break; case '2': $template; break; case '3': $template; break; case '4': $template; break; }; $query = "INSERT INTO tbl (Name,Size,Template) VALUES('$name', '$size', '$temp')"; } Is there a way to use this foreach statement twice but to run the same query. For example, I was thinking to do foreach( $size as $newsize) { switch( $newsize ) { //cases go here }; } A: The for loop would be more appropriate for what you've been trying to achieve: for($i=0; $i<count($size); $i++) { for($j=0; $j<count($template); $j++) { $currentSize = $template[$i]; $currentTemplate = $template[$j]; $query = "INSERT INTO tbl (Name, Size, Template) VALUES('$name', '$currentSize', '$currentTemplate')"; } } Warning: I only wrote the query in the same way you did to demonstrate the rest of the code. The query is actually vulnerable to SQL Injection attacks and you should definitely avoid it. Instead write the query like this: $query = "INSERT INTO tbl (Name, Size, Template) VALUES(?,?,?)"; The question marks are place holders. You will need to prepare this statement and then bind $name, $currentTemplate and $currentSize to them before executing. Check this for more information on prepared statements. Since you need to execute the same query multiple times with different data you have one more reason to use prepared statements. I highly recommend you check Example#3 of the documentation in the link above
{ "language": "en", "url": "https://stackoverflow.com/questions/40036649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a python REPL for Google App Engine? The Clojure/Compojure people have a drop in repl for Google App Engine, do Python people have anything similar? I use the repl quite a bit in "vanilla" python development, and it would be really useful if I could use it in Google App Engine Python as well. I have seen the following http://shell.appspot.com/ demo, and I was basically hoping there might be a drop-in replacement for any Python App Engine project that gave me a repl; even if the repl only worked against the dev server. Anyone know of such a thing? here is the source code to this demo, just for completeness. A: If you're okay with a REPL that works on the dev server, take a look at the bin/python script that Tipfy creates for you. It just loads the Python REPL with your project and the GAE SDK code. I've pasted my version of it here - YMMV, but you can use it as a starting point.
{ "language": "en", "url": "https://stackoverflow.com/questions/6208683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dropdown Contents below Modal I'm having challenges with a dropdown list in my project. When I have it on a regular page it works just fine. When I have it in a modal the contents are behind the modal and can't be accessed. I did some research and see I'm having problems with my z-index. However, I still can't get it to work. I've given the modal a z-index of 3000 and given the dropdown the absolute maximum z-index of 2147483647 and the dropdown still renders behind the modal. Here is the relevant CSS: /*trying to get query dropdown on top*/ .dropdown-on-top{ /*position: absolute;*/ z-index: 2147483647; } .modal-below-dropdown{ /*position: relative;*/ z-index: 3000; } /*end of tring to get query dropdown on top:*/ I'm using model-below-dropdown to set the z-index for the modal. I'm using dropdown-on-top to have the dropdown stay above the modal. FYI - I've commented out the position items for both because when I had them enabled the modal wouldn't display at all. But, from what I've read I need both of them to make this work. Here is the HTML for the modal: <div class="modal modal-message modal-below-dropdown fade" id="modal" style="display: none;"> <div class="modal-dialog modal-below-dropdown"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">Γ—</button> <h4 class="modal-title">Create Query</h4> </div> </br> <form class="form-horizontal"> <div class="form-group"> <label class="col-md-3 control-label">Query Name</label> <div class="col-md-6"> <input type="text" class="form-control" placeholder="Query Name"> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Media</label> <div class="col-md-6"> <div class="checkbox"> <label> <input type="checkbox" value=""> Print </label> </div> <div class="checkbox"> <label> <input type="checkbox" value=""> Digital </label> </div> </div> </div> <div class="form-group"> <label class="col-md-3 control-label">Type</label> <div class="col-md-6"> <div class="radio"> <label> <input type="radio" name="optionsRadios" value=""> Add </label> </div> <div class="radio"> <label> <input type="radio" name="optionsRadios" value=""> Drop </label> </div> </div> </div> </form> <!-- <hr> --> <table class="table table-valign-middle m-b-0"> <thead> <th class="col-md-8">Demographic</th> <th class="col-md-3">&nbsp;</th> <th class="col-md-2">Values</th> <th class="col-md-1">Operator</th> <th class="col-md-2">&nbsp;</th> </thead> <tbody> <tr> <td class="col-md-8"> <!-- trying jquery autocomplete combo box --> <div class="ui-widget"> <select id="combobox" class="dropdown-on-top"> <option value="Select one...">Select one...</option> <option value="Product Registration > Magazine > On File">"Product Registration > Magazine > On File"</option> <option value="Product Registration > Magazine > BPA Par 3B Source">"Product Registration > Magazine > BPA Par 3B Source"</option> <option value="Product Registration > Magazine > Promo Key">"Product Registration > Magazine > Promo Key"</option> <option value="Product Registration > Magazine > Record Status">"Product Registration > Magazine > Record Status"</option> <option value="Product Registration > Magazine > Subtype">"Product Registration > Magazine > Subtype"</option> <option value="Product Registration > Magazine > Verification Date">"Product Registration > Magazine > Verification Date"</option> <option value="Product Registration > Magazine > Activated Date">"Product Registration > Magazine > Activated Date"</option> </select><span <i class="fa fa-lg fa-sort-desc"></span> </div> <!-- end trying jquery autocomplete combo box --> </td> <td class="col-md-3"> <select class="form-control"> <option>Equals</option> <option>Not Equal To</option> <option>Contains</option> <option>Does Not Contain</option> <option>Is Empty</option> <option>Is Not Empty</option> </select> </td> <td class="col-md-3"> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <td class="col-md-1"> <select class="form-control"> <option>&nbsp;</option> <option>And</option> <option>Or</option> </select> </td> <td class="col-md-1"> <td>&nbsp;</td> </td> </tr> <tr> <td class="col-md-4"> <select class="form-control"> <option>&nbsp;</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <td class="col-md-3"> <select class="form-control"> <option>Equals</option> <option>Not Equal To</option> <option>Contains</option> <option>Does Not Contain</option> <option>Is Empty</option> <option>Is Not Empty</option> </select> </td> <td class="col-md-3"> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <td class="col-md-1"> <select class="form-control"> <option>&nbsp;</option> <option>And</option> <option>Or</option> </select> </td> <td class="col-md-1"> <td>&nbsp;</td> </td> </tr> <tr> <td class="col-md-4"> <select class="form-control"> <option>&nbsp;</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <td class="col-md-3"> <select class="form-control"> <option>Equals</option> <option>Not Equal To</option> <option>Contains</option> <option>Does Not Contain</option> <option>Is Empty</option> <option>Is Not Empty</option> </select> </td> <td class="col-md-3"> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <td class="col-md-1"> <select class="form-control"> <option>&nbsp;</option> <option>And</option> <option>Or</option> </select> </td> <td class="col-md-1"> <td class="text-left"><i class="fa fa-lg fa-plus-circle"></i></td> </td> </tr> </tbody> </table> <div class="modal-footer"> <a href="javascript:;" class="btn btn-sm btn-primary">Save Query</a> <a href="javascript:;" class="btn btn-sm btn-white" data-dismiss="modal">Cancel</a> </div> </div> </div> </div> <!-- End Add Query --> All help is greatly appreciated. A: The Jquery plugin hide the original select <select id="combobox"> and apply other HTML tags. So, write CSS for the hidden ones won't change a thing. You should use ui-autocomplete.ui-menu as the css selector to style the dropdown. Try: .ui-autocomplete.ui-menu { z-index: 3001; }
{ "language": "en", "url": "https://stackoverflow.com/questions/33373113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Specify Binding of DependencyProperty in UserControl itself Following up on my previous question (Change brushes based on ViewModel property) In my UserControl I have have a DependencyObject. I want to bind that object to a property of my ViewModel. In this case a CarViewModel, property name is Status and returns an enum value. public partial class CarView : UserControl { public CarStatus Status { get { return (CarStatus)GetValue(CarStatusProperty); } set { SetValue(CarStatusProperty, value); } } public static readonly DependencyProperty CarStatusProperty = DependencyProperty.Register("Status", typeof(CarStatus), typeof(CarView), new PropertyMetadata(OnStatusChanged)); private static void OnStatusChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { var control = (CarView)obj; control.LoadThemeResources((CarStatus)e.NewValue == CarStatus.Sold); } public void LoadThemeResources(bool isSold) { // change some brushes } } <UserControl x:Class="MySolution.Views.CarView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:views="clr-MySolution.Views" mc:Ignorable="d" views:CarView.Status="{Binding Status}"> <UserControl.Resources> </UserControl.Resources> <Grid> <TextBlock Text="{Binding Brand}"FontSize="22" HorizontalAlignment="Center" VerticalAlignment="Center"/> </Grid> <UserControl Where do I need to specify this binding? In the root of the UserControl it gives an error: The attachable property 'Status' was not found in type 'CarView' In my MainWindow I bind the CarView using a ContentControl: <ContentControl Content="{Binding CurrentCar}"> <ContentControl.Resources> <DataTemplate DataType="{x:Type viewmodel:CarViewModel}"> <views:CarView /> </DataTemplate> </ContentControl.Resources> </ContentControl> My ViewModel: [ImplementPropertyChanged] public class CarViewModel { public Car Car { get; private set; } public CarStatus Status { get { if (_sold) return CarStatus.Sold; return CarStatus.NotSold; } } } A: your binding isn't well written. instead of writing views:CarView.Status="{Binding Status}" you should write only Status="{Binding Status}" A: It seems that your Control is binding to itself. Status is looked for in CarView. You should have a line of code in your control CodeBehind like : this.DataContext = new ViewModelObjectWithStatusPropertyToBindFrom(); Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/33076560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java and UML: Relationship between a LinkedList class and an Iterator Interface I have a few questions on UML relationships in Java. The following classes and interfaces refer to classes and interfaces (either created or existing) in Java. Setup: Suppose I have a GenericLinkedList<T> implements Iterable<I> class (with private Node<T> head). This class also has a static inner class Node<D>. The GenericLinkedList<T> implements the abstract method iterator() (from Iterable<I>) that returns an Iterator<T>. The class that implements Iterator<T>, GLLIterator<T>, takes an GenericLinkedList<T> object as a parameter (in its constructor), but just stores the head of this list in a private cur variable. * *Would the relationship between GLLIterator<T> and GenericLinkedList<T> be Composition (with the black diamond pointing to the list), even though the latter does not contain the former? I thought it would because the "iterators" are meaningless without the the "lists". Or would it just be a dependency, since the iterator just "uses" the list to get head? *Would the relationship between Node<D> and GLLIterator<T> be Aggregation or Composition? I thought it would be Aggregation because we can have multiple iterators at the same node. But, on the other hand, when the cur node dies, the iterator is meaningless. *Would I draw a dependency between the list class and the iterator interface or the class that implements the interface? Edit: I was trying to reason through (1) as follows: So, the linked list has nodes and the iterator has a node. If Java had destructors, would I need to call the destructor of an iterator if I destroy the linked list? If I destroy the linked list, the destructors of the nodes should get called. But the iterator exists apart from the list, it (1) just points to a node in the list and (2) can be used as an iterator for another list. I ask because I was wondering the UML relationship between the iterator classes and the linked list class: Composition (owns) or Aggregation (has-a). Thank you. A: If Java had destructors, would I need to call the destructor of an iterator if I destroy the linked list? To delete an iterator because it corresponds to a deleted node (whatever the list is deleted or not, so all its nodes are deleted or not) is for me the worst possible choice, that means the iterator becomes silently unusable, a very practical way to introduce undefined behaviors at the execution. In case a node knows its iterators a good way is to mark them invalid when the node is deleted, and in that case to try access the corresponding element of the list or go to the previous/next element produces an exception. For me the list by itself do not need to know the iterators, and an iterator does not need to know the list by itself, so for question 1 no relation at all between GenericLinkedList<T> and GLLIterator<T>. For the question 2 no aggregation nor composition, because the iterator just references a node, the iterator has a node is false, an iterator is not composed of nodes nor owns them. In the reverse direction even a node knows the iterators pointing to it that node is not composed of iterator nor owns them, but also just reference them. If a node knows the iterators you have an association from node to iterator with the multiplicity *, else no relation at all. In iterator you have a simple association to node, the multiplicity can be 0..1 (0 means the iterator was invalidated) or 1 depending on the implementation. For the question 3 an interface having no implementation it cannot use something else, contrarily to the implementing class(es).
{ "language": "en", "url": "https://stackoverflow.com/questions/64200864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQUERY AJAX - change class of $(this) in case of success I have a div. Inside that div I have multiple elements. Some elements have the class 'myClass'. I also have a button. When clicked, a foreach loop runs for each element that has the class myClass within the div. An ajaxCall is send for each element. The text color of those elements are black by default. In case of success of the ajax call. I would like to remove the class classBlackFont and add the one classGreenFont. I tried the following code which is unfortunately not switching the classes eventhough the ajax call succeeded. $("#someDiv .myClass").each(function() { var ajaxData = "myAjaxData"; $.ajax({ type: "POST", url: "somefile.php", data: ajaxData, success: function(data) { $(this).removeClass('classBlackFont').addClass('classGreenFont'); } }); });​ A: this is not automatically a reference to the right object in the ajax callback. You can change that by closing over a variable that does have the right value: $("#someDiv .myClass").each(function() { var $this = $(this); var ajaxData = "myAjaxData"; $.ajax({ type: "POST", url: "somefile.php", data: ajaxData, success: function(data) { $this.removeClass('classBlackFont').addClass('classGreenFont'); } }); });​ or by using the context option of $.ajax(): $("#someDiv .myClass").each(function() { var ajaxData = "myAjaxData"; $.ajax({ type: "POST", url: "somefile.php", data: ajaxData, context: this, success: function(data) { $(this).removeClass('classBlackFont').addClass('classGreenFont'); } }); });​ A: context : this like something /** * Default ajax */ $.ajaxSetup({ type: 'post', dataType: 'json', context: this });
{ "language": "en", "url": "https://stackoverflow.com/questions/10298756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What tool can I use to view the changes in an in-memory H2 database? I switched to using an in-memory H2 database for development. It works great, but I'm not able to see my changes as I make them. This is their suggested list of tools: http://h2database.com/html/links.html#tools I tried DB Visualizer and SQL Developer, but I can't find the tables my software creates. Are there any gotcha's that I should be aware of when working with H2, or any suggestions on a nice tool for Linux. A: to be independent of the operating system used(Win,Linux(Ubuntu,..),Mac),Execute this command : java -cp h2*.jar org.h2.tools.Console It will open the browser : http://localhost:8082 A: I've generally just used their web interface, found at http://localhost:8082 by default. Their quickstart guide covers making it available on Windows in great detail, but I recommend simply checking http://localhost:8082 as a first step to see if it's already up and running.
{ "language": "en", "url": "https://stackoverflow.com/questions/11731978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error when checking model target: expected predictions to have shape (None, 1000) but got array with shape (64, 2) Notebook so far: Notebook I am trying to reshape the standard Keras VGG16 model to use for the classic cats vs dogs competition (Kaggle Cats vs Dogs) I had to recreate the pop() and add() functions of the Sequential() Keras model to remove the last Dense(1000) layer and replace it with Dense(2) layer. However, when I try to use the fit_generator() function, I get the following error: ValueError: Error when checking model target: expected predictions to have shape (None, 1000) but got array with shape (64, 2) It sounds like my model is still expecting to output 1000 categories rather than 2. Why is this? Model summary below: Layer (type) Output Shape Param # Connected to input_27 (InputLayer) (None, 224, 224, 3) 0 block1_conv1 (Convolution2D) (None, 224, 224, 64) 1792 input_27[0][0] block1_conv2 (Convolution2D) (None, 224, 224, 64) 36928 block1_conv1[0][0] block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 block1_conv2[0][0] block2_conv1 (Convolution2D) (None, 112, 112, 128) 73856 block1_pool[0][0] block2_conv2 (Convolution2D) (None, 112, 112, 128) 147584 block2_conv1[0][0] block2_pool (MaxPooling2D) (None, 56, 56, 128) 0 block2_conv2[0][0] block3_conv1 (Convolution2D) (None, 56, 56, 256) 295168 block2_pool[0][0] block3_conv2 (Convolution2D) (None, 56, 56, 256) 590080 block3_conv1[0][0] block3_conv3 (Convolution2D) (None, 56, 56, 256) 590080 block3_conv2[0][0] block3_pool (MaxPooling2D) (None, 28, 28, 256) 0 block3_conv3[0][0] block4_conv1 (Convolution2D) (None, 28, 28, 512) 1180160 block3_pool[0][0] block4_conv2 (Convolution2D) (None, 28, 28, 512) 2359808 block4_conv1[0][0] block4_conv3 (Convolution2D) (None, 28, 28, 512) 2359808 block4_conv2[0][0] block4_pool (MaxPooling2D) (None, 14, 14, 512) 0 block4_conv3[0][0] block5_conv1 (Convolution2D) (None, 14, 14, 512) 2359808 block4_pool[0][0] block5_conv2 (Convolution2D) (None, 14, 14, 512) 2359808 block5_conv1[0][0] block5_conv3 (Convolution2D) (None, 14, 14, 512) 2359808 block5_conv2[0][0] block5_pool (MaxPooling2D) (None, 7, 7, 512) 0 block5_conv3[0][0] flatten (Flatten) (None, 25088) 0 block5_pool[0][0] fc1 (Dense) (None, 4096) 102764544 flatten[0][0] fc2 (Dense) (None, 4096) 16781312 fc1[0][0] predictions (Dense) (None, 2) 8194 fc2[0][0] Total params: 134,268,738 Trainable params: 8,194 Non-trainable params: 134,260,544 The .add() function sets the model.built variable to False, so I am wondering if it's anything to do with that. And if it is, how do I "build" the model? Any help is greatly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/41817519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Database design, wish list and its items I am creating a new database to manage wish lists. Solution A: Two tables, * *wish_list and *wish_list_item Solution B: One table, * *wish_list_with_item This would have a wish list item per column, so it will be many columns on this table. Which is better? A: Solution A is better. Anytime you try to store collections in columns rather than rows, you're going to run into problems. A: solution A is normalized and solution B is not. In most situations solution A will be better and more flexible. The major time this is not true is if you are making a summary table of some complex join on large tables for use as a source of quick queries for common questions. Unless you are building a datamart, this is unlikely to be the case. Go with solution A. A: I would definitly go with the first solution : * *at least, it means you can have as many items you want -- and it'll probably be easier to deal with, on the application side (think about "deleting an item", or "adding an item", for instance) *the second solution absolutly doesn't feel right A: The second solution would be better only if you are forced to do a denormalization for the sake of easier caching or if your application grows immensely and you need database sharding. In all other cases I prefer a cleaner design of the database. A: Multi - table is complicated, so, single table is practical, simple and thus worth considering. Assuming wish list is a feature of a web site, where some users come, create user account, and then list their wishes it might not be completely obvious, but if you think of it, the question needs to be asked, why would you want to have a header table defining wish list(s) instead of having just the second table, listing wishes. In my mind the need for such an approach indicates that each user will ( likely ) want to have more than one wish list. One for close friends and relatives and one for space ship adventure planned for year 2050 :) Otherwise all the wishes could probably be neatly listed in the wish detail ( second ) table, without the first, for one huge wish list ( let's call it default wish list ), without distinction between wishes, be that something you would like for a present, or plan to accomplish while preparing for space ship adventures ( may all your wishes come true! :) ). Going back to design of tables, here is considerations. If you do not plan to * *use wish list for wish list fulfillment *add any specifics, details for each of the "whishes" separately than storing list in something like a long string field allows single table. If you need 2, than adding second table is justified, but still can be avoided by turning "long string" field into XML column with attributes, where you can pair wished item and some additional comments and / or information. If you need 1, than two table solution is required, so that a relationship can be established between items on the wish list and anything related to this specific item, be that a gift from close friend or relative, which fulfills the wish, or something like catalog of things stored in yet another table. If you do use multi - table approach than you will need to be careful so that table listing individual wish items didn't have entries without matching header entry defining the list itself. Usually databases use foreign key to enforce such a relationship. So, the "item" table will need to have a field with a key from the parent table. Summarizing, it is very likely you will have 2 or 3 tables. Table 1 - listing user accounts In the simplest case this table will have a field "my wish list" with long string and / or XML column. Table 2 - enumerating user wish lists with a key noting related user account. Table 3 - enumerating wish items, with key from either user account ( if user can have only one wish list ) or Table 2 if each user can have multiple distinct wish lists. Finally, in theory, users can have shared wish lists. For example, Kate and Simon plan to marry in year 2025. They wish to have a wedding ceremony in a cabin on Vashon Island ( the line is long and last time I checked the place is booked 4 years in advance ). In which case a possibility of 4th table comes along. This table will pare together "users" and "wish lists", to enable joined ownership of wish list. Hope this helps. -- cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/1407157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }