title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
In CustomView, only alpha Animation doesn't work
<p>I make my custom view. and I also make my custom view (making Circle). But In my custom view, Alpha Animation only don`t work.... </p> <p>My Customview extends linearlayout</p> <pre><code>public class mylayout extends FrameLayout implements View.OnClickListener { ...... public mylayout(Context context){ super(context); init(context); } void init(Context context){ this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mButton = new Button(getContext()); mButton.setText("Delete all Created Circle."); mButton.setId(10); mButton.setOnClickListener(this); bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.change_sea01); this.addView(mButton,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if(event.getAction() == MotionEvent.ACTION_DOWN) { this.addView(new MyCircleView(getContext(), (int)event.getX(), (int)event.getY())); return true; } else if(event.getAction() == MotionEvent.ACTION_MOVE) { this.addView(new MyCircleView(getContext(),(int)event.getX(), (int)event.getY())); return true; } return super.onTouchEvent(event); } </code></pre> <p>This is myCircle Class that make circle on touching point(x,y)</p> <pre><code>class MyCircleView extends ImageView{ ............. public MyCircleView(Context context, int xPos, int yPos) { super(context); pnt = new Paint(); pnt.setAntiAlias(true); bDelete = false; bmpCircle = BitmapFactory.decodeResource(context.getResources(), R.drawable.img_click); this.xPos = xPos; this.yPos = yPos; xWidth = bmpCircle.getWidth()/2; yWidht = bmpCircle.getHeight()/2; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if(setAnimation == null){ createAnimation(canvas); } canvas.drawBitmap(bmpCircle, xPos - xWidth, yPos - yWidht, pnt); } public void createAnimation(final Canvas canvas) { AlphaAnimation alpha; ScaleAnimation scale; alpha = new AlphaAnimation(1.0f, 0.0f); scale = new ScaleAnimation(1, 2, 1, 2, Animation.ABSOLUTE, xPos- xWidth, Animation.ABSOLUTE, yPos - yWidht); setAnimation = new AnimationSet(false); setAnimation.addAnimation(alpha); setAnimation.addAnimation(scale); setAnimation.setDuration(3000); startAnimation(setAnimation); } } </code></pre>
3
1,293
Application not working, beginner
<p>i am fairly new to android programming and usually find my answers to my problems by searching, but this one i just cant and its very confusing. The code itself doesn't show any signs of problems, well i do get 2 java exception breakpoints but i dont know how to fix those as they are "unknown"but when i run it on the emulator it says the application has stopped unexpectedly force close. I try to debug it but i dont know how to do it that well. any way here are the codes btw the app is just a test all it to do is have buttons that take me to other "pages" and back. I would appreciate any help.</p> <p>Main java file</p> <pre><code>package com.simbestia.original; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class original extends Activity implements View.OnClickListener { Button button1, button2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button1 = (Button) findViewById(R.id.pagetwo); button2 = (Button) findViewById(R.id.main); button1.setOnClickListener(this); button2.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.pagetwo: setContentView(R.layout.pagetwo); break; case R.id.main: setContentView(R.layout.main); break; } } } </code></pre> <p>Main xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /&gt; &lt;Button android:text="pagetwo" android:id="@+id/pagetwo" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; </code></pre> <p>Well here is what i change the code to this one is just one button but it works with multiple and i made a class for every page...</p> <pre><code>package com.simbestia.test; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button mainmenu = (Button) findViewById(R.id.mainmenu); mainmenu.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), mainmenu.class); startActivityForResult(myIntent, 0); } }); } </code></pre> <p>}</p> <p>Works how i wanted to so its all good i guess ty again</p>
3
1,125
POST request endpoint using Java/Spring-boot
<p>I'm trying to make a post request endpoint to send some form values to my database. When I test the request with postman, I get a 400 bad request error and this message in my console</p> <p>JSON parse error: Cannot deserialize value of type <code>abcd.Model.Quote</code> from Array value (token <code>JsonToken.START_ARRAY</code>);</p> <p>this is my controller:</p> <pre><code> @ResponseStatus(HttpStatus.CREATED) @PostMapping(&quot;/createQuote&quot;) public boolean newQuote(@RequestBody Quote newQuote) { return quoteDB.saveQuote(newQuote); }; </code></pre> <p>my model:</p> <pre><code>public class Quote { public int id; public String type_building; public int numElevator; public String typeService; public double total; public double totalElevatorPrice; public Quote( int _id, String _type_building, int _numElevator, String _typeService, double _total, double _totalElevatorPrice ){ this.id = _id; this.type_building = _type_building; this.numElevator = _numElevator; this.typeService = _typeService; this.total = _total; this.totalElevatorPrice = _totalElevatorPrice; } public String getType_building() { return type_building; } public void setType_building(String type_building) { this.type_building = type_building; } public int getNumElevator() { return numElevator; } public void setNumElevator(int numElevator) { this.numElevator = numElevator; } public String getTypeService() { return typeService; } public void setTypeService(String typeService) { this.typeService = typeService; } public double getTotal() { return total; } public void setTotal(int total) { this.total = total; } public double getTotalElevatorPrice() { return totalElevatorPrice; } public void setTotalElevatorPrice(int totalElevatorPrice) { this.totalElevatorPrice = totalElevatorPrice; } </code></pre> <p>}</p> <p>and this is the function saveQuote where I try to post to the database:</p> <pre><code> public boolean saveQuote(Quote newQuote){ PreparedStatement getData; try { Connection c; c = this.db.connectDB(); getData = c.prepareStatement(&quot;INSERT INTO Quote VALUES (&quot; +&quot;'&quot; +newQuote.getType_building() + &quot;'&quot; +&quot;,&quot; + &quot;'&quot; +newQuote.getNumElevator() + &quot;'&quot; + &quot;,&quot; + newQuote.getTypeService() + &quot;,&quot; + newQuote.getTotal() + &quot;,&quot; + newQuote.getTotalElevatorPrice() + &quot;)&quot;); getData.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } </code></pre> <p>Thank you for your help.</p> <p>UPDATE: this is the POST request im sending in postman:</p> <pre><code>[ { &quot;id&quot;: 2, &quot;type_building&quot;: &quot;commercial&quot;, &quot;numElevator&quot;: 10, &quot;typeService&quot;: &quot;standard&quot;, &quot;total&quot;: 100000.0, &quot;totalElevatorPrice&quot;: 1.0E7 } ] </code></pre>
3
1,161
Class SpringHibernateJpaPersistenceProvider does not implement the requested interface PersistenceProvider
<p>I'm stumped - I haven't used Hibernate in several years and then, never with Spring Boot. Spring Boot but never with Hibernate or JPA. So i'm trying to figure out how to get this to work for my job - I'm supposed to demo something Monday and if I can get 'this' to work, I'll copy it over to my work laptop and change the details of course. Btw - here's the message I get - I had to shorten it in the title:</p> <p>&quot;Class org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider does not implement the requested interface javax.persistence.spi.PersistenceProvider&quot;</p> <p>I have the &quot;main&quot; class - TestWebApplication:</p> <pre><code>package net.draconia.testWeb; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; @SpringBootApplication(scanBasePackages = {&quot;com.draconia.testWeb.controller&quot;}) public class TestWebApplication { @Bean public DataSource getDatasource() { BasicDataSource objDatasource = new BasicDataSource(); objDatasource.setDriverClassName(&quot;com.mysql.jdbc.Driver&quot;); objDatasource.setUrl(&quot;jdbc:mysql://localhost:3306/Test&quot;); objDatasource.setUsername(&quot;root&quot;); objDatasource.setPassword(&quot;R3g1n@ M1lL$ 1$ My Qu3eN!&quot;); return(objDatasource); } @Bean public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() { LocalContainerEntityManagerFactoryBean objEntityManager = new LocalContainerEntityManagerFactoryBean(); objEntityManager.setDataSource(getDatasource()); objEntityManager.setPackagesToScan(new String[] { &quot;net.draconia.testWeb.beans&quot; }); JpaVendorAdapter objVendorAdapter = new HibernateJpaVendorAdapter(); objEntityManager.setJpaVendorAdapter(objVendorAdapter); objEntityManager.setJpaProperties(getHibernateProperties()); return(objEntityManager); } protected Properties getHibernateProperties() { Properties objHibernateProperties = new Properties(); objHibernateProperties.setProperty(&quot;hibernate.hbm2ddl.auto&quot;, &quot;create-drop&quot;); objHibernateProperties.setProperty(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.MySQLDialect&quot;); return(objHibernateProperties); } @Bean public JpaTransactionManager getHibernateTransactionManager() { JpaTransactionManager objTransactionManager = new JpaTransactionManager(); objTransactionManager.setEntityManagerFactory(getEntityManagerFactory().getObject()); return(objTransactionManager); } public static void main(String[] args) { SpringApplication.run(TestWebApplication.class, args); } } </code></pre> <p>, the entity bean:</p> <pre><code>package net.draconia.testWeb.beans; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name = &quot;Books&quot;) public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer miId; @Column(columnDefinition = &quot;varchar(200) not null&quot;, insertable = true, length = 200, name = &quot;BookName&quot;, nullable = false, table = &quot;Books&quot;, unique = false, updatable = true) private String msBookName; @Column(columnDefinition = &quot;varchar(100) not null&quot;, insertable = true, length = 100, name=&quot;Author&quot;, nullable = false, table = &quot;Books&quot;, unique = false, updatable = true) private String msAuthor; public String getAuthor() { if(msAuthor == null) msAuthor = &quot;&quot;; return(msAuthor); } public String getBookName() { if(msBookName == null) msBookName = &quot;&quot;; return(msBookName); } public int getId() { if(miId == null) miId = 0; return(miId); } public void setAuthor(final String sAuthor) { if(sAuthor == null) msAuthor = &quot;&quot;; else msAuthor = sAuthor; } public void setBookName(final String sBookName) { if(sBookName == null) msBookName = &quot;&quot;; else msBookName = sBookName; } public void setId(final Integer iId) { if(iId == null) miId = 0; else miId = iId; } } </code></pre> <p>, the DAOConcrete class (the interface is just one method which is logical but if you want I'll post that too):</p> <pre><code>package net.draconia.testWeb.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import net.draconia.testWeb.beans.Book; @Repository(&quot;bookDAO&quot;) public class BookDAOImpl implements BookDAO { @Autowired private EntityManagerFactory mObjEntityManagerFactory; public List&lt;Book&gt; getAllBooks() { EntityManager objEntityManager = getEntityManagerFactory().createEntityManager(); List&lt;Book&gt; lstBooks = objEntityManager.createQuery(&quot;from Books&quot;, Book.class).getResultList(); return(lstBooks); } protected EntityManagerFactory getEntityManagerFactory() { return(mObjEntityManagerFactory); } } </code></pre> <p>, and the Controller class for the REST endpoints/MVC Controller:</p> <pre><code>package net.draconia.testWeb.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import net.draconia.testWeb.beans.Book; import net.draconia.testWeb.dao.BookDAO; @Controller public class TestController { @Autowired private BookDAO mObjDAO; @GetMapping(&quot;/Books&quot;) public List&lt;Book&gt; getBooks() { return(getDAO().getAllBooks()); } protected BookDAO getDAO() { return(mObjDAO); } } </code></pre> <p>The POM file is here just for completeness but I don't think it's necessarily a problem unless I'm missing a dependency:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.7.1&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;net.draconia&lt;/groupId&gt; &lt;artifactId&gt;testWeb&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;testWeb&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;properties&gt; &lt;hibernate.version&gt;6.1.0.Final&lt;/hibernate.version&gt; &lt;java.version&gt;11&lt;/java.version&gt; &lt;mysql.version&gt;8.0.29&lt;/mysql.version&gt; &lt;spring.version&gt;5.3.2&lt;/spring.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-core&lt;/artifactId&gt; &lt;version&gt;2.13.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jakarta.persistence&lt;/groupId&gt; &lt;artifactId&gt;jakarta.persistence-api&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.persistence&lt;/groupId&gt; &lt;artifactId&gt;javax.persistence-api&lt;/artifactId&gt; &lt;version&gt;2.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;${mysql.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.commons&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp2&lt;/artifactId&gt; &lt;version&gt;2.9.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate.orm&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>If you'll note, i'm including a dependency for the Jackson library because the list of books should return as a JSON object. I don't think that's a poblem but just saying - and I could probably have remoed that for this but then when it runs, the list of books would be unintelligible to me getting a response when/if it worked. What am I doing wrong???</p>
3
5,029
Optimization in resetting the values ​of an array
<p>Good evening everyone, I ask you my question by specifying that I have found a solution, but I would be interested to know if it can be optimized and improved to favor performance. I have the following subject given in response to a call to my server:</p> <pre><code>{ &quot;status&quot;: 200, &quot;error_code&quot;: 0, &quot;data&quot;: { &quot;2022-04-15&quot;: { &quot;dots&quot;: [ 2 ] }, &quot;2022-04-19&quot;: { &quot;dots&quot;: [ 2 ] }, &quot;2022-04-20&quot;: { &quot;dots&quot;: [ 1 ] }, &quot;2022-04-25&quot;: { &quot;dots&quot;: [ 1 ] }, &quot;2022-04-26&quot;: { &quot;dots&quot;: [ 2, 3 ] }, &quot;2022-04-27&quot;: { &quot;dots&quot;: [ 3 ] }, &quot;2022-04-28&quot;: { &quot;dots&quot;: [ 3 ] } } } </code></pre> <p>Now I am using a library for react native (specifically react-native-calendars) and I need to reformat the response of my server, replacing within the object dots the numbers 1, 2, 3 of the static objects I have defined as follows :</p> <pre><code>const data1 = { key: &quot;data1&quot;, color: Colors.color40, }; const data2 = { key: &quot;data2&quot;, color: Colors.colorYellow, }; const data3 = { key: &quot;data3&quot;, color: Colors.color44, }; const totalData = { 1: data1, 2: data2, 3: data3, }; </code></pre> <p>According to the react native calendars documentation, I need to have an object structured like this as a final result:</p> <pre><code>const vacation = {key: 'vacation', color: 'red', selectedDotColor: 'blue'}; const massage = {key: 'massage', color: 'blue', selectedDotColor: 'blue'}; const workout = {key: 'workout', color: 'green'}; &lt;Calendar markingType={'multi-dot'} markedDates={{ '2017-10-25': {dots: [vacation, massage, workout]}, '2017-10-26': {dots: [massage, workout]} }} /&gt;; </code></pre> <p>To get the expected result, I wrote the following function:</p> <pre><code> const formattedCalendarDots = (obj) =&gt; { Object.keys(obj).forEach((key) =&gt; { obj[key] = { dots: obj[key].dots.map((el) =&gt; totalData[el]) }; }); return obj; }; </code></pre> <p>I ask the more experienced. is this a good solution? Again, this function does what I ask, but I wanted to know if it was possible to optimize it in excellent performance. Thanks to those who will answer</p>
3
1,362
ifstream sets eof flag when file is opened
<p>I am trying to read from a text file using ifstream, but for some reason when I use g++ to compile, the eof flag is set before anything is even read from the file. Testing if the file is in fact open does return true. When using visual studio to compile it works correctly. Even when the file &quot;file.txt&quot; exists, the program below prints 1 when compiled with g++.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; int main() { std::ifstream file(&quot;file.txt&quot;); if (file) std::cout &lt;&lt; file.eof(); } </code></pre> <p>The following is from powershell</p> <pre><code>PS C:\Users\baat2\prosjekter\CPP\testdir&gt; dir Directory: C:\Users\baat2\prosjekter\CPP\testdir Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 24.01.2022 12:39 33 file.txt -a---- 24.01.2022 12:39 138 testfile.cpp -a---- 24.01.2022 12:47 130594 testfile.exe PS C:\Users\baat2\prosjekter\CPP\testdir&gt; g++ -o testfile.exe testfile.cpp PS C:\Users\baat2\prosjekter\CPP\testdir&gt; .\testfile 1 PS C:\Users\baat2\prosjekter\CPP\testdir&gt; type testfile.cpp #include &lt;iostream&gt; #include &lt;fstream&gt; int main() { std::ifstream file(&quot;file.txt&quot;); if (file) std::cout &lt;&lt; file.eof(); } PS C:\Users\baat2\prosjekter\CPP\testdir&gt; type file.txt a file with some text to test </code></pre> <p>OS is Windows 10. Version info for g++ is given below</p> <pre><code>PS C:\Users\baat2\prosjekter\CPP\testdir&gt; g++ -v Using built-in specs. COLLECT_GCC=C:\msys64\mingw64\bin\g++.exe COLLECT_LTO_WRAPPER=C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/lto-wrapper.exe Target: x86_64-w64-mingw32 Configured with: ../gcc-11.2.0/configure --prefix=/mingw64 --with-local-prefix=/mingw64/local --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --with-native-system-header-dir=/mingw64/x86_64-w64-mingw32/include --libexecdir=/mingw64/lib --enable-bootstrap --enable-checking=release --with-arch=x86-64 --with-tune=generic --enable-languages=c,lto,c++,fortran,ada,objc,obj-c++,jit --enable-shared --enable-static --enable-libatomic --enable-threads=posix --enable-graphite --enable-fully-dynamic-string --enable-libstdcxx-filesystem-ts --enable-libstdcxx-time --disable-libstdcxx-pch --disable-libstdcxx-debug --enable-lto --enable-libgomp --disable-multilib --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-libiconv --with-system-zlib --with-gmp=/mingw64 --with-mpfr=/mingw64 --with-mpc=/mingw64 --with-isl=/mingw64 --with-pkgversion='Rev2, Built by MSYS2 project' --with-bugurl=https://github.com/msys2/MINGW-packages/issues --with-gnu-as --with-gnu-ld --with-boot-ldflags='-pipe -Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high -Wl,--disable-dynamicbase -static-libstdc++ -static-libgcc' 'LDFLAGS_FOR_TARGET=-pipe -Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high' --enable-linker-plugin-flags='LDFLAGS=-static-libstdc++\ -static-libgcc\ -pipe\ -Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high\ -Wl,--stack,12582912' Thread model: posix Supported LTO compression algorithms: zlib zstd gcc version 11.2.0 (Rev2, Built by MSYS2 project) </code></pre>
3
1,429
Program crashing in munmap
<p>I am working at an Android app that, among other things, must send background data to a ftp server. The code that does this is written in native code, using standard Linux functions.</p> <p>Most of the time it works fine, but every once in a while it crashes, and the crash drives me crazy, because it makes no sense to me.</p> <p>Here is the relevant code:</p> <pre><code> if(!sbuf.st_size) { syslog(LOG_CRIT, &quot;FTP: OMFG WE GOT 0 FILE SIZE!!!11!!!! &quot;); close(fd); fclose(stream); close(dsock); return 0; } p = mmap(0, (size_t) sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if(p==MAP_FAILED) { syslog(LOG_CRIT, &quot;FTP: We got a mmap problem.... %s&quot;,strerror(errno)); close(fd); fclose(stream); close(dsock); return 0; } syslog(LOG_CRIT, &quot;Before fwrite&quot;); if(fwrite(p, 1, (size_t) sbuf.st_size, stream)!=(size_t) sbuf.st_size) { syslog(LOG_CRIT, &quot;FTP: We got a fwrite problem.... %s&quot;,strerror(errno)); munmap(p, (size_t) sbuf.st_size); close(fd); fclose(stream); close(dsock); return 0; } fflush(stream); usleep(150000); syslog(LOG_CRIT, &quot;Before munmap&quot;); munmap(p, (size_t) sbuf.st_size); //fflush(stream); close(fd); fclose(stream); close(dsock); int tries=0; while(1) { if(tries&gt;3)return 0; len = ftpTryRead(csock, buffer, 128); if (len &lt;= 0) { syslog(LOG_CRIT, &quot;FTP: Got null after upload, len is %i&quot;,len); //return 0; usleep(300000); tries++; continue; } if(!strncmp(buffer,&quot;226&quot;,3))break; else { syslog(LOG_CRIT, &quot;FTP: Expected 226 but got %s&quot;,buffer); return 0; } } //sleep(2); syslog(LOG_CRIT, &quot;FTP: Uploading of file %s should be completed.&quot;,file); unlink(file_name); return 1; </code></pre> <p>The relevant stuff in the logcat is this:</p> <pre><code>07-13 21:30:50.557 10268-10376/? E/com.example.ftp_cam: Before munmap 07-13 21:30:50.561 10268-15934/? E/IMemory: cannot dup fd=69, size=4096, err=0 (Bad file descriptor) 07-13 21:30:50.561 10268-15934/? E/IMemory: cannot map BpMemoryHeap (binder=0x7f57d239a0), size=4096, fd=-1 (Bad file descriptor) 07-13 21:30:50.561 10268-15934/? A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 15934 (Binder:10268_6) 07-13 21:30:50.570 10268-10376/? E/com.example.ftp_cam: FTP: Uploading of file IMG_20200713_082444.jpg should be completed. </code></pre> <p>So it seems that the code crashes in munmap. However, the code continues for a bit after the segfault, because it shows the file upload completed message (which is further down the code).</p> <p>Any idea what might the problem be? Thanks for your time!</p>
3
1,208
how to get the last inserted id and how to check in where condition to update query using php
<p>Hi iam inserting the data into database table and redirecting to another page and need to insert the details into the same table by comparing ids and email.But how to get the last inserted id and compare in where condition to update the details.</p> <p>Here is my code:</p> <p><strong>index.php</strong> </p> <pre><code>&lt;form method="post" action="properties.php" id="myform"&gt; &lt;input type='hidden' value="&lt;?php echo $username; ?&gt;" name='email'&gt; &lt;tr&gt;&lt;th&gt;Interest Paid&lt;/th&gt;&lt;td&gt;&lt;input type="text" name="house_interest_paid" value=""/&gt;&lt;/td&gt; &lt;tr&gt;&lt;th&gt;Total Interest Paid&lt;/th&gt;&lt;input type="text" name="house_total_interest_paid" value=""/&gt;&lt;/td&gt; &lt;tr&gt;&lt;th&gt;House Number&lt;/th&gt;&lt;input type="text" name="house_number" value=""/&gt;&lt;/td&gt; &lt;tr&gt;&lt;th&gt;Street&lt;/th&gt;&lt;input type="text" name="house_street" value=""/&gt;&lt;/td&gt; &lt;button type="submit" class = "large awesome yellows" onClick="document.location.href='ownerproperty.php'"&gt; Specify Co-owners Property&lt;/button&gt; &lt;/span&gt; &lt;/form&gt; </code></pre> <p><strong>properties.php</strong> </p> <pre><code>$email=$_POST['email']; $interest=$_POST['house_interest_paid']; $interestpaid=$_POST['house_total_interest_paid']; $number=$_POST['house_number']; $street=$_POST['house_street']; $query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')"); if($query) { session_start(); header("Location:ownerproperty.php"); } else{ echo "Registration has not been completed.Please try again"; } </code></pre> <p><strong>ownerproperty.php</strong></p> <pre><code>&lt;form style="display:none" method="POST" action="owner.php"&gt; &lt;h2&gt;Owner Property details&lt;/h2&gt; &lt;input type='hidden' value="&lt;?php echo $username; ?&gt;" name='email'&gt; &lt;?php include "ownership.php"; ?&gt; &lt;p&gt;&lt;label for="name_coowner"&gt;Coowner Name&lt;/label&gt; &lt;input value="&lt;?php echo $row['name_coowner'];?&gt;" type="text" name="name_coowner" /&gt;&lt;/p&gt; &lt;p&gt;&lt;label for="pan_coowner"&gt;PAN Of Coowner&lt;/label&gt; &lt;input value="&lt;?php echo $row['pan_coowner'];?&gt;" type="text" name="pan_coowner" /&gt;&lt;/p&gt; &lt;button type="submit" class = "medium" style="background-color: #2daebf;"&gt;Save&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>Ownership.php</strong></p> <pre><code>$res = "SELECT * FROM house_details WHERE email ='$username'"; $result=mysql_query($res); $row = mysql_fetch_array($result); </code></pre> <p><strong>Owner.php</strong></p> <pre><code>$email=$_POST['email']; $owner_name=$_POST['name_coowner']; $pan_owner=$_POST['pan_coowner']; $query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner' WHERE email='$email' AND house_details_id='2'"); if($query) { session_start(); header("Location:rentalproperty.php"); } </code></pre> <p>For the first time when i click on submit button the data is inserting into db and redirecting to ownerproperty.php .in that i need to get the inserted id and need to comapre that id and email and need to update the owner property details in the same column when the email and id are same.But how to get that id and compare in the where condition can anyone help me.</p>
3
1,407
Why may a generic type not use a concrete version of itself?
<h3>TL;DR</h3> <ul> <li>Why may we not use a concrete version of a generic type within its own generic implementation? Since it's a concrete type, I see no issues with &quot;recursive typing&quot;. Is this a design decision? Or a current limitation?</li> </ul> <hr /> <p><strong>Background</strong></p> <p>When playing around with generics, I stumbled over the following (for me, previously unknown) curiosity:</p> <pre><code>struct Foo&lt;T&gt; { let foo: T } struct Bar&lt;U&gt; { let bar: U func foobar() -&gt; Foo&lt;Bar&gt; { /* ^^^ Bar&lt;U&gt; inferred */ // no matter of the actual implementation ... return Foo(foo: self) } // even without inference help from the implemention func nilFoobar() -&gt; Foo&lt;Bar&gt;? { return nil } } </code></pre> <p>Particularly how the return type of <code>foobar()</code> needn't specify the placeholder type of <code>Bar</code> (which in turn is the placeholder for the generic <code>Foo</code> return), as this seems to be inferred as the same placeholder type as <code>Self</code> (concrete <code>U</code> in <code>Self</code>). I.e., as I see it, the above is equivalent to (except for the Option-click description of the <code>foo()</code> method in Xcode)</p> <pre><code>struct Foo&lt;T&gt; { let foo: T } struct Bar&lt;U&gt; { let bar: U func foobar() -&gt; Foo&lt;Bar&lt;U&gt;&gt; { return Foo(foo: self) } func nilFoobar() -&gt; Foo&lt;Bar&lt;U&gt;&gt;? { return nil } } </code></pre> <p>Since <code>Bar</code> in the return type of <code>foobar()</code> is inferred<sup>†</sup> as <code>Bar&lt;U&gt;</code>, I realized that this in turn should disallow a generic types using concrete versions of itself (something I've never had or have a reason to do ...). As expected, this theory holds:</p> <pre><code>struct Foo&lt;T&gt; { let foo: T } struct Bar&lt;U&gt; { let bar: U func foobar() -&gt; Foo&lt;Bar&lt;Int&gt;&gt; { return Foo(foo: Bar(bar: 1)) /* ^ error: 'Int' is not convertible to 'U' */ } // concrete version of other generic type naturally allowed func fooint() -&gt; Foo&lt;Int&gt; { return Foo(foo: 1) } } </code></pre> <p><sub>[†] Rather than inferred, perhaps a shortcut for is a better description? Since it compiles even without an actual implementation to fall back to w.r.t. inference.</sub></p> <p><strong>Question</strong></p> <p>I don't have any use for using concrete versions of <code>Self</code> within a generic type, but with some imagination, I could see this being used in some corner case context. More so, out of a technical viewpoint (and curiosity), I'm interested in why this seems to be disallowed by design.</p> <ul> <li>Why may we not use a concrete version of a generic type within its own implementation? Since it's a concrete type, I see no issues with &quot;recursive typing&quot;. Is this a design decision? A current limitation?</li> </ul> <p>I hope this question doesn't fall under opinion-based. Given the open official community of Swift, maybe someone can shed official-connecting light for the reasoning as to why this should be disallowed by design (or is it simply a current &quot;limitation&quot;?).</p>
3
1,131
Problems with scrolling in HorizontalListView(android)
<p>I use a <code>HorizontalListView</code> to scroll I use the code below (method setOnItemClickListener)</p> <pre><code> listview.post(new Runnable() { public void run() { int centerX = listview.getChildAt(position).getLeft(); listview.scrollTo(centerX); } }); </code></pre> <p>but there is a problem when position reaches <code>3</code> or more , then I get an error:</p> <pre><code>12-28 01:33:37.814 20841-20841/com.example.SmsService E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.SmsService, PID: 20841 java.lang.NullPointerException at com.example.SmsService.VideoView$1$1.run(VideoView.java:68) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5118) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>I think that probably because I use <strong>looped listView</strong>:</p> <pre><code> @Override public int getCount() { return Integer.MAX_VALUE;// } </code></pre> <p><strong>how I could fix this problem?</strong> And maybe there are other ways scroll listView? (Scrolling Smooth does not work ) <a href="https://gist.github.com/diha-o/c004352966f07bd02614" rel="nofollow">My Class.</a> And .xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:id="@+id/ll"&gt; &lt;VideoView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/videoView" android:layout_gravity="center_horizontal" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" /&gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="150dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="20dp"&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;com.devsmart.android.ui.HorizontalListView android:id="@+id/listview2" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:layout_weight="1"/&gt; &lt;com.devsmart.android.ui.HorizontalListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:smoothScrollbar="true" android:clickable="true" android:layout_alignParentRight="true" android:layout_weight="1"/&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; </code></pre>
3
1,680
How can I invoke this workflow?
<pre><code>static void Main(string[] args) { WorkflowDbContext db = new WorkflowDbContext(); var workflowFromDb = db.Workflows.Find("1"); string workFlowDefinition = workflowFromDb.WorkflowDefinition; ActivityXamlServicesSettings settings = new ActivityXamlServicesSettings { CompileExpressions = true }; } </code></pre> <p>When I try this:</p> <pre><code>DynamicActivity&lt;int&gt; wf = ActivityXamlServices.Load(new StringReader(workFlowDefinition), settings) as DynamicActivity&lt;int&gt;; </code></pre> <p>I get this error:</p> <pre><code>CacheMetadata for activity 'PeakTriggerActivities.SalesToService' threw 'System.Xaml.XamlObjectWriterException: Cannot create unknown type '{clr-namespace:PeakTriggerActivities}GetTouchPoint'. </code></pre> <p>I have also tried this, but wf just becomes a null value in this case:</p> <pre><code>//Encoding this way since xml file shows utf-16 MemoryStream mStream = new MemoryStream(Encoding.Unicode.GetBytes(workFlowDefinition)); //Also tried LocalAssembly = System.Reflection.Assembly.GetExecutingAssembly() instead of LocalAssembly = typeof(GetTouchPoint).Assembly DynamicActivity&lt;int&gt; wf = ActivityXamlServices.Load(new XamlXmlReader(mStream, new XamlXmlReaderSettings { LocalAssembly = typeof(GetTouchPoint).Assembly }), settings) as DynamicActivity&lt;int&gt;; </code></pre> <p>This is what the workFlowDefinition string contains, and the class called GetTouchPoint is in the same project as this main method in program.cs:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;Activity mc:Ignorable="sap sap2010 sads" x:Class="PeakTriggerActivities.SalesToService" sap2010:ExpressionActivityEditor.ExpressionActivityEditor="C#" sap2010:WorkflowViewState.IdRef="PeakTriggerActivities.SalesToService_1" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:local="clr-namespace:PeakTriggerActivities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mca="clr-namespace:Microsoft.CSharp.Activities;assembly=System.Activities" xmlns:sads="http://schemas.microsoft.com/netfx/2010/xaml/activities/debugger" xmlns:sap="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:sap2010="http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:sco="clr-namespace:System.Collections.ObjectModel;assembly=mscorlib" xmlns:t="clr-namespace:TouchPointModels;assembly=TouchPointModels" xmlns:t1="clr-namespace:TouchPointServices;assembly=TouchPointService" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;TextExpression.NamespacesForImplementation&gt; &lt;sco:Collection x:TypeArguments="x:String"&gt; &lt;x:String&gt;System&lt;/x:String&gt; &lt;x:String&gt;System.Collections.Generic&lt;/x:String&gt; &lt;x:String&gt;System.Data&lt;/x:String&gt; &lt;x:String&gt;System.Linq&lt;/x:String&gt; &lt;x:String&gt;System.Text&lt;/x:String&gt; &lt;x:String&gt;TouchPointModels&lt;/x:String&gt; &lt;/sco:Collection&gt; &lt;/TextExpression.NamespacesForImplementation&gt; &lt;TextExpression.ReferencesForImplementation&gt; &lt;sco:Collection x:TypeArguments="AssemblyReference"&gt; &lt;AssemblyReference&gt;Microsoft.CSharp&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;PresentationCore&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;PresentationFramework&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Activities&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Activities.Presentation&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Core&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Data&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Runtime.Serialization&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.ServiceModel&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.ServiceModel.Activities&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.ServiceModel.Channels&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Xaml&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Xml&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;System.Xml.Linq&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;WindowsBase&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;TouchPointModels&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;TouchPointService&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;mscorlib&lt;/AssemblyReference&gt; &lt;AssemblyReference&gt;PeakTriggerActivities&lt;/AssemblyReference&gt; &lt;/sco:Collection&gt; &lt;/TextExpression.ReferencesForImplementation&gt; &lt;Sequence sap2010:WorkflowViewState.IdRef="Sequence_1"&gt; &lt;Sequence.Variables&gt; &lt;Variable x:TypeArguments="x:String" Name="varTouchPointCode" /&gt; &lt;Variable x:TypeArguments="t:TouchPoint" Name="varTouchPoint" /&gt; &lt;Variable x:TypeArguments="x:Int32" Name="varProgramNumber" /&gt; &lt;/Sequence.Variables&gt; &lt;local:GetTouchPoint Text="{x:Null}" sap2010:WorkflowViewState.IdRef="GetTouchPoint_1" InProgramNumber="1" InTouchPointCode="SATM"&gt; &lt;local:GetTouchPoint.OutProgramNumber&gt; &lt;OutArgument x:TypeArguments="x:Int32"&gt; &lt;mca:CSharpReference x:TypeArguments="x:Int32"&gt;varProgramNumber&lt;/mca:CSharpReference&gt; &lt;/OutArgument&gt; &lt;/local:GetTouchPoint.OutProgramNumber&gt; &lt;local:GetTouchPoint.OutTouchPoint&gt; &lt;OutArgument x:TypeArguments="t:TouchPoint"&gt; &lt;mca:CSharpReference x:TypeArguments="t:TouchPoint"&gt;varTouchPoint&lt;/mca:CSharpReference&gt; &lt;/OutArgument&gt; &lt;/local:GetTouchPoint.OutTouchPoint&gt; &lt;local:GetTouchPoint.OutTouchPointCode&gt; &lt;OutArgument x:TypeArguments="x:String"&gt; &lt;mca:CSharpReference x:TypeArguments="x:String"&gt;varTouchPointCode&lt;/mca:CSharpReference&gt; &lt;/OutArgument&gt; &lt;/local:GetTouchPoint.OutTouchPointCode&gt; &lt;/local:GetTouchPoint&gt; &lt;If sap2010:WorkflowViewState.IdRef="If_1"&gt; &lt;If.Condition&gt; &lt;InArgument x:TypeArguments="x:Boolean"&gt; &lt;mca:CSharpValue x:TypeArguments="x:Boolean"&gt;varTouchPoint == null&lt;/mca:CSharpValue&gt; &lt;/InArgument&gt; &lt;/If.Condition&gt; &lt;If.Then&gt; &lt;WriteLine sap2010:WorkflowViewState.IdRef="WriteLine_1"&gt; &lt;InArgument x:TypeArguments="x:String"&gt; &lt;mca:CSharpValue x:TypeArguments="x:String"&gt;"Cannot find Touchpoint Code :" + varTouchPointCode&lt;/mca:CSharpValue&gt; &lt;/InArgument&gt; &lt;/WriteLine&gt; &lt;/If.Then&gt; &lt;If.Else&gt; &lt;Sequence sap2010:WorkflowViewState.IdRef="Sequence_2"&gt; &lt;WriteLine sap2010:WorkflowViewState.IdRef="WriteLine_3"&gt; &lt;InArgument x:TypeArguments="x:String"&gt; &lt;mca:CSharpValue x:TypeArguments="x:String"&gt;"Processing Touchpoint: " + varTouchPoint.Code + " - " + varTouchPoint.Name&lt;/mca:CSharpValue&gt; &lt;/InArgument&gt; &lt;/WriteLine&gt; &lt;t1:ProcessTouchPoint InTouchPoint="{x:Null}" Success="{x:Null}" Text="{x:Null}" sap2010:WorkflowViewState.IdRef="ProcessTouchPoint_1"&gt; &lt;t1:ProcessTouchPoint.InProgramNumber&gt; &lt;InArgument x:TypeArguments="x:Int32"&gt; &lt;mca:CSharpValue x:TypeArguments="x:Int32"&gt;varProgramNumber&lt;/mca:CSharpValue&gt; &lt;/InArgument&gt; &lt;/t1:ProcessTouchPoint.InProgramNumber&gt; &lt;t1:ProcessTouchPoint.InTouchPointCode&gt; &lt;InArgument x:TypeArguments="x:String"&gt; &lt;mca:CSharpValue x:TypeArguments="x:String"&gt;varTouchPointCode&lt;/mca:CSharpValue&gt; &lt;/InArgument&gt; &lt;/t1:ProcessTouchPoint.InTouchPointCode&gt; &lt;/t1:ProcessTouchPoint&gt; &lt;/Sequence&gt; &lt;/If.Else&gt; &lt;/If&gt; &lt;sads:DebugSymbol.Symbol&gt;d0tDOlxwcm9qZWN0c1xQZWFrVHJpZ2dlckFjdGl2aXRpZXNcUGVha1RyaWdnZXJBY3Rpdml0aWVzXFNhbGVzVG9TZXJ2aWNlLnhhbWwRMANrDgIBATYFRhsCARtHBWkKAgECNoEBNocBAgEpOQs5YAIBJUMLQ2ICASE+Cz5iAgEdNmw2bwIBHEoLSl8CAQNOCVIVAgEWVQlnFAIBB1ANUH4CARdWC1oXAgERWwtmIgIBCFgPWJgBAgESYxFjYAIBDV4RXl4CAQk= &lt;/sads:DebugSymbol.Symbol&gt; &lt;/Sequence&gt; &lt;sap2010:WorkflowViewState.ViewStateManager&gt; &lt;sap2010:ViewStateManager&gt; &lt;sap2010:ViewStateData Id="GetTouchPoint_1" sap:VirtualizedContainerService.HintSize="469,22" /&gt; &lt;sap2010:ViewStateData Id="WriteLine_1" sap:VirtualizedContainerService.HintSize="211,62" /&gt; &lt;sap2010:ViewStateData Id="WriteLine_3" sap:VirtualizedContainerService.HintSize="211,62" /&gt; &lt;sap2010:ViewStateData Id="ProcessTouchPoint_1" sap:VirtualizedContainerService.HintSize="211,22" /&gt; &lt;sap2010:ViewStateData Id="Sequence_2" sap:VirtualizedContainerService.HintSize="233,248"&gt; &lt;sap:WorkflowViewStateService.ViewState&gt; &lt;scg:Dictionary x:TypeArguments="x:String, x:Object"&gt; &lt;x:Boolean x:Key="IsExpanded"&gt;True&lt;/x:Boolean&gt; &lt;/scg:Dictionary&gt; &lt;/sap:WorkflowViewStateService.ViewState&gt; &lt;/sap2010:ViewStateData&gt; &lt;sap2010:ViewStateData Id="If_1" sap:VirtualizedContainerService.HintSize="469,398" /&gt; &lt;sap2010:ViewStateData Id="Sequence_1" sap:VirtualizedContainerService.HintSize="491,584"&gt; &lt;sap:WorkflowViewStateService.ViewState&gt; &lt;scg:Dictionary x:TypeArguments="x:String, x:Object"&gt; &lt;x:Boolean x:Key="IsExpanded"&gt;True&lt;/x:Boolean&gt; &lt;/scg:Dictionary&gt;&lt;/sap:WorkflowViewStateService.ViewState&gt; &lt;/sap2010:ViewStateData&gt; &lt;sap2010:ViewStateData Id="PeakTriggerActivities.SalesToService_1" sap:VirtualizedContainerService.HintSize="531,664" /&gt; &lt;/sap2010:ViewStateManager&gt; &lt;/sap2010:WorkflowViewState.ViewStateManager&gt; &lt;/Activity&gt; </code></pre>
3
4,459
How to connect firebase database to an android studio project where i am using sharedpreference
<p>So i am using sharedpreference in a voter app and i want to reset counts so that users can vote again next time</p> <p>So there are 10 counters with 10 textview I want at perticular time that counts at zero meaning i want to reset that counts but at perticular time. So how can i connect this to firebase so that everytime users will vote vote also increase in firebase database and at perticular time like 12 am i will manually update that value on zero so users can bote again for the same thing.</p> <p>Main activity</p> <pre><code>&lt;public class MainActivity extends AppCompatActivity { TextView tv10; Button btn10; int counter10 = 0; u/Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.*activity\_main* ); btn10 = findViewById ( R.id.*btn10* ); tv10 =findViewById ( R.id.*tv10* ); counter10= test10.*loadtotalfrompreftest10* ( this ); tv10.setText ( Integer.*toString* ( counter10 ) ); btn10.setOnClickListener ( new View.OnClickListener ( ) { u/Override public void onClick(View v) { counter10++; test10.*saveTotalInPreftest10* ( getApplicationContext (),counter10 ); tv10.setText ( Integer.*toString* ( counter10 ) ); Toast.*makeText* ( getApplicationContext (),&quot;you clicked button 10&quot;,Toast.*LENGTH\_SHORT* ).show (); } } ); } } </code></pre> <p>Class file</p> <pre><code> private static final String *MY\_PREFERENCE\_NAME* = &quot;package com.example.voting&quot;; private static final String *PREF\_TOTAL\_KEY10* = &quot;pref\_total\_key10&quot;; public static void saveTotalInPreftest10(Context context, int test10total){ SharedPreferences pref = context.getSharedPreferences ( *MY\_PREFERENCE\_NAME*,Context.*MODE\_PRIVATE* ); SharedPreferences.Editor editor = pref.edit (); editor.putInt ( *PREF\_TOTAL\_KEY10*,test10total ); editor.apply (); } public static int loadtotalfrompreftest10 (Context context){ SharedPreferences pref = context.getSharedPreferences ( *MY\_PREFERENCE\_NAME*,Context.*MODE\_PRIVATE* ); return pref.getInt ( *PREF\_TOTAL\_KEY10*,0 ); } } </code></pre> <p>Xml file</p> <pre><code>&lt;?*xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;*?&gt;* &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout\_width=&quot;match\_parent&quot; android:layout\_height=&quot;match\_parent&quot; tools:context=&quot;.MainActivity&quot;&gt; &lt;Button android:id=&quot;@+id/btn10&quot; android:layout\_width=&quot;178dp&quot; android:layout\_height=&quot;113dp&quot; android:text=&quot;Button&quot; app:layout\_constraintBottom\_toBottomOf=&quot;parent&quot; app:layout\_constraintEnd\_toEndOf=&quot;parent&quot; app:layout\_constraintStart\_toStartOf=&quot;parent&quot; app:layout\_constraintTop\_toTopOf=&quot;parent&quot; /&gt; &lt;TextView android:id=&quot;@+id/tv10&quot; android:layout\_width=&quot;119dp&quot; android:layout\_height=&quot;88dp&quot; android:text=&quot;0&quot; app:layout\_constraintBottom\_toTopOf=&quot;@+id/btn10&quot; app:layout\_constraintEnd\_toEndOf=&quot;parent&quot; app:layout\_constraintStart\_toStartOf=&quot;parent&quot; app:layout\_constraintTop\_toTopOf=&quot;parent&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre>
3
1,714
How do I JSON serialize a struct with ambiguous embedding in Go?
<p>It would seem that having both <code>Identity</code> and <code>Report</code> embed <code>CommonProperties</code> causes omission of all of the common fields in the JSON serialization of the <code>CompositeObject</code>.</p> <pre><code>package main import ( "encoding/json" "fmt" "time" ) type CommonProperties struct { Type string `json:"type,omitempty"` ID string `json:"id,omitempty"` CreatedByRef string `json:"created_by_ref,omitempty"` Created time.Time `json:"created,omitempty"` Modified time.Time `json:"modified,omitempty"` Revoked bool `json:"revoked,omitempty"` Labels []string `json:"labels,omitempty"` Confidence int `json:"confidence,omitempty"` Language string `json:"lang,omitempty"` } type Identity struct { CommonProperties Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` IdentityClass string `json:"identity_class,omitempty"` Sectors []string `json:"sectors,omitempty"` ContactInformation string `json:"contact_information,omitempty"` } type Report struct { CommonProperties Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` Published time.Time `json:"published,omitempty"` ObjectRefs []string `json:"object_refs,omitempty"` } type CompositeObject struct { InternalID string `json:"uid,omitempty"` Pending bool `json:"pending"` Type string `json:"type"` *Identity *Report } func main() { co := CompositeObject{ Type: "report", Pending: true, Report: &amp;Report{ Name: "Spear Phishing Report", Description: "...", Published: time.Date(2016, 5, 12, 8, 17, 27, 0, time.UTC), ObjectRefs: []string{ "indicator--26ffb872-1dd9-446e-b6f5-d58527e5b5d2", "campaign--83422c77-904c-4dc1-aff5-5c38f3a2c55c", "relationship--f82356ae-fe6c-437c-9c24-6b64314ae68a", }, CommonProperties: CommonProperties{ ID: "report--84e4d88f-44ea-4bcd-bbf3-b2c1c320bcb3", Type: "report", Created: time.Date(2016, 5, 12, 8, 17, 27, 0, time.UTC), CreatedByRef: "identity--a463ffb3-1bd9-4d94-b02d-74e4f1658283", Modified: time.Date(2016, 5, 12, 8, 17, 27, 0, time.UTC), }, }, } json, _ := json.Marshal(&amp;co) fmt.Println(string(json)) } </code></pre> <p>Play links:</p> <ul> <li><a href="https://play.golang.org/p/iVxtYHWVPw" rel="nofollow noreferrer">https://play.golang.org/p/iVxtYHWVPw</a></li> <li><a href="https://play.golang.org/p/6adrrJ9iac" rel="nofollow noreferrer">https://play.golang.org/p/6adrrJ9iac</a></li> </ul> <p>The second one gets the desired output by commenting out second <code>CommonProperties</code> embed.</p> <p>I don't understand why an embed w/ this type of ambiguity would prevent JSON serialization. Is there a solution that doesn't involve writing a bunch of <code>MarshalJSON()</code> functions?</p>
3
1,534
Capybara Poltergeist getting forced over https when using path helpers
<p>Poltergeist is unable to connect to the server. Here's the error I'm getting:</p> <pre><code> Failure/Error: visit root_path Capybara::Poltergeist::StatusFailError: Request to 'http://127.0.0.1:58638/' failed to reach server, check DNS and/or server status </code></pre> <p>I've got the phantomjs debug output on, and here's what looks like the relevant lines to me:</p> <pre><code>2016-12-14T14:24:47 [DEBUG] WebpageCallbacks - getJsConfirmCallback {"command_id":"5eab3091-26bd-47b7-b779-95ec9523fb5b","response":true} {"id":"1069af41-1b7c-4f5b-a9c7-258185aa8c73","name":"visit","args":["http://127.0.0.1:58638/"]} 2016-12-14T14:24:47 [DEBUG] WebPage - updateLoadingProgress: 10 2016-12-14T14:24:48 [DEBUG] Network - Resource request error: QNetworkReply::NetworkError(ConnectionRefusedError) ( "Connection refused" ) URL: "https://127.0.0.1/" 2016-12-14T14:24:48 [DEBUG] WebPage - updateLoadingProgress: 100 2016-12-14T14:24:48 [DEBUG] WebPage - setupFrame "" 2016-12-14T14:24:48 [DEBUG] WebPage - setupFrame "" 2016-12-14T14:24:48 [DEBUG] WebPage - evaluateJavaScript "(function() { return (function () {\n return typeof __poltergeist;\n })(); })()" 2016-12-14T14:24:48 [DEBUG] WebPage - evaluateJavaScript result QVariant(QString, "undefined") {"command_id":"1069af41-1b7c-4f5b-a9c7-258185aa8c73","error":{"name":"Poltergeist.StatusFailError","args":["http://127.0.0.1:58638/",null]}} {"id":"cbe42cdc-58db-49c5-a230-4a1f4634d830","name":"reset","args":[]} </code></pre> <p>This bit seemed like a clue <code>Network - Resource request error: QNetworkReply::NetworkError(ConnectionRefusedError) ( "Connection refused" ) URL: "https://127.0.0.1/"</code> and that it could be an ssl error, so I added the phantomjs option <code>--ignore-ssl-errors=true</code>, but it makes no difference to the response.</p> <p>I switched over to <code>capybara-webkit</code> to see if that would provide a bit more info as some people have recommended. I get a very similar error:</p> <pre><code>"Visit(http://127.0.0.1:64341/)" started page load Started request to "http://127.0.0.1:64341/" Finished "Visit(http://127.0.0.1:64341/)" with response "Success()" Started request to "https://127.0.0.1/" Received 301 from "http://127.0.0.1:64341/" Received 0 from "https://127.0.0.1/" Page finished with false Load finished Page load from command finished Wrote response false "{"class":"InvalidResponseError","message":"Unable to load URL: http://127.0.0.1:64341/ because of error loading https://127.0.0.1/: Unknown error"}" Received "Reset()" Started "Reset()" undefined|0|SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent. </code></pre> <p>With the help of @thomas-walpole I realised that if I specific a non-https url to visit in capybara, it works. E.g <code>visit "http://localhost:3000"</code> it works. Using <code>visit root_url</code> works, but using <code>visit root_path</code> I get directed to https and the error above.</p> <p><code>config.force_ssl</code> is not true. I've set <code>config.force_ssl = false</code> in <code>config/environments/test.rb</code> and also used pry to check the <code>Application.config</code> in the context of the test.</p> <p>Any ideas for why the path helpers are getting sent over https would be greatly appreciated.</p>
3
1,168
Angular -fill one column based on server response
<p>I'm new to angular so sorry if this is a very basic question.</p> <p>I built a client-server app, that allows to upload files, then validates them (some internal rules) and returns log file in case the validation failed.</p> <p>I'm using <a href="https://github.com/nervgh/angular-file-upload" rel="nofollow">Angular File Upload</a> module for the client side, the <a href="https://github.com/nervgh/angular-file-upload/tree/master/examples/simple" rel="nofollow">simple</a> example.</p> <p>The response from server looks like this (JSON)</p> <pre><code>{"status":"FAILED","entity":"download/logs/24f307d3-8964-4a5b-8d66-0763503892b1/","errors":[]} </code></pre> <p>What I want to do is to upload the download link (from response.entity) for every file.</p> <p>What I get is same link for all files (the one from the last file)</p> <p>When I check what is happening in debug mode (F12) I do see that the parameters are changing but somehow they are being overridden with the last one.</p> <p>I think that I have to use ng-repeat somehow, but the thing is that it is already being used for other columns.</p> <p>Please help.</p> <p>MY html table:</p> <pre class="lang-html prettyprint-override"><code>&lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th width="50%"&gt;Name&lt;/th&gt; &lt;th ng-show="uploader.isHTML5"&gt;Size&lt;/th&gt; &lt;th ng-show="uploader.isHTML5"&gt;Progress&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;th align="justify"&gt;Actions&lt;/th&gt; &lt;th&gt;Valid&lt;/th&gt; &lt;th&gt;Log&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr ng-repeat="item in uploader.queue"&gt; &lt;td&gt;{{ item.file.name }}&lt;/td&gt; &lt;td ng-show="uploader.isHTML5" nowrap&gt;{{ item.file.size/1024/1024|number:2 }} MB&lt;/td&gt; &lt;td ng-show="uploader.isHTML5"&gt; &lt;div class="progress" style="margin-bottom: 0;"&gt; &lt;div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class="text-center"&gt; &lt;span ng-show="item.isSuccess"&gt;&lt;i class="glyphicon glyphicon-ok"&gt;&lt;/i&gt;&lt;/span&gt; &lt;span ng-show="item.isCancel"&gt;&lt;i class="glyphicon glyphicon-ban-circle"&gt;&lt;/i&gt;&lt;/span&gt; &lt;span ng-show="item.isError"&gt;&lt;i class="glyphicon glyphicon-remove"&gt;&lt;/i&gt;&lt;/span&gt; &lt;/td&gt; &lt;td nowrap&gt; &lt;button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess"&gt; &lt;span class="glyphicon glyphicon-upload"&gt;&lt;/span&gt; Upload &lt;/button&gt; &lt;button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading"&gt; &lt;span class="glyphicon glyphicon-ban-circle"&gt;&lt;/span&gt; Cancel &lt;/button&gt; &lt;button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()"&gt; &lt;span class="glyphicon glyphicon-trash"&gt;&lt;/span&gt; Remove &lt;/button&gt; &lt;/td&gt; &lt;td ng-show="item.isSuccess"&gt; {{this.uploader.validationStatus }} &lt;/td&gt; &lt;td ng-show="uploader.showLog"&gt; &lt;a href={{this.uploader.logURL}} target="_blank"&gt;Log&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I'm talking about 2 last columns:</p> <pre><code> &lt;td ng-show="item.isSuccess"&gt; {{this.uploader.validationStatus }} &lt;/td&gt; &lt;td ng-show="uploader.showLog"&gt; &lt;a href={{this.uploader.logURL}} target="_blank"&gt;Log&lt;/a&gt; &lt;/td&gt; </code></pre> <p>I did the following change in the controller.js file:</p> <pre class="lang-js prettyprint-override"><code>uploader.onCompleteItem = function(fileItem, response, status, headers) { console.info('onCompleteItem', fileItem, response, status, headers); var resp = JSON.stringify(response.entity); if (resp == "\"Success\"") { this.validationStatus = "Yes"; this.showLog = false; } else { this.validationStatus = "No"; this.logURL = resp.replace(/\"/g, ""); this.showLog = true; } </code></pre> <p><strong>The solution:</strong></p> <p>changes in controllers.js file:</p> <pre class="lang-js prettyprint-override"><code>uploader.onCompleteItem = function(fileItem, response, status, headers) { console.info('onCompleteItem', fileItem, response, status, headers); if (response.status === 'FAILED') { fileItem.validationStatus = "No"; fileItem.logUrl = response.entity; fileItem.showLog = true; } else { fileItem.validationStatus = "Yes"; fileItem.showLog = false; } }; </code></pre> <p>Changes in html file:</p> <pre class="lang-html prettyprint-override"><code>&lt;td ng-show="item.isSuccess" ng-class="{green: item.validationStatus == 'Yes', red: item.validationStatus == 'No'}"&gt; {{item.validationStatus}} &lt;/td&gt; &lt;td ng-show="item.showLog"&gt; &lt;a href={{item.logUrl}} target="_blank"&gt;Log&lt;/a&gt; &lt;/td&gt; </code></pre>
3
2,278
MooseX::Types and coercion error
<p>As continue of <a href="https://stackoverflow.com/a/19624694/1515483">this answer</a> wow im fighting with the my own Moose "type library" - so trying to use "<a href="https://metacpan.org/pod/MooseX::Types" rel="nofollow noreferrer">MooseX::Types</a>".</p> <p>Based on the above <code>MooseX::Types</code> docs, and "hoobs" comment to the above answer, I defined my own "types" as next:</p> <pre><code>package MyTypes; use 5.016; use Moose; use MooseX::Types -declare =&gt; [qw( Dir File )]; use MooseX::Types::Moose qw( Str ); use Path::Class::Dir; use Path::Class::File; class_type Dir, { class =&gt; 'Path::Class::Dir' }; coerce Dir, from Str, via { Path::Class::Dir-&gt;new($_) }; class_type File, { class =&gt; 'Path::Class::File' }; coerce File, from Str, via { Path::Class::File-&gt;new($_) }; 1; </code></pre> <p>and used it in my package</p> <pre><code>package MyDir; use Moose; use warnings; use MyTypes qw(Dir); #to get the Dir type and its coercion has 'path' =&gt; ( is =&gt; 'ro', isa =&gt; Dir, # Dir is defined in the package MyTypes required =&gt; 1, ); 1; </code></pre> <p>and tried with the next short script</p> <pre><code>use 5.016; use warnings; use MyDir; my $d = MyDir-&gt;new(path =&gt; "/tmp"); </code></pre> <p>Error:</p> <pre><code>Attribute (path) does not pass the type constraint because: Validation failed for 'MyTypes::Dir' with value /tmp (not isa Path::Class::Dir) at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1279. Moose::Meta::Attribute::verify_against_type_constraint(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), "/tmp", "instance", MyDir=HASH(0x7f9e9b826bb8)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1266 Moose::Meta::Attribute::_coerce_and_verify(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), "/tmp", MyDir=HASH(0x7f9e9b826bb8)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 536 Moose::Meta::Attribute::initialize_instance_slot(Moose::Meta::Attribute=HASH(0x7f9e9b1c2618), Moose::Meta::Instance=HASH(0x7f9e9b1c3588), MyDir=HASH(0x7f9e9b826bb8), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 525 Class::MOP::Class::_construct_instance(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 498 Class::MOP::Class::new_object(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Class.pm line 284 Moose::Meta::Class::new_object(Moose::Meta::Class=HASH(0x7f9e9b9e6990), HASH(0x7f9e9b826a98)) called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Object.pm line 28 Moose::Object::new("MyDir", "path", "/tmp") called at t.pl line 5 </code></pre> <p>So, doesn't accept the 'Str' and don't do the coercion.</p> <p>What is wrong in the above few lines? I'm pretty sure than it is really very small bug, <em>because i followed the MooseX::Types docs</em> (at least i hope) - but unable to find the error. </p> <p>I'm starting be really hopeless with Moose, please HELP...</p> <p>Ps: My goal is defining all my own "types" in one place (package) and use it everywhere where i need them with one single "use...".</p>
3
1,526
Can't set propertys of objects in an ObservableList
<p>In my main class I initialise a static object (lkw), which contains the public ObservableList (ladung). Now I want to manipulate the data in the list whith the methode ergebniss, which is located in the class Methoden. I call the methode ergebniss in my JavaFx Gui. It doesn't work. I don't get an error, but the X property is empty. Also removing an element (<code>Main.lkw.ladung.remove(j)</code>) doesn't work. What I do wrong?</p> <p><strong>EDIT</strong></p> <p><strong>Code</strong> Class Main</p> <pre><code>public class Main extends Application{ public static Lkw lkw=new Lkw(); public static void main(String[] args) { javafx.application.Application.launch(Gui.class); } @Override public void start(Stage primaryStage) throws Exception { // TODO Auto-generated method stub } </code></pre> <p>Class Lkw</p> <pre><code>public class Lkw { private String name=""; private int länge=0; private int breite=0; private int höhe=0; public ObservableList&lt;Ladung&gt; ladung=FXCollections.observableArrayList(); public Lkw(String name, int länge, int breite, int höhe){ this.name=name; this.länge=länge; this.breite=breite; this.höhe=höhe; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public int getLänge() { return länge; } public void setLänge(int länge) { this.länge = länge; } public int getBreite() { return breite; } public void setBreite(int breite) { this.breite = breite; } public int getHöhe() { return höhe; } public void setHöhe(int höhe) { this.höhe = höhe; } public ObservableList&lt;Ladung&gt; getLadung() { return ladung; } public void setLadung(ObservableList&lt;Ladung&gt; ladung) { this.ladung = ladung; } </code></pre> <p>Class Ladung</p> <pre><code>public class Ladung { private int nr; private int länge = 0; private int breite = 0; private int höhe = 0; private int x = 0; private int y = 0; private int z = 0; private int raum = 0; private Rectangle farbe = new Rectangle(100, 50); public Ladung(int nr, int länge, int breite, int höhe) { this.nr = nr; this.länge = länge; this.breite = breite; this.höhe = höhe; this.farbe.setFill(new Color(Math.random(), Math.random(), Math.random(), 1)); } public Ladung(int nr, int länge, int breite, int höhe, int raum, int x, int y, int z, Rectangle farbe) { this.nr = nr; this.länge = länge; this.breite = breite; this.höhe = höhe; this.raum = raum; this.x = x; this.y = y; this.z = z; this.farbe=farbe; } public int getLänge() { return länge; } public void setLänge(int länge) { this.länge = länge; } public int getBreite() { return breite; } public void setBreite(int breite) { this.breite = breite; } public int getHöhe() { return höhe; } public void setHöhe(int höhe) { this.höhe = höhe; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getZ() { return z; } public void setZ(int z) { this.z = z; } public int getNr() { return nr; } public void setNr(int nr) { this.nr = nr; } public int getRaum() { return raum; } public void setRaum(int raum) { this.raum = raum; } public Rectangle getFarbe() { return farbe; } public void setFarbe(Rectangle farbe) { this.farbe = farbe; } </code></pre> <p>This is the class with some static methods</p> <pre><code>public class Methoden { public static int einlesen(String pfad) { int ret=0; String zeile = ""; String[] daten = null; FileReader fr = null; try { fr = new FileReader(pfad); BufferedReader br = new BufferedReader(fr); zeile = br.readLine(); daten = zeile.split(" "); Main.lkw.setLänge(Integer.valueOf(daten[1])); Main.lkw.setBreite(Integer.valueOf(daten[2])); Main.lkw.setHöhe(Integer.valueOf(daten[3])); zeile = br.readLine(); int j=0; while (zeile != null) { daten = null; daten = zeile.split(" "); Main.lkw.ladung.get(j).setX(Integer.valueOf(daten[5])); Main.lkw.ladung.get(j).setY(Integer.valueOf(daten[6])); Main.lkw.ladung.get(j).setZ(Integer.valueOf(daten[7])); Main.lkw.ladung.get(j).setRaum(Integer.valueOf(daten[4])); zeile = br.readLine(); } br.close(); fr.close(); if(Main.lkw.getLadung().size()==0){ ret=-1; } for(int i=0;i&lt;Main.lkw.getLadung().size();i++){ System.out.println(Main.lkw.getLadung().get(i)); System.out.println(Main.lkw.getLadung().get(i).getRaum()); if(Main.lkw.getLadung().get(i).getRaum()!=1){ ret=-1; System.out.println("achtung!!!!"); } } } catch (IOException e) { System.err.println(e.getMessage() + " " + e.getClass()); } return ret; } </code></pre> <p>I call the methode ergebniss from a JavaFx Gui class.</p>
3
2,361
data_GAN Logistic Regression in R
<p>I've been reading about logistical regression in R. It makes sense when there are columns/variables that actually mean something. My columns are A, B, and C. Column C has only 1's and 0's. How am I to do a regression with such a limited dataset? Any guidance or resources to read would be appreciated.</p> <pre><code>&gt; library(Amelia) &gt; library(mlbench) &gt; library(dplyr) &gt; my_data&lt;-read.csv(&quot;/Users/morenikeirving/GAN/data_GAN.csv&quot;) &gt; names(my_data) [1] &quot;A&quot; &quot;B&quot; &quot;C&quot; &gt; head(my_data) A B C 1 4.4189 69.580 NA 2 13.2019 61.250 NA 3 25.6290 56.740 1 4 22.2943 68.860 1 5 0.2163 57.690 NA 6 0.2875 72.914 NA &gt; summary(my_data) A B C Min. : 0.000 Min. :33.00 Min. :1 1st Qu.: 1.226 1st Qu.:59.69 1st Qu.:1 Median : 5.897 Median :61.87 Median :1 Mean : 7.450 Mean :65.40 Mean :1 3rd Qu.:12.600 3rd Qu.:69.58 3rd Qu.:1 Max. :25.800 Max. :95.00 Max. :1 NA's :2923 &gt; missmap(my_data, col=c(&quot;blue&quot;, &quot;red&quot;), legend=FALSE) &gt; my_data&lt;-my_data %&gt;% mutate(C = ifelse(is.na(C),0,C)) &gt; missmap(my_data, col=c(&quot;blue&quot;, &quot;red&quot;), legend=FALSE) &gt; model &lt;-glm(x~., data=my_data, family= binomial) Error in eval(predvars, data, env) : object 'x' not found &gt; #Library to read in xls file &gt; library(Amelia) &gt; library(mlbench) &gt; library(dplyr) &gt; &gt; #Read in csv file &gt; my_data&lt;-read.csv(&quot;/Users/GAN/data_GAN.csv&quot;) &gt; &gt; #Exploring Data &gt; #see what's on the data frame &gt; names(my_data) [1] &quot;A&quot; &quot;B&quot; &quot;C&quot; &gt; &gt; #Look at first few rows of the data &gt; head(my_data) A B C 1 4.4189 69.580 NA 2 13.2019 61.250 NA 3 25.6290 56.740 1 4 22.2943 68.860 1 5 0.2163 57.690 NA 6 0.2875 72.914 NA &gt; &gt; #Overall picture of data; looking at first few rows revealed missing data &gt; summary(my_data) A B C Min. : 0.000 Min. :33.00 Min. :1 1st Qu.: 1.226 1st Qu.:59.69 1st Qu.:1 Median : 5.897 Median :61.87 Median :1 Mean : 7.450 Mean :65.40 Mean :1 3rd Qu.:12.600 3rd Qu.:69.58 3rd Qu.:1 Max. :25.800 Max. :95.00 Max. :1 NA's :2923 &gt; #lots of NAs &gt; &gt; #Examine missing data &gt; &gt; missmap(my_data, col=c(&quot;blue&quot;, &quot;red&quot;), legend=FALSE) &gt; &gt; #Replace N/A &gt; &gt; my_data&lt;-my_data %&gt;% mutate(C = ifelse(is.na(C),0,C)) &gt; &gt; #Check to make sure missing values are resolved &gt; missmap(my_data, col=c(&quot;blue&quot;, &quot;red&quot;), legend=FALSE) </code></pre>
3
1,483
Filter results, slow performance Swift
<p>Swift question... I'm making a babyname app and trying to filter the results as chosen by the user. I managed to get it working, but it takes a while for the results to get filtered. I mean like 2-3 seconds.</p> <p>Here is what I wrote :</p> <pre><code>func apply(list: [String]) -&gt; [String] { let allSavedSettings = settings.all var newList = list if let short = allSavedSettings[&quot;short&quot;] as? Bool { if !short { print(&quot;filter short&quot;) newList = newList.filter({$0.count &gt; 4}) } } if let long = allSavedSettings[&quot;long&quot;] as? Bool { if !long { print(&quot;filter long&quot;) newList = newList.filter({$0.count &lt; 5}) } } if let dutch = allSavedSettings[&quot;dutch&quot;] as? Bool { if !dutch { print(&quot;filter dutch&quot;) newList = newList.filter({!dutchboy.contains($0)}) newList = newList.filter({!dutchgirl.contains($0)}) } } if let english = allSavedSettings[&quot;english&quot;] as? Bool { if !english { print(&quot;filter english&quot;) newList = newList.filter({!englishboy.contains($0)}) newList = newList.filter({!englishgirl.contains($0)}) } } if let arabic = allSavedSettings[&quot;arabic&quot;] as? Bool { if !arabic { print(&quot;filter arabic&quot;) newList = newList.filter({!arabicboy.contains($0)}) newList = newList.filter({!arabicgirl.contains($0)}) } } if let hebrew = allSavedSettings[&quot;hebrew&quot;] as? Bool { if !hebrew { print(&quot;filter hebrew&quot;) newList = newList.filter({!hebrewboy.contains($0)}) newList = newList.filter({!hebrewgirl.contains($0)}) } } if let latin = allSavedSettings[&quot;latin&quot;] as? Bool { if !latin { print(&quot;filter latin&quot;) newList = newList.filter({!latinboy.contains($0)}) newList = newList.filter({!latingirl.contains($0)}) } } if let chinese = allSavedSettings[&quot;chinese&quot;] as? Bool { if !chinese { print(&quot;filter chinese&quot;) newList = newList.filter({!chineseboy.contains($0)}) newList = newList.filter({!chinesegirl.contains($0)}) } } if let scandinavian = allSavedSettings[&quot;scandinavian&quot;] as? Bool { if !scandinavian { print(&quot;filter scandinavian&quot;) newList = newList.filter({!scandinavianboy.contains($0)}) newList = newList.filter({!scandinaviangirl.contains($0)}) } } if let spanish = allSavedSettings[&quot;spanish&quot;] as? Bool { if !spanish { print(&quot;filter spanish&quot;) newList = newList.filter({!spanishboy.contains($0)}) newList = newList.filter({!spanishgirl.contains($0)}) } } return newList } </code></pre> <p>So I save the users preferences as a Boolean value in an array called &quot;allSavedSettings&quot; with userdefaults. Whenever a setting is false it will filter the result from the complete list of names.</p> <p>Is there something else I should use, to speed things up? The list is about 5000 names.</p> <p>Thanks in advance.</p> <p>Patrick</p>
3
2,037
spring google oauth2 return no access_token
<p>I'm trying to implement OAuth2 with Google in my Spring Boot application and when I retrieve the Principle object, what I get is given at the last.</p> <p>Here is the method,that I use to retrieve the user:</p> <pre><code>@GetMapping("/user") public Principal user(Principal user) { return user; } </code></pre> <p>In the response I can find no <em>access_token</em> or something, although I find <em>hash of it</em> and <em>id_token</em>.</p> <p>So how can I retrieve it ?</p> <pre><code>{ "authorities": [ { "authority": "ROLE_USER", "attributes": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "idToken": { "tokenValue": "123", "issuedAt": 1590532243, "expiresAt": 1590535843, "claims": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "subject": "108161422188958518395", "authorizedParty": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "accessTokenHash": "jVwoBv3AueI07-VJqKN0-A", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "audience": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "issuer": "https://accounts.google.com", "authenticatedAt": null, "authorizationCodeHash": null, "authenticationContextClass": null, "authenticationMethods": null, "address": { "formatted": null, "streetAddress": null, "locality": null, "region": null, "postalCode": null, "country": null }, "locale": "en", "zoneInfo": null, "fullName": "test testing", "familyName": "testing", "nickName": null, "updatedAt": null, "website": null, "middleName": null, "birthdate": null, "gender": null, "givenName": "test", "email": "test@gamil.com", "phoneNumber": null, "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "profile": null, "emailVerified": true, "phoneNumberVerified": null, "preferredUsername": null }, "userInfo": null }, { "authority": "SCOPE_https://www.googleapis.com/auth/userinfo.email" }, { "authority": "SCOPE_https://www.googleapis.com/auth/userinfo.profile" }, { "authority": "SCOPE_openid" } ], "details": { "remoteAddress": "0:0:0:0:0:0:0:1", "sessionId": "D3DCD92FB24A25CFC8B64160DD5C155B" }, "authenticated": true, "principal": { "authorities": [ { "authority": "ROLE_USER", "attributes": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "idToken": { "tokenValue": "123", "issuedAt": 1590532243, "expiresAt": 1590535843, "claims": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "subject": "108161422188958518395", "authorizedParty": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "accessTokenHash": "jVwoBv3AueI07-VJqKN0-A", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "audience": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "issuer": "https://accounts.google.com", "authenticatedAt": null, "authorizationCodeHash": null, "authenticationContextClass": null, "authenticationMethods": null, "address": { "formatted": null, "streetAddress": null, "locality": null, "region": null, "postalCode": null, "country": null }, "locale": "en", "zoneInfo": null, "fullName": "test testing", "familyName": "testing", "nickName": null, "updatedAt": null, "website": null, "middleName": null, "birthdate": null, "gender": null, "givenName": "test", "email": "test@gamil.com", "phoneNumber": null, "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "profile": null, "emailVerified": true, "phoneNumberVerified": null, "preferredUsername": null }, "userInfo": null }, { "authority": "SCOPE_https://www.googleapis.com/auth/userinfo.email" }, { "authority": "SCOPE_https://www.googleapis.com/auth/userinfo.profile" }, { "authority": "SCOPE_openid" } ], "attributes": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "idToken": { "tokenValue": "123", "issuedAt": 1590532243, "expiresAt": 1590535843, "claims": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "subject": "108161422188958518395", "authorizedParty": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "accessTokenHash": "jVwoBv3AueI07-VJqKN0-A", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "audience": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "issuer": "https://accounts.google.com", "authenticatedAt": null, "authorizationCodeHash": null, "authenticationContextClass": null, "authenticationMethods": null, "address": { "formatted": null, "streetAddress": null, "locality": null, "region": null, "postalCode": null, "country": null }, "locale": "en", "zoneInfo": null, "fullName": "test testing", "familyName": "testing", "nickName": null, "updatedAt": null, "website": null, "middleName": null, "birthdate": null, "gender": null, "givenName": "test", "email": "test@gamil.com", "phoneNumber": null, "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "profile": null, "emailVerified": true, "phoneNumberVerified": null, "preferredUsername": null }, "userInfo": null, "claims": { "at_hash": "jVwoBv3AueI07-VJqKN0-A", "sub": "108161422188958518395", "email_verified": true, "iss": "https://accounts.google.com", "given_name": "test", "locale": "en", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "aud": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "azp": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "name": "test testing", "exp": 1590535843, "family_name": "testing", "iat": 1590532243, "email": "test@gamil.com" }, "name": "108161422188958518395", "subject": "108161422188958518395", "expiresAt": 1590535843, "authorizedParty": "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com", "accessTokenHash": "jVwoBv3AueI07-VJqKN0-A", "nonce": "4ByS7UbIYimkIOJvHUznNQGZ42GxgYh9tCM1K4vKfYc", "audience": [ "693417856482-slejtj57gb2nrcehe82ih45o2vdhkj5t.apps.googleusercontent.com" ], "issuer": "https://accounts.google.com", "issuedAt": 1590532243, "authenticatedAt": null, "authorizationCodeHash": null, "authenticationContextClass": null, "authenticationMethods": null, "address": { "formatted": null, "streetAddress": null, "locality": null, "region": null, "postalCode": null, "country": null }, "locale": "en", "zoneInfo": null, "fullName": "test testing", "familyName": "testing", "nickName": null, "updatedAt": null, "website": null, "middleName": null, "birthdate": null, "gender": null, "givenName": "test", "email": "test@gamil.com", "phoneNumber": null, "picture": "https://lh3.googleusercontent.com/a-/AOh14Gh6AHe4iGXQ9XKVgfVV35w31UbSzKs84xUYuNNS=s96-c", "profile": null, "emailVerified": true, "phoneNumberVerified": null, "preferredUsername": null }, "authorizedClientRegistrationId": "google", "credentials": "", "name": "108161422188958518395" } </code></pre>
3
6,957
no-data section loads first and then shows the data in v-data-table
<p>I am using vuetify v-data-table to display data. The issue I am facing here is No Settings Yet message always shows for like 1 second and then displays the data. Its like no data message loads first and then the actual data shows up. Is there a way to fix this.</p> <pre><code>&lt;template&gt; &lt;div&gt; &lt;v-card&gt; &lt;v-data-table :headers=&quot;headers&quot; :items=&quot;settings&quot; hide-default-footer disable-pagination :mobile-breakpoint=&quot;0&quot;&gt; &lt;template slot=&quot;top&quot; v-if=&quot;isLoading&quot;&gt; &lt;v-progress-linear indeterminate color=&quot;red&quot; &gt;&lt;/v-progress-linear&gt; &lt;/template&gt; &lt;template slot=&quot;item&quot; slot-scope=&quot;props&quot;&gt; &lt;tr&gt; &lt;td&gt;{{ props.item.name }}&lt;/td&gt; &lt;td&gt;{{ props.item.value }}&lt;/td&gt; &lt;/tr&gt; &lt;/template&gt; &lt;template slot=&quot;no-data&quot; &gt; &lt;v-alert id='no-data' :value=&quot;true&quot; color=&quot;error&quot; icon=&quot;warning&quot;&gt; No Settings Yet &lt;/v-alert&gt; &lt;/template&gt; &lt;/v-data-table&gt; &lt;/v-card&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { data: function() { return { settings: [], headers: [ { text: 'Name', value: 'name'}, { text: 'Value', value: 'value'}, { text: 'Actions', sortable: false} ], isLoading: false } }, created() { this.fetchSettings(); }, methods: { fetchSettings() { var that = this; that.isLoading = true; this.$axios.get('/settings.json') .then(response =&gt; { that.settings = response.data; that.isLoading = false; }); } } } &lt;/script&gt; </code></pre>
3
1,241
How nagivate between pages with BottomNavyBar
<p>I'm trying to navigate between my pages but I can't work it out. I'm not figuring it out. I tried to create a controller and put into &quot;BarItem&quot; but appers a mesage &quot;only static members can be accessed in initializers&quot; I'm trying to replace the part:</p> <pre><code>body: AnimatedContainer( color: widget.barItems[selectedBarIndex].color, duration: const Duration(milliseconds: 300),), </code></pre> <p>For a method to change my pages as I click on menu. Help me guys!</p> <pre><code>import 'package:flutter/material.dart'; class AnimatedBottomBar extends StatefulWidget { final List&lt;BarItem&gt; barItems; final Duration animationDuration; final Function onBarTap; AnimatedBottomBar({this.barItems, this.animationDuration = const Duration(milliseconds: 500), this.onBarTap}); @override _AnimatedBottomBarState createState() =&gt; _AnimatedBottomBarState(); } class _AnimatedBottomBarState extends State&lt;AnimatedBottomBar&gt; with TickerProviderStateMixin{ int selectedBarIndex = 0; @override Widget build(BuildContext context) { return Material( elevation: 10.0, child: Padding( padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: _buildBarItems(), ), ), ); } List&lt;Widget&gt; _buildBarItems() { List&lt;Widget&gt; _barItems = List(); for (int i = 0; i &lt; widget.barItems.length; i++){ BarItem item = widget.barItems[i]; bool isSelected = selectedBarIndex == i; _barItems.add(InkWell( splashColor: Colors.transparent, onTap: (){ setState(() { selectedBarIndex = i; widget.onBarTap(selectedBarIndex); }); }, child: AnimatedContainer( padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), duration: widget.animationDuration, decoration: BoxDecoration( color: isSelected ? item.color.withOpacity(0.2) : Colors.transparent, borderRadius: BorderRadius.all(Radius.circular(30)) ), child: Row( children: &lt;Widget&gt;[ Icon(item.iconData, color: isSelected ? item.color : Colors.black,), SizedBox(width: 10.0,), AnimatedSize( duration: widget.animationDuration, curve: Curves.easeInOut, vsync: this, child: Text( isSelected ? item.text : &quot;&quot;, style: TextStyle(color: item.color, fontWeight: FontWeight.w600, fontSize: 18.0),), ) ], ), ), )); } return _barItems; } } class BarItem { String text; IconData iconData; Color color; PageController controller;//deletar int page;//deletar BarItem({this.text, this.iconData, this.color, this.controller, this.page}); } </code></pre> <pre><code>import 'animated_bottom_bar.dart'; class BottomBarNavigationPattern extends StatefulWidget { final List&lt;BarItem&gt; barItems = [ BarItem( text: &quot;Home&quot;, iconData: Icons.home, color: Colors.indigo,), BarItem( text: &quot;Likes&quot;, iconData: Icons.favorite_border, color: Colors.pinkAccent), BarItem( text: &quot;Search&quot;, iconData: Icons.search, color: Colors.yellow.shade900), BarItem( text: &quot;Profile&quot;, iconData: Icons.person_outline, color: Colors.teal), ]; @override _BottomBarNavigationPatternState createState() =&gt; _BottomBarNavigationPatternState(); } class _BottomBarNavigationPatternState extends State&lt;BottomBarNavigationPattern&gt; { int selectedBarIndex = 0; @override Widget build(BuildContext context) { return Scaffold( body: AnimatedContainer( color: widget.barItems[selectedBarIndex].color, duration: const Duration(milliseconds: 300),), bottomNavigationBar: AnimatedBottomBar( barItems: widget.barItems, animationDuration: const Duration(milliseconds: 200), onBarTap: (index){ setState(() { selectedBarIndex = index; }); } ), ); } } </code></pre>
3
1,901
No rule to make target `libpython2.6.a'
<p>I am trying to compile Python2.6 from its source codes, and took steps as follow, and encountered an error message:</p> <pre><code>./configure ... [root@KuGouIdc Python-2.6.6]# ls config.log Demo Makefile.pre Objects Python config.status Doc Makefile.pre.in Parser README configure Grammar Makefile.pre.in.cflags PC RISCOS configure.in Include Makefile.pre.in.fix-parallel-make PCbuild setup.py configure.in.check-for-XML_SetHashSalt install-sh Makefile.pre.in.lib64 pyconfig.h setup.py.add-RPATH-to-pyexpat configure.in.disable-pymalloc-on-valgrind Lib Makefile.pre.in.no-static-lib pyconfig.h.in setup.py.expat configure.in.expat LICENSE Makefile.pre.in.systemtap pyconfig.h.in.disable-pymalloc-on-valgrind setup.py.lib64 configure.in.rpath Mac Misc pyconfig.h.in.systemtap systemtap-example.stp configure.in.systemtap Makefile Modules pyfuntop.stp Tools [root@KuGouIdc Python-2.6.6]# make -n all gcc -pthread -c -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -o Modules/python.o ./Modules/python.c make: *** No rule to make target `libpython2.6.a', needed by `python'. Stop. </code></pre> <p>I reviewed the Makefile detail, and really could not find any rule to make the target 'libpythonXXX.a'. I googled around, and it seemed that no one had encountered the same issue as me?</p> <p>In the Makefile, it really has a rule for making the target 'libpythonXXX.so'.</p>
3
1,187
My application get crashed
<p>My splash activity code is:</p> <pre><code>package com.example.hp_pc.earnmebucks; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; public class SplashActivity extends AppCompatActivity { Thread splashTread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Thread timerThread = new Thread() { public void run() { try { sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } finally { Intent intent = new Intent(SplashActivity.this, Login.class); startActivity(intent); } } }; timerThread.start(); } } </code></pre> <p>My Login.java code is :</p> <pre><code>package com.example.hp_pc.earnmebucks; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.OptionalPendingResult; import com.google.android.gms.common.api.ResultCallback; public class Login extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = MainActivity.class.getSimpleName(); private static final int RC_SIGN_IN = 007; private GoogleApiClient mGoogleApiClient; private ProgressDialog mProgressDialog; private SignInButton btnSignIn; private Button btnSignOut, btnRevokeAccess; private LinearLayout llProfileLayout; private ImageView imgProfilePic; private TextView txtName, txtEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); super.getIntent(); btnSignIn = (SignInButton) findViewById(R.id.sign_in_button); btnSignIn.setOnClickListener(this); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // Customizing G+ button btnSignIn.setSize(SignInButton.SIZE_STANDARD); btnSignIn.setScopes(gso.getScopeArray()); } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } private void handleSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { // Signed in successfully, show authenticated UI. GoogleSignInAccount acct = result.getSignInAccount(); Log.e(TAG, "display name: " + acct.getDisplayName()); updateUI(true); } else { // Signed out, show unauthenticated UI. updateUI(false); } } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.sign_in_button: signIn(); break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result); } } @Override public void onStart() { super.onStart(); OptionalPendingResult&lt;GoogleSignInResult&gt; opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); if (opr.isDone()) { // If the user's cached credentials are valid, the OptionalPendingResult will be "done" // and the GoogleSignInResult will be available instantly. Log.d(TAG, "Got cached sign-in"); GoogleSignInResult result = opr.get(); handleSignInResult(result); } else { // If the user has not previously signed in on this device or the sign-in has expired, // this asynchronous branch will attempt to sign in the user silently. Cross-device // single sign-on will occur in this branch. showProgressDialog(); opr.setResultCallback(new ResultCallback&lt;GoogleSignInResult&gt;() { @Override public void onResult(GoogleSignInResult googleSignInResult) { hideProgressDialog(); handleSignInResult(googleSignInResult); } }); } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); } private void showProgressDialog() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("loading"); mProgressDialog.setIndeterminate(true); } mProgressDialog.show(); } private void hideProgressDialog() { if (mProgressDialog != null &amp;&amp; mProgressDialog.isShowing()) { mProgressDialog.hide(); } } private void updateUI(boolean isSignedIn) { if (isSignedIn) { btnSignIn.setVisibility(View.GONE); Intent i = new Intent(Login.this,Signin.class); startActivity(i); } else { btnSignIn.setVisibility(View.VISIBLE); btnSignOut.setVisibility(View.GONE); btnRevokeAccess.setVisibility(View.GONE); llProfileLayout.setVisibility(View.GONE); } } } </code></pre> <p>And its xml code is :</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:weightSum="4"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" android:gravity="center_horizontal" android:orientation="vertical"&gt; &lt;/LinearLayout&gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="2"&gt; &lt;com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:visibility="visible" tools:visibility="gone" /&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>My LogCat is :</p> <pre><code> at com.google.android.gms.auth.api.Auth$4.zza(Unknown Source) at com.google.android.gms.common.api.GoogleApiClient$Builder.zza(Unknown Source) at com.google.android.gms.common.api.GoogleApiClient$Builder.zzuQ(Unknown Source) at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source) at com.example.hp_pc.earnmebucks.Login.onCreate(Login.java:67) at android.app.Activity.performCreate(Activity.java:6001) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5233) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) </code></pre> <p>Please help. My app crashes after splash activity. I will be highly grateful if anybody can help me. I dont able to know where is the null pointer exception. Thanks in advance.</p>
3
4,364
Unable to load file to Hadoop using flume
<p>Im using flume to move files to hdfs ... while moving file its showing this error.. please help me to solve this issue.</p> <pre><code>15/05/20 15:49:26 INFO instrumentation.MonitoredCounterGroup: Component type: SOURCE, name: r1 started 15/05/20 15:49:26 INFO avro.ReliableSpoolingFileEventReader: Preparing to move file /home/crayondata.com/shanmugapriya/apache-flume-1.5.2-bin/staging/HypeVisitorTest.java to /home/crayondata.com/shanmugapriya/apache-flume-1.5.2-bin/staging/HypeVisitorTest.java.COMPLETED 15/05/20 15:49:26 INFO source.SpoolDirectorySource: Spooling Directory Source runner has shutdown. 15/05/20 15:49:26 INFO hdfs.HDFSDataStream: Serializer = TEXT, UseRawLocalFileSystem = false 15/05/20 15:49:26 INFO hdfs.BucketWriter: Creating hdfs://localhost:9000/sha/HypeVisitorTest.java.1432117166377.tmp 15/05/20 15:49:26 ERROR hdfs.HDFSEventSink: process failed java.lang.UnsupportedOperationException: Not implemented by the DistributedFileSystem FileSystem implementation at org.apache.hadoop.fs.FileSystem.getScheme(FileSystem.java:216) at org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2564) at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2574) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2630) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2612) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370) at org.apache.hadoop.fs.Path.getFileSystem(Path.java:296) at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:270) at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:262) at org.apache.flume.sink.hdfs.BucketWriter$9$1.run(BucketWriter.java:718) at org.apache.flume.sink.hdfs.BucketWriter.runPrivileged(BucketWriter.java:183) at org.apache.flume.sink.hdfs.BucketWriter.access$1700(BucketWriter.java:59) at org.apache.flume.sink.hdfs.BucketWriter$9.call(BucketWriter.java:715) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 15/05/20 15:49:26 ERROR flume.SinkRunner: Unable to deliver event. Exception follows. org.apache.flume.EventDeliveryException: java.lang.UnsupportedOperationException: Not implemented by the DistributedFileSystem FileSystem implementation at org.apache.flume.sink.hdfs.HDFSEventSink.process(HDFSEventSink.java:471) at org.apache.flume.sink.DefaultSinkProcessor.process(DefaultSinkProcessor.java:68) at org.apache.flume.SinkRunner$PollingRunner.run(SinkRunner.java:147) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.UnsupportedOperationException: Not implemented by the DistributedFileSystem FileSystem implementation at org.apache.hadoop.fs.FileSystem.getScheme(FileSystem.java:216) at org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2564) at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2574) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2630) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2612) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370) at org.apache.hadoop.fs.Path.getFileSystem(Path.java:296) at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:270) at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:262) at org.apache.flume.sink.hdfs.BucketWriter$9$1.run(BucketWriter.java:718) at org.apache.flume.sink.hdfs.BucketWriter.runPrivileged(BucketWriter.java:183) at org.apache.flume.sink.hdfs.BucketWriter.access$1700(BucketWriter.java:59) at org.apache.flume.sink.hdfs.BucketWriter$9.call(BucketWriter.java:715) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ... 1 more 15/05/20 15:49:26 INFO source.SpoolDirectorySource: Spooling Directory Source runner has shutdown. </code></pre> <p>Here is my flumeconf.conf file</p> <pre><code># example.conf: A single-node Flume configuration # Name the components on this agent a1.sources = r1 a1.sinks = k1 a1.channels = c1 # Describe/configure the source a1.sources.r1.type = spooldir a1.sources.r1.spoolDir = /home/shanmugapriya/apache-flume-1.5.2-bin/staging a1.sources.r1.fileHeader = true a1.sources.r1.maxBackoff = 10000 a1.sources.r1.basenameHeader = true # Describe the sink a1.sinks.k1.type = hdfs a1.sinks.k1.hdfs.path = hdfs://localhost:9000/sha a1.sinks.k1.hdfs.writeFormat = Text a1.sinks.k1.hdfs.fileType = DataStream a1.sinks.k1.hdfs.rollInterval = 0 a1.sinks.k1.hdfs.rollSize = 0 a1.sinks.k1.hdfs.rollCount = 0 a1.sinks.k1.hdfs.idleTimeout = 100 a1.sinks.k1.hdfs.filePrefix = %{basename} # Use a channel which buffers events in memory a1.channels.c1.type = memory a1.channels.c1.capacity = 100000 a1.channels.c1.transactionCapacity = 1000 a1.channels.c1.byteCapacity = 0 # Bind the source and sink to the channel a1.sources.r1.channels = c1 a1.sinks.k1.channel = c1 </code></pre> <p>please help to solve this.. TIA...</p>
3
2,244
small space keeps showing to right side of my website w
<p>I've been having this issue with this webpage I've been working on. Whenever I view the page in google chrome on my mac, I get a sliver of space to the right of page when I scroll to the right. I'm not really sure how to fix the problem. Here's an image to show what I'm talking about, along with my html and css. Thanks in advance to anyone that can help me.</p> <p>Image: <a href="http://imgur.com/0JAZsgg&amp;KcUfJZl&amp;ephxQZC#2" rel="nofollow">http://imgur.com/0JAZsgg&amp;KcUfJZl&amp;ephxQZC#2</a></p> <p>Here's my html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="../scripts/javascript/responsive_drop_down.js"&gt;&lt;/script&gt; &lt;link href="../css/main_stylesheet.css" rel="stylesheet" type="text/css" media="screen"/&gt; &lt;link href="../css/print_stylesheet.css" rel="stylesheet" type="text/css" media="print"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;header&gt; &lt;h1&gt;This is a placeholder &lt;br /&gt; for header&lt;/h1&gt; &lt;/header&gt; &lt;nav class="nm"&gt; &lt;div class="mobilmenu"&gt;&lt;/div&gt; &lt;div class="mobile-container"&gt; &lt;ul&gt; &lt;li class="white"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="red"&gt;&lt;a href="#"&gt;Video&lt;/a&gt;&lt;/li&gt; &lt;li class="purple"&gt;&lt;a href="#"&gt;Pictures&lt;/a&gt;&lt;/li&gt; &lt;li class="blue"&gt;&lt;a href="#"&gt;Audio&lt;/a&gt;&lt;/li&gt; &lt;li class="green"&gt;&lt;a href="#"&gt;Other Work&lt;/a&gt;&lt;/li&gt; &lt;li class="yellow"&gt;&lt;a href="#"&gt;About Me&lt;/a&gt;&lt;/li&gt; &lt;li class="gray"&gt;&lt;a href="#"&gt;Contact Me&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class="content-container"&gt; &lt;article class="content-main"&gt; &lt;section&gt; &lt;h1&gt;Heading goes here...&lt;/h1&gt; &lt;time datetime="#"&gt;Time will go here.&lt;/time&gt; &lt;p&gt;Content will go here...&lt;/p&gt; &lt;/section&gt; &lt;/article&gt; &lt;aside class="sidebar"&gt; &lt;p&gt;More Content to come soon.&lt;/p&gt; &lt;/aside&gt; &lt;/div&gt; &lt;div class="footer-position"&gt; &lt;footer&gt; &lt;span class="copyright"&gt;All rights reserved 2014.&lt;/span&gt; &lt;nav class="nf"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Video&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Pictures&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Audio&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Other Work&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;About Me&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact Me&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's the css:</p> <pre><code>@import url(http://fonts.googleapis.com/css?family=Ubuntu:300,400,300italic,400italic); @font-face { font-family: 'bebas_neueregular'; src: url('../font/BebasNeue/bebasneue-webfont.eot'); src: url('../font/BebasNeue/bebasneue-webfont.eot?#iefix') format('embedded-opentype'), url('../font/BebasNeue/bebasneue-webfont.woff') format('woff'), url('../font/BebasNeue/bebasneue-webfont.ttf') format('truetype'), url('../font/BebasNeue/bebasneue-webfont.svg#bebas_neueregular') format('svg'), url('../font/BebasNeue/BebasNeu.otf') format('opentype'); font-weight: normal; font-style: normal; } body { width:100%; font-family: 'Ubuntu', sans-serif; margin:0; padding:0; background-color:#84888B; overflow-y:scroll; direction:ltr; display:block; } #wrapper { display:block; width:100%; margin:0 auto; padding:0 auto; } header { font-family:'bebas_neueregular', sans-serif; background-color:#5D0660; color:#E21208; text-align:center; padding:15px; } nav { display:block; font-family:'bebas_neueregular', sans-serif; text-align:center; overflow:hidden; } nav ul { list-style:none; } nav ul li { display:inline-block; } nav ul li a { text-decoration:none; } nav.nm { width:100%; background-color:#000000; font-size:125%; margin:0; padding:0; } nav.nm ul { margin:0 auto; margin-top:0; } nav.nm ul li a { display:block; color:#ffffff; padding:15px 16px; } nav.nm ul li a:hover { color:#000000; -webkit-transition:450ms ease; -moz-transition:450ms ease; transition:450ms ease; } nav.nm ul li.white a:hover { background-color:#ffffff; } nav.nm ul li.red a:hover { background-color:#E21208; } nav.nm ul li.purple a:hover { background-color:#9E00A3; } nav.nm ul li.blue a:hover { background-color:#1A297F; } nav.nm ul li.green a:hover { background-color:#319032; } nav.nm ul li.yellow a:hover { background-color:#E1E13D; } nav.nm ul li.gray a:hover { background-color:#84888B; } nav.nf { font-size:85%; } nav.nf ul li:last-child { border-right:none; } nav.nf ul li { border-right:1px solid #000000; } nav.nf ul li a { display:block; padding:2px 9px; color:#000000; } nav.nf ul li a:hover { color:#ffffff; } footer { width:100%; background-color:#1A297F; text-align:center; margin-top:38.6%; padding:0.2%; } </code></pre>
3
3,287
Button to submit form data to another URL containing #
<p>This is my HTML:</p> <pre><code>&lt;form action=&quot;http://example.com/rezervari/index.html#/hotelbooking&quot; method=&quot;get&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;hotel&quot; value=&quot;&lt;?= $hotel ?&gt;&quot; class=&quot;form-control&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;roomtypegroups&quot; value=&quot;&lt;?= $roomtypegroups ?&gt;&quot; class=&quot;form-control&quot;&gt; &lt;div class=&quot;form-row&quot;&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label&gt;Sosire&lt;/label&gt; &lt;div class=&quot;input-group mb-3&quot;&gt; &lt;input id=&quot;from&quot; type=&quot;text&quot; name=&quot;from&quot; value=&quot;&lt;?= $arrival == 'CURRENT' ? date('Y-m-d') : $arrival ?&gt;&quot; class=&quot;form-control datepicker1&quot;&gt; &lt;div class=&quot;input-group-append datepicker1-h&quot;&gt; &lt;span class=&quot;input-group-text&quot; id=&quot;basic-addon2&quot;&gt;&lt;i class=&quot;fa fa-calendar-check-o&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label&gt;Plecare&lt;/label&gt; &lt;div class=&quot;input-group mb-3&quot;&gt; &lt;input id=&quot;to&quot; type=&quot;text&quot; name=&quot;to&quot; value=&quot;&lt;?= $arrival == 'CURRENT' ? date('Y-m-d', strtotime(date('Y-m-d') . ' ' . $departure . ' day')) : date('Y-m-d', strtotime($arrival . ' ' . $departure . ' day')) ?&gt;&quot; class=&quot;form-control datepicker2&quot;&gt; &lt;div class=&quot;input-group-append datepicker2-h&quot;&gt; &lt;span class=&quot;input-group-text&quot; id=&quot;basic-addon2&quot;&gt;&lt;i class=&quot;fa fa-calendar-times-o&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>When I submit the form, the URL loses the &quot;#&quot; and messes it up, and that's no good because the query doesn't work on the secondary website, as it becomes:</p> <p><a href="http://example.com/rezervari/index.html?hotel=14315&amp;roomtypegroups=44332&amp;from=2020-11-23&amp;to=2020-11-24&amp;roomscount=1&amp;adult=1#/hotelbooking" rel="nofollow noreferrer">http://example.com/rezervari/index.html?hotel=14315&amp;roomtypegroups=44332&amp;from=2020-11-23&amp;to=2020-11-24&amp;roomscount=1&amp;adult=1#/hotelbooking</a></p> <p>Instead, it should be:</p> <p><a href="http://example.com/rezervari/index.html#/hotelbooking?hotel=14315&amp;roomtypegroups=44332&amp;from=2020-09-91&amp;to=2020-09-14&amp;adult=1&amp;numchild1=1&amp;numchild2=1&amp;numchild3=1" rel="nofollow noreferrer">http://example.com/rezervari/index.html#/hotelbooking?hotel=14315&amp;roomtypegroups=44332&amp;from=2020-09-91&amp;to=2020-09-14&amp;adult=1&amp;numchild1=1&amp;numchild2=1&amp;numchild3=1</a></p> <p>How can I pass on the link without the &quot;#&quot; getting removed and the whole URL messed up? Thanks!</p>
3
1,714
Express router: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string
<p>I know I am struggling in this problem. I am working on a webpack Universal React App but i got this error message and I have no idea where it come from:</p> <pre><code>TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type function ([Function (anonymous)]) at new NodeError (node:internal/errors:372:5) at Function.from (node:buffer:323:9) at ServerResponse.send (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\response.js:193:22) at eval (webpack://isomorphic-react-redux-router-app/./app/serverside/server.js?:17:19) at Layer.handle [as handle_request] (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\layer.js:95:5) at next (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\layer.js:95:5) at C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Dev\isomorphic-react-redux-router-app\node_modules\express\lib\router\index.js:346:12) </code></pre> <p>I think it is because of the url on the eval argument:</p> <pre><code>webpack://isomorphic-react-redux-router-app/./app/serverside/server.js?:17:19 </code></pre> <p>Having a relative path in the middle of the url is not good. Here are my webpack file:</p> <pre><code>const path = require('path'); require(&quot;core-js/stable&quot;); require(&quot;regenerator-runtime/runtime&quot;); const nodeExternals = require('webpack-node-externals'); module.exports = [ { mode: 'development', stats: {warnings:false}, target:'web', entry: { '/bundle-app': ['core-js','regenerator-runtime/runtime','./app/clientside/client.jsx'] }, output: { path: path.resolve(__dirname, 'build/dev'), filename: '[name].js', publicPath: '/' }, module: { rules: [ { test: /\.jpe?g|png$/, exclude: /node_modules/, use: [&quot;url-loader&quot;, &quot;file-loader&quot;] }, { test: /\.(jsx|js)$/, include: path.resolve(__dirname, '/'), exclude: /node_modules/, use: [{ loader: 'babel-loader', }] } ] }, }, { name: 'server', mode: 'development', target: 'node', stats: {warnings:false}, externals: [nodeExternals()], entry: { '/server/bundle-server': ['core-js','regenerator-runtime/runtime','./app/serverside/server.js'], }, output: { path: path.resolve(__dirname, 'build/dev'), filename: '[name].js', }, plugins: [], module: { rules: [ { test: /\.(jsx|js)$/, include: path.resolve(__dirname, '/'), exclude: /node_modules/, use: [{ loader: 'babel-loader', }] }, ] } } ] </code></pre> <p>my express server file:</p> <pre><code>import express from 'express'; import serverRenderer from './renderSSR.js'; import cors from 'cors'; let app = express(); app.use(cors()); app.use(express.urlencoded({extended:false})); app.use(express.json()); app.get('/', (req, res) =&gt; { res.status(200).send(serverRenderer()); }); // when the user connect to the root of the server we send the page app.listen(8080, () =&gt; console.log(&quot;Example app listening on port 8080!&quot;)); </code></pre> <pre><code>import { renderToString } from 'react-dom/server'; import fs from 'fs'; import App from '../src/App.jsx'; export default function serverRenderer() { return (req, res, next) =&gt; { const html = renderToString( // on rend côté serveur du pur HTML &lt;StaticRouter location={req.url}&gt; &lt;App/&gt; &lt;/StaticRouter&gt; ); // we read the index.html page and we change the div to insert the app content fs.readFile('../html/index.html', 'utf8', function (err,data) { if (err) { return console.log(err); } // after succefuly read the html file, we insert the App component content var htmlApp = data.replace('&lt;div id=&quot;app&quot;&gt;','&lt;div id=&quot;app&quot;&gt;' + html); return htmlApp; }); }; } </code></pre> <p>my client file:</p> <pre><code>// principal programme côté client, est capable de faire du rendue HTML, sera appelé une deuxième par le client. import * as React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter as Router} from 'react-router-dom'; import App from '../src/App.jsx'; ReactDOM.render( &lt;Router&gt; &lt;App/&gt; &lt;/Router&gt;, document.getElementById('root') ); // on rend le react dans l'element HTML root </code></pre> <p>and finally my commun App file:</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; export default function App(props) { return ( &lt;p&gt;Hello App!&lt;/p&gt; ) }; </code></pre> <p>Where does the problem come from? How to fix it? Thanks in advance for your responses.</p>
3
2,340
search string in pandas column
<p>I am trying to find a substring in below hard_skills_name column, like i want all rows which has 'Apple Products' as hard skill.</p> <p><a href="https://i.stack.imgur.com/NAeMb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NAeMb.png" alt="enter image description here" /></a></p> <p>I tried below code:</p> <pre><code>df.loc[df['hard_skills_name'].str.contains(&quot;Apple Products&quot;, case=False)] </code></pre> <p>but getting this error:</p> <pre><code>KeyError Traceback (most recent call last) &lt;ipython-input-49-acdcdfbdfd3d&gt; in &lt;module&gt; ----&gt; 1 df.loc[df['hard_skills_name'].str.contains(&quot;Apple Products&quot;, case=False)] ~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexing.py in __getitem__(self, key) 877 878 maybe_callable = com.apply_if_callable(key, self.obj) --&gt; 879 return self._getitem_axis(maybe_callable, axis=axis) 880 881 def _is_scalar_access(self, key: Tuple): ~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexing.py in _getitem_axis(self, key, axis) 1097 raise ValueError(&quot;Cannot index with multidimensional key&quot;) 1098 -&gt; 1099 return self._getitem_iterable(key, axis=axis) 1100 1101 # nested tuple slicing ~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexing.py in _getitem_iterable(self, key, axis) 1035 1036 # A collection of keys -&gt; 1037 keyarr, indexer = self._get_listlike_indexer(key, axis, raise_missing=False) 1038 return self.obj._reindex_with_indexers( 1039 {axis: [keyarr, indexer]}, copy=True, allow_dups=True ~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexing.py in _get_listlike_indexer(self, key, axis, raise_missing) 1252 keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr) 1253 -&gt; 1254 self._validate_read_indexer(keyarr, indexer, axis, raise_missing=raise_missing) 1255 return keyarr, indexer 1256 ~/anaconda3/envs/python3/lib/python3.6/site-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing) 1296 if missing == len(indexer): 1297 axis_name = self.obj._get_axis_name(axis) -&gt; 1298 raise KeyError(f&quot;None of [{key}] are in the [{axis_name}]&quot;) 1299 1300 # We (temporarily) allow for some missing keys with .loc, except in KeyError: &quot;None of [Float64Index([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n nan, nan, nan, nan, nan, nan, nan, nan, nan],\n dtype='float64')] are in the [index]&quot; </code></pre>
3
1,543
Update List after deleting an element
<p>I have a project generated with JHipster 5.5.0 and I have 2 entities: parent &amp; child.</p> <p>I list the children when I see the details of the parent. When I want to delete a child, I use the child's modal and it works as it should be.</p> <p>My issue is after deleting the entity the list is not being updated and I don't know where to look. I tried using static methods so I can reload the list but I'm unable to do so. Any help will be appreciated.</p> <p>Child's Angular code:</p> <pre><code>import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager } from 'ng-jhipster'; import { IChild } from 'app/shared/model/child.model'; import { ChildService } from './Child.service'; @Component({ selector: 'jhi-child-delete-dialog', templateUrl: './child-delete-dialog.component.html' }) export class ChildDeleteDialogComponent { child: IChild; constructor( private childService: ChildService, public activeModal: NgbActiveModal, private eventManager: JhiEventManager ) {} clear() { this.activeModal.dismiss('cancel'); } confirmDelete(id: number) { this.childService.delete(id).subscribe(response =&gt; { this.eventManager.broadcast({ name: 'childtModification', content: 'Deleted a child' }); this.activeModal.dismiss(true); }); } } @Component({ selector: 'jhi-child-delete-popup', template: '' }) export class ChildDeletePopupComponent implements OnInit, OnDestroy { private ngbModalRef: NgbModalRef; constructor(private activatedRoute: ActivatedRoute, private router: Router, private modalService: NgbModal) {} ngOnInit() { this.activatedRoute.data.subscribe(({ child }) =&gt; { setTimeout(() =&gt; { this.ngbModalRef = this.modalService.open(ChildDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); this.ngbModalRef.componentInstance.child = child; this.ngbModalRef.result.then( result =&gt; { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, reason =&gt; { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; } ); }, 0); }); } ngOnDestroy() { this.ngbModalRef = null; } } </code></pre> <p>In the parent entity, I have a button like this:</p> <pre><code>&lt;button type="submit" [routerLink]="['/', { outlets: { popup: 'child/'+ child.id + '/delete'} }]" replaceUrl="true" queryParamsHandling="merge" class="btn btn-danger btn-sm"&gt; &lt;fa-icon [icon]="'times'"&gt;&lt;/fa-icon&gt; &lt;span class="d-none d-md-inline" jhiTranslate="entity.action.delete"&gt;Delete&lt;/span&gt; &lt;/button&gt; </code></pre> <p>The modal neither the component that deletes the child have not been modified.</p>
3
1,469
Making a table horizontally scrollable without changing the existing CSS properties
<p>Please help me make this table horizontally scrollable without changing the existing CSS properties. The existing CSS is changing rows to column and I want to keep it that way only.</p> <pre><code>&lt;style&gt; tr{ display:block; float:left; } td,th{ display: block; border: 1px solid #ddd; clear:both } &lt;/style&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;h2&gt;Bordered Table&lt;/h2&gt; &lt;p&gt;The .table-bordered class adds borders to a table:&lt;/p&gt; &lt;table class="table table-bordered"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Firstname&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;John&lt;/td&gt; &lt;td&gt;Doe&lt;/td&gt; &lt;td&gt;john@example.com&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Mary&lt;/td&gt; &lt;td&gt;Moe&lt;/td&gt; &lt;td&gt;mary@example.com&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;July&lt;/td&gt; &lt;td&gt;Dooley&lt;/td&gt; &lt;td&gt;july@example.com&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; </code></pre>
3
1,813
Unable To Call Task Within A Thread
<p>I am trying to display multiple pin locations on the map i.e. my location and another location I get from the cloud server.</p> <p>Based on the code below:</p> <p>I keep getting a NullPointer Error message when I try to tokenize my string. This implies that my CloudTask activity is never fired.... I can't figure out why and the Eclipse Debugger won't step through the threads...any help is appreciated.</p> <pre><code> public class MapsActivity extends com.google.android.maps.MapActivity { private static final String TAG = null; private MapController mapController; private MapView mapView; private LocationManager locationManager; private MyOverlays itemizedoverlay; private MyLocationOverlay myLocationOverlay; private MyLocationOverlay otherLocationOverlay; private Handler handler; private String message; StringTokenizer tokens; Integer p1 = null; Integer p2; GeoPoint point; static Context mContext = null; public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.main); // bind the layout to the activity // Configure the Map mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.setSatellite(true); mapController = mapView.getController(); mapController.setZoom(14); // Zoon 1 is world view locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500, 0,(LocationListener) new GeoUpdateHandler()); //new Intent("android.intent.action.LOCATION_CHANGED"); //(LocationListener) new GeoUpdateHandler()); myLocationOverlay = new MyLocationOverlay(this, mapView); mapView.getOverlays().add(myLocationOverlay); handler = new Handler(); // new AsyncTask&lt;Void, Void, String&gt;() { myLocationOverlay.runOnFirstFix(new Runnable(){ public void run(){ MyRequestFactory requestFactory = Util.getRequestFactory(mContext, MyRequestFactory.class); final CloudTask1Request request = requestFactory.cloudTask1Request(); Log.i(TAG, "Sending request to server"); request.queryTasks().fire(new Receiver&lt;List&lt;TaskProxy&gt;&gt;() { @Override public void onSuccess(List&lt;TaskProxy&gt; taskList) { //message = result; message = "\n"; for (TaskProxy task : taskList) { message += task.getId()+","+task.getNote()+","; } } }); //return message; //} if(message.length() == 0){ Log.i("MESSAGE","Did not get any points from cloud"); } tokens = new StringTokenizer(message,","); tokens.nextToken(); p1 = Integer.parseInt(tokens.nextToken()); p2 = Integer.parseInt(tokens.nextToken()); point = new GeoPoint(p1,p2); mapView.getController().animateTo(point); } }); Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin); itemizedoverlay = new MyOverlays(this, drawable); createMarker(); myLocationOverlay.runOnFirstFix(new Runnable() { public void run() { mapView.getController().animateTo( myLocationOverlay.getMyLocation()); } }); //Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin); itemizedoverlay = new MyOverlays(this, drawable); createMarker(); } @Override protected boolean isRouteDisplayed() { return false; } public class GeoUpdateHandler implements LocationListener { @Override public void onLocationChanged(Location location) { int lat = (int) (location.getLatitude() * 1E6); int lng = (int) (location.getLongitude() * 1E6); GeoPoint point = new GeoPoint(lat, lng); createMarker(); mapController.animateTo(point); // mapController.setCenter(point); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } } private void createMarker() { GeoPoint p = mapView.getMapCenter(); OverlayItem overlayitem = new OverlayItem(p, "", ""); itemizedoverlay.addOverlay(overlayitem); if (itemizedoverlay.size() &gt; 0) { mapView.getOverlays().add(itemizedoverlay); } } @Override protected void onResume() { super.onResume(); myLocationOverlay.enableMyLocation(); myLocationOverlay.enableCompass(); } @Override protected void onPause() { super.onResume(); myLocationOverlay.disableMyLocation(); myLocationOverlay.disableCompass(); } } </code></pre>
3
2,619
Error: "Only unicode objects are escapable. Got None of type <class 'NoneType'>". Could someone please help me spot the mistake(s) in my code?
<p>I am a beginner at Twitter Development and Python programming in general, but recently I have been trying to build a bot that, when tagged in reply to a Tweet, finds keywords and uses Google to deliver some info from reliable sources regarding the topic of the original Tweet. However, I have encountered one major problem while programming: <code>API</code> doesn't get created since the code triggers the error &quot;only unicode objects are escapable&quot;. I have used module Config to set my Twitter API credentials as environmental variables and that seems to work fine on its own. Before trying to run the bot, I activate my virtual environment and export the env variables, so I do not think this issue has to do with incorrectly setting those variables, but I would not say I am certain about that either! The code goes this way:</p> <pre><code>import tweepy import logging from config import create_api import time import re from googlesearch import search import sys import io logging.basicConfig(level=logging.INFO) logger = logging.getLogger() api = tweepy.API def check_mentions(api, keywords, since_id): logger.info(&quot;Collecting info&quot;) new_since_id = since_id for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id).items(): new_since_id = max(tweet.id, new_since_id) if tweet.in_reply_to_status_id is not None: in_reply_to_status_id = previous_tweet.id status_id = tweet.in_reply_to_status_id tweet_u = api.get_status(status_id,tweet_mode='extended') #to store the output -links- as a variable to use it later old_stdout = sys.stdout new_stdout = io.StringIO() sys.stdout = new_stdout output = new_stdout.getvalue() sys.stdout = old_stdout print(output) text = output # remove words that are between 1 and 3 characters long shortword = re.compile(r'\W*\b\w{1,3}\b') print(shortword.sub('', text)) keywords_search = print(shortword.sub('', text)) if keywords_search is not None: mystring = search(keywords_search, num_results=500) else: mystring = search(&quot;error&quot;, num_results=1) for word in mystring: if &quot;harvard&quot; in word or &quot;cornell&quot; in word or &quot;researchgate&quot; in word or &quot;yale&quot; in word or &quot;rutgers&quot; in word or &quot;caltech&quot; in word or &quot;upenn&quot; in word or &quot;princeton&quot; in word or &quot;columbia&quot; in word or &quot;journal&quot; in word or &quot;mit&quot; in word or &quot;stanford&quot; in word or &quot;gov&quot; in word or &quot;pubmed&quot; in word: print(word) #to store the output -links- as a variable to use it later old_stdout = sys.stdout new_stdout = io.StringIO() sys.stdout = new_stdout for word in mystring: if &quot;harvard&quot; in word or &quot;cornell&quot; in word or &quot;researchgate&quot; in word or &quot;yale&quot; in word or &quot;rutgers&quot; in word or &quot;caltech&quot; in word or &quot;upenn&quot; in word or &quot;princeton&quot; in word or &quot;columbia&quot; in word or &quot;journal&quot; in word or &quot;mit&quot; in word or &quot;stanford&quot; in word or &quot;gov&quot; in word or &quot;pubmed&quot; in word: print(word) #to print normally again output = new_stdout.getvalue() sys.stdout = old_stdout print(output) if output is not None: status = &quot;Hi there! This may be what you're looking for&quot; and print(output), len(status) &lt;= 280 api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=False), else: status = &quot;Sorry, I cannot help you with that :(. You might want to try again with a distinctly sourced Tweet&quot;, len(status) &lt;= 280 api.update_status(status, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=False), return new_since_id def main(): api = create_api() since_id = 1 #the last mention you have. while True: print(since_id) since_id = check_mentions(api, [&quot;help&quot;, &quot;support&quot;], since_id) logger.info(&quot;Waiting...&quot;) time.sleep(15) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>My Config module:</p> <pre><code> import tweepy import logging import os logger = logging.getLogger() def create_api(): consumer_key = os.getenv(&quot;XXXXXXXXXX&quot;) consumer_secret = os.getenv(&quot;XXXXXXXXXX&quot;) access_token = os.getenv(&quot;XXXXXXXXXX&quot;) access_token_secret = os.getenv(&quot;XXXXXXXXXX&quot;) auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) try: api.verify_credentials() except Exception as e: logger.error(&quot;Error creating API&quot;, exc_info=True) raise e logger.info(&quot;API created&quot;) return api </code></pre> <p>The error goes:</p> <pre><code>ERROR:root:Error creating API Traceback (most recent call last): File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 184, in execute resp = self.session.request(self.method, File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 516, in request prep = self.prepare_request(req) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 449, in prepare_request p.prepare( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 318, in prepare self.prepare_auth(auth, url) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 549, in prepare_auth r = auth(self) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests_oauthlib\oauth1_auth.py&quot;, line 108, in __call__ r.url, headers, _ = self.client.sign( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 313, in sign ('oauth_signature', self.get_oauth_signature(request))) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 127, in get_oauth_signature uri, headers, body = self._render(request) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 209, in _render headers = parameters.prepare_headers( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 32, in wrapper return target(params, *args, **kwargs) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\parameters.py&quot;, line 59, in prepare_headers escaped_value = utils.escape(value) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 56, in escape raise ValueError('Only unicode objects are escapable. ' + ValueError: Only unicode objects are escapable. Got None of type &lt;class 'NoneType'&gt;. During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\config.py&quot;, line 23, in create_api api.verify_credentials() File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\api.py&quot;, line 672, in verify_credentials return bind_api( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 253, in _call return method.execute() File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 192, in execute six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\six.py&quot;, line 702, in reraise raise value.with_traceback(tb) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 184, in execute resp = self.session.request(self.method, File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 516, in request prep = self.prepare_request(req) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 449, in prepare_request p.prepare( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 318, in prepare self.prepare_auth(auth, url) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 549, in prepare_auth r = auth(self) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests_oauthlib\oauth1_auth.py&quot;, line 108, in __call__ r.url, headers, _ = self.client.sign( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 313, in sign ('oauth_signature', self.get_oauth_signature(request))) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 127, in get_oauth_signature uri, headers, body = self._render(request) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 209, in _render headers = parameters.prepare_headers( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 32, in wrapper return target(params, *args, **kwargs) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\parameters.py&quot;, line 59, in prepare_headers escaped_value = utils.escape(value) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 56, in escape raise ValueError('Only unicode objects are escapable. ' + tweepy.error.TweepError: Failed to send request: Only unicode objects are escapable. Got None of type &lt;class 'NoneType'&gt;. Traceback (most recent call last): File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 184, in execute resp = self.session.request(self.method, File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 516, in request prep = self.prepare_request(req) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 449, in prepare_request p.prepare( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 318, in prepare self.prepare_auth(auth, url) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 549, in prepare_auth r = auth(self) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests_oauthlib\oauth1_auth.py&quot;, line 108, in __call__ r.url, headers, _ = self.client.sign( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 313, in sign ('oauth_signature', self.get_oauth_signature(request))) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 127, in get_oauth_signature uri, headers, body = self._render(request) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 209, in _render headers = parameters.prepare_headers( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 32, in wrapper return target(params, *args, **kwargs) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\parameters.py&quot;, line 59, in prepare_headers escaped_value = utils.escape(value) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 56, in escape raise ValueError('Only unicode objects are escapable. ' + ValueError: Only unicode objects are escapable. Got None of type &lt;class 'NoneType'&gt;. During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring20.py&quot;, line 114, in &lt;module&gt; main() File &quot;C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\botstring20.py&quot;, line 105, in main api = create_api() File &quot;C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\config.py&quot;, line 26, in create_api raise e File &quot;C:\Users\maria\OneDrive\Documentos\Lara\Python\Factualbot\config.py&quot;, line 23, in create_api api.verify_credentials() File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\api.py&quot;, line 672, in verify_credentials return bind_api( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 253, in _call return method.execute() File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 192, in execute six.reraise(TweepError, TweepError('Failed to send request: %s' % e), sys.exc_info()[2]) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\six.py&quot;, line 702, in reraise raise value.with_traceback(tb) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\binder.py&quot;, line 184, in execute resp = self.session.request(self.method, File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 516, in request prep = self.prepare_request(req) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\sessions.py&quot;, line 449, in prepare_request p.prepare( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 318, in prepare self.prepare_auth(auth, url) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py&quot;, line 549, in prepare_auth r = auth(self) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests_oauthlib\oauth1_auth.py&quot;, line 108, in __call__ r.url, headers, _ = self.client.sign( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 313, in sign ('oauth_signature', self.get_oauth_signature(request))) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 127, in get_oauth_signature uri, headers, body = self._render(request) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\__init__.py&quot;, line 209, in _render headers = parameters.prepare_headers( File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 32, in wrapper return target(params, *args, **kwargs) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\parameters.py&quot;, line 59, in prepare_headers escaped_value = utils.escape(value) File &quot;C:\Users\maria\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\oauthlib\oauth1\rfc5849\utils.py&quot;, line 56, in escape raise ValueError('Only unicode objects are escapable. ' + tweepy.error.TweepError: Failed to send request: Only unicode objects are escapable. Got None of type &lt;class 'NoneType'&gt;. </code></pre> <p>I know it is pretty long but I just wanted to know if anyone could tell me which direction to go with the bug-solving process, since I am kind of lost and I did not know where else to ask! Thank you in advance and sorry for how long this is!!!!&lt;3</p>
3
8,376
Incrementing Variable in v-for Loop by Amount Returned from Method
<p>I have a table that uses v-for to loop through an object of days returned from using axios. I've given the ability to manipulate a variety of booleans on each row which change some calculated values in some columns. What I need is to calculate the total of these columns in a bottom row accounting for changes from the values in the rest of the table.</p> <p>I've tried calling on a method to do something like this.total.b2cTotal += someNumber; but it bugs out the page.</p> <p>the code</p> <pre class="lang-html prettyprint-override"><code> &lt;table v-if="userSelect != 0" class="w-full text-md bg-white shadow-md rounded mb-4 reports text-sm"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th v-if="userSelect == 'all'" class="text-left p-3 px-5"&gt;User Name&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Day&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Show Code&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Day Type&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Sch. (hrs)&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Actual&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Reg&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;OT&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;1.5x&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;DT&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Rate&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;B2C?&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;OT Apr?&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;OT B2C?&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;PD?&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;PD $&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;TRV?&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;B2C Labor&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;B2C OT&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;FT Labor&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;FT OT&lt;/th&gt; &lt;th class="text-left p-3 px-5"&gt;Worker Paid&lt;/th&gt; &lt;/tr&gt; &lt;tr class="text-center" v-for="(day,index) in userDays" :key="index"&gt; &lt;td v-if="userSelect == 'all'" class="p-3 px-5"&gt;{{ day.userName }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ day.date }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ day.projectCode }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;tbd&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ day.scheduledHours }}&lt;/td&gt; &lt;td class="p-3 px-5 font-bold"&gt;{{ day.actualHours }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ day.regHours }}&lt;/td&gt; &lt;td class="p-3 px-5 font-bold"&gt;{{ day.otHours }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ day.timeAndAHalfHours }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ day.doubleTimeHours }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ day.costRate }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt; &lt;!-- billable to client --&gt; &lt;img v-if="day.billable == 1" @click="(toggleDayBoolean(day.dayID,'billable','disable'),day.billable = 0)" src="https://img.icons8.com/ultraviolet/22/000000/checked-2.png"&gt; &lt;img v-if="day.billable == 0" @click="(toggleDayBoolean(day.dayID,'billable','enable'),day.billable = 1)" src="https://img.icons8.com/officel/22/000000/stop.png"&gt; &lt;/td&gt; &lt;td class="p-3 px-5"&gt; &lt;!-- over time --&gt; &lt;img v-if="day.otApproved == 1" @click="(toggleDayBoolean(day.dayID,'otApproved','disable'),day.otApproved = 0)" src="https://img.icons8.com/ultraviolet/22/000000/checked-2.png"&gt; &lt;img v-if="day.otApproved == 0" @click="(toggleDayBoolean(day.dayID,'otApproved','enable'),day.otApproved = 1)" src="https://img.icons8.com/officel/22/000000/stop.png"&gt; &lt;/td&gt; &lt;td class="p-3 px-5"&gt; &lt;!-- over time --&gt; &lt;img v-if="day.otBillable == 1" @click="(toggleDayBoolean(day.dayID,'otBillable','disable'),day.otBillable = 0)" src="https://img.icons8.com/ultraviolet/22/000000/checked-2.png"&gt; &lt;img v-if="day.otBillable == 0" @click="(toggleDayBoolean(day.dayID,'otBillable','enable'),day.otBillable = 1)" src="https://img.icons8.com/officel/22/000000/stop.png"&gt; &lt;/td&gt; &lt;td class="p-3 px-5"&gt; &lt;!-- per diem --&gt; &lt;img v-if="day.pdApproved == 1" @click="(toggleDayBoolean(day.dayID,'pdApproved','disable'),day.pdApproved = 0)" src="https://img.icons8.com/ultraviolet/22/000000/checked-2.png"&gt; &lt;img v-if="day.pdApproved == 0" @click="(toggleDayBoolean(day.dayID,'pdApproved','enable'),day.pdApproved = 1)" src="https://img.icons8.com/officel/22/000000/stop.png"&gt; &lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ day.pdAmount }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt; &lt;!-- travel --&gt; &lt;img v-if="day.travel == 1" @click="(toggleDayBoolean(day.dayID,'travel','disable'),day.travel = 0)" src="https://img.icons8.com/ultraviolet/22/000000/checked-2.png"&gt; &lt;img v-if="day.travel == 0" @click="(toggleDayBoolean(day.dayID,'travel','enable'),day.travel = 1)" src="https://img.icons8.com/officel/22/000000/stop.png"&gt; &lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ costDistributor('b2c',day).b2c }} &lt;div v-text="addTo()"&gt;&lt;/div&gt;&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ costDistributor('b2cOT',day).b2cOT }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ costDistributor('ft',day).ft }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ costDistributor('ftOT',day).ftOT }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt; &lt;strong&gt;${{ day.totalCost + day.pdAmount }}&lt;/strong&gt;&amp;nbsp; &lt;span class="view-icon"&gt;&lt;a target="dayView" :href='"/tracker/resources/days/"+day.dayID' class="cursor-pointer text-70 hover:text-primary mr-3" data-testid="projects-items-3-view-button" dusk="10-view-button" title="View"&gt; &lt;img src="https://img.icons8.com/ultraviolet/40/000000/visible.png"&gt;&lt;/a&gt;&lt;/span&gt; &lt;!-- &lt;span class="lock-icon"&gt;&lt;a href="" class="cursor-pointer text-70 hover:text-primary mr-3" data-testid="projects-items-3-view-button" dusk="10-view-button" title="View"&gt; &lt;img src="https://img.icons8.com/ultraviolet/40/000000/lock.png"&gt;&lt;/a&gt;&lt;/span&gt; --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr v-if="userSelect!=0" class="font-bold text-lg"&gt; &lt;td v-if="userSelect == 'all'" class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ finalTotal(userSelect,'scheduledHours') }} hrs&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ finalTotal(userSelect,'actualHours') }} hrs&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ finalTotal(userSelect,'otHours') }} hrs&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ finalTotal(userSelect,'timeAndAHalfHours') }} hrs&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ finalTotal(userSelect,'doubleTimeHours') }} hrs&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ finalTotal(userSelect,'pdAmount') }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;{{ }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ addToTotal('show','b2c',0) }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ finalTotal(userSelect,'b2cOT') }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ finalTotal(userSelect,'ft') }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ finalTotal(userSelect,'ftOT') }}&lt;/td&gt; &lt;td class="p-3 px-5"&gt;${{ finalTotal(userSelect,'totalCost') }}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><em>I added in the finalTotal code though it's irrelevant to what I'm trying to solve</em></p> <pre class="lang-js prettyprint-override"><code>methods: { /** * distribute costs to company or client * * @param string * @param App\CrewCallReports@getUserDays object * * @return object */ costDistributor(type,day){ let totals = { b2c: 0, b2cOT: 0, ft: 0, ftOT: 0, b2cTotal: 0 }; switch(type){ case 'b2c': if(day.billable &amp;&amp; day.regHours == 'straight'){ // if straight time then bill actual hours if(day.billable){ totals.b2c = day.costRate * day.actualHours; totals.b2cTotal += totals.b2c; } // if pd approved then add it if(day.pdApproved){ totals.b2c += day.pdAmount; totals.b2cTotal += day.pdAmount; } }else if(day.billable &amp;&amp; day.regHours != 'straight'){ // if not straight time but billable to client if(day.billable){ totals.b2c = day.costRate * day.regularHours; totals.b2cTotal += totals.b2c; } // if pd approved then add it if(day.pdApproved){ totals.b2c += day.pdAmount; totals.b2cTotal += day.pdAmount; } }else if(!day.billable){ // no labor charged to client totals.b2c = 0; totals.b2cTotal += totals.b2c; // in case pd applies but regular labor doesn't (weird case) if(day.pdApproved){ totals.b2c += day.pdAmount; totals.b2cTotal += day.pdAmount; } } // we need to add travel into this formula break; case 'ft': if(!day.billable &amp;&amp; day.regHours == 'straight'){ // add base hour cost if(!day.billable){ totals.ft = day.costRate * day.actualHours; } // add per diem if applicable if(!day.pdApproved){ totals.ft += day.pdAmount; } }else if(!day.billable &amp;&amp; day.regHours != 'straight'){ // add base cost if not straight time if(!day.billable){ totals.ft = day.costRate * day.regularHours; } // add per diem if applicable if(!day.pdApproved){ totals.ft += day.pdAmount; } }else if(day.billable){ // labor charged to client totals.ft = 0; if(!day.pdApproved){ totals.ft += day.pdAmount; } } break; case 'b2cOT': // if OT is billable to client and approved if(day.otBillable &amp;&amp; day.otApproved){ totals.b2cOT = (day.costRate * day.timeAndAHalfHours * 1.5) + (day.costRate * day.doubleTimeHours * 2); }else{ // all other cases don't bill client at all totals.b2cOT = 0; } break; case 'ftOT': // if OT is not billable to client but approved if(!day.otBillable &amp;&amp; day.otApproved){ totals.ftOT = (day.costRate * day.timeAndAHalfHours * 1.5) + (day.costRate * day.doubleTimeHours * 2); }else{ totals.ftOT = 0; } break; } return totals; }, getUserDays(e){ // grab the days for this user and spit it to the table axios.get(this.userURI+e.target.value+'/days').then(response=&gt;{ this.userDays = response.data.days; }); this.userID = e.target.value; }, finalTotal($userID,$field){ // set user ID to 0 if all are selected for lookup if($userID == 'all'){ $userID = 0; } let days = this.userDays; function sumFinder(id,field) { return days.reduce((sum, e) =&gt; { if(id == 0){ sum += e[field]; return sum; }else{ e.userID == id ? (sum += e[field]) : (sum += 0); return sum; } }, 0); } // Create our number formatter. var formatter = new Intl.NumberFormat('en-US', { currency: 'USD', }); return formatter.format(sumFinder($userID,$field)); }, } </code></pre>
3
9,401
Label caption changes only once
<p>I am trying to print out a table into a sheet which has an image with some activex labels on it. As the pages change, I want the label captions to change too and reflect the data in the table. But what is happening is that only the first page is getting printed and the others are not. My MsgBox seems to get the right data but during printing it is just printing the first page. Is it even possible to print out sheets within a for loop? I tried to run the code one page number at a time and it prints out just fine. But when I am looping through page numbers, it prints out only the first page over and over again. </p> <p>Here's my code. </p> <pre><code> Dim temp As String Dim rowlast As Integer Dim page As Integer rowlast = Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Row 'MsgBox WorksheetFunction.RoundUp((rowlast - 1) / 4, 0) For page = 1 To WorksheetFunction.RoundUp((rowlast - 1) / 4, 0) 'Msgbox for first entry in current page Label1.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2, 1) MsgBox Label1.Caption Label3.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 1, 1) Label5.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 2, 1) Label7.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 1) Label2.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2, 2) Label4.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 1, 2) Label6.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 2, 2) Label8.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 2) Label9.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2, 3) Label10.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 1, 3) Label11.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 2, 3) Label12.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 3) Label13.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 5) Label14.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 5) Label15.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 5) Label16.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 5) Label17.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 4) Label18.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 4) Label19.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 4) Label20.Caption = Sheets("Data").Cells(((page - 1) * 4) + 2 + 3, 4) 'MsgBox "OK" Sheets("Card Print").PrintOut Next page </code></pre> <p>Here's my table: </p> <p><a href="https://i.stack.imgur.com/XVUyI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XVUyI.jpg" alt="enter image description here"></a></p> <p>Here's my output sheet: </p> <p><a href="https://i.stack.imgur.com/AZxn8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AZxn8.jpg" alt="enter image description here"></a></p>
3
1,248
Failure in arp poisoning python (linux)
<p>Okay, so I'm running Ubunutu 14.04 LTS, and I'm trying to poison my own ARP Cache, by doing this,</p> <p>my private IP address is <strong>10.0.0.1</strong>.</p> <p>My phone's private IP address is <strong>10.0.0.8</strong>.</p> <p>for this example only let's say my MAC address is <strong>axaxaxaxaxax</strong>.</p> <p>I've wrote the following python code:</p> <pre><code>from binascii import * from struct import * import socket; class ethernetframe: def __init__(self, destmac, srcmac, ethrtype): self.destmac = unhexlify(destmac) self.srcmac = unhexlify(srcmac) self.ethrtype = unhexlify(ethrtype) def uniteframe(self, payload): frame = '' frame = frame + self.destmac frame = frame + self.srcmac frame = frame + self.ethrtype frame = frame + payload frame = frame + unhexlify("00000000") return frame class arppacket: def __init__(self,opcode,srcmac,srcip,dstmac,dstip): if opcode == 1: dstmac = "000000000000" opcode = "0001" else: opcode = "0002" self.opcode = unhexlify(opcode) self.srcmac = unhexlify(srcmac) self.srcip = pack('!4B',srcip[0],srcip[1],srcip[2],srcip[3]) self.dstmac = unhexlify(dstmac) self.dstip = pack('!4B',dstip[0],dstip[1],dstip[2],dstip[3]) def unitepacket(self): packet = '' packet = packet + "\x00\x01\x08\x00\x06\x04" packet = packet + self.opcode packet = packet + self.srcmac packet = packet + self.srcip packet = packet + self.dstmac packet = packet + self.dstip return packet e1 = ethernetframe("axaxaxaxaxax","axaxaxaxaxax","0800") arp1 = arppacket(2,"axaxaxaxaxax",(10,0,0,8),"axaxaxaxaxax",(10,0,0,1)) arpacket = arp1.unitepacket() fullethframe = e1.uniteframe(arpacket) s = socket.socket(socket.AF_PACKET,socket.SOCK_RAW,socket.htons(0x0806)) s.bind(("eth0",0)) s.send(fullethframe) </code></pre> <p>now, I'm monitoring this whole process with Wireshark, the ARP packet is being send and it is formed correctly, In wire shark I see the following line:</p> <p><strong>10.0.0.8 is at axaxaxaxaxax</strong></p> <p>This means that I have successfully sent an ARP reply! to my own computer, stating that the MAC address that is resolved for <strong>10.0.0.8</strong> is <strong>axaxaxaxaxax</strong> since ARP cache automatically update if a reply is received REGARDLESS if a request was sent, this means that in my NIC driver's arp cache there should've been a line added stating that <strong>10.0.0.8 is resolved with axaxaxaxaxax</strong></p> <p>however, when I run inside my ubunutu's terminal </p> <pre><code>arp - a </code></pre> <p>or </p> <pre><code>arp - an </code></pre> <p>it doesn't show up....., which means I've failed to poison my own ARP cache, any ideas how to fix this?</p>
3
1,241
Laravel sync users to all of categoires which they can be unlimited
<p>In our web application each user can create multiple nested category by selecting the parent which that specified with <code>category_id</code> column.</p> <pre class="lang-php prettyprint-override"><code>Schema::create('categories', function (Blueprint $table) { $table-&gt;bigIncrements('id'); $table-&gt;unsignedBigInteger('category_id')-&gt;index()-&gt;nullable(); $table-&gt;foreign('category_id')-&gt;references('id')-&gt;on('categories')-&gt;onDelete('cascade'); $table-&gt;string('category_name'); ... $table-&gt;timestamp('created_at')-&gt;useCurrent(); $table-&gt;timestamp('updated_at')-&gt;useCurrent(); }); </code></pre> <p>now you supposed one of our user created this category structure:</p> <p><a href="https://i.stack.imgur.com/3xjXo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3xjXo.png" alt="enter image description here" /></a></p> <p>multiple nested categories children are unlimited, that means every category can be have child and we can't use any static or fixed number for example in <code>for</code> statement to sync the category to specify <code>users</code>.</p> <p>my question is how can i set specify <code>users</code> to all of categories from parent?</p> <p>this query only can set users for single child of parent. you can suppose <code>1</code>,<code>3</code>,<code>4</code>,<code>5</code>,<code>6</code>,<code>7</code> in above screen shot and not working for <code>2</code> and all of their children</p> <p>children of <code>parent category</code> can be unlimited and how can we set <code>users</code> from the parent to all of nested and children categories?</p> <pre class="lang-php prettyprint-override"><code>$category = Category::whereId($request-&gt;category_id)-&gt;whereNull('category_id')-&gt;with('childrenCategories')-&gt;first(); $category-&gt;users()-&gt;sync($request-&gt;users); foreach ($category-&gt;childrenCategories as $category) { $category-&gt;users()-&gt;sync($request-&gt;users); } </code></pre> <p>simplified output of query:</p> <pre><code>App\Entities\Category {#2114 ▼ ... #attributes: array:11 [▶] #original: array:11 [▶] ... #relations: array:1 [▼ &quot;childrenCategories&quot; =&gt; Illuminate\Database\Eloquent\Collection {#2118 ▼ #items: array:4 [▼ 0 =&gt; App\Entities\Category {#2133 ▶} 1 =&gt; App\Entities\Category {#2134 ▶} 2 =&gt; App\Entities\Category {#2135 ▼ ... #attributes: array:11 [▶] #original: array:11 [▶] ... #relations: array:1 [▼ &quot;categories&quot; =&gt; Illuminate\Database\Eloquent\Collection {#2138 ▼ #items: array:1 [▼ 0 =&gt; App\Entities\Category {#2157 ▼ ... #attributes: array:11 [▶] #original: array:11 [▶] ... #relations: [] ... } ] } ] ... } 3 =&gt; App\Entities\Category {#2136 ▶} ] } ] ... } </code></pre>
3
1,331
Pareto front for matplotlib scatter plot
<p>I'm trying to add pareto front to scatter plot I have. The scatter plot data is:</p> <pre><code>array([[1.44100000e+04, 3.31808987e+07], [1.21250000e+04, 3.22901074e+07], [6.03000000e+03, 2.84933900e+07], [8.32500000e+03, 2.83091317e+07], [6.68000000e+03, 2.56373373e+07], [5.33500000e+03, 1.89331461e+07], [3.87500000e+03, 1.84107940e+07], [3.12500000e+03, 1.60416570e+07], [6.18000000e+03, 1.48054565e+07], [4.62500000e+03, 1.33395341e+07], [5.22500000e+03, 1.23150492e+07], [3.14500000e+03, 1.20244820e+07], [6.79500000e+03, 1.19525083e+07], [2.92000000e+03, 9.18176770e+06], [5.45000000e+02, 5.66882578e+06]]) </code></pre> <p>and the the scatter plot looks like this:</p> <p><a href="https://i.stack.imgur.com/4JMzG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4JMzG.png" alt="enter image description here" /></a></p> <p>I have used this <a href="https://pythonhealthcare.org/tag/pareto-front/" rel="nofollow noreferrer">tutorial</a> in order to plot the pareto, but for some reason the result is very weird and I get tiny red line :</p> <p><a href="https://i.stack.imgur.com/ARmog.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ARmog.png" alt="enter image description here" /></a></p> <p>This is the code I have used:</p> <pre><code>def identify_pareto(scores): # Count number of items population_size = scores.shape[0] # Create a NumPy index for scores on the pareto front (zero indexed) population_ids = np.arange(population_size) # Create a starting list of items on the Pareto front # All items start off as being labelled as on the Parteo front pareto_front = np.ones(population_size, dtype=bool) print(pareto_front) # Loop through each item. This will then be compared with all other items for i in range(population_size): # Loop through all other items for j in range(population_size): # Check if our 'i' pint is dominated by out 'j' point if all(scores[j] &gt;= scores[i]) and any(scores[j] &gt; scores[i]): # j dominates i. Label 'i' point as not on Pareto front pareto_front[i] = 0 # Stop further comparisons with 'i' (no more comparisons needed) break # Return ids of scenarios on pareto front return population_ids[pareto_front] pareto = identify_pareto(scores) pareto_front_df = pd.DataFrame(pareto_front) pareto_front_df.sort_values(0, inplace=True) pareto_front = pareto_front_df.values #here I get as output weird results: &gt;&gt;&gt; array([[ 5, 81], [15, 80], [30, 79], [55, 77], [70, 65], [80, 60], [90, 40], [97, 23], [99, 4]]) x_all = scores[:, 0] y_all = scores[:, 1] x_pareto = pareto_front[:, 0] y_pareto = pareto_front[:, 1] plt.scatter(x_all, y_all) plt.plot(x_pareto, y_pareto, color='r') plt.xlabel('Objective A') plt.ylabel('Objective B') plt.show() </code></pre> <p>the result is the tiny red line.</p> <p>My question is, where is my mistake? how can I get back the pareto line?</p>
3
1,495
Reading YUY2 data from an IMFSample that appears to have improper data on Windows 10
<p>I am developing an application that using IMFSourceReader to read data from video files. I am using DXVA for improved performance. I am having trouble with one specific full-HD H.264 encoded AVI file. Based on my investigation this far, I believe that the IMFSample contains incorrect data. My workflow is below:</p> <ol> <li>Create a source reader with a D3D manager to enable hardware acceleration.</li> <li>Set the current media type to YUY2 as DXVA does not decode to any RGB colorspace. </li> <li>Call ReadSample to get an IMFSample. Works fine.</li> <li>Use the VideoProcessorBlt to perform YUY2 to BGRA32 conversion. For this specific file it errors out with an E_INVALIDARGS error code. Decided to do the conversion myself. </li> <li>Used IMFSample::ConvertToContiguousBuffer to receive an IMFMediaBuffer. When locking this buffer, the pitch is reported as 1280 bytes. This I believe is incorrect, because for a full HD video, the pitch should be (1920 + 960 + 960 = 3840 bytes).</li> </ol> <p>I dumped the raw memory and extracted the Y, U and V components based on my understanding of the YUY2 layout. You can find it below. So, the data is there but I do not believe it is laid out as YUY2. Need some help in interpreting the data.</p> <p><a href="https://i.stack.imgur.com/RNxQP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RNxQP.png" alt="Y component"></a></p> <p><a href="https://i.stack.imgur.com/VAM1s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VAM1s.png" alt="U component"></a></p> <p><a href="https://i.stack.imgur.com/emllC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/emllC.png" alt="V component"></a> My code for reading is below:</p> <pre><code> // Direct3D surface that stores the result of the YUV2RGB conversion CComPtr&lt;IDirect3DSurface9&gt; _pTargetSurface; IDirectXVideoAccelerationService* vidAccelService; initVidAccelerator(&amp;vidAccelService); // Omitting the code for this. // Create a new surface for doing the color conversion, set it up to store X8R8G8B8 data. hr = vidAccelService-&gt;CreateSurface( static_cast&lt;UINT&gt;( 1920 ), static_cast&lt;UINT&gt;( 1080 ), 0, // no back buffers D3DFMT_X8R8G8B8, // data format D3DPOOL_DEFAULT, // default memory pool 0, // reserved DXVA2_VideoProcessorRenderTarget, // to use with the Blit operation &amp;_pTargetSurface, // surface used to store frame NULL); GUID processorGUID; DXVA2_VideoDesc videoDescriptor; D3DFORMAT processorFmt; UINT numSubStreams; IDirectXVideoProcessor* _vpd; initVideoProcessor(&amp;vpd); // Omitting the code for this // We get the videoProcessor parameters on creation, and fill up the videoProcessBltParams accordingly. _vpd-&gt;GetCreationParameters(&amp;processorGUID, &amp;videoDescriptor, &amp;processorFmt, &amp;numSubStreams); RECT targetRECT; // { 0, 0, width, height } as left, top, right, bottom targetRECT.left = 0; targetRECT.right = videoDescriptor.SampleWidth; targetRECT.top = 0; targetRECT.bottom = videoDescriptor.SampleHeight; SIZE targetSIZE; // { width, height } targetSIZE.cx = videoDescriptor.SampleWidth; targetSIZE.cy = videoDescriptor.SampleHeight; // Parameters that are required to use the video processor to perform // YUV2RGB and other video processing operations DXVA2_VideoProcessBltParams _frameBltParams; _frameBltParams.TargetRect = targetRECT; _frameBltParams.ConstrictionSize = targetSIZE; _frameBltParams.StreamingFlags = 0; // reserved. _frameBltParams.BackgroundColor.Y = 0x0000; _frameBltParams.BackgroundColor.Cb = 0x0000; _frameBltParams.BackgroundColor.Cr = 0x0000; _frameBltParams.BackgroundColor.Alpha = 0xFFFF; // copy attributes from videoDescriptor obtained above. _frameBltParams.DestFormat.VideoChromaSubsampling = videoDescriptor.SampleFormat.VideoChromaSubsampling; _frameBltParams.DestFormat.NominalRange = videoDescriptor.SampleFormat.NominalRange; _frameBltParams.DestFormat.VideoTransferMatrix = videoDescriptor.SampleFormat.VideoTransferMatrix; _frameBltParams.DestFormat.VideoLighting = videoDescriptor.SampleFormat.VideoLighting; _frameBltParams.DestFormat.VideoPrimaries = videoDescriptor.SampleFormat.VideoPrimaries; _frameBltParams.DestFormat.VideoTransferFunction = videoDescriptor.SampleFormat.VideoTransferFunction; _frameBltParams.DestFormat.SampleFormat = DXVA2_SampleProgressiveFrame; // The default values are used for all these parameters. DXVA2_ValueRange pRangePABrightness; _vpd-&gt;GetProcAmpRange(DXVA2_ProcAmp_Brightness, &amp;pRangePABrightness); DXVA2_ValueRange pRangePAContrast; _vpd-&gt;GetProcAmpRange(DXVA2_ProcAmp_Contrast, &amp;pRangePAContrast); DXVA2_ValueRange pRangePAHue; _vpd-&gt;GetProcAmpRange(DXVA2_ProcAmp_Hue, &amp;pRangePAHue); DXVA2_ValueRange pRangePASaturation; _vpd-&gt;GetProcAmpRange(DXVA2_ProcAmp_Saturation, &amp;pRangePASaturation); _frameBltParams.ProcAmpValues = { pRangePABrightness.DefaultValue, pRangePAContrast.DefaultValue, pRangePAHue.DefaultValue, pRangePASaturation.DefaultValue }; _frameBltParams.Alpha = DXVA2_Fixed32OpaqueAlpha(); _frameBltParams.DestData = DXVA2_SampleData_TFF; // Input video sample for the Blt operation DXVA2_VideoSample _frameVideoSample; _frameVideoSample.SampleFormat.VideoChromaSubsampling = videoDescriptor.SampleFormat.VideoChromaSubsampling; _frameVideoSample.SampleFormat.NominalRange = videoDescriptor.SampleFormat.NominalRange; _frameVideoSample.SampleFormat.VideoTransferMatrix = videoDescriptor.SampleFormat.VideoTransferMatrix; _frameVideoSample.SampleFormat.VideoLighting = videoDescriptor.SampleFormat.VideoLighting; _frameVideoSample.SampleFormat.VideoPrimaries = videoDescriptor.SampleFormat.VideoPrimaries; _frameVideoSample.SampleFormat.VideoTransferFunction = videoDescriptor.SampleFormat.VideoTransferFunction; _frameVideoSample.SrcRect = targetRECT; _frameVideoSample.DstRect = targetRECT; _frameVideoSample.PlanarAlpha = DXVA2_Fixed32OpaqueAlpha(); _frameVideoSample.SampleData = DXVA2_SampleData_TFF; CComPtr&lt;IMFSample&gt; sample; // Assume that this was read in from a call to ReadSample CComPtr&lt;IMFMediaBuffer&gt; buffer; HRESULT hr = sample-&gt;GetBufferByIndex(0, &amp;buffer); CComPtr&lt;IDirect3DSurface9&gt; pSrcSurface; // From the MediaBuffer, we get the Source Surface using MFGetService hr = MFGetService( buffer, MR_BUFFER_SERVICE, __uuidof(IDirect3DSurface9), (void**)&amp;pSrcSurface ); // Update the videoProcessBltParams with frame specific values. LONGLONG sampleStartTime; sample-&gt;GetSampleTime(&amp;sampleStartTime); _frameBltParams.TargetFrame = sampleStartTime; LONGLONG sampleDuration; sample-&gt;GetSampleDuration(&amp;sampleDuration); _frameVideoSample.Start = sampleStartTime; _frameVideoSample.End = sampleStartTime + sampleDuration; _frameVideoSample.SrcSurface = pSrcSurface; // Run videoProcessBlt using the parameters setup (this is used for color conversion) // The returned code is E_INVALIDARGS hr = _vpd-&gt;VideoProcessBlt( _pTargetSurface, // target surface &amp;_frameBltParams, // parameters &amp;_frameVideoSample, // video sample structure 1, // one sample NULL); // reserved </code></pre>
3
2,924
An unknown server-side error occurred Did not get any response after 300s while running Web testing
<p><strong>The problem</strong></p> <blockquote> <p>An unknown server-side error occurred while processing the command. Original error: Did not get any response after 300s</p> </blockquote> <p><strong>Environment</strong></p> <ul> <li>Appium version (or git revision) that exhibits the issue: 1.15.0/1.15.1</li> <li>Desktop OS/version used to run Appium: mac OS 10.15.1</li> <li>Node.js version (unless using Appium.app|exe): v13.2.0</li> <li>Npm or Yarn package manager: 6.13.1</li> <li>Mobile platform/version under test: iOS 13.1.2</li> <li>Real device or emulator/simulator: iPhone X</li> </ul> <p><strong>Details</strong></p> <p>I run web testing on iOS 13.1.2. The previous steps can be implemented without error. while it implemented CLICK command. It took about 10 mins and reported the error above.</p> <p>I used to use Appium 1.15.1 and now downgrade to 1.15.0. I also tried to upgraded and downgraded the Katalon Studio Version but the issue still occurs.</p> <pre><code>Test Cases/Mobile/M-Queenb - Login FAILED. Reason: com.kms.katalon.core.exception.StepFailedException: Unable to click on object 'Object Repository/Mobile - Login/Page_Home Decor Online Store queen/a_Categories' at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.stepFailed(WebUIKeywordMain.groovy:64) at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.runKeyword(WebUIKeywordMain.groovy:26) at com.kms.katalon.core.webui.keyword.builtin.ClickKeyword.click(ClickKeyword.groovy:79) at com.kms.katalon.core.webui.keyword.builtin.ClickKeyword.execute(ClickKeyword.groovy:42) at com.kms.katalon.core.keyword.internal.KeywordExecutor.executeKeywordForPlatform(KeywordExecutor.groovy:60) at com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords.click(WebUiBuiltInKeywords.groovy:616) at com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords$click$3.call(Unknown Source) at M-Queenb - Login.run(M-Queenb - Login:34) at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194) at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119) at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:337) at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:328) at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:307) at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:299) at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:233) at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:114) at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:105) at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source) at TempTestCase1574827926297.run(TempTestCase1574827926297.groovy:23) Caused by: org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Did not get any response after 300s Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53' System info: host: 'PACMAN.ecommistry.com', ip: 'fe80:0:0:0:1887:6d13:ace3:24c4%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.1', java.version: '1.8.0_181' Driver info: io.appium.java_client.ios.IOSDriver Capabilities {automationName: XCUITest, browserName: Safari, databaseEnabled: false, deviceName: test, javascriptEnabled: true, locationContextEnabled: false, networkConnectionEnabled: false, newCommandTimeout: 1800, platform: MAC, platformName: iOS, platformVersion: 13.1.2, realDeviceLogger: /Applications/Katalon Studi..., takesScreenshot: true, udid: 0f040a74e28d16c7291dcc3eca2..., wdaLocalPort: 62547, webStorageEnabled: false} Session ID: e38d6851-f76b-4815-8cea-1362dead6450 at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552) at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42) at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1) at io.appium.java_client.ios.IOSDriver.execute(IOSDriver.java:1) at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285) at io.appium.java_client.DefaultGenericMobileElement.execute(DefaultGenericMobileElement.java:45) at io.appium.java_client.MobileElement.execute(MobileElement.java:1) at io.appium.java_client.ios.IOSElement.execute(IOSElement.java:1) at org.openqa.selenium.remote.RemoteWebElement.isDisplayed(RemoteWebElement.java:326) at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement.lambda$new$0(EventFiringWebDriver.java:404) at com.sun.proxy.$Proxy10.isDisplayed(Unknown Source) at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement.isDisplayed(EventFiringWebDriver.java:470) at org.openqa.selenium.support.ui.ExpectedConditions.elementIfVisible(ExpectedConditions.java:314) at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:43) at org.openqa.selenium.support.ui.ExpectedConditions$10.apply(ExpectedConditions.java:300) at org.openqa.selenium.support.ui.ExpectedConditions$10.apply(ExpectedConditions.java:297) at org.openqa.selenium.support.ui.ExpectedConditions$23.apply(ExpectedConditions.java:670) at org.openqa.selenium.support.ui.ExpectedConditions$23.apply(ExpectedConditions.java:666) at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:249) at com.kms.katalon.core.webui.keyword.builtin.ClickKeyword$_click_closure1.doCall(ClickKeyword.groovy:56) at com.kms.katalon.core.webui.keyword.builtin.ClickKeyword$_click_closure1.call(ClickKeyword.groovy) at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.runKeyword(WebUIKeywordMain.groovy:20) ``` </code></pre>
3
2,387
show data linked to logged in user and custom database email address
<p>I'm new to coding and I need a little help, please</p> <p>I need logged in user on WordPress(website) linked to my custom DB via email address to show data from my custom DB, like a company, address, etc etc for the logged in user only</p> <p>I've managed to get the data from the custom DB to display and logged in user info to display too(this part is so i can see logged in info), with the code below</p> <p>I guess there must be a way of doing this and would I need to have a relationship in DB tying user email and customer email</p> <p>any help would be much appreciated</p> <p>thank you for your time</p> <p>peter</p> <p>edited</p> <p>I now get the results from email addresses that are the same in both tables, but I just require the logged in user to be displayed, how can i do that?</p> <pre><code> &lt;?php global $wpdb; $result = $wpdb-&gt;get_results( "SELECT * FROM `CustomerT`, `wp_users` where `Email` = `wp_users`.`user_email`"); foreach ( $result as $print ) { ?&gt; Customer ID: &lt;?php echo $print-&gt;CustomerID; ?&gt; &lt;/br&gt; Company: &lt;?php echo $print-&gt;Company; ?&gt; &lt;/br&gt; Address: &lt;?php echo $print-&gt;Address; ?&gt;&lt;/br&gt; City: &lt;?php echo $print-&gt;City; ?&gt;&lt;/br&gt; County: &lt;?php echo $print-&gt;County; ?&gt;&lt;/br&gt; Postcode: &lt;?php echo $print-&gt;Postcode; ?&gt;&lt;/br&gt; First Name: &lt;?php echo $print-&gt;FirstName; ?&gt;&lt;/br&gt; Last Name: &lt;?php echo $print-&gt;LastName; ?&gt;&lt;/br&gt; Email: &lt;?php echo $print-&gt;Email; ?&gt;&lt;/br&gt; Phone No: &lt;?php echo $print-&gt;PhoneNo; ?&gt;&lt;/br&gt; &lt;?php global $current_user; wp_get_current_user(); ?&gt; &lt;?php if ( is_user_logged_in() ) { echo 'Username: ' . $current_user-&gt;user_login . '&lt;br /&gt;'; echo 'User email: ' . $current_user-&gt;user_email . '&lt;br /&gt;'; echo 'User first name: ' . $current_user-&gt;user_firstname . '&lt;br /&gt;'; echo 'User last name: ' . $current_user-&gt;user_lastname . '&lt;br /&gt;'; echo 'User display name: ' . $current_user-&gt;display_name . '&lt;br /&gt;'; echo 'User ID: ' . $current_user-&gt;ID . '&lt;br /&gt;'; } else { wp_loginout(); } ?&gt; &lt;?php } ?&gt; </code></pre>
3
1,099
Unable to run Tensorflow Data Validation on Google Cloud Platform (Dataflow)
<p>I have been trying to run TensorFlow Data Validation following Google Documents</p> <p>Followed same steps as <a href="https://www.tensorflow.org/tfx/data_validation/install" rel="nofollow noreferrer">https://www.tensorflow.org/tfx/data_validation/install</a>:</p> <p><code>&gt;pip install tensorflow-data-validation</code></p> <p><code>&gt;git clone https://github.com/tensorflow/data-validation</code></p> <p><code>&gt;cd data-validation</code></p> <p><code>&gt;pip install strip-hints</code></p> <p><code>&gt;python tensorflow_data_validation/tools/strip_type_hints.py tensorflow_data_validation/</code></p> <p><code>&gt;sudo docker-compose build manylinux2010</code></p> <p><code>&gt;sudo docker-compose run -e PYTHON_VERSION=${PYTHON_VERSION} manylinux2010</code></p> <p>Updated with proper path</p> <pre><code>import tensorflow_data_validation as tfdv from apache_beam.options.pipeline_options import PipelineOptions, GoogleCloudOptions, StandardOptions, SetupOptions PROJECT_ID = '' JOB_NAME = '' GCS_STAGING_LOCATION = '' GCS_TMP_LOCATION = '' GCS_DATA_LOCATION = '' # GCS_STATS_OUTPUT_PATH is the file path to which to output the data statistics # result. GCS_STATS_OUTPUT_PATH = '' PATH_TO_WHL_FILE = 'tensorflow_data_validation-0.13.1-cp27-cp27mu-manylinux1_x86_64.whl' # Create and set your PipelineOptions. options = PipelineOptions() # For Cloud execution, set the Cloud Platform project, job_name, # staging location, temp_location and specify DataflowRunner. google_cloud_options = options.view_as(GoogleCloudOptions) google_cloud_options.project = PROJECT_ID google_cloud_options.job_name = JOB_NAME google_cloud_options.staging_location = GCS_STAGING_LOCATION google_cloud_options.temp_location = GCS_TMP_LOCATION options.view_as(StandardOptions).runner = 'DataflowRunner' setup_options = options.view_as(SetupOptions) # PATH_TO_WHL_FILE should point to the downloaded tfdv wheel file. setup_options.extra_packages = [PATH_TO_WHL_FILE] tfdv.generate_statistics_from_csv(GCS_DATA_LOCATION, output_path=GCS_STATS_OUTPUT_PATH, pipeline_options=options) </code></pre> <p>Also followed same procedure with python3 which gave me below .whl</p> <p><code>tensorflow_data_validation-0.23.0.dev0-cp37-cp37m-manylinux2010_x86_64.whl</code> ` I get 2 kinds of error, </p> <p>while use <code>cp27</code> </p> <p><code>Error message from worker: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/dataflow_worker/batchworker.py", line 647, in do_work work_executor.execute() File "/usr/local/lib/python2.7/site-packages/dataflow_worker/executor.py", line 153, in execute test_shuffle_sink=self._test_shuffle_sink) File "/usr/local/lib/python2.7/site-packages/dataflow_worker/executor.py", line 118, in create_operation is_streaming=False) File "apache_beam/runners/worker/operations.py", line 1050, in apache_beam.runners.worker.operations.create_operation op = create_pgbk_op(name_context, spec, counter_factory, state_sampler) File "apache_beam/runners/worker/operations.py", line 856, in apache_beam.runners.worker.operations.create_pgbk_op return PGBKCVOperation(step_name, spec, counter_factory, state_sampler) File "apache_beam/runners/worker/operations.py", line 914, in apache_beam.runners.worker.operations.PGBKCVOperation.__init__ fn, args, kwargs = pickler.loads(self.spec.combine_fn)[:3] File "/usr/local/lib/python2.7/site-packages/apache_beam/internal/pickler.py", line 287, in loads return dill.loads(s) File "/usr/local/lib/python2.7/site-packages/dill/_dill.py", line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python2.7/site-packages/dill/_dill.py", line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python2.7/site-packages/dill/_dill.py", line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python2.7/pickle.py", line 864, in load dispatch[key](self) File "/usr/local/lib/python2.7/pickle.py", line 1139, in load_reduce value = func(*args) File "/usr/local/lib/python2.7/site-packages/dill/_dill.py", line 827, in _import_module return getattr(__import__(module, None, None, [obj]), obj) File "/usr/local/lib/python2.7/site-packages/tensorflow_data_validation/__init__.py", line 18, in &lt;module&gt; from tensorflow_data_validation.api.stats_api import GenerateStatistics File "/usr/local/lib/python2.7/site-packages/tensorflow_data_validation/api/stats_api.py", line 50, in &lt;module&gt; from tensorflow_data_validation import types ImportError: cannot import name types</code></p> <p>While using <code>cp37</code></p> <p><code>Error message from worker: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/apache_beam/internal/pickler.py", line 283, in loads return dill.loads(s) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 462, in find_class return StockUnpickler.find_class(self, module, name) File "/usr/local/lib/python3.7/site-packages/tensorflow_data_validation/statistics/stats_impl.py", line 31, in &lt;module&gt; from tensorflow_data_validation import constants File "/usr/local/lib/python3.7/site-packages/tensorflow_data_validation/__init__.py", line 39, in &lt;module&gt; from tensorflow_data_validation.statistics.generators.lift_stats_generator import LiftStatsGenerator File "/usr/local/lib/python3.7/site-packages/tensorflow_data_validation/statistics/generators/lift_stats_generator.py", line 68, in &lt;module&gt; ('y', _YType)]) File "/usr/local/lib/python3.7/typing.py", line 1448, in __new__ return _make_nmtuple(typename, fields) File "/usr/local/lib/python3.7/typing.py", line 1341, in _make_nmtuple types = [(n, _type_check(t, msg)) for n, t in types] File "/usr/local/lib/python3.7/typing.py", line 1341, in &lt;listcomp&gt; types = [(n, _type_check(t, msg)) for n, t in types] File "/usr/local/lib/python3.7/typing.py", line 142, in _type_check raise TypeError(f"{msg} Got {arg!r:.100}.") TypeError: NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type Got Any. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/dataflow_worker/batchworker.py", line 647, in do_work work_executor.execute() File "/usr/local/lib/python3.7/site-packages/dataflow_worker/executor.py", line 153, in execute test_shuffle_sink=self._test_shuffle_sink) File "/usr/local/lib/python3.7/site-packages/dataflow_worker/executor.py", line 118, in create_operation is_streaming=False) File "apache_beam/runners/worker/operations.py", line 1050, in apache_beam.runners.worker.operations.create_operation File "apache_beam/runners/worker/operations.py", line 856, in apache_beam.runners.worker.operations.create_pgbk_op File "apache_beam/runners/worker/operations.py", line 914, in apache_beam.runners.worker.operations.PGBKCVOperation.__init__ File "/usr/local/lib/python3.7/site-packages/apache_beam/internal/pickler.py", line 287, in loads return dill.loads(s) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 275, in loads return load(file, ignore, **kwds) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 270, in load return Unpickler(file, ignore=ignore, **kwds).load() File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 472, in load obj = StockUnpickler.load(self) File "/usr/local/lib/python3.7/site-packages/dill/_dill.py", line 462, in find_class return StockUnpickler.find_class(self, module, name) File "/usr/local/lib/python3.7/site-packages/tensorflow_data_validation/statistics/stats_impl.py", line 31, in &lt;module&gt; from tensorflow_data_validation import constants File "/usr/local/lib/python3.7/site-packages/tensorflow_data_validation/__init__.py", line 39, in &lt;module&gt; from tensorflow_data_validation.statistics.generators.lift_stats_generator import LiftStatsGenerator File "/usr/local/lib/python3.7/site-packages/tensorflow_data_validation/statistics/generators/lift_stats_generator.py", line 68, in &lt;module&gt; ('y', _YType)]) File "/usr/local/lib/python3.7/typing.py", line 1448, in __new__ return _make_nmtuple(typename, fields) File "/usr/local/lib/python3.7/typing.py", line 1341, in _make_nmtuple types = [(n, _type_check(t, msg)) for n, t in types] File "/usr/local/lib/python3.7/typing.py", line 1341, in &lt;listcomp&gt; types = [(n, _type_check(t, msg)) for n, t in types] File "/usr/local/lib/python3.7/typing.py", line 142, in _type_check raise TypeError(f"{msg} Got {arg!r:.100}.") TypeError: NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type Got Any.</code></p>
3
3,269
Unexpected character encountered while parsing value in azure durable function
<p>I have a problem with the <code>CallActivityAsync</code> function, I am trying to pass the value (<a href="https://www.web.eu/a?b=0123456789" rel="nofollow noreferrer">https://www.web.eu/a?b=0123456789</a>) to <code>ActivityTrigger</code> (to <code>GetWebContent</code>) and I still get the error:</p> <blockquote> <p><strong>Unexpected character encountered while parsing value: {. Path '', line 1, position 1</strong>. </p> </blockquote> <p>I do not know what's going on. I send via Postman <code>"0123456789"</code> the value and the next value is combined with URL. The value passed is a plain string. Could someone tell me what's going on? Where is the problem?</p> <pre><code>This exception was originally thrown at this call stack: Newtonsoft.Json.JsonTextReader.ReadStringValue(Newtonsoft.Json.ReadType) Newtonsoft.Json.JsonTextReader.ReadAsString() Newtonsoft.Json.JsonReader.ReadForType(Newtonsoft.Json.Serialization.JsonContract, bool) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(Newtonsoft.Json.JsonReader, System.Type, bool) Newtonsoft.Json.JsonSerializer.DeserializeInternal(Newtonsoft.Json.JsonReader, System.Type) Newtonsoft.Json.JsonSerializer.Deserialize(Newtonsoft.Json.JsonReader, System.Type) DurableTask.Core.Serializing.JsonDataConverter.Deserialize(string, System.Type) in JsonDataConverter.cs DurableTask.Core.TaskOrchestrationContext.ScheduleTaskInternal(string, string, string, System.Type, object[]) in TaskOrchestrationContext.cs System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) ... [Call Stack Truncated] </code></pre> <pre><code>[FunctionName(nameof(DurableHttpStart))] public async Task&lt;HttpResponseMessage&gt; Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "{functionName}")] HttpRequestMessage requestMessage, [DurableClient] IDurableClient durableClient, string functionName, ILogger logger) { var input = await requestMessage.Content.ReadAsAsync&lt;object&gt;(); var instanceId = await durableClient.StartNewAsync(functionName, input); logger.LogInformation($"Started orchestration with ID = '{instanceId}'."); return durableClient.CreateCheckStatusResponse(requestMessage, instanceId); } [FunctionName("Parse")] public async Task&lt;IActionResult&gt; Run([OrchestrationTrigger] IDurableOrchestrationContext context, ILogger log) { try { log.LogInformation("C# HTTP trigger function processed a request."); var value = context.GetInput&lt;string&gt;(); var result = new Result(); var link = await context.CallActivityAsync&lt;string&gt;(nameof(GetLink), value); result.Url = link; var webContent = await context.CallActivityAsync&lt;string&gt;(nameof(GetWebContent), link); var parsedContent = await context.CallActivityAsync&lt;string&gt;(nameof(RunParser), webContent); result.Data = parsedContent; return new OkObjectResult(result); } catch (Exception e) { Console.WriteLine(e); throw; } } [FunctionName("GetLink")] public static async Task&lt;string&gt; Run( [ActivityTrigger] string value, ILogger log) { var url = LinkHelper.CreateLink(value); return url; } [FunctionName("GetWebContent")] public static async Task&lt;IActionResult&gt; Run( [ActivityTrigger] string url, ILogger log) { log.LogInformation("C# 'GetWebContent' HTTP trigger function processed a request."); log.LogInformation($"Url from request body: {url}"); var content = await HttpHelper.GetWebPageSource(url); return content != null ? (IActionResult) new OkObjectResult(content) : new BadRequestObjectResult($"Provided url: {url} is bad. Try again later."); } </code></pre>
3
1,516
How do I suppress knit2pdf LaTeX output in the R console
<p>When running <code>knit2pdf()</code>, it does not suppress the LaTeX output when using <code>quiet = TRUE</code> within the R console. I am running <code>knitr v1.11</code>. A simple example would be:</p> <h2>test.Rnw file</h2> <pre><code>\documentclass[a4paper,12pt]{article} \begin{document} some stuff \end{document} </code></pre> <h2>R Code</h2> <pre><code>knitr::knit2pdf(input = "./test.Rnw", quiet = TRUE) </code></pre> <h2>Output to R console:</h2> <pre><code>This is pdfTeX, Version 3.14159265-2.6-1.40.16 (MiKTeX 2.9 64-bit) entering extended mode (test.tex LaTeX2e &lt;2015/01/01&gt; patch level 2 Babel &lt;3.9m&gt; and hyphenation patterns for 69 languages loaded. (C:\MiKTeX\tex\latex\base\article.cls Document Class: article 2014/09/29 v1.4h Standard LaTeX document class (C:\MiKTeX\tex\latex\base\size12.clo)) (C:\MiKTeX\tex\latex\graphics\graphicx.sty (C:\MiKTeX\tex\latex\graphics\keyval.sty) (C:\MiKTeX\tex\latex\graphics\graphics.sty (C:\MiKTeX\tex\latex\graphics\trig.sty) (C:\MiKTeX\tex\latex\00miktex\graphics.cfg) (C:\MiKTeX\tex\latex\pdftex-def\pdftex.def (C:\MiKTeX\tex\generic\oberdiek\infwarerr.sty) (C:\MiKTeX\tex\generic\oberdiek\ltxcmds.sty)))) (C:\MiKTeX\tex\latex\graphics\color.sty (C:\MiKTeX\tex\latex\00miktex\color.cfg )) (C:\MiKTeX\tex\latex\framed\framed.sty) (C:\MiKTeX\tex\latex\base\alltt.sty) (C:\MiKTeX\tex\latex\upquote\upquote.sty) (test.aux) (C:\MiKTeX\tex\context\base\supp-pdf.mkii [Loading MPS to PDF converter (version 2006.09.02).] ) [1{C:/Users/neastwood1/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map}] (test.aux) )&lt;C:/MiKTeX/fonts/type1/public/amsfonts/cm/cmr12.pfb&gt; Output written on test.pdf (1 page, 10374 bytes). Transcript written on test.log. This is pdfTeX, Version 3.14159265-2.6-1.40.16 (MiKTeX 2.9 64-bit) entering extended mode (test.tex LaTeX2e &lt;2015/01/01&gt; patch level 2 Babel &lt;3.9m&gt; and hyphenation patterns for 69 languages loaded. (C:\MiKTeX\tex\latex\base\article.cls Document Class: article 2014/09/29 v1.4h Standard LaTeX document class (C:\MiKTeX\tex\latex\base\size12.clo)) (C:\MiKTeX\tex\latex\graphics\graphicx.sty (C:\MiKTeX\tex\latex\graphics\keyval.sty) (C:\MiKTeX\tex\latex\graphics\graphics.sty (C:\MiKTeX\tex\latex\graphics\trig.sty) (C:\MiKTeX\tex\latex\00miktex\graphics.cfg) (C:\MiKTeX\tex\latex\pdftex-def\pdftex.def (C:\MiKTeX\tex\generic\oberdiek\infwarerr.sty) (C:\MiKTeX\tex\generic\oberdiek\ltxcmds.sty)))) (C:\MiKTeX\tex\latex\graphics\color.sty (C:\MiKTeX\tex\latex\00miktex\color.cfg )) (C:\MiKTeX\tex\latex\framed\framed.sty) (C:\MiKTeX\tex\latex\base\alltt.sty) (C:\MiKTeX\tex\latex\upquote\upquote.sty) (test.aux) (C:\MiKTeX\tex\context\base\supp-pdf.mkii [Loading MPS to PDF converter (version 2006.09.02).] ) [1{C:/Users/neastwood1/AppData/Local/MiKTeX/2.9/pdftex/config/pdftex.map}] (test.aux) )&lt;C:/MiKTeX/fonts/type1/public/amsfonts/cm/cmr12.pfb&gt; Output written on test.pdf (1 page, 10374 bytes). Transcript written on test.log. [1] "test.pdf" </code></pre> <h2>Session Info:</h2> <pre><code>R version 3.2.2 (2015-08-14) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1 locale: [1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252 LC_MONETARY=English_United Kingdom.1252 [4] LC_NUMERIC=C LC_TIME=English_United Kingdom.1252 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] knitr_1.11 loaded via a namespace (and not attached): [1] tools_3.2.2 RODBC_1.3-12 </code></pre> <p>My wish is to stop this output from returning to the console. I have thought about maybe running a call to <code>knit2pdf</code> using a shell command and piping the output to <code>&gt;NUL</code> but I am not sure if this would be wise or easy to do?</p>
3
1,683
elasticsearch bool filter should clause performance
<p>first query:</p> <pre><code> { "query" : { "filtered" : { "filter" : { "bool" : { "must" : [ {"term" : {"user1_id" : "1"}}, {"range" : {"day" : {"gte" : "2015-04-01", "lte" : "2015-04-30"}}} ] } } } } </code></pre> <p>In relational SQL, the first query equals to SQL:</p> <pre><code>select * from table where user1_id =1 and (day&gt;=2015-04-01 and day &lt;= 2015-04-30) </code></pre> <p>Second query:</p> <pre><code>{ "query" : { "filtered" : { "filter" : { "bool" : { "should" : [{"term" : {"user1_id" : "1"}}, {"term" : {"user2_id" : "1"}}], "must" : {"range" : {"day" : {"gte" : "2015-04-02", "lte" : "2015-04-30"}} }, "_cache" : true } } } } } </code></pre> <p>In relational SQL, the second query equals to SQL: </p> <pre><code>select * from table where (user1_id =1 or user2_id = 1) and (day&gt;=2015-04-01 and day &lt;= 2015-04-30) </code></pre> <p>The difference is, </p> <p>the first query only considers <code>user1_id</code>, while the second one also check <code>user2_id</code>.</p> <p>both <code>user1_id</code> and <code>user2_id</code> are indexed.</p> <p>However, the performance differs a lot. </p> <p>the first query took 5 seconds, while the second one took 20 seconds.</p> <p>Is there any better way for the second query?</p> <p>Mapping:</p> <pre><code> user1_id: type: "string" index: "not_analyzed" doc_values: true user2_id: type: "string" index: "not_analyzed" doc_values: true day: type: "date" format: "YYYY-MM-dd" ignore_malformed: true doc_values: true </code></pre> <p>If I run the first query twice, the first time is <code>user1_id</code>, the second time is <code>user2_id</code>, then combine two results. It is much faster than using the second query. </p> <p>Have 10 Billion documents in total. AWS, m2.4xlarge, 8 instances in total. </p> <p><code>/usr/bin/java -Xms30g -Xmx30g</code> </p>
3
1,134
Vega plot not displaying within a holoviz panel in jupyter notebook
<p>I find the <a href="https://github.com/holoviz/panel" rel="nofollow noreferrer">holoviz panel</a> a very interesting solution to building data visualisation dashboards. Unfortunately, I have some issues getting a vega plot of a node-link diagram to work within a panel in a jupyter notebook.</p> <p>The relevant imports etc:</p> <ul> <li><code>import panel</code></li> <li><code>pn.extension()</code></li> <li><code>from vega import Vega</code></li> </ul> <p>My findings:</p> <ul> <li>The vega import works nicely when used outside of a panel: the Vega specification copy/pasted from <a href="https://vega.github.io/editor/#/examples/vega/force-directed-layout" rel="nofollow noreferrer">https://vega.github.io/editor/#/examples/vega/force-directed-layout</a> is visualised as it should be using <code>Vega(spec)</code> (see screenshot 1).</li> <li>When using <code>pn.pane.Vega(spec)</code> I get an empty space. Running the visualisation externally using <code>pn.pane.Vega(spec).show()</code> and looking at the source code, I see that the div is empty (see screenshot 2).</li> </ul> <p>Any help with getting this working much appreciated...</p> <p>Thank you, jan.</p> <ul> <li>screenshot 1:<a href="https://i.stack.imgur.com/OK0ci.png" rel="nofollow noreferrer">screenshot1</a></li> <li>screenshot 2:<a href="https://i.stack.imgur.com/oumpo.png" rel="nofollow noreferrer">screenshot2</a></li> </ul> <p>Here is a minimal script to show the issue:</p> <pre><code>#!/usr/bin/env python import panel as pn from bokeh.plotting import output_notebook from vega import Vega pn.extension('vega') output_notebook() spec = { "$schema": "https://vega.github.io/schema/vega/v5.json", "width": 400, "height": 200, "data": [ { "name": "table", "values": [ {"category": "A", "amount": 28}, {"category": "B", "amount": 55}, {"category": "C", "amount": 43} ] } ], "scales": [ { "name": "xscale", "type": "band", "domain": {"data": "table", "field": "category"}, "range": "width" }, { "name": "yscale", "domain": {"data": "table", "field": "amount"}, "range": "height" } ], "marks": [ { "type": "rect", "from": {"data":"table"}, "encode": { "enter": { "x": {"scale": "xscale", "field": "category"}, "width": {"scale": "xscale", "band": 1}, "y": {"scale": "yscale", "field": "amount"}, "y2": {"scale": "yscale", "value": 0} }, "update": { "fill": {"value": "steelblue"} } } } ] } Vega(spec) # =&gt; shows barchart =&gt; OK pn.Column(pn.panel("## Vega test"), pn.pane.Vega(spec), pn.panel("_end of test_")) # =&gt; shows "Vega test", then empty space, the "end of test" pn.Column(pn.panel("## Vega test"), pn.panel(spec), pn.panel("_end of test_")) # =&gt; shows "Vega test", then empty space, the "end of test" </code></pre>
3
1,273
How do you delete an Item from a ListView from a dialog box class?
<p>I made my own dialog box class. This class has a button to delete an item from a listview(which is the main acctivity_main.xml). When I push the delete button the item does not get deleted. </p> <p>I have seen this topic <a href="https://stackoverflow.com/questions/4698386/android-how-to-remove-an-item-from-a-listview-and-arrayadapter">Android: how to remove an item from a listView and arrayAdapter</a>. It just appears the user does not know how to get the item index correctly, which I believe I have done correctly.</p> <p><a href="https://stackoverflow.com/questions/2558591/remove-listview-items-in-android">Remove ListView items in Android</a> This one is pretty close. But in my code I created my own dialog, this one is using a positive and negative button. I am passing variables between my dialog class and to the mainActivity. </p> <p>my onClickListener in OnCreate withing the MainActivity</p> <pre><code> mFoodDataAdapter = new FoodDataAdapter(); final ListView listFoodData = (ListView) findViewById(R.id.listView); listFoodData.setAdapter(mFoodDataAdapter); //Handle clicks on the ListView listFoodData.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; adapter, View view, int whichItem, long id) { FoodData tempFoodData = mFoodDataAdapter.getItem(whichItem); //create a new dialog window DialogShowFood dialog = new DialogShowFood(); // send in a reference to the note to be shown dialog.sendFoodDataSelected(tempFoodData); FoodDataAdapter adapter1 = new FoodDataAdapter(); /*this is where i send the data to the DialogShowFood.java*/ dialog.sendFoodDataAdapter(adapter1, whichItem); // show the dialog window with the note in it dialog.show(getFragmentManager(),""); } }); </code></pre> <p>Here is my class for the dialog "DialogShowFood.java"</p> <pre><code>public class DialogShowFood extends DialogFragment { FoodData mFood; MainActivity.FoodDataAdapter mAdapter; int mitemToDelete; @Override public Dialog onCreateDialog(Bundle savedInstanceState){ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View dialogView = inflater.inflate(R.layout.dialog_show_food, null); Button btnDelete = (Button) dialogView.findViewById(R.id.btnDelete); builder.setView(dialogView).setMessage("Your food"); /*this sends the item to delete to the adapter*/ btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mAdapter.deleteFoodData(mitemToDelete); dismiss(); } }); return builder.create(); } /*this gets the data to delete from the MainActivity*/ public void sendFoodDataAdapter(MainActivity.FoodDataAdapter adapter1, int whichItem) { mAdapter = adapter1; mitemToDelete = whichItem; } } </code></pre> <p>The function inside the adapter</p> <pre><code> /*this is the function in the base adapter to delete the item*/ public void deleteFoodData(int n){ Toast.makeText(MainActivity.this,Integer.toString(n), Toast.LENGTH_SHORT).show(); foodDataList.remove(n); notifyDataSetChanged(); } </code></pre> <p>The Toast outputs the proper indexes of the item to delete, it just does not delete the item for some reason. </p>
3
1,392
Customized Windows 10 Backup not porting well
<p>So basically I customized a Windows 10 install. I have the PerfLogs, Program Data, Temp and Users folders in C:\ replaced as symlinks to their actual location to D:\</p> <p>The purpose being, I will only keep a image backup of C:\ and when the need arises that I need a fresh install of the OS, I will only overwrite the whole C: drive with the backup and don't even have to touch my old user profiles. It works without a glitch even as I moved my C: to an SSD.</p> <p>I did it with a few simple tricks (I don't exactly remember everything I did, but once I got the build right, I just left it as it is as I thought I would never have to touch it again):</p> <ol> <li><p>I remembered following tips and other guides like this:</p> <p><a href="https://commaster.net/content/windows-installation-tips-moving-user-folder-another-drive" rel="nofollow">https://commaster.net/content/windows-installation-tips-moving-user-folder-another-drive</a></p> <ul> <li>the difference being I used symlinks instead of junctions with mklink command.</li> </ul></li> <li><p>Some modification with registry and other files.</p></li> <li>Several stages of booting until everything has been transferred and having windows re-create the profiles and configurations.</li> </ol> <p>Anyways, I had to fix my Mom's PC, which was in a state of disarray as she thought she had to save all her files in C:\ and NEVER in Documents. I opted to install my customized Windows install, so if I need to fix it again, it would just be a cinch.</p> <p>Before building this custom Windows install, I've made backups of my system with my usual backup tool, Paragon Partition Manager. They worked fine and when I had to change PC builds, such as changing my motherboard, all I had to do was change the drivers. So I thought with my custom Windows 10 install, that's all I had to do for my Mom's PC.</p> <p>But I kept running into problems with Window's User Profile Service. At first, it was having difficulty loading the Administrator account and seems to be defaulting to C:\Windows\System32\config\systemprofile, as it cannot seem to write to it's D:\Users\Administrator folder. I quickly fixed that, but, still, it can't load the Start Menu and other services. </p> <p>The only one that was working <em>almost</em> completely was the user (just one - me) that was existing when I created the backup AND only works with a copy of the corresponding folder in D:\Users\<em>MyUsername</em>.</p> <p>Obviously I wanted to create a user just for my Mom and one that is <em>completely</em> working and I don't wanna leave a copy of D:\Users\<em>MyUsername</em> in her PC. I figured all I had to do was create a user profile in Control Panel and Windows will recreate everything and all the configurations. The add user service in Control Panel wasn't working with Administrator, but only with <em>MyUsername</em>. But whenever I try to sign in to the newly created user, the "User Profile Service failed to sign-in" keeps popping up. I can sign into it in safe mode, at the first seemingly recreating everything with the first-time-sign-in-welcome-screen, but a lot of the services are not working. So creating another user profile with this new profile doesn't work. </p> <p>More notably, I've tried:</p> <pre><code>net user username /add </code></pre> <p>and adding through advanced user profiles:</p> <pre><code>control userpasswords2 </code></pre> <p>But the new registry keys for the new users in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList never gets created -- even after I go safe mode and manage to sign in to the new users.</p> <p>I've also considered it might be a user permission issue, somehow being carried over from my PC build (if that makes sense, it still doesn't to me). Anyways, so with the newly created user logged in with safe mode, I tried changing permission for C: and D: for every single group to "Full Control". Then from that newly created user, create another user either through <code>net user username /add</code> or <code>control userpasswords2</code>. I even tried booting to Linux LiveCD and chmod-ding everything to 777 (I'm not even sure how that transfer to an NTFS. Then I try to sign in and even if I can forcibly sign in, it just isn't a glitch-free user profile.</p>
3
1,146
Yii: CHtml image link - how to get to the image in one table through relation in other table?
<p>I'm trying to display link to an <em>album/view</em> through image that belongs to that album. I have my model 'Album' and there I have the relation with my 'Photo' model, which represents table where pictures are saved(or to be more accurate-picture names, pictures are saved in the folder 'uploads': </p> <pre><code>public function relations() { return array( 'photos' =&gt; array(self::HAS_MANY, 'Photo', 'album_id'), ); } </code></pre> <p>Now I'm displaying <em>album/index</em> view, where I parse $dataProvider object which contains all my albums. Now that $dataProvider is parsed to a <em>_view</em> view and there I'm trying to access pictures (actually I just need one picture per album) that belongs to each album displayed. That picture will represent the link to an <em>album/view</em> view where one can see all pictures belonging to that album. I have no ide how to do that. I've tried with: </p> <pre><code>CHtml::link( CHtml::image(Yii::app()-&gt;request-&gt;baseUrl."/uploads/thumbs/".$data-&gt;photos-&gt;name), array('view', 'id'=&gt;$data-&gt;id)); </code></pre> <p>and I got the error: <strong>Trying to get property of non-object</strong></p> <p>PS: I have no problem with displaying all pictures within one album in <em>album/view</em> view (but these cross controllers, cross table whatever things are giving me hard time). There I have nested <em>photo/index</em> view, and the pictures are displayed like this: </p> <pre><code>echo CHtml::link( CHtml::image(Yii::app()-&gt;request-&gt;baseUrl."/uploads/thumbs/".$data-&gt;name), Yii::app()-&gt;request-&gt;baseUrl."/uploads/".$data-&gt;name ), </code></pre> <p>(as a link I'm displaying thumbnail of an image, that why i have "/uploads/thumbs/". "name" is column in table which represents filename of an image)</p> <p><strong>Edit 1</strong></p> <p>@Stu</p> <p>in my album where I have three photos this: </p> <pre><code>array (size=3) 0 =&gt; object(Photo)[84] private '_uploads' =&gt; null private '_new' (CActiveRecord) =&gt; boolean false private '_attributes' (CActiveRecord) =&gt; array (size=6) 'id' =&gt; string '1' (length=1) 'album_id' =&gt; string '1' (length=1) 'name' =&gt; string 'WP_20140907_18_34_12_Pro.jpg' (length=28) 'caption' =&gt; string 'Balerina' (length=8) 'date_created' =&gt; string '2014-10-27 19:56:13' (length=19) 'date_updated' =&gt; null private '_related' (CActiveRecord) =&gt; array (size=0) empty private '_c' (CActiveRecord) =&gt; null private '_pk' (CActiveRecord) =&gt; string '1' (length=1) private '_alias' (CActiveRecord) =&gt; string 't' (length=1) private '_errors' (CModel) =&gt; array (size=0) empty private '_validators' (CModel) =&gt; null private '_scenario' (CModel) =&gt; string 'update' (length=6) private '_e' (CComponent) =&gt; null private '_m' (CComponent) =&gt; null 1 =&gt; object(Photo)[85] private '_uploads' =&gt; null private '_new' (CActiveRecord) =&gt; boolean false private '_attributes' (CActiveRecord) =&gt; array (size=6) 'id' =&gt; string '2' (length=1) 'album_id' =&gt; string '1' (length=1) 'name' =&gt; string 'WP_20140907_18_49_33_Pro.jpg' (length=28) 'caption' =&gt; string '' (length=0) 'date_created' =&gt; string '2014-10-27 19:56:45' (length=19) 'date_updated' =&gt; null private '_related' (CActiveRecord) =&gt; array (size=0) empty private '_c' (CActiveRecord) =&gt; null private '_pk' (CActiveRecord) =&gt; string '2' (length=1) private '_alias' (CActiveRecord) =&gt; string 't' (length=1) private '_errors' (CModel) =&gt; array (size=0) empty private '_validators' (CModel) =&gt; null private '_scenario' (CModel) =&gt; string 'update' (length=6) private '_e' (CComponent) =&gt; null private '_m' (CComponent) =&gt; null 2 =&gt; object(Photo)[86] private '_uploads' =&gt; null private '_new' (CActiveRecord) =&gt; boolean false private '_attributes' (CActiveRecord) =&gt; array (size=6) 'id' =&gt; string '3' (length=1) 'album_id' =&gt; string '1' (length=1) 'name' =&gt; string 'WP_20140907_18_49_38_Pro.jpg' (length=28) 'caption' =&gt; string '' (length=0) 'date_created' =&gt; string '2014-10-27 20:00:41' (length=19) 'date_updated' =&gt; null private '_related' (CActiveRecord) =&gt; array (size=0) empty private '_c' (CActiveRecord) =&gt; null private '_pk' (CActiveRecord) =&gt; string '3' (length=1) private '_alias' (CActiveRecord) =&gt; string 't' (length=1) private '_errors' (CModel) =&gt; array (size=0) empty private '_validators' (CModel) =&gt; null private '_scenario' (CModel) =&gt; string 'update' (length=6) private '_e' (CComponent) =&gt; null private '_m' (CComponent) =&gt; null </code></pre> <p><strong>Edit 2</strong></p> <p>This is really driving me crazy... In the same Album model, I have the other relation with other table "user": </p> <pre><code>public function relations() { return array( 'owner' =&gt; array(self::BELONGS_TO, 'User', 'owner_id'), ... ); } </code></pre> <p>And I have no problem accessing attributes in the User model within album view, checked the var_dump($data->owner): </p> <pre><code>object(User)[83] public 'passSave' =&gt; null public 'passRepeat' =&gt; null private '_new' (CActiveRecord) =&gt; boolean false private '_attributes' (CActiveRecord) =&gt; array (size=7) 'id' =&gt; string '1' (length=1) 'email' =&gt; string 'fdhghhg@gmail.com' (length=25) 'username' =&gt; string 'admin' (length=5) 'firstname' =&gt; string 'Emina' (length=5) 'lastname' =&gt; string 'Hasanović' (length=10) 'pass' =&gt; string 'sa1aY64JOY94w' (length=13) 'date_created' =&gt; string '2014-10-27 11:20:55' (length=19) private '_related' (CActiveRecord) =&gt; array (size=0) empty private '_c' (CActiveRecord) =&gt; null private '_pk' (CActiveRecord) =&gt; string '1' (length=1) private '_alias' (CActiveRecord) =&gt; string 't' (length=1) private '_errors' (CModel) =&gt; array (size=0) empty private '_validators' (CModel) =&gt; null private '_scenario' (CModel) =&gt; string 'update' (length=6) private '_e' (CComponent) =&gt; null private '_m' (CComponent) =&gt; null </code></pre> <p>It's the exact same output as with var_dump($data->lastPhoto) (just with it's own attributes), but when I try with $data->lastPhoto->name it's <strong>Trying to get property of non-object</strong>, while $data->owner->username works just well</p> <p><strong>Edit 3</strong></p> <p>Here is my Album model: </p> <pre><code>&lt;?php /** * This is the model class for table "album". * * The followings are the available columns in table 'album': * @property string $id * @property string $name * @property string $owner_id * @property integer $shareable * @property string $date_created * * The followings are the available model relations: * @property User $owner * @property Photo[] $photos */ class Album extends CActiveRecord { public function tableName() { return 'album'; } public function rules() { return array( array('name', 'required'), array('shareable', 'numerical', 'integerOnly'=&gt;true), array('name', 'length', 'max'=&gt;100), array('owner_id', 'length', 'max'=&gt;10), array('name', 'safe', 'on'=&gt;'search'), ); } protected Function beforeSave() { if(parent::beforeSave()) { if($this-&gt;isNewRecord) { $this-&gt;owner_id=Yii::app()-&gt;user-&gt;getId(); } return true; } else return false; } public function relations() { return array( 'owner' =&gt; array(self::BELONGS_TO, 'User', 'owner_id'), 'photos' =&gt; array(self::HAS_MANY, 'Photo', 'album_id'), 'lastPhoto' =&gt; array(self::HAS_ONE, 'Photo', 'album_id', 'order'=&gt;'lastPhoto.id DESC'), ); } public function scopes() { return array( 'mine'=&gt;array( 'order'=&gt;'date_created DESC', 'condition'=&gt;'owner_id=:owner', 'params'=&gt;array( 'owner'=&gt;Yii::app()-&gt;user-&gt;getId(), ) ) ); } public function attributeLabels() { return array( 'id' =&gt; 'ID', 'name' =&gt; 'Name', 'owner_id' =&gt; 'Owner', 'shareable' =&gt; 'Shareable', 'date_created' =&gt; 'Date Created', ); } public function search() { $criteria=new CDbCriteria; $criteria-&gt;compare('name',$this-&gt;name,true); $criteria-&gt;compare('shareable',$this-&gt;shareable); $criteria-&gt;scopes='mine'; return new CActiveDataProvider($this, array( 'criteria'=&gt;$criteria, )); } public static function model($className=__CLASS__) { return parent::model($className); } } </code></pre> <p>Controller action is(from AlbumController):</p> <pre><code>public function actionIndex() { $dataProvider=new CActiveDataProvider('Album', array( 'criteria'=&gt;array( 'condition'=&gt;'shareable=1', 'order'=&gt;'date_created DESC' ) ) ); $this-&gt;render('index',array( 'dataProvider'=&gt;$dataProvider, )); } </code></pre> <p>And the view files are album/index.php:</p> <pre><code>&lt;h1&gt;Albums&lt;/h1&gt; &lt;?php $this-&gt;widget('zii.widgets.CListView', array( 'dataProvider'=&gt;$dataProvider, 'itemView'=&gt;'_view', )); ?&gt; </code></pre> <p>_view.php:</p> <pre><code>&lt;div class="view"&gt; &lt;h&gt;&lt;?php // echo CHtml::encode($data-&gt;name); ?&gt;&lt;/h1&gt; &lt;h1&gt; echo CHtml::link( CHtml::image(Yii::app()-&gt;request-&gt;baseUrl."/uploads/thumbs".$data-&gt;lastPhoto-&gt;name), array('view', 'id'=&gt;$data-&gt;id)); ?&gt; &lt;/h1&gt; &lt;br /&gt; &lt;br /&gt; &lt;b&gt;&lt;?php echo CHtml::encode($data-&gt;getAttributeLabel('shareable')); ?&gt;:&lt;/b&gt; &lt;?php echo CHtml::encode($data-&gt;shareable)? 'Public' : 'No'; ?&gt; &lt;br /&gt; &lt;b&gt;&lt;?php echo 'Created by'; ?&gt;:&lt;/b&gt; &lt;?php echo CHtml::encode($data-&gt;owner-&gt;fullName()); ?&gt; &lt;b&gt;&lt;?php echo 'on Date'; ?&gt;:&lt;/b&gt; &lt;?php echo CHtml::encode($data-&gt;date_created); ?&gt; &lt;br /&gt; &lt;/div&gt; </code></pre>
3
5,532
main.js:1 Uncaught TypeError:Cannot read property 'prototype' of undefined
<p>I have upgraded my project from Angular 8 to Angular 11. it runs fine in DEV mode, but if I run it in Prod mode or build it and deploy it to web server. I am getting below error when launching the website in browser:</p> <pre><code>main.js:1 Uncaught TypeError: Cannot read property 'prototype' of undefined at main.js:1 at main.js:1 at Module.zUnb (main.js:1) at l (runtime.js:1) at Object.0 (main.js:1) at l (runtime.js:1) at t (runtime.js:1) at Array.r [as push] (runtime.js:1) at main.js:1 </code></pre> <p>Something wrong when it compiles the code to bundles using webpack, I guess. package.json before upgrade:</p> <pre><code>{ &quot;name&quot;: &quot;xxxxxx&quot;, &quot;version&quot;: &quot;1.1.1&quot;, &quot;license&quot;: &quot;UNLICENSED&quot;, &quot;scripts&quot;: { &quot;ng&quot;: &quot;ng&quot;, &quot;start&quot;: &quot;ng serve&quot;, &quot;start-ssl&quot;: &quot;ng serve --proxy-config proxy.conf.json --ssl true&quot;, &quot;start-nossl&quot;: &quot;ng serve --proxy-config proxy.conf.json&quot;, &quot;build&quot;: &quot;ng build&quot;, &quot;build-prod&quot;: &quot;node --max_old_space_size=2000000 ./node_modules/@angular/cli/bin/ng build --prod --base-href /caui/&quot;, &quot;build-prod19&quot;: &quot;node --max_old_space_size=2000000 ./node_modules/@angular/cli/bin/ng build --prod --base-href /caui19/&quot;, &quot;build-test&quot;: &quot;node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng test --watch=false -cc&quot;, &quot;test&quot;: &quot;ng test&quot;, &quot;lint&quot;: &quot;ng lint&quot;, &quot;e2e&quot;: &quot;ng e2e&quot; }, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@angular/animations&quot;: &quot;8.2.0&quot;, &quot;@angular/common&quot;: &quot;8.2.0&quot;, &quot;@angular/compiler&quot;: &quot;8.2.0&quot;, &quot;@angular/compiler-cli&quot;: &quot;8.2.0&quot;, &quot;@angular/core&quot;: &quot;8.2.0&quot;, &quot;@angular/forms&quot;: &quot;8.2.0&quot;, &quot;@angular/platform-browser&quot;: &quot;8.2.0&quot;, &quot;@angular/platform-browser-dynamic&quot;: &quot;8.2.0&quot;, &quot;@angular/platform-server&quot;: &quot;8.2.0&quot;, &quot;@angular/router&quot;: &quot;8.2.0&quot;, &quot;@angular/cdk&quot;: &quot;8.1.2&quot;, &quot;@ng-bootstrap/ng-bootstrap&quot;: &quot;5.1.1&quot;, &quot;@ngrx/core&quot;: &quot;^1.2.0&quot;, &quot;@ngrx/effects&quot;: &quot;^8.2.0&quot;, &quot;@ngrx/router-store&quot;: &quot;^8.2.0&quot;, &quot;@ngrx/store&quot;: &quot;^8.2.0&quot;, &quot;@swimlane/ngx-datatable&quot;: &quot;15.0.2&quot;, &quot;@types/lodash&quot;: &quot;^4.14.136&quot;, &quot;ag-grid-angular&quot;: &quot;^20.2.0&quot;, &quot;ag-grid-community&quot;: &quot;^20.2.0&quot;, &quot;angular-tree-component&quot;: &quot;^8.4.0&quot;, &quot;angular2-csv&quot;: &quot;^0.2.9&quot;, &quot;angular2-hotkeys&quot;: &quot;^2.1.5&quot;, &quot;core-js&quot;: &quot;^3.1.4&quot;, &quot;font-awesome&quot;: &quot;^4.7.0&quot;, &quot;lodash&quot;: &quot;^4.17.15&quot;, &quot;ng-http-loader&quot;: &quot;^6.0.1&quot;, &quot;ngrx-store-localstorage&quot;: &quot;^8.0.0&quot;, &quot;ngx-clipboard&quot;: &quot;^12.2.0&quot;, &quot;primeicons&quot;: &quot;^2.0.0&quot;, &quot;primeng&quot;: &quot;^8.0.2&quot;, &quot;reselect&quot;: &quot;^4.0.0&quot;, &quot;rxjs&quot;: &quot;^6.5.2&quot;, &quot;rxjs-compat&quot;: &quot;6.5.2&quot;, &quot;zone.js&quot;: &quot;^0.10.0&quot; }, &quot;devDependencies&quot;: { &quot;@angular-devkit/build-angular&quot;: &quot;~0.802.0&quot;, &quot;@angular/cli&quot;: &quot;8.2.0&quot;, &quot;@angular/language-service&quot;: &quot;8.2.0&quot;, &quot;@types/jasmine&quot;: &quot;^3.3.16&quot;, &quot;@types/jasminewd2&quot;: &quot;^2.0.6&quot;, &quot;@types/node&quot;: &quot;~8.9.4&quot;, &quot;codelyzer&quot;: &quot;^5.1.0&quot;, &quot;jasmine-core&quot;: &quot;^3.4.0&quot;, &quot;jasmine-spec-reporter&quot;: &quot;^4.2.1&quot;, &quot;karma&quot;: &quot;^4.2.0&quot;, &quot;karma-chrome-launcher&quot;: &quot;^2.2.0&quot;, &quot;karma-cli&quot;: &quot;^2.0.0&quot;, &quot;karma-coverage-istanbul-reporter&quot;: &quot;^2.1.0&quot;, &quot;karma-jasmine&quot;: &quot;^2.0.1&quot;, &quot;karma-jasmine-html-reporter&quot;: &quot;^1.4.2&quot;, &quot;ngrx-store-logger&quot;: &quot;^0.2.4&quot;, &quot;protractor&quot;: &quot;~5.1.2&quot;, &quot;ts-node&quot;: &quot;~8.3.0&quot;, &quot;tslint&quot;: &quot;^5.18.0&quot;, &quot;typescript&quot;: &quot;^3.5.3&quot;, &quot;webpack&quot;: &quot;^4.39.1&quot; } </code></pre> <p>package.json after upgrade:</p> <pre><code>{ &quot;name&quot;: &quot;xxxxxx&quot;, &quot;version&quot;: &quot;18.5.0&quot;, &quot;license&quot;: &quot;UNLICENSED&quot;, &quot;scripts&quot;: { &quot;ng&quot;: &quot;ng&quot;, &quot;start&quot;: &quot;ng serve&quot;, &quot;start-ssl&quot;: &quot;node --max_old_space_size=2000000 ./node_modules/@angular/cli/bin/ng serve --proxy-config proxy.conf.json --ssl true --prod&quot;, &quot;start-nossl&quot;: &quot;node --max_old_space_size=2000000 ./node_modules/@angular/cli/bin/ng serve --proxy-config proxy.conf.json --prod&quot;, &quot;build&quot;: &quot;ng build&quot;, &quot;build-prod&quot;: &quot;node --max_old_space_size=2000000 ./node_modules/@angular/cli/bin/ng build --prod --base-href /caui/&quot;, &quot;build-prod19&quot;: &quot;node --max_old_space_size=2000000 ./node_modules/@angular/cli/bin/ng build --prod --base-href /caui19/&quot;, &quot;build-test&quot;: &quot;node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng test --watch=false -cc&quot;, &quot;test&quot;: &quot;ng test&quot;, &quot;lint&quot;: &quot;ng lint&quot;, &quot;e2e&quot;: &quot;ng e2e&quot; }, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@angular/animations&quot;: &quot;~11.2.1&quot;, &quot;@angular/common&quot;: &quot;~11.2.1&quot;, &quot;@angular/compiler&quot;: &quot;~11.2.1&quot;, &quot;@angular/core&quot;: &quot;~11.2.1&quot;, &quot;@angular/forms&quot;: &quot;~11.2.1&quot;, &quot;@angular/platform-browser&quot;: &quot;~11.2.1&quot;, &quot;@angular/platform-browser-dynamic&quot;: &quot;~11.2.1&quot;, &quot;@angular/router&quot;: &quot;~11.2.1&quot;, &quot;@angular/cdk&quot;: &quot;11.1.1&quot;, &quot;@ng-bootstrap/ng-bootstrap&quot;: &quot;5.1.1&quot;, &quot;@ngrx/core&quot;: &quot;^1.2.0&quot;, &quot;@ngrx/effects&quot;: &quot;^11.0.1&quot;, &quot;@ngrx/router-store&quot;: &quot;^11.0.1&quot;, &quot;@ngrx/store&quot;: &quot;^11.0.1&quot;, &quot;@swimlane/ngx-datatable&quot;: &quot;19.0.0&quot;, &quot;@types/lodash&quot;: &quot;4.14.160&quot;, &quot;@types/mousetrap&quot;: &quot;^1.6.5&quot;, &quot;mousetrap&quot;: &quot;^1.6.5&quot;, &quot;ag-grid-angular&quot;: &quot;^25.0.1&quot;, &quot;ag-grid-community&quot;: &quot;^25.0.1&quot;, &quot;angular-tree-component&quot;: &quot;^8.5.6&quot;, &quot;angular2-csv&quot;: &quot;^0.2.9&quot;, &quot;core-js&quot;: &quot;^3.8.3&quot;, &quot;font-awesome&quot;: &quot;^4.7.0&quot;, &quot;lodash&quot;: &quot;^4.17.15&quot;, &quot;ng-http-loader&quot;: &quot;^9.1.0&quot;, &quot;ngrx-store-localstorage&quot;: &quot;^10.1.2&quot;, &quot;ngx-clipboard&quot;: &quot;^14.0.1&quot;, &quot;primeicons&quot;: &quot;^4.1.0&quot;, &quot;primeng&quot;: &quot;^11.2.0&quot;, &quot;reselect&quot;: &quot;^4.0.0&quot;, &quot;rxjs&quot;: &quot;~6.6.0&quot;, &quot;rxjs-compat&quot;: &quot;~6.6.0&quot;, &quot;tslib&quot;: &quot;^2.0.0&quot;, &quot;zone.js&quot;: &quot;~0.11.3&quot; }, &quot;devDependencies&quot;: { &quot;@angular-devkit/build-angular&quot;: &quot;~0.1102.1&quot;, &quot;@angular/cli&quot;: &quot;~11.2.1&quot;, &quot;@angular/compiler-cli&quot;: &quot;~11.2.1&quot;, &quot;@types/jasmine&quot;: &quot;~3.6.0&quot;, &quot;@types/node&quot;: &quot;^12.11.1&quot;, &quot;codelyzer&quot;: &quot;^6.0.0&quot;, &quot;jasmine-core&quot;: &quot;~3.6.0&quot;, &quot;jasmine-spec-reporter&quot;: &quot;~5.0.0&quot;, &quot;karma&quot;: &quot;~5.2.0&quot;, &quot;karma-chrome-launcher&quot;: &quot;~3.1.0&quot;, &quot;karma-coverage&quot;: &quot;~2.0.3&quot;, &quot;karma-jasmine&quot;: &quot;~4.0.0&quot;, &quot;karma-jasmine-html-reporter&quot;: &quot;^1.5.0&quot;, &quot;protractor&quot;: &quot;~7.0.0&quot;, &quot;ts-node&quot;: &quot;~8.3.0&quot;, &quot;tslint&quot;: &quot;~6.1.0&quot;, &quot;typescript&quot;: &quot;~4.1.2&quot;, &quot;ngrx-store-logger&quot;: &quot;^0.2.4&quot;, &quot;webpack&quot;: &quot;^4.39.1&quot; } } </code></pre> <p>tsconfig.json</p> <pre><code>{ &quot;compileOnSave&quot;: false, &quot;compilerOptions&quot;: { &quot;outDir&quot;: &quot;./dist/out-tsc&quot;, &quot;baseUrl&quot;: &quot;src&quot;, &quot;sourceMap&quot;: true, &quot;declaration&quot;: false, &quot;downlevelIteration&quot;: true, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;emitDecoratorMetadata&quot;: true, &quot;experimentalDecorators&quot;: true, &quot;target&quot;: &quot;es5&quot;, &quot;module&quot;: &quot;esnext&quot;, &quot;typeRoots&quot;: [ &quot;node_modules/@types&quot; ], &quot;lib&quot;: [ &quot;es2018&quot;, &quot;dom&quot; ] }, &quot;angularCompilerOptions&quot;: { &quot;enableI18nLegacyMessageIdFormat&quot;: false } } </code></pre> <p>Any idea what could be wrong?</p>
3
5,518
Exporting data to excel with PHP
<p>I'm making a simple form that asks for 2 dates , when inputted by the user and submitted a table will appear with the data in that date range. -&gt; this works</p> <p>code :</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt; &lt;title&gt;SWI report&lt;/title&gt; &lt;style&gt; table { font-family: Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #ddd; padding: 8px; } tr:nth-child(even) { background-color: #f2f2f2; } tr:hover { background-color: #ddd; } th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form method=&quot;post&quot; action=&quot;&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;&quot;&gt; startdate: &lt;input type=&quot;date&quot; name=&quot;from_date&quot;&gt; enddate: &lt;input type=&quot;date&quot; name=&quot;to_date&quot;&gt; &lt;input type=&quot;submit&quot; name=&quot;date&quot; id=&quot;date&quot;&gt; &lt;/form&gt; &lt;div&gt; &lt;!-- excel export !--&gt; &lt;form action=&quot;&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;&quot; method=&quot;POST&quot;&gt; &lt;button type=&quot;submit&quot; name=&quot;excel&quot; value=&quot;excel&quot; id='excel'&gt; Export to excel&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php require('settings.php'); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); if (isset($_POST[&quot;date&quot;])) { $startDate = date(&quot;Y-m-d&quot;, strtotime($_POST['from_date'])); $endDate = date(&quot;Y-m-d&quot;, strtotime($_POST['to_date'])); $sql = &quot;SELECT latestv.* from( select distinct Werkomschrijving_nr from POH_GL4 where versie Between ? and ? ) changedw left join (select Werkomschrijving_nr, max(versie) AS maxdate, omschrijving from POH_GL4 group by Werkomschrijving_nr,omschrijving) latestv on latestv.Werkomschrijving_nr = changedw.Werkomschrijving_nr&quot;; $stmt = $db-&gt;prepare($sql); $stmt-&gt;execute([$startDate, $endDate]); $result = $stmt-&gt;fetchAll(); echo &quot;&lt;table&gt;&quot;; echo &quot;&lt;tr&gt;&lt;th&gt;nr werkomschrijving&lt;/th&gt;&lt;th&gt;Last change date &lt;/th&gt;&lt;th&gt;Omschrijving&lt;/th&gt;&lt;/tr&gt;&quot;; foreach ($result as $key =&gt; $row) { echo &quot;&lt;tr&gt;&quot;; echo &quot;&lt;td&gt;&quot; . $row['Werkomschrijving_nr'] . &quot;&lt;/td&gt;&quot;; echo &quot;&lt;td&gt;&quot; . $row['maxdate'] . &quot;&lt;/td&gt;&quot;; echo &quot;&lt;td&gt;&quot; . $row['omschrijving'] . &quot;&lt;/td&gt;&quot;; echo &quot;&lt;/tr&gt;&quot;; } echo &quot;&lt;/table&gt;&quot;; if (!empty($_POST)) { if (empty($result)) { echo '&lt;/br&gt;'; echo 'no results for this timeframe'; } } } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I want to export the data in the table to excel but I cant seem to make it work. I tried putting the table data in a session but when I try to click on the export to excel button it looks like it just wipes the data. can someone help me on this one ?</p> <p>kind regards</p>
3
2,038
Why are the buttons inside the UIView squashed to the top?
<p>I have installed the <code>ABVideoRangeSlider</code> pod into my project, it all works fine besides that the start, end and progress sliders are squashed to the top. Here's my code:</p> <pre class="lang-swift prettyprint-override"><code>import Foundation import AVFoundation import UIKit import Photos import AVKit import ABVideoRangeSlider class SliderTest: UIViewController, ABVideoRangeSliderDelegate { var url: URL? var rangeSlider: ABVideoRangeSlider! let rangeView: UIView = { let view = UIView() view.backgroundColor = .systemRed return view }() override func viewDidLoad() { super.viewDidLoad() AppUtility.lockOrientation(.portrait) view.backgroundColor = .lightText self.rangeSlider = ABVideoRangeSlider() rangeView.addSubview(rangeSlider) self.view.addSubview(rangeView) view.bringSubviewToFront(rangeView) rangeView.bringSubviewToFront(rangeSlider) rangeView.translatesAutoresizingMaskIntoConstraints = false self.rangeView.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 20, paddingBottom: 20, paddingRight: 20, width: 0, height: 40) self.rangeSlider.delegate = self rangeSlider.frame = CGRect(x: 0, y: 0, width: 40, height: 40) rangeSlider.centerXAnchor.constraint(equalToSystemSpacingAfter: rangeView.centerXAnchor, multiplier: 1).isActive = true rangeSlider.centerYAnchor.constraint(equalToSystemSpacingBelow: rangeView.centerYAnchor, multiplier: 1).isActive = true rangeSlider.widthAnchor.constraint(equalToConstant: 200).isActive = true rangeSlider.heightAnchor.constraint(equalToConstant: 40).isActive = true rangeSlider.translatesAutoresizingMaskIntoConstraints = false rangeSlider.contentMode = .scaleToFill rangeSlider.clipsToBounds = false rangeSlider.autoresizesSubviews = true rangeSlider.clearsContextBeforeDrawing = true rangeSlider.isOpaque = true rangeSlider.semanticContentAttribute = .unspecified rangeSlider.isUserInteractionEnabled = true self.rangeSlider.setVideoURL(videoURL: url!) self.rangeSlider.minSpace = 5.0 self.rangeSlider.maxSpace = 30.0 self.rangeSlider.setStartPosition(seconds: 0.0) self.rangeSlider.setEndPosition(seconds: 30.0) self.rangeSlider.updateProgressIndicator(seconds: 0.0) self.rangeSlider.updateThumbnails() } func didChangeValue(videoRangeSlider: ABVideoRangeSlider, startTime: Float64, endTime: Float64) { print(startTime) // Prints the position of the Start indicator in seconds print(endTime) // Prints the position of the End indicator in seconds } func indicatorDidChangePosition(videoRangeSlider: ABVideoRangeSlider, position: Float64) { print(position) // Prints the position of the Progress indicator in seconds } } </code></pre> <p>I've also downloaded the example project to see what's wrong, but I don't know why what's the problem.</p> <p>My project:</p> <p><a href="https://i.stack.imgur.com/P9OJ2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P9OJ2.png" alt="enter image description here"></a></p> <p>example project:</p> <p><a href="https://i.stack.imgur.com/PYfHp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PYfHp.png" alt="enter image description here"></a></p> <p>example code:</p> <p><a href="https://i.stack.imgur.com/zkqUR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zkqUR.png" alt="enter image description here"></a></p> <pre class="lang-swift prettyprint-override"><code>import UIKit import ABVideoRangeSlider import AVKit import AVFoundation class ViewController: UIViewController, ABVideoRangeSliderDelegate { @IBOutlet var videoRangeSlider: ABVideoRangeSlider! @IBOutlet var playerView: UIView! @IBOutlet var lblStart: UILabel! @IBOutlet var lblEnd: UILabel! @IBOutlet var lblMinSpace: UILabel! let path = Bundle.main.path(forResource: "test", ofType:"mp4") override func viewDidLoad() { super.viewDidLoad() } @IBAction func playVideo(_ sender: Any) { let player = AVPlayer(url: URL(fileURLWithPath: path!)) let playerViewController = AVPlayerViewController() playerViewController.player = player self.present(playerViewController, animated: true) { playerViewController.player!.play() } } override func viewWillAppear(_ animated: Bool) { videoRangeSlider.setVideoURL(videoURL: URL(fileURLWithPath: path!)) videoRangeSlider.delegate = self videoRangeSlider.minSpace = 60.0 // videoRangeSlider.maxSpace = 180.0 lblMinSpace.text = "\(videoRangeSlider.minSpace)" // Set initial position of Start Indicator videoRangeSlider.setStartPosition(seconds: 50.0) // Set initial position of End Indicator videoRangeSlider.setEndPosition(seconds: 150.0) } // MARK: ABVideoRangeSlider Delegate - Returns time in seconds func didChangeValue(videoRangeSlider: ABVideoRangeSlider, startTime: Float64, endTime: Float64) { lblStart.text = "\(startTime)" lblEnd.text = "\(endTime)" } func indicatorDidChangePosition(videoRangeSlider: ABVideoRangeSlider, position: Float64) { print("position of indicator: \(position)") } } </code></pre>
3
2,163
Docker Swarm load balancing or mesh routing issue
<p>I have a single docker node configured as a docker swarm.</p> <p>I have created an overlay network called main_net which uses encryption.</p> <p>I have mutiple containers connected to this network. One of which is called kong and runs kong. I have a service called saas_thumbsum_0_0_13 - this has a single container running inside it. </p> <p>Kong is configured as a reverse proxy for saas_thumbsum_0_0_13, and uses the address saas_thumbsum_0_0_13. This setup was working this morning when I had a service called saas_thumbsum_0_0_12 running, Kong was sending requests to <a href="http://saas_thumbsum_0_0_12:80/public" rel="nofollow noreferrer">http://saas_thumbsum_0_0_12:80/public</a> without a problem.</p> <p>I have now created another service 0_0_13 and connected it to the network but kong can not access <a href="http://saas_thumbsum_0_0_13:80/public" rel="nofollow noreferrer">http://saas_thumbsum_0_0_13:80/public</a></p> <p>I have logged into the console of the kong container and ran the following commands:</p> <pre><code>/ # nslookup saas_thumbsum_0_0_13 nslookup: can't resolve '(null)': Name does not resolve Name: saas_thumbsum_0_0_13 Address 1: 10.0.0.39 / # nslookup tasks.saas_thumbsum_0_0_13 nslookup: can't resolve '(null)': Name does not resolve Name: tasks.saas_thumbsum_0_0_13 Address 1: 10.0.0.40 d4c3034462d1.main_net </code></pre> <p>so the service resolves to 10.0.0.39 which I guess is the load balanced ip, and the service has one task with an ip of 10.0.0.40. Seems ok so far. Now I try and ping the two ip's from inside the kong container:</p> <pre><code>/ # ping 10.0.0.39 PING 10.0.0.39 (10.0.0.39): 56 data bytes 64 bytes from 10.0.0.39: seq=0 ttl=64 time=0.089 ms 64 bytes from 10.0.0.39: seq=1 ttl=64 time=0.083 ms ^C --- 10.0.0.39 ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 0.083/0.086/0.089 ms / # ping 10.0.0.40 PING 10.0.0.40 (10.0.0.40): 56 data bytes 64 bytes from 10.0.0.40: seq=0 ttl=64 time=0.146 ms 64 bytes from 10.0.0.40: seq=1 ttl=64 time=0.091 ms ^C --- 10.0.0.40 ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 0.091/0.118/0.146 ms </code></pre> <p>I can successfully ping both IP addresses. This seems fine to me as from my beginner level knowldege they should load balance to the same endpoint and the results should not differ.</p> <p>Now if I try and get the webpage from the load balanced ip it fails:</p> <pre><code>/ # wget 10.0.0.39/public/web/frontend Connecting to 10.0.0.39 (10.0.0.39:80) wget: can't connect to remote host (10.0.0.39): Connection refused </code></pre> <p>Same if I use the service name</p> <pre><code>/ # wget saas_thumbsum_0_0_13/public/web/frontend Connecting to saas_thumbsum_0_0_13 (10.0.0.39:80) wget: can't connect to remote host (10.0.0.39): Connection refused </code></pre> <p>same with and without http://</p> <p>but it works if I go to the task ip:</p> <pre><code>/ # wget 10.0.0.40/public/web/frontend Connecting to 10.0.0.40 (10.0.0.40:80) Connecting to 10.0.0.40 (10.0.0.40:80) frontend 100% |*******************************************************| 1769 0:00:00 ETA </code></pre> <p>But I should be using the service endpoint not the task endpoint!</p> <p>If the address is load balanced then they both should go to the same target so the result should be the same.</p> <p>The target container is running nginx and I have checked the config files there but I don't see any kind of source ip restriction. Not sure how I would do this anyway because the ip addresses would be different every time anyway!</p> <p>So this is broken, wget saas_thumbsum_0_0_13/public/web/frontend should be giving me the page but it is not working.</p> <p>If anyone can spot my mistake or give me any debugging pointers it would be appreciated.</p> <p>Some other info that might be helpful:</p> <pre><code>robert@metcaac4:~$ docker --version Docker version 18.09.3, build 774a1f4 robert@metcaac4:~$ docker network ls NETWORK ID NAME DRIVER SCOPE ac295a4f901c bridge bridge local 5aa2eea87b33 docker_gwbridge bridge local 3744b0f39195 host host local lffazc510t7z ingress overlay swarm r8z2bb9idtwt main_net overlay swarm 0ad4a8efa4cc none null local robert@metcaac4:~$ docker network inspect main_net [ { "Name": "main_net", "Id": "r8z2bb9idtwtyfr20e6u1p2f8", "Created": "2019-03-07T20:24:38.553471996Z", "Scope": "swarm", "Driver": "overlay", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "10.0.0.0/24", "Gateway": "10.0.0.1" } ] }, "Internal": false, "Attachable": true, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "2b3b0d5311f23b084a2aa5282f451acb2c6d636b5ceb11926a46ee0a62e3035a": { "Name": "code_site2_code_site2.1.bqcsxy73pczsurit07lxmmoru", "EndpointID": "c9974c99e83338aa07f17eda56342757bce6a247105eb8fa4afab1b71f8d0366", "MacAddress": "02:42:0a:00:00:b7", "IPv4Address": "10.0.0.183/24", "IPv6Address": "" }, "2ed56f6b2b06cbdeed62037cf10e40683b2960b2d53866e22a4080fa7a50a563": { "Name": "saas_user_management_0_0_66.1.0092odmxl4er803jhcrad7xhb", "EndpointID": "90f6cc3368c1fd0e5ff0be990f7cd0b1a854584eea3cdac3a80c0d535aa94c43", "MacAddress": "02:42:0a:00:00:f5", "IPv4Address": "10.0.0.245/24", "IPv6Address": "" }, "7059b7eb266a6ad159fab1606b176c23d70f91841fb2635e5e163afa44f78e32": { "Name": "kong_kong.1.dr5afpgi5me23p96kub2qmjaq", "EndpointID": "0bfc5ece35f5278596b05232cbc5f88deef9c9a6d132d6f54b82b4c7c7e4d4fe", "MacAddress": "02:42:0a:00:00:b8", "IPv4Address": "10.0.0.184/24", "IPv6Address": "" }, "7e0153b62eab821019b8f0757c842de367a61025e2848c0548c3cb7bd28d2df0": { "Name": "code_site2_code_site2_nginx.1.ijxkoaxzrly1b0dkt2ysdot3r", "EndpointID": "d776003ee4a98acd9cb1df2d3fe2861f4c8aca9c655a01dac9b371aebc4a6b2f", "MacAddress": "02:42:0a:00:00:27", "IPv4Address": "10.0.0.39/24", "IPv6Address": "" }, "9cebbcf75312ce906786d722c38c30c85a84ec5b4efbe46656388f49fa50f942": { "Name": "saas_user_management_0_0_50.1.9xkwovfqejqerzi5co2mfb5l4", "EndpointID": "28cfcbd20723b272f787f1ecea7603b65f1bd48df8dcb89474087d3f5ae77ed7", "MacAddress": "02:42:0a:00:00:21", "IPv4Address": "10.0.0.33/24", "IPv6Address": "" }, "a44f86449e19ca3a6fc170c3ed997156f0d3db66fece23883c1a3f844714e504": { "Name": "kong_dbb.1.l4d1xzqtr4t0thjnf39twfo0j", "EndpointID": "a410b8db987fd7eb261865c27dc84905bdfab273ccf20906c7b5a1ba0cbd1ab8", "MacAddress": "02:42:0a:00:00:ad", "IPv4Address": "10.0.0.173/24", "IPv6Address": "" }, "d4c3034462d106496da5df3449d1da26dd50bcf40e4b954aea0b64a33a88d954": { "Name": "saas_thumbsum_0_0_13.1.of39j50gs0d5376nqgtsszx7m", "EndpointID": "a10e51cc60c559f9631a0fb883ca00a654bd1c815cc0a4730222be27847a802f", "MacAddress": "02:42:0a:00:00:28", "IPv4Address": "10.0.0.40/24", "IPv6Address": "" }, "deda51bfbee097093ccb3e5be7ea11aa0648bdc74381f1552fe102b8646343cf": { "Name": "dockerregistry_dockerregistry.1.rty0eoy404m870f6qkpla9c9z", "EndpointID": "ff64d38ae4f932b7567cb0b5417df0cb8eef12e46572636a40d59da37511eff9", "MacAddress": "02:42:0a:00:00:ae", "IPv4Address": "10.0.0.174/24", "IPv6Address": "" }, "e117e90a37cacbdbfc2768e2c77512b1c967e268718884f0372d63c1f6b79cbd": { "Name": "code_site2_code_site2_nginx.1.dihdw4g5n8i20pbb7nfwwi6ud", "EndpointID": "620d3c5de8169a380cb3c2e2caa91e18c91a1d4cf244900e5ea4912941e9c4c8", "MacAddress": "02:42:0a:00:00:ac", "IPv4Address": "10.0.0.172/24", "IPv6Address": "" }, "lb-main_net": { "Name": "main_net-endpoint", "EndpointID": "d4b3747a3701b05f716f47295132939bed6f68c566fbf5ab50b70071e2d5cd0d", "MacAddress": "02:42:0a:00:00:02", "IPv4Address": "10.0.0.2/24", "IPv6Address": "" } }, "Options": { "com.docker.network.driver.overlay.vxlanid_list": "4097", "encrypted": "" }, "Labels": {}, "Peers": [ { "Name": "1a2559b7bdb0", "IP": "78.31.105.225" } ] } ] robert@metcaac4:~$ docker service ls ID NAME MODE REPLICAS IMAGE PORTS miqimzjmh0qe code_site2_code_site2 replicated 1/1 metcarob/phpfpm_for_drupal:0.0.6 bgixg86fhaqs code_site2_code_site2_nginx replicated 1/1 nginx:1.13.0-alpine 0d2267ul4iv4 dockerregistry_dockerregistry replicated 1/1 registry:2 *:5000-&gt;5000/tcp 4tn5xqbss3i5 kong_dbb replicated 1/1 postgres:9.6 u9xo3prf53v2 kong_kong replicated 1/1 kong:1.1.2 *:80-&gt;8000/tcp, *:443-&gt;8443/tcp kgmhthn93qwy saas_thumbsum_0_0_13 replicated 1/1 metcarob/saas_thumbsum:0.0.13 zhyna2ktbgw4 saas_user_management_0_0_66 replicated 1/1 metcarob/saas_user_management_system:0.0.66 </code></pre> <p>I have tried removing and recreating the saas_thumbsum service but this made no difference. (Only altered the ip's in question)</p> <p>I can supply the saas_thumbsum_0_0_13 nginx config but this hasn't changed since the working version and I don't think this is the problem.</p> <p>Thanks for any help!</p> <h2>Update 001 - Extra information</h2> <p>I have exactly the same setup with my saas_user_management_0_0_66 service. This is working without a problem.</p> <pre><code>robert@metcaac4:~$ docker exec -it kong_kong.1.dr5afpgi5me23p96kub2qmjaq /bin/sh / # nslookup saas_user_management_system_0_0_66 nslookup: can't resolve '(null)': Name does not resolve nslookup: can't resolve 'saas_user_management_system_0_0_66': Name does not resolve / # nslookup saas_user_management_0_0_66 nslookup: can't resolve '(null)': Name does not resolve Name: saas_user_management_0_0_66 Address 1: 10.0.0.244 / # nslookup tasks.saas_user_management_0_0_66 nslookup: can't resolve '(null)': Name does not resolve Name: tasks.saas_user_management_0_0_66 Address 1: 10.0.0.245 saas_user_management_0_0_66.1.0092odmxl4er803jhcrad7xhb.main_net / # pint 10.0.0.244 /bin/sh: pint: not found / # ping 10.0.0.244 PING 10.0.0.244 (10.0.0.244): 56 data bytes 64 bytes from 10.0.0.244: seq=0 ttl=64 time=0.082 ms 64 bytes from 10.0.0.244: seq=1 ttl=64 time=0.113 ms ^C --- 10.0.0.244 ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 0.082/0.097/0.113 ms / # ping 10.0.0.245 PING 10.0.0.245 (10.0.0.245): 56 data bytes 64 bytes from 10.0.0.245: seq=0 ttl=64 time=0.177 ms 64 bytes from 10.0.0.245: seq=1 ttl=64 time=0.112 ms ^C --- 10.0.0.245 ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max = 0.112/0.144/0.177 ms / # wget 10.0.0.245 Connecting to 10.0.0.245 (10.0.0.245:80) wget: server returned error: HTTP/1.1 404 Not Found / # wget 10.0.0.244 Connecting to 10.0.0.244 (10.0.0.244:80) wget: server returned error: HTTP/1.1 404 Not Found </code></pre> <p>In the above wget to both 10.0.0.245 and 10.0.0.244 give exactly the same 404 not found response from the server.I have no idea why saas_thumbsum gets connection refused.</p>
3
6,869
E-mails not being delivered
<p>I am using the System.Net.Mail library to send e-mails through a remote desktop connection. The e-mails are sent correctly if the address is my company's, but for all other addresses, e-mails are not sent. I do not get any exception or error, they just never reach the address, or go to Spam/Junk. When i synchronize my 'Sent' folder, the e-mail appears.</p> <p>The code i am using to send e-mails is below </p> <pre><code> var smtpClient = new System.Net.Mail.SmtpClient(hostName) { EnableSsl = false, DeliveryMethod = SmtpDeliveryMethod.Network }; smtpClient.Credentials = new NetworkCredential(userName, password); smtpClient.SendAndSaveMessageToIMAP(mailMessage, hostName, port, userName, password, "INBOX.Sent"); </code></pre> <p>and the following</p> <pre><code> static System.IO.StreamWriter sw = null; static System.Net.Sockets.TcpClient tcpc = null; static System.Net.Security.SslStream ssl = null; static string path; static int bytes = -1; static byte[] buffer; static System.Text.StringBuilder sb = new System.Text.StringBuilder(); static byte[] dummy; private static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3; private static readonly System.Reflection.BindingFlags Flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; private static readonly System.Type MailWriter = typeof(System.Net.Mail.SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter"); private static readonly System.Reflection.ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(Flags, null, new[] { typeof(System.IO.Stream) }, null); private static readonly System.Reflection.MethodInfo CloseMethod = MailWriter.GetMethod("Close", Flags); private static readonly System.Reflection.MethodInfo SendMethod = typeof(System.Net.Mail.MailMessage).GetMethod("Send", Flags); public static void SendAndSaveMessageToIMAP(this System.Net.Mail.SmtpClient self, System.Net.Mail.MailMessage mailMessage, string imapServer, int imapPort, string userName, string password, string sentFolderName) { try { path = System.Environment.CurrentDirectory + "\\emailresponse.txt"; if (System.IO.File.Exists(path)) System.IO.File.Delete(path); sw = new System.IO.StreamWriter(System.IO.File.Create(path)); tcpc = new System.Net.Sockets.TcpClient(imapServer, imapPort); ssl = new System.Net.Security.SslStream(tcpc.GetStream()); try { ssl.AuthenticateAsClient(imapServer); } catch (Exception ex) { throw; } SendCommandAndReceiveResponse(""); SendCommandAndReceiveResponse(string.Format("$ LOGIN {1} {2} {0}", System.Environment.NewLine, userName, password)); using (var m = mailMessage.RawMessage()) { m.Position = 0; var sr = new System.IO.StreamReader(m); var myStr = sr.ReadToEnd(); SendCommandAndReceiveResponse(string.Format("$ APPEND {1} (\\Seen) {{{2}}}{0}", System.Environment.NewLine, sentFolderName, myStr.Length)); SendCommandAndReceiveResponse(string.Format("{1}{0}", System.Environment.NewLine, myStr)); } SendCommandAndReceiveResponse(string.Format("$ LOGOUT{0}", System.Environment.NewLine)); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine("error: " + ex.Message); } finally { if (sw != null) { sw.Close(); sw.Dispose(); } if (ssl != null) { ssl.Close(); ssl.Dispose(); } if (tcpc != null) { tcpc.Close(); } } self.Send(mailMessage); } private static void SendCommandAndReceiveResponse(string command) { try { if (command != "") { if (tcpc.Connected) { dummy = System.Text.Encoding.ASCII.GetBytes(command); ssl.Write(dummy, 0, dummy.Length); } else { throw new System.ApplicationException("TCP CONNECTION DISCONNECTED"); } } ssl.Flush(); buffer = new byte[2048]; bytes = ssl.Read(buffer, 0, 2048); sb.Append(System.Text.Encoding.ASCII.GetString(buffer)); sw.WriteLine(sb.ToString()); sb = new System.Text.StringBuilder(); } catch (System.Exception ex) { throw new System.ApplicationException(ex.Message); } } public static System.IO.MemoryStream RawMessage(this System.Net.Mail.MailMessage self) { var result = new System.IO.MemoryStream(); var mailWriter = MailWriterConstructor.Invoke(new object[] { result }); SendMethod.Invoke(self, Flags, null, IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null); result = new System.IO.MemoryStream(result.ToArray()); CloseMethod.Invoke(mailWriter, Flags, null, new object[] { }, null); return result; } </code></pre> <p>Any help would be highly appreciated. </p>
3
2,839
File upload field validation in Web Forms for Marketers 8.1 update 3
<p>I am trying file upload validation in sitecore 8 using Web forms for Marketers but it is not working please suggest me solution. Here is my code.</p> <pre class="lang-cs prettyprint-override"><code>namespace Test.Web.WFFM { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class LimitFileSizeAttribute : DynamicValidationBase { private const string FileSizeLimitKey = "filesizelimit"; private const string ErrorMessageKey = "filesizelimiterror"; protected override ValidationResult ValidateFieldValue(IViewModel model, object value, ValidationContext validationContext) { // Required attribute should handle null value if (value == null) { return ValidationResult.Success; } var fileBase = value as HttpPostedFileBase; if (fileBase == null) { return new ValidationResult(ErrorMessage); } var fileUploadField = validationContext.ObjectInstance as FileUploadField; var limit = GetLimit(fileUploadField); if (limit == -1) // Limit not set { return ValidationResult.Success; } if (fileBase.ContentLength &gt; limit) { return new ValidationResult(GetErrorMessage(fileUploadField)); } return ValidationResult.Success; } private static int GetLimit(IViewModel field) { if (field == null || !field.Parameters.ContainsKey(FileSizeLimitKey)) { return -1; } var parameter = field.Parameters[FileSizeLimitKey]; int intValue; if (int.TryParse(parameter, out intValue)) { return intValue; } return -1; } private string GetErrorMessage(IViewModel field) { if (field != null &amp;&amp; field.Parameters.ContainsKey(ErrorMessageKey)) { return field.Parameters[ErrorMessageKey]; } return ErrorMessage; } }} </code></pre> <blockquote> <p>Created RestrictedUploadField class</p> </blockquote> <pre class="lang-cs prettyprint-override"><code>namespace Test.Web.WFFM.MVC { public class RestrictedUploadField : FileUploadField { [LimitFileSize] public override HttpPostedFileBase Value { get; set; } }} </code></pre> <blockquote> <p>Created custom validation in sitecore and added "Parameters" and "Localized Parameters"</p> </blockquote> <p><a href="https://i.stack.imgur.com/34vv4.png" rel="nofollow"><img src="https://i.stack.imgur.com/34vv4.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/Cz6wX.png" rel="nofollow"><img src="https://i.stack.imgur.com/Cz6wX.png" alt="enter image description here"></a></p> <p>Created custom field type "Restricted File Upload", added validation in "Validation" field, added "Parameters" and "Localized Parameters". <a href="https://i.stack.imgur.com/0rJwp.png" rel="nofollow"><img src="https://i.stack.imgur.com/0rJwp.png" alt="enter image description here"></a></p>
3
1,172
rich:listShuttle error when using complex object
<p><strong>WORKING:</strong> This is my working rich:listShuttle when sourceValue and target value are List of strings. </p> <p><strong>1. JSF Page</strong></p> <pre><code>&lt;rich:listShuttle id="companyJurisdictionShutle" sourceValue="#{companyAdminAction.statesList}" targetValue="#{companyAdminAction.selectedStates}" var="item" orderControlsVisible="false" fastOrderControlsVisible="false" sourceCaptionLabel="Available" targetCaptionLabel="Selected" styleClass="lishShuttle"&gt; &lt;rich:column&gt; #{item} &lt;/rich:column&gt; &lt;/rich:listShuttle&gt; </code></pre> <p><strong>2. Backing Bean</strong></p> <pre><code>//sourceValue public List&lt;String&gt; getStatesList() { for (DMPJurisdiction dmpJurisdiction: jurisdictionList) { if(!statesList.contains(dmpJurisdiction.getJurisName())) { statesList.add(dmpJurisdiction.getJurisName()); } } return statesList; } //targetValue public List&lt;String&gt; getSelectedStates() { return selectedStates; } </code></pre> <p><strong>3. Value Object</strong></p> <pre><code>public class DMPJurisdiction implements Serializable { /** serial version UID **/ private final static Long serialVersionUID = 109892748283726L; /** jurisdiction id **/ private Long jurisId; /** name **/ private String jurisName; /** description **/ private String jurisDescription; /** code **/ private String jurisCode; //Getters and Setters } </code></pre> <p><strong>NOT-WORKING:</strong> I changed the list shuttle, so that sourceValue and targetValue are list of complex object (DMPJurisdiction), not list of Strings as before. For which I wrote a converter.</p> <p><strong>1. JSF Page</strong></p> <pre><code>&lt;rich:listShuttle id="companyJurisdictionShutle" sourceValue="#{companyAdminAction.jurisdictionList}" targetValue="#{companyAdminAction.targetJurisdictionList}" converter="#{dmpJurisdictionConverter}" var="item" orderControlsVisible="false" fastOrderControlsVisible="false" sourceCaptionLabel="Available" targetCaptionLabel="Selected" styleClass="lishShuttle"&gt; &lt;rich:column&gt; #{item.jurisName} &lt;/rich:column&gt; &lt;/rich:listShuttle&gt; </code></pre> <p><strong>2. Backing Bean</strong>: Now return list of complex object DMPJurisdiction listed above.</p> <pre><code>//sourceValue public List&lt;DMPJurisdiction&gt; getJurisdictionList() { return jurisdictionList; } //targetValue public List&lt;DMPJurisdiction&gt; getTargetJurisdictionList() { return targetJurisdictionList; } </code></pre> <p><strong>3. Converter</strong></p> <pre><code>public class DmpJurisdictionConverter implements javax.faces.convert.Converter { public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) { List&lt;DMPJurisdiction&gt; dmpJurisdictionList = Cache.loadAllDmpJurisdictions(); for (DMPJurisdiction dmpJurisdiction : dmpJurisdictionList) { if (dmpJurisdiction.getJurisName().equals(s)) { return dmpJurisdiction; } } return null; } public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) { List&lt;DMPJurisdiction&gt; dmpJurisdictionList = Cache.loadAllDmpJurisdictions(); for (DMPJurisdiction dmpJurisdiction : dmpJurisdictionList) { if (((DMPJurisdiction) o).getJurisName().equals(dmpJurisdiction.getJurisName())) { return dmpJurisdiction.getJurisName(); } } return null; } } </code></pre> <p><strong>4. Error:</strong> <code>sourceId=accountWorkcaseOpenTabForm:addDmpCompanySubview:companyJurisdictionShutle[severity=(ERROR 2), summary=(javax.el.PropertyNotFoundException: /html/workcase/type/dmp/admin/AddCompany.xhtml @55,98 sourceValue="#{companyAdminAction.jurisdictionList}": Property 'jurisdictionList' not writable on type java.util.List), detail=(javax.el.PropertyNotFoundException: /html/workcase/type/dmp/admin/AddCompany.xhtml @55,98 sourceValue="#{companyAdminAction.jurisdictionList}": Property 'jurisdictionList' not writable on type java.util.List)] ||||</code></p> <p><strong>NOTE:</strong> Just a side note, I am using the same dmpJurisdictionConverter successfully for selectOneMenu as shown below in a different <strong>unrelated</strong> JSF page.</p> <pre><code>&lt;h:selectOneMenu value="#{companyAdminAction.dmpJurisdiction}" converter="#{dmpJurisdictionConverter}"&gt; &lt;s:selectItems var="item" value="#{companyAdminAction.jurisdictionList}" label="#{item.jurisName}" hideNoSelectionLabel="true" noSelectionLabel="-- Select Jurisdiction --"/&gt; &lt;a4j:support event="onchange" action="#{companyAdminAction.loadCompanyList()}" reRender="dmpCompanies"/&gt; &lt;/h:selectOneMenu&gt; </code></pre>
3
2,172
Bootstrap menu won't close on touch devices
<p>Pulling my hair out trying to get this working. Responsive menu works fine when browser is scaled down to mobile size, ie, clicking a link closes the menu and page scrolls to correct section. When I enable touch emulation however in Google dev tools, I can see that data-toggle="collapse" is not being fired, so menu stays open upon click. Now, here's the thing, I bought a theme and there is a fair bit of extra js written by whoever created it that is more than likely causing the issue. Theme is no longer supported so I'm really stuck.</p> <p>My menu code:</p> <pre><code>&lt;div class="header" id="header"&gt; &lt;div class="navbar-wrapper" id="navigation" role="navigation"&gt; &lt;div class="navbar navbar-inverse"&gt; &lt;div class="container"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-down"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand brand-container " href="#home" title="CandyPOP!" rel="home" id="brand" &gt; &lt;img src="img/logocp1bcolour2.png" alt="CandyPOP logo" class="firstb" width="160"&gt; &lt;!-- logo to display on scrolling --&gt; &lt;img src="img/logocp1bcolour2.png" alt="CandyPOP logo" class="last" width="160"&gt; &lt;/a&gt; &lt;div class="navbar-collapse collapse" id="navbar-collapse-down"&gt; &lt;ul id="nav" class="nav navbar-nav"&gt; &lt;li class ="active"&gt;&lt;a href="#home" data-spy="#home" data-toggle="collapse" data-target="#navbar-collapse-down"&gt;Home&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#portfolio" data-spy="#portfolio" data-toggle="collapse" data-target="#navbar-collapse-down"&gt;Line Up&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tickets" class="menu-item" data-spy="#tickets" data-toggle="collapse" data-target="#navbar-collapse-down"&gt;Tickets&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#blog" class="menu-item" data-spy="#blog" data-toggle="collapse" data-target="#navbar-collapse-down"&gt;News&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact" data-spy="#contact" data-toggle="collapse" data-target="#navbar-collapse-down"&gt;Contact&lt;span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And here is all menu related js that came with the theme:</p> <pre><code>var lastId, topMenuHeight, topMenu = $('#nav'), menuItems = topMenu.find('a'), menuItemsTop = topMenu.find('&gt; li &gt; a'), scrollItems = menuItemsTop.map(function(){ var item = $($(this).data('spy')); if (item.length) { return item; } }); if ($('body').hasClass('leftnav')){ topMenuHeight = 0; } else { topMenuHeight = 50; } menuItems.not('.external-link').on('click touchend',function(e) { e.preventDefault(); var target = $(this).attr('href'); if (!$(this).parent().parent().hasClass('dropdown-menu')){ $(this).parent().siblings().removeClass('active'); } $(this).data('clicked', true); // If the url item is defined, this for dropdowns if ( typeof ( $(target).offset() ) !== 'undefined'){ $('html,body').stop().animate({ scrollTop: $(target).offset().top - topMenuHeight }, '1000' ,'easeOutExpo'); } }); // Drop down navigation $('.dropdown-menu li a').click(function(){ var j = $(this).parent().index(); var subnavigation = $(this).closest('ul').data('subnav'); $('#'+ subnavigation + ' li').removeClass('active'); $('#'+ subnavigation + ' li').each(function(i){ if ( j === i){ $(this).addClass('active'); } }) var target = $('#'+ subnavigation + ' li').closest('.parent'); $('html,body').stop().animate({ scrollTop: target.offset().top - topMenuHeight }, '1000' ,'easeOutExpo'); }) // Scroll on click links $('.link-more[href*=#]').click(function(e){ e.preventDefault(); var target = $(this.hash); $('html,body').stop().animate({ scrollTop: target.offset().top - topMenuHeight }, '1000' ,'easeOutExpo'); }) // Scroll to the section clicked on navigation $(window).scroll(function(){ var fromTop = $(this).scrollTop() + topMenuHeight; var cur = scrollItems.map(function(){ if($(this).offset().top &lt; fromTop + 1) return this; }); cur = cur[cur.length-1]; var id = cur &amp;&amp; cur.length ? cur[0].id : ''; if (lastId !== id) { lastId = id; menuItemsTop .parent().removeClass('active') .end().filter("[data-spy=#"+id+"]").parent().addClass("active"); } }) $('.navbar-toggle').on('click', function(e){ $('.nav').toggle(); }); </code></pre> <p>I also copied the last couple of lines from the js and changed it to be triggered from .menu-item like this:</p> <pre><code>$('.menu-item').on('click', function(e){ $('.nav').toggle(); }); </code></pre> <p>If anyone would be so kind as to help me out I would be very grateful. Cheers</p>
3
2,639
SparkJob on GCP dataproc failing with error - java.lang.NoSuchMethodError: io.netty.buffer.PooledByteBufAllocator.<init>(ZIIIIIIZ)V
<p>I'm running a spark job on GCP dataproc using below command,</p> <pre><code>gcloud dataproc workflow-templates instantiate-from-file --file=job_config.yaml --region us-east1 </code></pre> <p>Below is my job_config.yaml</p> <pre><code>jobs: - sparkJob: args: - filepath mainJarFileUri: gs://&lt;host&gt;/my-project-1.0.0-SNAPSHOT.jar stepId: sparkjob placement: managedCluster: clusterName: mysparkcluster config: configBucket: my-dataproc-spark gceClusterConfig: zoneUri: 'us-east1-c' subnetworkUri: '&lt;uri&gt;' masterConfig: diskConfig: bootDiskSizeGb: 30 bootDiskType: 'pd-ssd' machineTypeUri: 'e2-standard-4' workerConfig: diskConfig: bootDiskSizeGb: 30 bootDiskType: 'pd-ssd' machineTypeUri: 'e2-standard-4' numInstances: 2 secondaryWorkerConfig: diskConfig: bootDiskType: 'pd-ssd' numInstances: 2 softwareConfig: imageVersion: '2.0.44-debian10' properties: dataproc:dataproc.logging.stackdriver.job.driver.enable: 'true' dataproc:dataproc.logging.stackdriver.job.yarn.container.enable: 'true' dataproc:dataproc.monitoring.stackdriver.enable: 'true' dataproc:dataproc.scheduler.driver-size-mb: '256' dataproc:ranger.cloud-sql.use-private-ip: 'true' spark:spark.dynamicAllocation.enabled: 'false' spark:spark.shuffle.service.enabled: 'false' spark:spark.executor.instances: '30' spark:spark.executor.memory: '9g' spark:spark.executors.cores: '3' </code></pre> <p>Below is my pom.xml:</p> <pre><code>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.sai.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-project&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.cloud.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-bigquery_2.12&lt;/artifactId&gt; &lt;version&gt;0.22.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-core_2.12&lt;/artifactId&gt; &lt;version&gt;3.1.2&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; &lt;artifactId&gt;gson&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.protobuf&lt;/groupId&gt; &lt;artifactId&gt;protobuf-java&lt;/artifactId&gt; &lt;version&gt;3.11.4&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.scala-lang&lt;/groupId&gt; &lt;artifactId&gt;scala-library&lt;/artifactId&gt; &lt;version&gt;2.12.14&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt; &lt;artifactId&gt;httpclient&lt;/artifactId&gt; &lt;version&gt;4.5.4&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.spark&lt;/groupId&gt; &lt;artifactId&gt;spark-sql_2.12&lt;/artifactId&gt; &lt;version&gt;3.1.2&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.elasticsearch&lt;/groupId&gt; &lt;artifactId&gt;elasticsearch&lt;/artifactId&gt; &lt;version&gt;7.5.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.cloud&lt;/groupId&gt; &lt;artifactId&gt;google-cloud-secretmanager&lt;/artifactId&gt; &lt;version&gt;0.3.0&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;io.grpc&lt;/groupId&gt; &lt;artifactId&gt;grpc-grpclb&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/com.typesafe/config --&gt; &lt;dependency&gt; &lt;groupId&gt;com.typesafe&lt;/groupId&gt; &lt;artifactId&gt;config&lt;/artifactId&gt; &lt;version&gt;1.4.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;sourceDirectory&gt;src/main/scala&lt;/sourceDirectory&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt; &lt;version&gt;3.2.3&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;shade&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;createDependencyReducedPom&gt;false&lt;/createDependencyReducedPom&gt; &lt;artifactSet&gt; &lt;includes&gt; &lt;!-- dependencies to be packed in the fat jar --&gt; &lt;include&gt;*&lt;/include&gt; &lt;/includes&gt; &lt;/artifactSet&gt; &lt;transformers&gt; &lt;transformer implementation=&quot;org.apache.maven.plugins.shade.resource.AppendingTransformer&quot;&gt; &lt;resource&gt;reference.conf&lt;/resource&gt; &lt;/transformer&gt; &lt;transformer implementation=&quot;org.apache.maven.plugins.shade.resource.ManifestResourceTransformer&quot;&gt; &lt;manifestEntries&gt; &lt;Main-Class&gt;com.sai.spark.Test&lt;/Main-Class&gt; &lt;/manifestEntries&gt; &lt;/transformer&gt; &lt;transformer implementation=&quot;org.apache.maven.plugins.shade.resource.ServicesResourceTransformer&quot;/&gt; &lt;/transformers&gt; &lt;filters&gt; &lt;filter&gt; &lt;artifact&gt;*:*&lt;/artifact&gt; &lt;excludes&gt; &lt;exclude&gt;META-INF/maven/**&lt;/exclude&gt; &lt;exclude&gt;META-INF/*.SF&lt;/exclude&gt; &lt;exclude&gt;META-INF/*.DSA&lt;/exclude&gt; &lt;exclude&gt;META-INF/*.RSA&lt;/exclude&gt; &lt;/excludes&gt; &lt;/filter&gt; &lt;/filters&gt; &lt;relocations&gt; &lt;relocation&gt; &lt;pattern&gt;com&lt;/pattern&gt; &lt;shadedPattern&gt;repackaged.com&lt;/shadedPattern&gt; &lt;includes&gt; &lt;include&gt;com.google.protobuf.**&lt;/include&gt; &lt;include&gt;com.google.common.**&lt;/include&gt; &lt;include&gt;com.google.gson.**&lt;/include&gt; &lt;include&gt;com.google.api.**&lt;/include&gt; &lt;/includes&gt; &lt;/relocation&gt; &lt;relocation&gt; &lt;pattern&gt;org&lt;/pattern&gt; &lt;shadedPattern&gt;repackaged.org&lt;/shadedPattern&gt; &lt;includes&gt; &lt;include&gt;org.apache.commons.**&lt;/include&gt; &lt;/includes&gt; &lt;/relocation&gt; &lt;/relocations&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>StackTrace:</p> <pre><code>22/07/01 16:58:00 ERROR io.grpc.internal.ManagedChannelImpl: [Channel&lt;1&gt;: (secretmanager.googleapis.com:443)] Uncaught exception in the SynchronizationContext. Panic! java.lang.NoSuchMethodError: io.netty.buffer.PooledByteBufAllocator.&lt;init&gt;(ZIIIIIIZ)V at io.grpc.netty.Utils.createByteBufAllocator(Utils.java:172) at io.grpc.netty.Utils.access$000(Utils.java:71) at io.grpc.netty.Utils$ByteBufAllocatorPreferDirectHolder.&lt;clinit&gt;(Utils.java:93) at io.grpc.netty.Utils.getByteBufAllocator(Utils.java:140) at io.grpc.netty.NettyClientTransport.start(NettyClientTransport.java:231) at io.grpc.internal.ForwardingConnectionClientTransport.start(ForwardingConnectionClientTransport.java:33) at io.grpc.internal.ForwardingConnectionClientTransport.start(ForwardingConnectionClientTransport.java:33) at io.grpc.internal.InternalSubchannel.startNewTransport(InternalSubchannel.java:258) at io.grpc.internal.InternalSubchannel.access$400(InternalSubchannel.java:65) at io.grpc.internal.InternalSubchannel$2.run(InternalSubchannel.java:200) at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:95) at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:127) at io.grpc.internal.ManagedChannelImpl$NameResolverListener.onResult(ManagedChannelImpl.java:1852) at io.grpc.internal.DnsNameResolver$Resolve.run(DnsNameResolver.java:333) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:750) Exception in thread &quot;main&quot; repackaged.com.google.api.gax.rpc.InternalException: io.grpc.StatusRuntimeException: INTERNAL: Panic! This is a bug! at repackaged.com.google.api.gax.rpc.ApiExceptionFactory.createException(ApiExceptionFactory.java:67) at repackaged.com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:72) at repackaged.com.google.api.gax.grpc.GrpcApiExceptionFactory.create(GrpcApiExceptionFactory.java:60) at repackaged.com.google.api.gax.grpc.GrpcExceptionCallable$ExceptionTransformingFuture.onFailure(GrpcExceptionCallable.java:97) at repackaged.com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:68) at repackaged.com.google.common.util.concurrent.Futures$CallbackListener.run(Futures.java:1074) at repackaged.com.google.common.util.concurrent.DirectExecutor.execute(DirectExecutor.java:30) at repackaged.com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1213) at repackaged.com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:983) at repackaged.com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:771) at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:522) at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:497) at io.grpc.internal.DelayedClientCall$DelayedListener$3.run(DelayedClientCall.java:463) at io.grpc.internal.DelayedClientCall$DelayedListener.delayOrExecute(DelayedClientCall.java:427) at io.grpc.internal.DelayedClientCall$DelayedListener.onClose(DelayedClientCall.java:460) at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:553) at io.grpc.internal.ClientCallImpl.access$300(ClientCallImpl.java:68) at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInternal(ClientCallImpl.java:739) at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:718) at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37) at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:750) </code></pre> <p>I have tried solutions specified in below stackoverflow questions, but issue is not getting resolved.</p> <ul> <li><a href="https://stackoverflow.com/questions/47582740/netty-version-conflict-with-spark-elasticsearch-transport">Netty Version Conflict with Spark + Elasticsearch Transport</a></li> <li><a href="https://stackoverflow.com/questions/50055656/java-sparkcontext-error-java-lang-nosuchmethoderror-io-netty-buffer-pooledbyte">Java SparkContext error: java.lang.NoSuchMethodError: io.netty.buffer.PooledByteBufAllocator</a></li> <li><a href="https://stackoverflow.com/questions/49137397/spark-2-3-0-netty-version-issue-nosuchmethod-io-netty-buffer-pooledbytebufalloc">Spark 2.3.0 netty version issue: NoSuchMethod io.netty.buffer.PooledByteBufAllocator.metric()</a></li> </ul>
3
7,044
Class Shopware_Controllers_Backend_MytestPaymentServices does not exist in engine/Library/Enlight/Hook/ProxyFactory.php on line 164
<p>I am trying to implement a test button as refs <a href="https://developers.shopware.com/developers-guide/plugin-guidelines/#testing-communication-with-external-apis" rel="nofollow noreferrer">here</a></p> <p>Here is my service file</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"&gt; &lt;services&gt; &lt;service id="mytest_payment.mytest_payment_controllers_backend_mytest_payment_services" class="MytestPayment\Controllers\Backend\MytestPaymentServices"&gt; &lt;argument type="service" id="http_client"/&gt; &lt;argument type="service" id="MytestPayment.logger" /&gt; &lt;tag name="shopware.controller" module="backend" controller="MytestPayment\Controllers\Backend\MytestPaymentServices"/&gt; &lt;/service&gt; &lt;/services&gt; &lt;/container&gt; </code></pre> <p>and</p> <p>MytestPaymentServices.php </p> <pre><code>&lt;?php namespace MytestPayment\Controllers\Backend; use Monolog\Logger; use Shopware\Components\HttpClient\HttpClientInterface; use Shopware\Components\HttpClient\RequestException; use Symfony\Component\HttpFoundation\Response; class MytestPaymentServices extends \Shopware_Controllers_Backend_ExtJs { private const EXTERNAL_API_BASE_URL = 'https://www.dom.com/api'; /** * @var HttpClientInterface */ private $client; /** * @var Logger */ private $logger; public function __construct(HttpClientInterface $client, Logger $logger) { $this-&gt;client = $client; $this-&gt;logger = $logger; parent::__construct(); } public function testAction() { try { $response = $this-&gt;client-&gt;get(self::EXTERNAL_API_BASE_URL); if ((int) $response-&gt;getStatusCode() === Response::HTTP_OK) { $this-&gt;View()-&gt;assign('response', 'Success!'); } else { $this-&gt;View()-&gt;assign('response', 'Oh no! Something went wrong :('); } } catch (RequestException $exception) { $this-&gt;logger-&gt;addError($exception-&gt;getMessage()); $this-&gt;response-&gt;setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); $this-&gt;View()-&gt;assign('response', $exception-&gt;getMessage()); } } } </code></pre> <p>but I get the following error</p> <p><code>Class Shopware_Controllers_Backend_MytestPaymentServices does not exist in engine/Library/Enlight/Hook/ProxyFactory.php on line 164</code></p>
3
1,209
Why I obtain this exception when I try to handle an AJAX request with a Laravel controller method?
<p>I am absolutely new in PHP and Laravel and I have the following problem.</p> <p>From my view I perform an AJAX <strong>POST</strong> request via JQuery, by this code:</p> <pre><code>jQuery.ajax({ url: '/doSearch', type: 'POST', dataType: 'json', //data: $form.serialize(), success: function(data){ console.info('ssssssssssiiii',data); }, error: function(data, b){ console.info('erroreeeeee'); } }); </code></pre> <p>This <strong>POST</strong> request is handled by this simple controller method:</p> <pre><code>public function doSearch(){ echo 'SEARCHED'; } </code></pre> <p>that have to return the view the <strong>SEARCHED</strong> string.</p> <p>The problem is that I am obtaining this error message:</p> <pre><code>http://localhost:8000/doSearch 500 (Internal Server Error) </code></pre> <p>that is create by this exception casauted by a <strong>TokenMismatchException</strong>, in the Laravel stackrace I can see something like this:</p> <pre><code>in VerifyCsrfToken.php line 68 at VerifyCsrfToken-&gt;handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline-&gt;Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49 at ShareErrorsFromSession-&gt;handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline-&gt;Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64 at StartSession-&gt;handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline-&gt;Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37 at AddQueuedCookiesToResponse-&gt;handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline-&gt;Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59 at EncryptCookies-&gt;handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline-&gt;Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104 at Pipeline-&gt;then(object(Closure)) in Router.php line 644 at Router-&gt;runRouteWithinStack(object(Route), object(Request)) in Router.php line 618 at Router-&gt;dispatchToRoute(object(Request)) in Router.php line 596 at Router-&gt;dispatch(object(Request)) in Kernel.php line 267 at Kernel-&gt;Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46 at CheckForMaintenanceMode-&gt;handle(object(Request), object(Closure)) in Pipeline.php line 137 at Pipeline-&gt;Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33 at Pipeline-&gt;Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104 at Pipeline-&gt;then(object(Closure)) in Kernel.php line 149 at Kernel-&gt;sendRequestThroughRouter(object(Request)) in Kernel.php line 116 at Kernel-&gt;handle(object(Request)) in index.php line 54 at require_once('C:\xampp\htdocs\www.betrivius.it\application\public\index.php') in server.php line 21 </code></pre> <p>What could be the problem? How can I solve this issue?</p>
3
1,160
(NGINX) NodeJS Reverse Proxy Subdomain
<p>This question has probably been asked a lot, but I can't seem to find a really simple solution that actually works. And I need help to set this up.</p> <p><strong>I'll list my current enviroment so you can get a quick overview:</strong></p> <ul> <li>Server Host: HETZNER Cloud Server</li> <li>Domain Host: Webhuset.no (DNS Records are here)</li> <li>OS: CentOS 7 (Hetzner)</li> <li>Website: Running NGINX with NodeJS reverse proxy</li> <li>DNS: I have not added *.domain.example in my DNS Record, because I don't want every sub-host to to to my server.</li> <li>SSL: Enabled, using Let's Encrypt Certbot.</li> </ul> <p>I am only running one site, with of course, different pages for different stuff (Not multiple sites)</p> <p>My goal is to have something similar to CPanel-subdomains. Where I can add <strong>admin.domain.example</strong> and set it to for example <strong>domain.example/admin</strong> without redirect.</p> <p>But I have found this to be harder than expected, because I have been reading so many forum-posts and so many docs now and I just can't get it to work.</p> <p>I have come far enough to understand that the subdomain has to be configured in Nginx. Before this I kept trying to do this in the nodejs config.</p> <p>My current <strong>nginx.conf</strong> which makes my domain <strong>example.domain</strong> go straight to root folder of my website, with SSL. This works fine.</p> <pre><code>user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { server { server_name example.domain www.example.domain; include /etc/nginx/default.d/*.conf; location / { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } listen [::]:443 ssl ipv6only=on; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/example.domain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.domain/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } } </code></pre> <p>Here I assume I have to add a server block in order to make <strong>admin.example.domain</strong> route to <strong>example.domain/admin</strong></p> <p>How can I do this and still maintain SSL? I need SSL in order to make the images render. I have tried adding a server block like this:</p> <pre><code> server { server_name admin.example.domain location / { proxy_pass http://127.0.0.1:3000/admin; } listen [::]:443 ssl ipv6only=on; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/example.domain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.domain/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } </code></pre> <p>If this were to work <em>(It doesn't unless I listen to port 80 and use http://)</em>, it would just redirect me to <strong>(UNSECURE)<a href="https://admin.example.domain/admin" rel="nofollow noreferrer">https://admin.example.domain/admin</a></strong></p> <p>And everybody who do the same as I just did above, gets it to work. But I don't. What is different, and how can I solve this?</p>
3
1,273
Elasticsearch dynamic choose query
<p>When querying with the should command, I am wondering if there is a way to make only the responses of queries with higher scores come out.</p> <p>I'm sorry I'm not good at English, please understand it. Let's assume I have such data</p> <h3>index</h3> <pre><code>{ &quot;mappings&quot;: { &quot;properties&quot;: { &quot;name&quot;: { &quot;type&quot;: &quot;keyword&quot; } } } } </code></pre> <h3>data</h3> <pre><code>{ &quot;_index&quot; : &quot;dismisstest&quot;, &quot;_type&quot; : &quot;_doc&quot;, &quot;_id&quot; : &quot;1&quot;, &quot;_score&quot; : 1.0, &quot;_source&quot; : { &quot;name&quot; : &quot;chul&quot; } }, { &quot;_index&quot; : &quot;dismisstest&quot;, &quot;_type&quot; : &quot;_doc&quot;, &quot;_id&quot; : &quot;2&quot;, &quot;_score&quot; : 1.0, &quot;_source&quot; : { &quot;name&quot; : &quot;wedul&quot; } } </code></pre> <h3>query (example..)</h3> <pre><code>GET dismisstest/_search { &quot;query&quot;: { &quot;bool&quot;: { &quot;should&quot;: [ { &quot;term&quot;: { &quot;name&quot;: { &quot;value&quot;: &quot;wedul&quot;, &quot;boost&quot;: 2 } } }, { &quot;term&quot;: { &quot;name&quot;: { &quot;value&quot;: &quot;chul&quot;, &quot;boost&quot;: 4 } } } ] } } } </code></pre> <h3>want result (Document using only wedul query)</h3> <pre><code>{ &quot;_index&quot; : &quot;dismisstest&quot;, &quot;_type&quot; : &quot;_doc&quot;, &quot;_id&quot; : &quot;2&quot;, &quot;_score&quot; : 1.0, &quot;_source&quot; : { &quot;name&quot; : &quot;wedul&quot; } } </code></pre> <p>The above query is a simple example, but I want to use only the query that returns the document with a high score among the two should queries. Is there any possible way??</p>
3
1,072
Caused by: java.lang.ClassNotFoundException: org.springframework.js.resource.ResourceServlet
<p>When I tried to deploy an application in JBoss, I get the following error stack at the end. I'm using JBoss 5.1, Maven 4.0, JDK 1.7</p> <pre><code>13:00:26,930 INFO [ServerImpl] JBoss (Microcontainer) [5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 1m:17s:735ms 13:00:50,898 ERROR [AbstractKernelController] Error installing to Real: name=vfsfile:/C:/Windows/debug/WIA/Knight%20Rider/workspace_2/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_5.1_Runtime_Server1441347036052/deploy/ecosystem.ear/ state=PreReal mode=Manual requiredState=Real org.jboss.deployers.spi.DeploymentException: Error during deploy: vfsfile:/C:/Windows/debug/WIA/Knight%20Rider/workspace_2/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_5.1_Runtime_Server1441347036052/deploy/ecosystem.ear/ecosystem.war/ at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:177) at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1210) at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553) at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781) at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702) at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117) at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:362) at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: java.lang.NoClassDefFoundError: org/springframework/js/resource/ResourceServlet at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at org.jboss.classloader.spi.base.BaseClassLoader.access$200(BaseClassLoader.java:63) at org.jboss.classloader.spi.base.BaseClassLoader$2.run(BaseClassLoader.java:572) at org.jboss.classloader.spi.base.BaseClassLoader$2.run(BaseClassLoader.java:532) at java.security.AccessController.doPrivileged(Native Method) at org.jboss.classloader.spi.base.BaseClassLoader.loadClassLocally(BaseClassLoader.java:530) at org.jboss.classloader.spi.base.BaseClassLoader.loadClassLocally(BaseClassLoader.java:507) at org.jboss.classloader.spi.base.BaseDelegateLoader.loadClass(BaseDelegateLoader.java:134) at org.jboss.classloader.spi.filter.FilteredDelegateLoader.loadClass(FilteredDelegateLoader.java:131) at org.jboss.classloader.spi.base.ClassLoadingTask$ThreadTask.run(ClassLoadingTask.java:452) at org.jboss.classloader.spi.base.ClassLoaderManager.nextTask(ClassLoaderManager.java:251) at org.jboss.classloader.spi.base.ClassLoaderManager.process(ClassLoaderManager.java:150) at org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:265) at org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:1119) at org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:798) at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:441) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at org.jboss.wsf.container.jboss50.deployer.JAXWSDeployerHookPreJSE.getRelevantServlets(JAXWSDeployerHookPreJSE.java:121) at org.jboss.wsf.container.jboss50.deployer.JAXWSDeployerHookPreJSE.isWebServiceDeployment(JAXWSDeployerHookPreJSE.java:97) at org.jboss.wsf.container.jboss50.deployer.ArchiveDeployerHook.deploy(ArchiveDeployerHook.java:65) at org.jboss.wsf.container.jboss50.deployer.AbstractWebServiceDeployer.internalDeploy(AbstractWebServiceDeployer.java:60) at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50) at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171) ... 23 more Caused by: java.lang.ClassNotFoundException: org.springframework.js.resource.ResourceServlet at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:270) at org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:292) at org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:1119) at org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:798) at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:441) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 47 more </code></pre>
3
2,442
Error: [$injector:nomod] Module 'app' is not available
<p>Can somebody help please. I havn't any experience in Angular 1 to 2 migration. I have this code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> import * as angular from 'angular'; import 'angular-resource'; import '@uirouter/angularjs'; export const app = angular.module('app', ['ui.router', 'ngResource']) .config(($stateProvider) =&gt; { $stateProvider .state('app1', { url: '/app1', component: 'app1' }) .state('app2', { url: '/app2/:id', component: 'app2' }) .state('app3', { url: '/app3', component: 'app3' }) .state('app4', { url: '/app4', component: 'app4' }) });</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> import 'angular' import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { UpgradeModule } from '@angular/upgrade/static' import {AppModule} from './app.module'; import {app} from "./app"; //I try to use first variant platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef =&gt; { const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule; upgrade.bootstrap(document.body, ['app'], {strictDi: true}); }); //and second platformBrowserDynamic().bootstrapModule(AppModule).then(ref =&gt; { const upgrade = (&lt;any&gt;ref.instance).upgrade; upgrade.bootstrap(document.body, [app.name]); });</code></pre> </div> </div> </p> <p>and after first appers this error:</p> <p>Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.</p> <p>And after second variany this one:</p> <p>Error: TypeError: angular.module is not a function</p> <p>app.module.ts</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import {NgModule} from '@angular/core'; import {BrowserModule} from "@angular/platform-browser"; import {UpgradeModule} from "@angular/upgrade/static"; import {AppComponent} from "./app.component" @NgModule({ imports: [BrowserModule, UpgradeModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { constructor(public upgrade: UpgradeModule){} }</code></pre> </div> </div> </p> <p>package.json</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>{ "name": "app", "version": "0.0.1", "description": "app to migrate", "keywords": [], "homepage": "http://angularjs.org/", "main": "scripts/server.js", "scripts": { "build": "webpack", "build:watch": "tsc -p -w", "build:e2e": "tsc -p e2e/", "serve": "lite-server -c=bs-config.json", "serve:e2e": "lite-server -c=bs-config.e2e.json", "prestart": "npm run build", "start": "concurrently \"npm run build:watch\" \"npm run serve\"", "pree2e": "npm run build:e2e", "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first", "preprotractor": "webdriver-manager update", "protractor": "protractor protractor.config.js", "pretest": "npm run build", "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", "pretest:once": "npm run build", "test:once": "karma start karma.conf.js --single-run", "lint": "tslint ./**/*.ts -t verbose" }, "dependencies": { "@angular/common": "~4.0.0", "@angular/compiler": "~4.0.0", "@angular/compiler-cli": "^4.1.3", "@angular/core": "~4.0.0", "@angular/forms": "~4.0.0", "@angular/http": "~4.0.0", "@angular/platform-browser": "~4.0.0", "@angular/platform-browser-dynamic": "~4.0.0", "@angular/router": "~4.0.0", "@angular/upgrade": "^4.1.3", "@uirouter/angularjs": "^1.0.3", "angular": "^1.6.1", "angular-in-memory-web-api": "~0.3.0", "angular-resource": "^1.6.1", "body-parser": "^1.17.2", "core-js": "^2.4.1", "csv": "&gt;= 0.2.1", "express": "&gt;= 3.0.0", "morgan": "^1.8.2", "open": "&gt;= 0.0.2", "reflect-metadata": "^0.1.10", "rxjs": "5.0.1", "systemjs": "0.19.40", "testacular": "canary", "zone.js": "^0.8.4" }, "devDependencies": { "@angular/compiler-cli": "^4.0.0", "@ngtools/webpack": "1.2.4", "@types/jasmine": "2.5.36", "@types/node": "^6.0.46", "canonical-path": "0.0.2", "concurrently": "^3.2.0", "jasmine-core": "~2.4.1", "karma": "^1.3.0", "karma-chrome-launcher": "^2.0.0", "karma-cli": "^1.0.1", "karma-jasmine": "^1.0.2", "karma-jasmine-html-reporter": "^0.2.2", "lite-server": "^2.2.2", "lodash": "^4.16.4", "protractor": "~4.0.14", "rimraf": "^2.5.4", "tslint": "^3.15.1", "typescript": "~2.1.0", "webpack": "^2.6.1" }, "engines": { "node": "&gt;= 0.8.4" }, "license": "MIT" }</code></pre> </div> </div> </p>
3
2,468
java ssl hanshake exception
<p>I know there has been lots of questions regarding this ssl hand shake, I still could not figure this out. I am trying to submit a java-ws soap message to <a href="https://demo296.vertexinc.com/vertex-ws/services/CalculateTax70?wsdl" rel="nofollow">link</a> and end point got proper certificate, but why java won't honor it and gives this well known exception:</p> <pre><code>Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target </code></pre> <p>When I enable network debugging, I get following:</p> <pre><code>%% No cached client session *** ClientHello, TLSv1 RandomCookie: GMT: 1460059402 bytes = { 161, 121, 184, 113, 145, 191, 213, 189, 184, 72, 172, 65, 62, 227, 170, 31, 178, 118, 248, 177, 185, 159, 199, 169, 12, 109, 219, 190 } Session ID: {} Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, TLS_KRB5_WITH_3DES_EDE_CBC_SHA, TLS_KRB5_WITH_3DES_EDE_CBC_MD5, TLS_KRB5_WITH_RC4_128_SHA, TLS_KRB5_WITH_RC4_128_MD5, TLS_KRB5_WITH_DES_CBC_SHA, TLS_KRB5_WITH_DES_CBC_MD5, TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, TLS_KRB5_EXPORT_WITH_RC4_40_SHA, TLS_KRB5_EXPORT_WITH_RC4_40_MD5] Compression Methods: { 0 } Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1} Extension ec_point_formats, formats: [uncompressed] Extension server_name, server_name: [host_name: demo296.vertexinc.com] *** http-bio-443-exec-2, WRITE: TLSv1 Handshake, length = 213 http-bio-443-exec-2, READ: TLSv1 Handshake, length = 49 *** ServerHello, TLSv1 RandomCookie: GMT: 1460059402 bytes = { 87, 39, 164, 163, 199, 232, 199, 16, 238, 235, 203, 206, 70, 140, 226, 224, 163, 188, 121, 208, 109, 2, 153, 126, 2, 19, 50, 82 } Session ID: {} Cipher Suite: SSL_RSA_WITH_RC4_128_SHA Compression Method: 0 Extension renegotiation_info, renegotiated_connection: &lt;empty&gt; *** %% Initialized: [Session-2, SSL_RSA_WITH_RC4_128_SHA] ** SSL_RSA_WITH_RC4_128_SHA http-bio-443-exec-2, READ: TLSv1 Handshake, length = 1292 *** Certificate chain chain [0] = [ [ Version: V3 Subject: CN=*.vertexinc.com, OU=Vertex Inc., O=Vertex Inc, L=Berwyn, ST=Pennsylvania, C=US Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11 Key: Sun RSA public key, 2048 bits modulus: 21011005644752221458440925799952678183823792833716434828539993186933856337574997854121938343987119300440905398000025082799836849602033704013027189447726880355089766117512592061516178819039391085455553102645007112453032938831724998233033633698493476955604784493337783750130439099745399832839029789567413380485885064049847898628887513164667338660464585157036580363609549890856904881728624134009162466528991105337058182437282700845235389976741141724118492275741871053644597590803795354460154631255971959996923189046439657231520344375967087626815565942867567333556795133804268135785335388269336344735453096564729483564909 public exponent: 65537 Validity: [From: Sun Nov 09 19:00:00 EST 2014, To: Wed Nov 09 18:59:59 EST 2016] Issuer: CN=GeoTrust SSL CA - G3, O=GeoTrust Inc., C=US SerialNumber: [ 254cae2c 09b790ad ef6c356f 343deac7] Certificate Extensions: 8 [1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false AuthorityInfoAccess [ [ accessMethod: ocsp accessLocation: URIName: http://gn.symcd.com , accessMethod: caIssuers accessLocation: URIName: http://gn.symcb.com/gn.crt ] ] [2]: ObjectId: 2.5.29.35 Criticality=false AuthorityKeyIdentifier [ KeyIdentifier [ 0000: D2 6F F7 96 F4 85 3F 72 3C 30 7D 23 DA 85 78 9B .o....?r&lt;0.#..x. 0010: A3 7C 5A 7C ..Z. ] ] [3]: ObjectId: 2.5.29.19 Criticality=false BasicConstraints:[ CA:false PathLen: undefined ] [4]: ObjectId: 2.5.29.31 Criticality=false CRLDistributionPoints [ [DistributionPoint: [URIName: http://gn.symcb.com/gn.crl] ]] [5]: ObjectId: 2.5.29.32 Criticality=false CertificatePolicies [ [CertificatePolicyId: [2.16.840.1.113733.1.7.54] [PolicyQualifierInfo: [ qualifierID: 1.3.6.1.5.5.7.2.1 qualifier: 0000: 16 33 68 74 74 70 73 3A 2F 2F 77 77 77 2E 67 65 .3https://www.ge 0010: 6F 74 72 75 73 74 2E 63 6F 6D 2F 72 65 73 6F 75 otrust.com/resou 0020: 72 63 65 73 2F 72 65 70 6F 73 69 74 6F 72 79 2F rces/repository/ 0030: 6C 65 67 61 6C legal ], PolicyQualifierInfo: [ qualifierID: 1.3.6.1.5.5.7.2.2 qualifier: 0000: 30 35 0C 33 68 74 74 70 73 3A 2F 2F 77 77 77 2E 05.3https://www. 0010: 67 65 6F 74 72 75 73 74 2E 63 6F 6D 2F 72 65 73 geotrust.com/res 0020: 6F 75 72 63 65 73 2F 72 65 70 6F 73 69 74 6F 72 ources/repositor 0030: 79 2F 6C 65 67 61 6C y/legal ]] ] ] [6]: ObjectId: 2.5.29.37 Criticality=false ExtendedKeyUsages [ serverAuth clientAuth ] [7]: ObjectId: 2.5.29.15 Criticality=true KeyUsage [ DigitalSignature Key_Encipherment ] [8]: ObjectId: 2.5.29.17 Criticality=false SubjectAlternativeName [ DNSName: *.vertexinc.com DNSName: vertexinc.com ] ] Algorithm: [SHA256withRSA] Signature: 0000: 8B 63 CB B1 74 E3 15 E8 24 1D C9 31 DF 0B A5 F2 .c..t...$..1.... 0010: 04 72 FF 9A CD E0 AD 36 4B E1 C6 2C 02 39 BB C2 .r.....6K..,.9.. 0020: CB 8C CE BE 60 EF 59 59 7E 20 47 90 47 9A 10 35 ....`.YY. G.G..5 0030: C4 1C 96 3D 11 7C C0 1D 02 E5 E8 32 FC 2E E8 E5 ...=.......2.... 0040: 17 DB 52 70 C1 79 38 1B 9E 4F CF 8E 09 5B 96 EB ..Rp.y8..O...[.. 0050: F9 FB DD 66 33 17 53 32 C7 37 AA 1D D1 84 05 D6 ...f3.S2.7...... 0060: 53 84 CA AB 5F E7 DB 0E 12 F6 82 A9 24 7A ED 3C S..._.......$z.&lt; 0070: ED CC 5C 77 8D 0B D3 FD FD FA 6A 8B 34 C3 E1 2E ..\w......j.4... 0080: FB D8 31 B9 A1 5C BD 63 FD 66 01 00 69 D2 8A 13 ..1..\.c.f..i... 0090: 99 08 84 66 97 65 93 93 27 B7 70 A0 07 01 4F AD ...f.e..'.p...O. 00A0: 5C B4 BB 79 18 18 50 CD 64 85 38 9E 5C 39 20 FB \..y..P.d.8.\9 . 00B0: A3 C4 97 7C 65 9F 53 ED 25 D3 7A 02 08 BC DB 28 ....e.S.%.z....( 00C0: 09 F1 12 62 D7 9E 21 22 BF 36 B3 66 35 77 1C 6D ...b..!".6.f5w.m 00D0: EE E8 67 F2 49 A9 6A B1 1B B8 70 63 09 19 F2 71 ..g.I.j...pc...q 00E0: 7C BD 6C 70 5B C1 FE 17 1A E4 80 26 55 7F F1 1D ..lp[......&amp;U... 00F0: BF 57 38 D2 34 49 80 13 5B DB 1F 16 C1 A6 A8 82 .W8.4I..[....... ] *** %% Invalidated: [Session-2, SSL_RSA_WITH_RC4_128_SHA] http-bio-443-exec-2, SEND TLSv1 ALERT: fatal, description = certificate_unknown http-bio-443-exec-2, WRITE: TLSv1 Alert, length = 2 http-bio-443-exec-2, called closeSocket() http-bio-443-exec-2, handling exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target </code></pre> <p>As you can see from the end point, cert chain is coming from authority.</p> <p><a href="http://i.stack.imgur.com/UdA1I.png" rel="nofollow">screenshot</a></p> <p>GeoTrust Global CA is the root chain and included in default jdk cacerts. I was thinking if root issuer is trusted and in cacerts then java should honor it, but it did not. Then 2nd cacerts chain GeoTrust SSL CA - G3 is not there and I imported it. Still did not work. I can import the entire cert chain, but why java won't honor trusted authority in this case?</p> <p>Thank you!</p>
3
3,826
Chrome web app using firebase returns mismatchsenderid error
<p>I apologise as this question has been asked many times, but none of the responses have been helpful in resolving my issue.</p> <p>I am using firebase with my web app and attempting to send notifications via php or terminal curl command. Have tried both with same error:</p> <blockquote> <p>{"multicast_id":4984414565388562908,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}</p> </blockquote> <p>I am getting the API key and sender id straight from firebase from the same place. Copying and pasting, no typos. Checked about 50 times... 100% sure the sender id matches the API key as i am copying and pasting from the same screen.</p> <p><a href="https://i.stack.imgur.com/HKmDC.png" rel="nofollow"><img src="https://i.stack.imgur.com/HKmDC.png" alt="Firebase console"></a></p> <p>I am getting the endpoint from the Chrome console:</p> <p><a href="https://i.stack.imgur.com/mFPu4.png" rel="nofollow"><img src="https://i.stack.imgur.com/mFPu4.png" alt="Endpoint"></a></p> <p>Again, copied and pasted with no typos.</p> <p>My PHP file:</p> <pre><code>&lt;?php // API access key from Google API's Console define( 'API_ACCESS_KEY', '**API_KEY**' ); $registrationIds = array('**SUBSCRIPTION_ID**'); // prep the bundle $msg = array ( 'message' =&gt; $_GET["message"], 'title' =&gt; $_GET["title"], 'subtitle' =&gt; $_GET["subtitle"], 'tickerText' =&gt; $_GET["ticker"], 'vibrate' =&gt; 1, 'sound' =&gt; 1, 'largeIcon' =&gt; 'http://a4.mzstatic.com/au/r30/Purple4/v4/d2/8b/e4/d28be43c-9a6a-4b91-1981-a108ba5cec84/icon175x175.png', 'smallIcon' =&gt; 'http://www.uidownload.com/files/303/56/11/small-arrow-left-fast-rewind-icon.png', 'click_action' =&gt; 'https://aiatsis.gov.au' ); $fields = array ( 'registration_ids' =&gt; $registrationIds, 'data' =&gt; $msg ); $headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch ); echo $result; ?&gt; </code></pre> <p>My Manifest file:</p> <pre><code>{ "name": "Webpush", "gcm_sender_id": "**SENDER_ID**" } </code></pre> <p>The curl terminal command i am using is:</p> <pre><code>curl --header "Authorization: key=**API_KEY**" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"registration_ids\":[\"**SUBSCRIPTION_ID**\"]}" </code></pre> <p>I have no idea why this is not working. I have tried:</p> <ul> <li>Checking the Key matches the sender id about 150 times.</li> <li>Deleting my firebase project and starting again with new API key and Sender ID (yes i generated a new endpoint subscription id after i did this).</li> <li>As mentioned, tried both php and terminal push requests.</li> </ul> <p>I have run out of options. And as mentioned several times already the API key matches the corresponding sender ID. I am 100% sure of this. As far as my understanding of the "MismatchSenderId" error, they are trying to tell me that the API key and sender ID do not match. They do match.</p> <ul> <li>The sender ID matches the API key</li> <li>The Subscription ID was generated using the correct sender ID</li> </ul> <p>Does anyone have any idea why this is happening?</p>
3
1,382
XAMPP/AJAX/PHP Issue with saving
<p>I'm very new to programming and have been trying to make a website application to learn some web development, using XAMPP on Windows as the local web server. I've gotten to the point where I'm trying to incorporate some AJAX by loading some info from the database asynchronously. But any time I make a change to the PHP file that is being called by myFunction() below and save it, the updates don't show up when I refresh the page. I have to close and reopen the browser in order for the changes I've made to appear. The only thing I can think of is that when the browser gets closed the session gets destroyed, but I can't figure out why an update to the PHP file shouldn't show up when I refresh the page. Any help would be appreciated. Here is the file that is shown in the browser: </p> <pre><code>&lt;?php include 'core/init.php'; include 'includes/overall/header.php'; protect_page(); ?&gt; &lt;body&gt; &lt;div id="ticker"&gt; &lt;?php include 'includes/teams.php'; ?&gt; &lt;/div&gt; &lt;div id="teaminfo"&gt;&lt;/div&gt; &lt;h2&gt;Welcome to your homepage, &lt;?php echo $user_data['first_name']; ?&gt;&lt;/h2&gt; &lt;a href="createleague.php"&gt;Create a League&lt;/a&gt;&lt;br&gt;&lt;br&gt; &lt;a href="logout.php"&gt;Logout&lt;/a&gt;&lt;br&gt;&lt;br&gt; &lt;script&gt; function myFunction(team_id) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) { document.getElementById("teaminfo").innerHTML = xmlhttp.responseText; } } xmlhttp.open('GET', 'teaminfo.php?x=' + team_id, true); xmlhttp.send(); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and the php page:</p> <pre><code>&lt;?php include 'core/database/connect.php'; $team_id = $_GET['x']; $sql = "SELECT name, wins, losses FROM hockey_team WHERE id = '$team_id'"; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)) { echo "&lt;h1 id='team_name'&gt;" . $row['name'] . "&lt;/h1&gt;"; echo "&lt;p id='wins'&gt;" . $row['wins'] . "&lt;/p&gt;"; echo "&lt;p id='losses'&gt;" . $row['losses'] . "&lt;/p&gt;"; } mysql_close(); ?&gt; </code></pre>
3
1,064
Spring Hibernate integration test returns unexpected result
<p>I am using Maven, Hibernate and Spring in my application. I have implemented entity classes, DAO classes and service classes in packages of their own. I have problem when testing a service. When unit testing a DAO method that this specific service is calling the result is expected. But when testing a service method that is using this DAO method I don't get the same result. I think this problem is related to integration. Service is annoted with @Transactional. Data source and service are annotated with @Autowired in testing class of service. I attached context configuration of the service testing class.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"&gt; &lt;bean id="class1Dao" class="org.project.datalayer.implementation.Class1DaoImplementation"&gt; &lt;/bean&gt; &lt;bean id="service" class="org.project.services.implementation.Service1Implementation"&gt; &lt;property name="class1Dao"&gt; &lt;ref bean="class1Dao" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver" /&gt; &lt;property name="url" value="jdbc:hsqldb:mem:project" /&gt; &lt;property name="username" value="username" /&gt; &lt;property name="password" value="password" /&gt; &lt;/bean&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;context:annotation-config /&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;tx:annotation-driven /&gt; &lt;/beans&gt; </code></pre> <p>Sample code as requested:</p> <p><strong>Entities</strong></p> <pre><code>@MappedSuperclass public abstract class ClassBase implements Serializable { @Id() @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Integer id; @Version private int version = 0; private Date created; private Date updated; /** * @return the id */ public Integer getId() { return id; } @PrePersist @Column(name = "created", nullable = false) protected void onCreate() { this.created = new Date(); } @PreUpdate @Column(name = "updated", nullable = false) protected void onUpdate() { this.updated = new Date(); } /** * @return the version */ public int getVersion() { return this.version; } /** * @param version the version to set */ public void setVersion(int version) { this.version = version; } /** * @return the created */ public Date getCreated() { return this.created; } /** * @return the updated */ public Date getUpdated() { return this.updated; } } @Entity @Table(name = "class1") class Class1 extends ClassBase { @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "class1_id") private List&lt;Class2&gt; class2List = new ArrayList&lt;Class2&gt;(); @OneToMany(mappedBy = "class1", cascade = CascadeType.ALL) private List&lt;Class1Class4&gt; class1Class4List = new ArrayList&lt;Class1Class4&gt;(); } @Entity @Table(name = "class1_class4") class Class1Class4 extends ClassBase { @ManyToOne(optional = false, cascade = CascadeType.ALL) @JoinColumn(name="class4_id") private Class4 class4; @ManyToOne(optional = false, cascade = CascadeType.ALL) @JoinColumn(name="class1_id") private Class1 class1; } @Entity @Table(name = "class2") class Class2 extends ClassBase { @OneToMany(mappedBy = "class1", cascade = CascadeType.ALL) private Class1 class1; @OneToMany(mappedBy = "class2", cascade = CascadeType.ALL) private List&lt;Class2Class3&gt; class2Class3List = new ArrayList&lt;Class2Class3&gt;(); } @Entity @Table(name = "class2_class3") class Class2Class3 extends ClassBase { @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "class2_id") private Class2 class2; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "class3_id") private Class3 class3; } @Entity @Table(name = "class3") class Class3 extends ClassBase { @OneToMany(mappedBy = "class3", cascade = CascadeType.ALL) private List&lt;Class2Class3&gt; class2Class3List = new ArrayList&lt;Class2Class3&gt;(); @OneToOne(cascade = CascadeType.ALL) @JoinColumns({ @JoinColumn(name = "class4_id", referencedColumnName = "id") }) private Class4 class4; @ManyToOne(cascade = CascadeType.ALL) @ForeignKey(name = "fk_class3_to_parent", inverseName = "fk_parent_to_class3") private Class3 parent; @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL) private Set&lt;Class3&gt; descendantList = new HashSet&lt;Class3&gt;(); ... } @Entity @Table(name = "class4") class Class4 extends ClassBase { @OneToOne(mappedBy="class4") private Class3 class3; @OneToMany(mappedBy = "class4", cascade = CascadeType.ALL) private List&lt;Class1Class4&gt; class1Class4List = new ArrayList&lt;Class1Class4&gt;(); } </code></pre> <p><strong>DAO</strong></p> <pre><code>public class Class1DaoImplementation extends BaseDaoTemplate&lt;Class1&gt; implements Class1Dao { public Class1DaoImplementation() { super(Class1.class); } public Class getPublicByPrimaryKey(Integer id) { EntityManager em = getEntityManager(); Query q = em.createQuery("SELECT distinct(p) FROM Class1 p" + " INNER JOIN p.class5 ps" + " INNER JOIN FETCH p.class2 it" + " INNER JOIN FETCH it.class2Class3List itfs" + " INNER JOIN FETCH itfs.class3 f" + " LEFT JOIN FETCH f.parent fp" // PROBLEM: null when running integration test + " LEFT JOIN FETCH f.descendants fd" + " WHERE p.id = :class1Id" + " AND ps.id = 5" + " ORDER BY p.id" ); q.setParameter("class1Id", id); return (Class1) q.getSingleResult(); } } </code></pre> <p>Could the problem be related to the complexity of the query of the method getPublicByPrimaryKey? But if the method is working fine during unit tests why it is working differently while running integration tests?</p> <p>Test data:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;dataset&gt; &lt;!--ELEMENT CLASS3 EMPTY--&gt; &lt;!--ATTLIST CLASS3 PARAM1 CDATA #REQUIRED ID CDATA #REQUIRED PARAM2 CDATA #REQUIRED PARENT_ID CDATA #IMPLIED --&gt; ]&gt; &lt;class3 param1="0" id="1" param2="5" /&gt; &lt;class3 param1="0" id="2" param2="5" /&gt; &lt;class3 param1="0" id="3" param2="5" parent_id="1" /&gt; &lt;class3 param1="0" id="4" param2="5" parent_id="1" /&gt; &lt;class3 param1="0" id="5" param2="5" parent_id="2" /&gt; </code></pre> <p></p> <p>Loading of test data: Connection connection = DataSourceUtils.getConnection(dataSource);</p> <pre><code>ArrayList&lt;String&gt; dbunitFilePaths = new ArrayList&lt;String&gt;(); dbunitFilePaths.add("/class3.xml"); ListIterator&lt;String&gt; dbunitFilePathsIterator = dbunitFilePaths.listIterator(); try { IDatabaseConnection dbUnitConnection = new DatabaseConnection(connection); String dbunitFilePath; ClassPathResource xml; IDataSet[] dataSets = new IDataSet[dbunitFilePaths.size()]; for(int i = 0; i &lt; dbunitFilePaths.size(); i++) { dbunitFilePath = dbunitFilePathsIterator.next(); xml = new ClassPathResource(dbunitFilePath); dataSets[i] = new FlatXmlDataSetBuilder().build(xml.getInputStream()); } CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets); DatabaseOperation.CLEAN_INSERT.execute(dbUnitConnection, compositeDataSet); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } </code></pre> <p>If I edit the file loading method like this...</p> <pre><code> ... ListIterator&lt;String&gt; dbunitFilePathsIterator = dbunitFilePaths.listIterator(); FlatXmlDataSetBuilder flatXmlDataSetBuilder; try { ... xml = new ClassPathResource(dbunitFilePath); flatXmlDataSetBuilder = new FlatXmlDataSetBuilder().setColumnSensing(true); dataSets[i] = flatXmlDataSetBuilder.build(xml.getInputStream()); } ... </code></pre> <p>...I then get the following message for the all BUT the first test method:</p> <pre><code> java.sql.SQLException: Integrity constraint violation FK_CLASS3_TO_PARENT table: CLASS3 </code></pre>
3
4,199
How to Pass Data From a BroadcastReceiver to an Activity in Android
<p>I am working on my first Android app, which is a paging device. It will intercept a SMS message from a certain number with a certain content in it, display that and then allow the user to send a pre-defined reply back to that same number. I have gathered up code snippets from numerous sources (including stackoverflow of course) but I haven't yet got it working.</p> <p>My file structure is as shown here</p> <p><a href="https://i.stack.imgur.com/QhnyE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QhnyE.jpg" alt="enter image description here" /></a></p> <p>The part I am struggling with is SmsBroadcastReceiver and ReceiveAlert, which should display the content of the SMS and has a button to initiate the reply.</p> <p>SmsBroadcastReceiver.java looks like this:</p> <pre><code>package com.example.alert6; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.provider.Telephony; import android.telephony.SmsMessage; public class SmsBroadcastReceiver extends BroadcastReceiver { public static final String EXTRA_MESSAGE = &quot;com.example.alert6.MESSAGE&quot;; @Override public void onReceive(Context context, Intent intent) { String smsSender = &quot;&quot;; String smsBody = &quot;&quot;; for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { smsSender = smsMessage.getOriginatingAddress(); smsBody = smsMessage.getMessageBody(); } if (smsSender.equals(&quot;+420775367297&quot;)) { if (smsBody.contains(&quot;Test&quot;)) { intent.putExtra(EXTRA_MESSAGE, smsBody); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // adding this flag starts the new Activity in a new Task context.startActivity(); } } } } </code></pre> <p>ReceiveAlertActivity.java is this:</p> <pre><code>package com.example.alert6; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class ReceiveAlertActivity extends AppCompatActivity { private static final int SMS_PERMISSION_CODE = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_receive_alert); } // Get the Intent that started this activity and extract the string Intent intent = getIntent(); String taskingalert = intent.getStringExtra(SmsBroadcastReceiver.EXTRA_MESSAGE); // Capture the layout's TextView and set the string as its text TextView receivedAlert = findViewById(R.id.receivedAlert); receivedAlert.setText(taskingalert); public boolean respond(View view) { if (!hasReadSmsPermission()) { requestReadAndSendSmsPermission(); return false; } Intent intent = new Intent(this, SendResponseActivity.class); startActivity(intent); return false; } /** * Runtime permission shenanigans */ private boolean hasReadSmsPermission() { return (ContextCompat.checkSelfPermission(ReceiveAlertActivity.this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) &amp;&amp; (ContextCompat.checkSelfPermission(ReceiveAlertActivity.this, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) &amp;&amp; (ContextCompat.checkSelfPermission(ReceiveAlertActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED); } private void requestReadAndSendSmsPermission() { ActivityCompat.requestPermissions(ReceiveAlertActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS}, SMS_PERMISSION_CODE); } } </code></pre> <p>And the manifest is this:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; package=&quot;com.example.alert6&quot;&gt; &lt;uses-permission android:name=&quot;android.permission.RECEIVE_SMS&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.READ_SMS&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.SEND_SMS&quot; /&gt; &lt;application android:allowBackup=&quot;true&quot; android:icon=&quot;@mipmap/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:roundIcon=&quot;@mipmap/ic_launcher_round&quot; android:supportsRtl=&quot;true&quot; android:theme=&quot;@style/Theme.Alert6&quot;&gt; &lt;activity android:name=&quot;.SendResponseActivity&quot; android:parentActivityName=&quot;.ReceiveAlertActivity&quot;&gt; &lt;/activity&gt; &lt;activity android:name=&quot;.ReceiveAlertActivity&quot; android:parentActivityName=&quot;.MainActivity&quot;&gt; &lt;/activity&gt; &lt;activity android:name=&quot;.MainActivity&quot;&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;receiver android:name=&quot;.SmsBroadcastReceiver&quot; android:enabled=&quot;true&quot; android:exported=&quot;true&quot; tools:ignore=&quot;Instantiatable&quot;&gt; &lt;intent-filter android:priority=&quot;999&quot; &gt; &lt;action android:name=&quot;android.provider.Telephony.SMS_RECEIVED&quot; /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>Android Studio is showing errors in SmsBroadcastReceiver and ReceiveAlertActivity but not giving enough information to resolve them.</p> <p>In SmsBroadcastReceiver, it tells me it cannot resolve method 'startActivity()'. Something needs to go in the brackets, but what?</p> <p>In ReceiveAlertActivity the problems revolve around receivedalert and taskingalert. It cannot resolve setText because taskingalert is an unknown class. Obviously it's not a class, it's a string so I'm doing something wrong, but what?</p> <p>Sorting out these problems may not be the end. At the moment I can't test if the app works because the build fails due to the above. Then if I get this lot working, I have some other challenges, like waking up the screen and playing a sound the broadcast receiver is triggered, and stopping the sound when the button is pressed.</p>
3
2,880
ChartJS doughnut colors not showing from a Flask app. All gray
<p>Looking for some help here. The doughnut chart is rendering properly, but all the colors are gray. I've scoured the chartjs site and googled, but I can't seem to solve this.</p> <p>Here's my code:</p> <pre><code>@app.route('/doughnut_chart') def doughnut_chart(): values = [] labels =['good', 'mediocre','bad'] colors = ['rgba(0, 153, 0, 0.1)', 'rgba(0,153,153,0.1)','rgba(102,153,51,0.1)'] good_high = db.session.query(func.sum(Jf_Q1.highwellbeing)/func.sum(Jf_Q1.good_job)).\ filter(Jf_Q1.working==1).filter(Jf_Q1.good_job==1) good_mod = db.session.query(func.sum(Jf_Q1.moderatewellbeing)/func.sum(Jf_Q1.good_job)).\ filter(Jf_Q1.working==1).filter(Jf_Q1.good_job==1) good_low = db.session.query(func.sum(Jf_Q1.lowwellbeing)/func.sum(Jf_Q1.good_job)).\ filter(Jf_Q1.working==1).filter(Jf_Q1.good_job==1) values = [0.82483097725875845114*100,0.14935464044253226798*100,0.01966810079901659496*100] return render_template('results.html', values=values,labels=labels, colors=colors) </code></pre> <p>and my script code on the web page:</p> <pre><code> new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels : {{labels | safe}}, backgroundColor: {{colors | safe}}, datasets: [{ data : {{values | safe}} }] }, options: { title: { display: true, text: 'Doughnut Chart Title' } } }); </code></pre> <p>Here's how it looks in Chrome's inspector:</p> <pre><code> new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels : ['good', 'mediocre', 'bad'], backgroundColor: ['rgba(0, 153, 0, 0.1)', 'rgba(0,153,153,0.1)', 'rgba(102,153,51,0.1)'], datasets: [{ data : [82.48309772587584, 14.935464044253226, 1.9668100799016592] }] }, options: { title: { display: true, text: 'Doughnut Chart Title' } } }); </code></pre> <p>I've tried hex colors such as:</p> <pre><code>backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"] </code></pre> <p>But still no dice</p> <p>This is what is looks like in Chrome and in FF:</p> <p><a href="https://i.stack.imgur.com/QYiIB.png" rel="nofollow noreferrer">my chart</a></p> <p>Any assistance is greatly appreciated.</p> <p>Thanks</p>
3
1,378
How to get Row where two Columns equal specific values
<p>I'm very new and I'm trying to create a Time in/Time out sheet. I have 2 separate sheets, first(ACTIVE) is where the trigger happens that starts the onEdit(e) script. All the functions that start onEdit(e) affects the second sheet(PASSIVE) to fill out Columns A(Last Name), B(First Name), C(Location), D(Time Out). I finished making the Time out functions by getting value of A, B, C + Active Row(this isn't the code). The trigger is always on the same row as the values being copied, so it was relatively simple. On the PASSIVE sheet I have all the values being stored using a code someone made called addRecord where it gets last row + 1 of the PASSIVE sheet and installs the values grabbed from the ACTIVE sheet and plugs them in. So it adds records without overwriting anything. Works beautifully. However making a "time in" function has been difficult. E(Time In) My idea is to getRow of the PASSIVE sheet by searching PASSIVE!A for the Value grabbed from (ACTIVE!A + Active Row) once it finds a match, it sees if (PASSIVE!E + the matched row) is empty. If it is, it adds new.Date and finishes. If it isn't empty, it ignores this row and continues searching down the line for the next Row that has PASSIVE!A match the grabbed value. Once it finds this Row, getRow. setValue of (PASSIVE!E + grabbed row, new Date()) </p> <p>I did find a function online to find the first row that matched the ACTIVE!A with PASSIVE!A. But it kept overwriting the date on the first match. It never ignored row with nonempty cell to the next match row. Maybe I was just slightly off, which is why I'm asking for a lot of detail and explanation in the Answers. This was the Code I used from another answer. </p> <pre><code>function getCurrentRow() { var currentRow = SpreadsheetApp.getActiveSheet().getActiveSelection().getRowIndex(); return currentRow; } function onSearch1() { </code></pre> <p>What I added</p> <pre><code> var row = getCurrentRow(); var activeLocation = getValue('ACTIVE!A' + row); </code></pre> <p>Continued Other Code</p> <pre><code> var searchString = activeLocation; var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PASSIVE"); var column =1; //column Index var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st is header row var searchResult = columnValues.findIndex(searchString); //Row Index - 2 </code></pre> <p>What I added</p> <pre><code> setValue(PASSIVE!E + searchResult, new Date().toLocaleString()) </code></pre> <p>It worked if everyone has a different name, but the search Result always found the first row of the match, I tried adding an if ACTIVE!A == PASSIVE!A &amp;&amp; PASSIVE!E =="", grabRow (I know this isn't proper code) But I didn't even know where to put this if function or if it would work or if it would just keep coming up false after it runs the first time true. </p> <p>Continued Other Code</p> <pre><code>if(searchResult != -1) { //searchResult + 2 is row index. SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PASSIVE").setActiveRange(sheet.getRange(searchResult + 2, 1)) } if(searchResult = searchResult2) { setValue('PASSIVE!E' + searchResult, new Date().toLocaleString()) } } Array.prototype.findIndex = function(search){ if(search == "") return false; for (var i=0; i&lt;this.length; i++) if(this[i] == search) return i; return -1; } </code></pre> <p>So this is what I used, but not sure if it's the right way to go about this. Every time I used it, it would only set the SearchResult to the first row it found that had the searchString I'd actually prefer if it found the last row, considering the add record goes down over time and signing in should be the most recent name. But I'm guessing if I can just get a function that searches a range and finds the row for two values in specific columns, I can then just <code>setValue('PASSIVE!E' + foundRow, new Date().toLocaleString())</code></p> <p>Edit 5/9/2019 17:34 PST Thank you to those Answering. I'm expanding on the question.</p> <pre><code>function rowWhereTwoColumnsEqual(value1,col1,value2,col2) { var value1=value1 || 'A1';//testing var value2=value2 || ""; </code></pre> <p>The idea I'm having is to search Column1 of another sheet for, let's say, 'SheetA1' (the first sheet). And Column3 of another sheet for "" (cellisempty).</p> <pre><code>var value1= 'Sheet1!A1'; var value2= ""; var col1='Sheet2!A'; var col2='Sheet2!C'; var ss=SpreadsheetApp.getActive(); var sh=ss.getSheetByName('Sheet2'); var rg=sh.getDataRange(); var vA=rg.getValues(); </code></pre> <p>However, I don't know how the vA works. I also want to getRow() of the Row that is found in order to use that number in another function.</p>
3
1,471
Why am I receiving a error when trying to use tkinter to make multiple windows?
<p>I bolded the parts where I think the problem occurs. When run, the program stops and does not do anything but continues to run. This is a part of a bigger project to try to code minesweeper. I put ###HERE### on places where the problem occurs. ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎ ‏‏‎ ‎‏‏‎ ‎ ‏‏‎ ‎</p> <pre><code>from tkinter import * from tkinter import Canvas from PIL import ImageTk, Image from time import sleep class ResizingCanvas(Canvas): def __init__(self,parent,**kwargs): Canvas.__init__(self,parent,**kwargs) self.bind(&quot;&lt;Configure&gt;&quot;, self.on_resize) self.height = self.winfo_reqheight() self.width = self.winfo_reqwidth() def on_resize(self,event): # determine the ratio of old width/height to new width/height wscale = float(event.width)/self.width hscale = float(event.height)/self.height self.width = event.width self.height = event.height # resize the canvas self.config(width=self.width, height=self.height) # rescale all the objects tagged with the &quot;all&quot; tag self.scale(&quot;all&quot;,0,0,wscale,hscale) class Minesweeper(Tk): def __init__(self, master): Tk.__init__(self) fr = Frame(self) fr.pack(fill=BOTH, expand=YES) self.canvas = ResizingCanvas(fr, width=940, height=920, bg=&quot;black&quot;, highlightthickness=0) self.canvas.pack(fill=BOTH, expand=YES) self.count = 0 self.start = 0 self.newWindow = Toplevel(self.master) ####HERE### self.app = Control(self.newWindow) ####HERE### self.title(&quot;MineSweeper&quot;) x1 = 20 y1 = 20 x2 = 80 y2 = 80 self.block_pic = PhotoImage(file='C:/Users/akiva/OneDrive/Desktop/block.PNG') self.flag_pic = PhotoImage(file='C:/Users/akiva/OneDrive/Desktop/flag.PNG') for k in range(14): for i in range(15): self.canvas.create_rectangle(x1, y1, x2, y2, fill='white') x1 += 60 x2 += 60 x1 = 20 x2 = 80 y1 += 60 y2 += 60 def shift_image(self): if self.count == 0: Tk.canvas.itemconfig(self.block_pic, image=self.flag_pic) def end(self): del self.block_pic print(&quot;Game has ended&quot;) self.after(2000, quit()) print(&quot;Game has ended&quot;) self.start = 0 def frame(self): self.start += 1 if self.start == 1: x1 = 50 y1 = 50 for i in range(14): for k in range(15): self.canvas.create_image(x1, y1, image=self.block_pic) x1 += 60 x1 = 50 y1 += 60 self.canvas.pack() else: print(&quot;Game has already started&quot;) class Control: def __init__(self, master): self.master = master self.frame = Frame(self.master) **start_button = Button(self.frame, text=&quot;Start Game&quot;, command=Minesweeper(Tk).frame(),) ####HERE### stop_button = Button(self.frame, text=&quot;End Game&quot;, command=Minesweeper(Tk).end()) ####HERE### start_button.pack() stop_button.pack() self.quitButton = Button(self.frame, text='Quit', width=25, command=self.close_windows) self.quitButton.pack() self.frame.pack() def close_windows(self): self.master.destroy() if __name__ == &quot;__main__&quot;: root = Tk window = Minesweeper(root) root.mainloop() </code></pre> <pre><code>Traceback (most recent call last): File &quot;C:/Users/akiva/PycharmProjects/helloOpencv/Mine_sweeper.py&quot;, line 107, in &lt;module&gt; window = Minesweeper(root) File &quot;C:/Users/akiva/PycharmProjects/helloOpencv/Mine_sweeper.py&quot;, line 37, in __init__ self.app = Control(self.newWindow) File &quot;C:/Users/akiva/PycharmProjects/helloOpencv/Mine_sweeper.py&quot;, line 86, in __init__ start_button = Button(self.frame, text=&quot;Start Game&quot;, command=Minesweeper(Tk).frame(),) File &quot;C:/Users/akiva/PycharmProjects/helloOpencv/Mine_sweeper.py&quot;, line 37, in __init__ self.app = Control(self.newWindow) File &quot;C:/Users/akiva/PycharmProjects/helloOpencv/Mine_sweeper.py&quot;, line 86, in __init__ start_button = Button(self.frame, text=&quot;Start Game&quot;, command=Minesweeper(Tk).frame(),) File &quot;C:/Users/akiva/PycharmProjects/helloOpencv/Mine_sweeper.py&quot;, line 29, in __init__ Tk.__init__(self) </code></pre>
3
2,248
post method not working in angular js
<p>I am trying to add data's in table by using angularjs, spring, and hibernet. Below is the code that I am using :</p> <p><strong>addCustomer.js</strong></p> <pre><code>var addNewCustomerModule = angular.module('addNewCustomer',[]); var c=angular.module('addCustomerController',[]); addNewCustomerModule.controller('addCustomerController', function ($scope,$http) { //$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; var urlBase="http://localhost:8081/manufacturing"; var customerDetails={}; $scope.addCustomer = function addCustomer() { customerDetails=$scope.customer; alert("hai"); $http.post(urlBase + '/addCustomer/new/',customerDetails). success(function(data) { alert("Customer added"); $scope.customer = data; }); } }); </code></pre> <p><strong>addCustomer.jsp</strong></p> <pre><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html ng-app="addNewCustomer"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Add Customer&lt;/title&gt; &lt;script data-require="angular.js@*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"&gt;&lt;/script&gt; &lt;script src="&lt;c:url value="/resources/js/addCustomer.js"/&gt;"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="addCustomerController"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; FirstName:&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.firstName"/&gt;&lt;/td&gt; &lt;td&gt;LastName:&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.lastName"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Designation&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.designation"/&gt;&lt;/td&gt; &lt;td&gt;Email&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.email"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Phone&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.phone"/&gt;&lt;/td&gt; &lt;td&gt;Fax&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.fax"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Website&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.website"/&gt;&lt;/td&gt; &lt;td&gt;ContactType&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.contact_type"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AddressTitle&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.addressTitle"/&gt;&lt;/td&gt; &lt;td&gt;AddressLine1&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.addressLine1"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AddressLine2&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.addressLine2"/&gt;&lt;/td&gt; &lt;td&gt;City&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.city"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;State&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.state"/&gt;&lt;/td&gt; &lt;td&gt;Country&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.country"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;PinCode&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.pincode"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Type&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.type"/&gt;&lt;/td&gt; &lt;td&gt;Name&lt;/td&gt; &lt;td&gt;&lt;input type="text" ng-model="customer.name"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button ng-click="addCustomer()" class="btn-panel-big"&gt;Add New Customer&lt;/button&gt;&lt;/td&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>spring controller</strong></p> <pre><code> @RequestMapping(value="/addCustomer/new/",method=RequestMethod.POST) public String updateUser(@RequestBody Customer cu,HttpSession session) throws ParseException{ customerService.addCustomer(cu); return "addCustomer"; } </code></pre> <p>Here <strong>$http.post(urlBase + '/addCustomer/new/',customerDetails)</strong> it doesn't call my spring controller.i checked in browser debug it says url 404 error but i have the controller for this url. i don't know how to fix this can any one help me to fix this</p>
3
2,373
T4240RDB-64B - QoIQ SDK 2.0 - Kernel crashes
<p>I built T4240rdb-64b with QorIQ-SDK-V2.0-20160527-yocto on Ubuntu Linux 16. LTS 64bit. This is my commands to build it:</p> <pre><code>~/QorIQ-SDK-V2.0-20160527-yocto$ source ./fsl-setup-env -m t4240rdb-64b Configuring for t4240rdb-64b ... ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b was created before. Back to build project ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b. Nothing is changed. ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b$ bitbake fsl-image-minimal WARNING: Host distribution "Ubuntu-16.04" has not been validated with this version of the build system; you may possibly experience unexpected failures. It is recommended that you use a tested distribution. Loading cache: 100% |##########################################################################################################| ETA: 00:00:00 Loaded 6050 entries from dependency cache. NOTE: Resolving any missing task queue dependencies Build Configuration: BB_VERSION = "1.28.0" BUILD_SYS = "x86_64-linux" NATIVELSBSTRING = "Ubuntu-16.04" TARGET_SYS = "powerpc64-fsl-linux" MACHINE = "t4240rdb-64b" DISTRO = "fsl-qoriq" DISTRO_VERSION = "2.0" TUNE_FEATURES = "m64 fpu-hard e6500 altivec" TARGET_FPU = "hard" meta meta-yocto meta-yocto-bsp = "HEAD:9a211a4a2c1bfcb292dc97d8dcac149bca9e3f1b" meta-oe meta-multimedia meta-gnome meta-networking meta-perl meta-python meta-ruby meta-filesystems meta-webserver meta-xfce = "HEAD:dc5634968b270dde250690609f0015f881db81f2" meta-freescale = "HEAD:7facbdb726e2dda0515e084c2066a4b8dd99c6d2" meta-freescale-internal = "HEAD:4829293f807e35a1111e79763294fc8b98b97810" meta-freescale-extra = "HEAD:bee911b027e0480b034674d0ddee3fcb06d2e985" meta-virtualization = "HEAD:042425c1d98bdd7e44a62789bd03b375045266f5" meta-java = "HEAD:8b776ac68f9af4596be3824152bcf0bc6b67fa1d" meta-openstack meta-openstack-aio-deploy meta-openstack-compute-deploy meta-openstack-compute-test-config meta-openstack-controller-deploy meta-openstack-controller-test-config meta-openstack-qemu meta-openstack-swift-deploy meta-cloud-services = "HEAD:d8bc0d92d0f741e2ea1e6d3d9bc6b7a091d03cfb" meta-security = "HEAD:f9367e71f923fc7d2fb600208e2b97535ea41777" NOTE: Preparing RunQueue NOTE: Executing SetScene Tasks NOTE: Executing RunQueue Tasks NOTE: Tasks Summary: Attempted 1499 tasks of which 1499 didn't need to be rerun and all succeeded. Summary: There was 1 WARNING message shown. ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b$ </code></pre> <p>When I run QEMU with this command:</p> <pre><code>sudo ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b/tmp/sysroots/x86_64-linux/usr/bin/qemu-system-ppc64 \ -cpu e5500 -nographic -m 1028 -M ppce500 \ -kernel ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b/tmp/deploy/images/t4240rdb-64b/uImage \ -initrd ~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b/tmp/deploy/images/t4240rdb-64b/fsl-image-minimal-t4240rdb-64b.ext2.gz \ -append "root=/dev/ram rw console=ttyS0,115200 \ ip=26.26.26.2::26.26.26.1:255.255.255.0 mem=1028M" -serial tcp::4444,server,telnet -net nic,model=e1000 \ -net tap,ifname=tap0,script=no,downscript=no </code></pre> <p>It couldn't boot. This is boot massages:</p> <pre><code>~/QorIQ-SDK-V2.0-20160527-yocto/build_t4240rdb-64b$ telnet 26.26.26.1 4444 Trying 26.26.26.1... Connected to 26.26.26.1. Escape character is '^]'. Using QEMU e500 machine description MMU: Supported page sizes 4 KB as direct 4096 KB as direct 16384 KB as direct 65536 KB as direct 262144 KB as direct 1048576 KB as direct MMU: Book3E HW tablewalk not supported Found initrd at 0xc000000004000000:0xc000000004423e3b bootconsole [udbg0] enabled CPU maps initialized for 1 thread per core Starting Linux PPC64 #1 SMP Sun Jan 8 12:42:09 ICT 2017 ----------------------------------------------------- ppc64_pft_size = 0x0 phys_mem_size = 0x40000000 dcache_line_size = 0x40 icache_line_size = 0x40 cpu_features = 0x00180400181802c0 possible = 0x00180480581802c8 always = 0x00180400581802c0 cpu_user_features = 0xcc008000 0x08000000 mmu_features = 0x000a0010 firmware_features = 0x0000000000000000 ----------------------------------------------------- &lt;- setup_system() Linux version 4.1.8-rt8+gbd51baf (hstan@server-06) (gcc version 4.9.2 (GCC) ) #1 SMP Sun Jan 8 12:42:09 ICT 2017 qemu_e500_setup_arch() Zone ranges: DMA [mem 0x0000000000000000-0x000000003fffffff] DMA32 empty Normal empty Movable zone start for each node Early memory node ranges node 0: [mem 0x0000000000000000-0x000000003fffffff] Initmem setup node 0 [mem 0x0000000000000000-0x000000003fffffff] MMU: Allocated 2112 bytes of context maps for 255 contexts PERCPU: Embedded 17 pages/cpu @c00000003f000000 s28824 r0 d40808 u1048576 Built 1 zonelists in Zone order, mobility grouping on. Total pages: 258560 Kernel command line: root=/dev/ram rw console=ttyS0,115200 ip=26.26.26.2::26.26.26.1:255.255.255.0 mem=1028M PID hash table entries: 4096 (order: 3, 32768 bytes) Dentry cache hash table entries: 131072 (order: 8, 1048576 bytes) Inode-cache hash table entries: 65536 (order: 7, 524288 bytes) Sorting __ex_table... Memory: 949036K/1048576K available (7856K kernel code, 1132K rwdata, 3008K rodata, 364K init, 764K bss, 99540K reserved, 0K cma-reserved) Hierarchical RCU implementation. RCU debugfs-based tracing is enabled. CONFIG_RCU_FANOUT set to non-default value of 32 Additional per-CPU info printed with stalls. RCU restricting CPUs from NR_CPUS=24 to nr_cpu_ids=1. RCU: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=1 NR_IRQS:512 nr_irqs:512 16 mpic: Setting up MPIC " OpenPIC " version 1.2 at fe0040000, max 1 CPUs mpic: ISU size: 256, shift: 8, mask: ff mpic: Initializing for 256 sources clocksource timebase: mask: 0xffffffffffffffff max_cycles: 0x5c4093a7d1, max_idle_ns: 440795210635 ns clocksource: timebase mult[2800000] shift[24] registered Console: colour dummy device 80x25 pid_max: default: 32768 minimum: 301 Mount-cache hash table entries: 2048 (order: 2, 16384 bytes) Mountpoint-cache hash table entries: 2048 (order: 2, 16384 bytes) e500 family performance monitor hardware support registered Brought up 1 CPUs devtmpfs: initialized clocksource jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645041785100000 ns xor: measuring software checksum speed 8regs : 1289.000 MB/sec 8regs_prefetch: 1079.000 MB/sec 32regs : 1745.000 MB/sec 32regs_prefetch: 1572.000 MB/sec xor: using function: 32regs (1745.000 MB/sec) NET: Registered protocol family 16 Found FSL PCI host bridge at 0x0000000fe0008000. Firmware bus number: 0-&gt;255 PCI host bridge /pci@fe0008000 (primary) ranges: MEM 0x0000000c00000000..0x0000000c1fffffff -&gt; 0x00000000e0000000 IO 0x0000000fe1000000..0x0000000fe100ffff -&gt; 0x0000000000000000 /pci@fe0008000: PCICSRBAR @ 0xdff00000 setup_pci_atmu: end of DRAM 40000000 EDAC PCI0: Giving out device to module MPC85xx_edac controller mpc85xx_pci_err: DEV fe0008000.pci (INTERRUPT) MPC85xx_edac acquired irq 24 for PCI Err MPC85xx_edac PCI err registered fsl-pamu: fsl_pamu_init: could not find a PAMU node PCI: Probing PCI hardware fsl-pci fe0008000.pci: PCI host bridge to bus 0000:00 pci_bus 0000:00: root bus resource [io 0x10000-0x1ffff] (bus address [0x0000-0xffff]) pci_bus 0000:00: root bus resource [mem 0xc00000000-0xc1fffffff] (bus address [0xe0000000-0xffffffff]) pci_bus 0000:00: root bus resource [bus 00-ff] pci 0000:00:00.0: bridge configuration invalid ([bus 00-00]), reconfiguring pci 0000:00:00.0: PCI bridge to [bus 01-ff] PCI: Cannot allocate resource region 0 of device 0000:00:00.0, will remap pci 0000:00:00.0: BAR 0: assigned [mem 0xc00000000-0xc000fffff] pci 0000:00:00.0: BAR 8: assigned [mem 0xc00100000-0xc001fffff] pci 0000:00:01.0: BAR 6: assigned [mem 0xc00200000-0xc0023ffff pref] pci 0000:00:01.0: BAR 0: assigned [mem 0xc00240000-0xc0025ffff] pci 0000:00:01.0: BAR 1: assigned [io 0x11000-0x1103f] pci 0000:00:00.0: PCI bridge to [bus 01] pci 0000:00:00.0: bridge window [io 0x10000-0x10fff] pci 0000:00:00.0: bridge window [mem 0xc00100000-0xc001fffff] raid6: int64x1 gen() 721 MB/s raid6: int64x1 xor() 495 MB/s raid6: int64x2 gen() 1018 MB/s raid6: int64x2 xor() 370 MB/s raid6: int64x4 gen() 1334 MB/s raid6: int64x4 xor() 890 MB/s raid6: int64x8 gen() 650 MB/s raid6: int64x8 xor() 440 MB/s raid6: using algorithm int64x4 gen() 1334 MB/s raid6: .... xor() 890 MB/s, rmw enabled raid6: using intx1 recovery algorithm vgaarb: loaded SCSI subsystem initialized usbcore: registered new interface driver usbfs usbcore: registered new interface driver hub usbcore: registered new device driver usb pps_core: LinuxPPS API ver. 1 registered pps_core: Software ver. 5.3.6 - Copyright 2005-2007 Rodolfo Giometti &lt;giometti@linux.it&gt; PTP clock support registered EDAC MC: Ver: 3.0.0 No BMan portals available! QMan: Allocated lookup table at 8000000000002000, entry count 65537 No QMan portals available! No USDPAA memory, no 'fsl,usdpaa-mem' in device-tree Switched to clocksource timebase NET: Registered protocol family 2 TCP established hash table entries: 8192 (order: 4, 65536 bytes) TCP bind hash table entries: 8192 (order: 5, 131072 bytes) TCP: Hash tables configured (established 8192 bind 8192) UDP hash table entries: 512 (order: 2, 16384 bytes) UDP-Lite hash table entries: 512 (order: 2, 16384 bytes) NET: Registered protocol family 1 RPC: Registered named UNIX socket transport module. RPC: Registered udp transport module. RPC: Registered tcp transport module. RPC: Registered tcp NFSv4.1 backchannel transport module. Trying to unpack rootfs image as initramfs... rootfs image is not initramfs (no cpio magic); looks like an initrd Freeing initrd memory: 4236K (c000000004000000 - c000000004423000) futex hash table entries: 256 (order: 2, 16384 bytes) audit: initializing netlink subsys (disabled) audit: type=2000 audit(0.952:1): initialized HugeTLB registered 4 MB page size, pre-allocated 0 pages HugeTLB registered 16 MB page size, pre-allocated 0 pages HugeTLB registered 64 MB page size, pre-allocated 0 pages HugeTLB registered 256 MB page size, pre-allocated 0 pages HugeTLB registered 1 GB page size, pre-allocated 0 pages NFS: Registering the id_resolver key type Key type id_resolver registered Key type id_legacy registered ntfs: driver 2.1.32 [Flags: R/O]. jffs2: version 2.2. (NAND) © 2001-2006 Red Hat, Inc. async_tx: api initialized (async) io scheduler noop registered io scheduler deadline registered io scheduler cfq registered (default) Serial: 8250/16550 driver, 4 ports, IRQ sharing enabled console [ttyS0] disabled serial8250.0: ttyS0 at MMIO 0xfe0004500 (irq = 42, base_baud = 115200) is a 16550A console [ttyS0] enabled console [ttyS0] enabled bootconsole [udbg0] disabled bootconsole [udbg0] disabled ePAPR hypervisor byte channel driver brd: module loaded loop: module loaded st: Version 20101219, fixed bufsize 32768, s/g segs 256 libphy: Fixed MDIO Bus: probed Freescale FM module, FMD API version 21.1.0 Freescale FM Ports module fsl_mac: fsl_mac: FSL FMan MAC API based driver fsl_dpa: FSL DPAA Ethernet driver fsl_advanced: FSL DPAA Advanced drivers: fsl_proxy: FSL DPAA Proxy initialization driver fsl_dpa_shared: FSL DPAA Shared Ethernet driver fsl_dpa_macless: FSL DPAA MACless Ethernet driver fsl_oh: FSL FMan Offline Parsing port driver e1000e: Intel(R) PRO/1000 Network Driver - 2.3.2-k e1000e: Copyright(c) 1999 - 2014 Intel Corporation. ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver ehci-pci: EHCI PCI platform driver usbcore: registered new interface driver usb-storage i2c /dev entries driver md: raid6 personality registered for level 6 md: raid5 personality registered for level 5 md: raid4 personality registered for level 4 Freescale(R) MPC85xx EDAC driver, (C) 2006 Montavista Software sdhci: Secure Digital Host Controller Interface driver sdhci: Copyright(c) Pierre Ossman sdhci-pltfm: SDHCI platform and OF driver helper usbcore: registered new interface driver usbhid usbhid: USB HID core driver No fsl,qman node Freescale USDPAA process driver fsl-usdpaa: no region found Freescale USDPAA process IRQ driver dce_sys_init done! No fsl,dce node Freescale pme2 db driver PME2: fsl_pme2_db_init: not on ctrl-plane Freescale pme2 scan driver fsl-pme2-scan: device pme_scan registered Freescale hypervisor management driver fsl-hv: no hypervisor found ipip: IPv4 over IPv4 tunneling driver Initializing XFRM netlink socket NET: Registered protocol family 10 sit: IPv6 over IPv4 tunneling driver NET: Registered protocol family 17 NET: Registered protocol family 15 8021q: 802.1Q VLAN Support v1.8 Key type dns_resolver registered fsl_generic: FSL DPAA Generic Ethernet driver hctosys: unable to open rtc device (rtc0) md: Skipping autodetection of RAID arrays. (raid=autodetect will force) RAMDISK: gzip image found at block 0 VFS: Mounted root (ext2 filesystem) on device 1:0. devtmpfs: mounted Freeing unused kernel memory: 364K (c000000000aa3000 - c000000000afe000) init[1]: unhandled signal 4 at 00003fff90c3c0fc nip 00003fff90c3c0fc lr 00003fff90c1dd94 code 30001 Kernel panic - not syncing: Attempted to kill init! exitcode=0x00000004 CPU: 0 PID: 1 Comm: init Not tainted 4.1.8-rt8+gbd51baf #1 Call Trace: [c0000000390538d0] [c0000000007a34fc] .dump_stack+0x8c/0xb8 (unreliable) [c000000039053950] [c0000000007a0e34] .panic+0xf0/0x270 [c0000000390539f0] [c00000000003b520] .do_exit+0xa00/0xa04 [c000000039053ae0] [c00000000003c5a4] .do_group_exit+0x54/0xec [c000000039053b70] [c000000000048640] .get_signal+0x2f8/0x674 [c000000039053c70] [c0000000000092bc] .do_signal+0x44/0x218 [c000000039053db0] [c00000000000959c] .do_notify_resume+0x64/0x78 [c000000039053e30] [c000000000000c4c] .ret_from_except_lite+0x78/0x7c Rebooting in 180 seconds.. </code></pre> <p>I've try boot from SD card on real T4240RDB board, it happen the same error.</p> <p>Please help me. Thanks in advance</p>
3
5,172
Aquery image progressbar cant hide
<p>i was trying image load in a listadapter using android query library, My problem is progress is showing but not disapearing after image load completely </p> <p>I followed aquery documentation</p> <p>see this</p> <pre><code>String imageUrl = "http://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg"; aq.id(R.id.image).progress(R.id.progress).image(imageUrl, false, false); </code></pre> <p>And layout</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="100dip" &gt; &lt;ProgressBar android:layout_width="15dip" android:layout_height="15dip" android:id="@+id/progress" android:layout_centerInParent="true" /&gt; &lt;ImageView android:id="@+id/image" android:layout_width="fill_parent" android:layout_height="75dip" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>In my code its is like </p> <pre><code> public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate( R.layout.galleryitem, null); holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.imageview.setId(position); holder.checkbox.setVisibility(View.GONE); holder.imageview.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub int id = v.getId(); Intent ia = new Intent(getApplicationContext(),PreviewImage.class); ia.putExtra("url",id); startActivity(ia); } }); AQuery aq = new AQuery(convertView); try{ aq.id(holder.imageview).image(arrPath[position]).progress(R.id.progress); } catch(Exception e) {} holder.id = position; return convertView; } } </code></pre>
3
1,219
Sql transaction is complete exception
<p>I have a strange problem. All documentation states that the <code>SaveChanges()</code> method must be first called before committing the transaction but in my case it is throwing an exception if done this way. By calling Commit before <code>SaveChanges()</code> I can avoid the "Sql transaction is complete exception"</p> <pre><code> [HttpPost] public ActionResult ajax_SaveScreentest(string ScreenTestResult = "") { var shops = from m in db_emp.WorkLocations where m.LocationType == "Shop" select m; db.Database.Connection.Open(); using (var dbtran = db.Database.Connection.BeginTransaction()) { try { if (ScreenTestResult != "") { var sc = js.Deserialize&lt;ScreenTest&gt;(ScreenTestResult); AppFieldValidator.Validate(sc); db.Entry(sc).State = System.Data.EntityState.Added; dbtran.Commit(); //needs to commit first before savechanges otherwise The sql transaction is completed exception will occur db.SaveChanges(); foreach (var obj in shops) { ScreenShop ss = new ScreenShop(); ss.ScreenID = sc.ID; ss.ShopID = obj.WorkLocationID; ss.ScreenStatus = "Outstanding"; ss.ScreenDateSubmitted = null; db.Entry(ss).State = System.Data.EntityState.Added; } db.SaveChanges(); return Json(new { success = true, message = "" }); } return Json(new { success = false, message = "Screen Test is not supplied" }); } catch (Exception e) { dbtran.Rollback(); if (e.Message.IndexOf("Validation failed for one or more entities.") != -1) return Json(new { success = false, message = "One of the entries you made is ether too long or unacceptable!" }); return Json(new { success = false, message = e.InnerException != null ? e.InnerException.Message : e.Message }); } finally { db.Dispose(); } } </code></pre>
3
1,197
The size of the indicated variable or array appears to be changing with each loop iteration
<p>I tried to plot the <code>Hx</code> and <code>Hy</code> for the following Matlab script but, I got the following :</p> <p><code>Undefined function or variable 'HxR'</code> </p> <p>however, I have already defined it as <code>Hx=HxR+HxL</code> in my code. Matlab give the reason for this problem as(The size of the indicated variable or array appears to be changing with each loop iteration). Could anyone have any idea to help, I appreciate it </p> <pre><code>Ro=10.0; % enclosing area radius To=pi/3; % angle between sheets Uo=1.0; y= 1.0; g = 10e-9; % gap length Uo = 1.0; ro = 10.0; to = pi/3; % Interior angle m = 1; for x = -g/2:g/100:g/2 SQP= sqrt((g+x).^2+y^2); if ( x&lt;= 0) HxL = (4*Uo*(SQP/Ro).^(-To/(pi+To))*(Ro*y*SQP)*(-1+(SQP/Ro)^(2*pi/(pi+To))*cos(pi*(- pi+atan(y/(x+g)))/(pi+To))+(g+x).*(1+(SQP./Ro)^(2*pi/(pi+To))*sin(pi*(-pi+atan(y./(x+g)))./(pi+To))))/(Ro*(pi+To)*(g+x).* sqrt((1+y^2)./(g+x)^2)*(1+(SQP./Ro)^(4*pi/(pi+To)))-2*(SQP./Ro)^(2*pi/(pi+To))*cos((2*pi^2 + 2*atan(y./(g+x))./(pi+To))))); HyL= -(4*Uo*(SQP./Ro).^(-To/(pi+To))*(Ro*(g+x).*SQP)*(-1+(SQP./Ro)^(2*pi/(pi+To))*cos(pi*(-pi+atan(y./(x+g)))/(pi+To))+ y*(1+(SQP./Ro)^(2*pi/(pi+To))*sin(pi*(pi-atan(y./(x+g)))/(pi+To))))/(Ro*(pi+To)*(g+x).* sqrt((1+y^2)./(g+x)^2)*(1+(SQP./Ro)^(4*pi/(pi+To)))-2*(SQP/Ro)^(2*pi/(pi+To)))); else SQM= sqrt((-g+x).^2+y^2); HxR = (4*Uo*(SQM/Ro).^(-1+(To/(pi+To)))*(y*(-1+(SQM./Ro)^(-2*pi/(-2*pi+To))*cos((pi*atan(y./(x-g))/(2*pi-To)))+(g-x)*(1+(SQM ./Ro)^(-2*pi./-2*(pi+To/2))*sin((pi*atan(y./(x-g)))/(2*pi-To)))))/(Ro*(2*pi-To).*(g-x).* sqrt((1+y^2)./(g-x)^2)* (1+(SQM/Ro)^(-4*pi/(-2*pi+To)))-2.*(SQM/Ro)^(-2*pi/(-2*pi+To))*cos((2*pi*atan(y./(-g+x))./(2*pi-To))))); HyR= (4*Uo*(SQM./Ro).^(-1+(pi/(2*pi-To)))*((g-x).*(-1+(SQM./Ro)^(-2*pi/(-2*pi+To))*cos((pi*atan(y./(x-g))/(2*pi-To)))-y*(1+(SQM./Ro)^(-2*pi/-2*(pi+To/2))*sin((pi*atan(y./(x-g)))/(2*pi-To)))))/(Ro*(2*pi-To)*(g-x).* sqrt((1+y^2)./(g-x)^2)*(1+(SQM./Ro)^(-4*pi/(-2*pi+To)))-2*(SQM./Ro)^(-2*pi/(-2*pi+To))*cos((2*pi*atan(y./(-g+x))/(2*pi- end Hx(m) = HxR + HxL; Hy(m) = HyR + HyL; m = m+1; end x = -g/2:g/100:g/2; figure plot(x,Hx) title('Hx') figure plot(y,Hy,'-r') title('Hy') </code></pre>
3
1,318
How to display the correct data in their respective text inputs?
<p>I am having trouble displaying the SessionName, SessionDate and SessionTime in their respective text inputs. What should happen is that the user is suppose to select a Session (Assessment) from the drop down menu. Now when they submit the drop down menu, the details of the Session which are SessionName, SessionDate and SessionTime, should be displayed in their text inputs. But instead I am recieving undefined variable errors which are these below:</p> <blockquote> <p>Notice: Undefined variable: dbSessionName in ...on line 243</p> <p>Notice: Undefined variable: dbSessionDate in ... on line 244</p> <p>Notice: Undefined variable: dbSessionTime in ... on line 245</p> </blockquote> <p>How can I get the SessionName, SessionTime and SessionDate to be displayed in their respective text inputs?</p> <p>Below is the code:</p> <pre><code>$sessionquery = " SELECT SessionId, SessionName, SessionDate, SessionTime, ModuleId FROM Session WHERE (ModuleId = ?) ORDER BY SessionDate, SessionTime "; $sessionqrystmt=$mysqli-&gt;prepare($sessionquery); // You only need to call bind_param once $sessionqrystmt-&gt;bind_param("s",$_POST['modules']); // get result and assign variables (prefix with db) $sessionqrystmt-&gt;execute(); $sessionqrystmt-&gt;bind_result($dbSessionId,$dbSessionName,$dbSessionDate,$dbSessionTime, $dbModuleId); $sessionqrystmt-&gt;store_result(); $sessionnum = $sessionqrystmt-&gt;num_rows(); if($sessionnum ==0){ echo "&lt;p&gt;Sorry, You have No Assessments under this Module&lt;/p&gt;"; } else { $sessionHTML = '&lt;select name="session" id="sessionsDrop"&gt;'.PHP_EOL; $sessionHTML .= '&lt;option value=""&gt;Please Select&lt;/option&gt;'.PHP_EOL; while ( $sessionqrystmt-&gt;fetch() ) { $sessionHTML .= sprintf("&lt;option value='%s'&gt;%s - %s - %s&lt;/option&gt;", $dbSessionId, $dbSessionName, $dbSessionDate, $dbSessionTime) . PHP_EOL; } $sessionHTML .= '&lt;/select&gt;'; $assessmentform = "&lt;form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post' onsubmit='return sessionvalidation();'&gt; &lt;p&gt;Assessments: {$sessionHTML} &lt;/p&gt; &lt;p&gt;&lt;input id='sessionSubmit' type='submit' value='Submit Assessment' name='sessionSubmit' /&gt;&lt;/p&gt; &lt;div id='sessionAlert'&gt;&lt;/div&gt; &lt;/form&gt;"; echo $assessmentform; } } if (isset($_POST['sessionSubmit'])) { $currentsession = "form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post'&gt; &lt;p&gt;Current Assessment's Date/Start Time:&lt;/p&gt; &lt;p&gt;Assessment: &lt;input type='text' id='currentAssessment' name='Assessmentcurrent' readonly='readonly' value='{$dbSessionName}'/&gt; &lt;/p&gt; //Line 243 &lt;p&gt;Date: &lt;input type='text' id='currentDate' name='Datecurrent' readonly='readonly' value='{$dbSessionDate}'/&gt; &lt;/p&gt; //Line 244 &lt;p&gt;Start Time: &lt;input type='text' id='currentTime' name='Timecurrent' readonly='readonly' value='{$dbSessionTime}'/&gt; &lt;/p&gt; //Line 245 &lt;/form&gt; "; echo $currentsession; } </code></pre> <p><strong>UPDATE:</strong></p> <p>Could the code below do it:</p> <pre><code>if (isset($_POST['sessionSubmit'])) { $sessionquery = " SELECT SessionId, SessionName, SessionDate, SessionTime, ModuleId FROM Session WHERE (ModuleId = ?) ORDER BY SessionDate, SessionTime "; $sessionqrystmt=$mysqli-&gt;prepare($sessionquery); // You only need to call bind_param once $sessionqrystmt-&gt;bind_param("s",$_POST['modules']); // get result and assign variables (prefix with db) $sessionqrystmt-&gt;execute(); $sessionqrystmt-&gt;bind_result($dbSessionId,$dbSessionName,$dbSessionDate,$dbSessionTime, $dbModuleId); $sessionqrystmt-&gt;store_result(); $currentsession = "&lt;form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post'&gt; &lt;p&gt;Current Assessment's Date/Start Time:&lt;/p&gt; &lt;p&gt;Assessment: &lt;input type='text' id='currentAssessment' name='Assessmentcurrent' readonly='readonly' value='{$dbSessionName}'/&gt; &lt;/p&gt; &lt;p&gt;Date: &lt;input type='text' id='currentDate' name='Datecurrent' readonly='readonly' value='{$dbSessionDate}'/&gt; &lt;/p&gt; &lt;p&gt;Start Time: &lt;input type='text' id='currentTime' name='Timecurrent' readonly='readonly' value='{$dbSessionTime}'/&gt; &lt;/p&gt; &lt;input type='hidden' id='hiddenId' name='hiddenAssessment' value='{$dbSessionId}'/&gt; &lt;/form&gt; "; echo $currentsession; } </code></pre> <p>Do I need the store_result(); in this situation?</p>
3
1,708
icons are not showing in footer angular
<p>i am new in angular , i have installed bootsrap 4.6.0 on angular 12 and the bootsrap worked fine and the footer section appeared like it should appear except one little thing , the icons are refusing to show up , it is like they are not part of bootsrap or something , my code is from an example in codepen</p> <p>here what i have tried:</p> <pre><code>&lt;div class=&quot;footer-dark&quot;&gt; &lt;footer&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-sm-6 col-md-3 item&quot;&gt; &lt;h3&gt;Services&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Web design&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Development&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Hosting&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class=&quot;col-sm-6 col-md-3 item&quot;&gt; &lt;h3&gt;About&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Company&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Team&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Careers&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6 item text&quot;&gt; &lt;h3&gt;Company Name&lt;/h3&gt; &lt;p&gt;Praesent sed lobortis mi. Suspendisse vel placerat ligula. Vivamus ac sem lacus. Ut vehicula rhoncus elementum. Etiam quis tristique lectus. Aliquam in arcu eget velit pulvinar dictum vel in justo.&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;col item social&quot;&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;icon ion-social-facebook&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;icon ion-social-twitter&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;icon ion-social-snapchat&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;a href=&quot;#&quot;&gt;&lt;i class=&quot;icon ion-social-instagram&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;p class=&quot;copyright&quot;&gt;Company Name © 2018&lt;/p&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/div&gt; </code></pre> <p>footer scss:</p> <pre><code>.footer-dark { padding:50px 0; color:#f0f9ff; background-color:#282d32; } .footer-dark h3 { margin-top:0; margin-bottom:12px; font-weight:bold; font-size:16px; } .footer-dark ul { padding:0; list-style:none; line-height:1.6; font-size:14px; margin-bottom:0; } .footer-dark ul a { color:inherit; text-decoration:none; opacity:0.6; } .footer-dark ul a:hover { opacity:0.8; } @media (max-width:767px) { .footer-dark .item:not(.social) { text-align:center; padding-bottom:20px; } } .footer-dark .item.text { margin-bottom:36px; } @media (max-width:767px) { .footer-dark .item.text { margin-bottom:0; } } .footer-dark .item.text p { opacity:0.6; margin-bottom:0; } .footer-dark .item.social { text-align:center; } @media (max-width:991px) { .footer-dark .item.social { text-align:center; margin-top:20px; } } .footer-dark .item.social &gt; a { font-size:20px; width:36px; height:36px; line-height:36px; display:inline-block; text-align:center; border-radius:50%; box-shadow:0 0 0 1px rgba(255,255,255,0.4); margin:0 8px; color:#fff; opacity:0.75; } .footer-dark .item.social &gt; a:hover { opacity:0.9; } .footer-dark .copyright { text-align:center; padding-top:24px; opacity:0.3; font-size:13px; margin-bottom:0; } </code></pre> <p>I have no idea why my icons are not launching</p> <p>a screen capture:</p> <p><a href="https://i.stack.imgur.com/5aWl7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5aWl7.png" alt="enter image description here" /></a></p> <p>a screen capture about how it supposed to be: <a href="https://i.stack.imgur.com/h1UWr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h1UWr.png" alt="enter image description here" /></a></p> <p>What i am searching for is to find what is the dependency that i am missing in angular (bootstrap 4 is already installed and works fine!) or find the solution for this problem</p>
3
2,510
which way is the best for playing 5 songs in android app?
<p>I have 5 songs that must be played in my app, I locate them in <code>raw</code> resource folder. how can I play them? please give me the best way. I use default player or use <code>mediaplayer.start()</code>? I use 5 buttons to show them and play them.</p> <pre><code>public class MusicActivity extends AppCompatActivity implements View.OnClickListener{ private MediaPlayer a,b,c,d,e; private Button aBTN,bBTN,cBTN, dBTN ,fBTN; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music); a = MediaPlayer.create(getApplicationContext(), R.raw.a); b = MediaPlayer.create(getApplicationContext(), R.raw.b); c = MediaPlayer.create(getApplicationContext(), R.raw.c); d = MediaPlayer.create(getApplicationContext(), R.raw.d); e = MediaPlayer.create(getApplicationContext(), R.raw.f); aBTN = (Button)findViewById(R.id.a); bBTN = (Button)findViewById(R.id.b); cBTN = (Button)findViewById(R.id.c); dBTN = (Button)findViewById(R.id.d); fBTN = (Button)findViewById(R.id.e); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.a: if (b.isPlaying() || d.isPlaying() || e.isPlaying()){ b.pause(); d.pause(); e.pause(); a.start(); } else a.pause(); break; case R.id.b: if (a.isPlaying() || d.isPlaying() || e.isPlaying()){ a.pause(); d.pause(); e.pause(); b.start(); } else b.pause(); break; case R.id.d: // if (a.isPlaying() || b.isPlaying() || e.isPlaying()){ // a.pause(); b.pause(); e.pause(); d.start(); // } else d.pause(); break; case R.id.e: if (a.isPlaying() || b.isPlaying() || d.isPlaying()){ a.pause(); b.pause(); d.pause(); e.start(); } else e.pause(); break; } } </code></pre> <p>EDIT/Exception :</p> <pre><code>E/AndroidRuntime: FATAL EXCEPTION: main Process: , PID: 2583 java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:6199) at android.widget.TextView.performClick(TextView.java:11090) at android.view.View$PerformClick.run(View.java:23647) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6682) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:6199)  at android.widget.TextView.performClick(TextView.java:11090)  at android.view.View$PerformClick.run(View.java:23647)  at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6682)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference at MusicActivity.handlePlayer(MusicActivity.java:70) at maxsoftapps.com.MusicActivity.onClick(MusicActivity.java:50) at java.lang.reflect.Method.invoke(Native Method)  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  at android.view.View.performClick(View.java:6199)  at android.widget.TextView.performClick(TextView.java:11090)  at android.view.View$PerformClick.run(View.java:23647)  at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6682)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)  </code></pre> <p>EDIT:</p> <pre><code>public class MusicActivity extends AppCompatActivity implements View.OnClickListener{ private MediaPlayer a,b,d,f,currentMedia; private Button aBTN,bBTN, dBTN ,fBTN; private int preCurrentDataSource =0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music); a = MediaPlayer.create(getApplicationContext(), R.raw.a); b = MediaPlayer.create(this, R.raw.b); d = MediaPlayer.create(this, R.raw.d); f = MediaPlayer.create(this, R.raw.f); aBTN = (Button)findViewById(R.id.a); bBTN = (Button)findViewById(R.id.b); dBTN = (Button)findViewById(R.id.d); fBTN = (Button)findViewById(R.id.e); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.a: handlePlayer(R.raw.a); break; case R.id.b: handlePlayer(R.raw.b); break; case R.id.d: handlePlayer(R.raw.d); break; case R.id.e: handlePlayer(R.raw.f); break; } } private void handlePlayer(int currentDataSource) { currentMedia=MediaPlayer.create(this,currentDataSource); if (preCurrentDataSource != currentDataSource) { currentMedia.stop(); currentMedia.release(); currentMedia = MediaPlayer.create(this, currentDataSource); currentMedia.start(); preCurrentDataSource= currentDataSource; } else { if (currentMedia.isPlaying()) currentMedia.pause(); else currentMedia.start(); } } public void onStop() { super.onStop(); currentMedia.stop(); currentMedia.release(); currentMedia.stop(); currentMedia.release(); finish(); } </code></pre> <p>} EDIT handelerPalying():</p> <pre><code>private void handlePlayer(int currentDataSource) { if (preCurrentDataSource == 0){ currentMedia = MediaPlayer.create(this,currentDataSource); currentMedia.start(); preCurrentDataSource=currentDataSource; } else { currentMedia.stop(); currentMedia.release(); currentMedia=MediaPlayer.create(this,currentDataSource); currentMedia.start(); preCurrentDataSource=currentDataSource; } </code></pre>
3
3,568
Multiple table update in single page handler method razor pages
<p>I am getting this error when i am submitting the data</p> <blockquote> <p>DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded</p> </blockquote> <p>My Page have more than 50 fields which are inserting into different database.</p> <p>this is how i am handling the submit functionality</p> <pre><code>public async Task&lt;IActionResult&gt; OnPostSubmitAsync() { RequestStatus = new SelectList(_context.RequestStatus.OrderBy(e =&gt; e.ID), &quot;RequestStatusValues&quot;, &quot;RequestStatusValues&quot;); RequestType = new SelectList(_context.RequestType.OrderBy(e =&gt; e.ID), &quot;ReqType&quot;, &quot;ReqType&quot;); Priority = new SelectList(_context.Priority.OrderBy(e =&gt; e.ID), &quot;PriorityValues&quot;, &quot;PriorityValues&quot;); Status = new List&lt;SelectListItem&gt; { new SelectListItem { Value = &quot;Yes&quot;, Text = &quot;Yes&quot; }, new SelectListItem { Value = &quot;No&quot;, Text = &quot;No&quot; } }; RequestFormMaster.LastModifiedBy = HttpContext.Session.GetString(&quot;firstname&quot;) + &quot; &quot; + HttpContext.Session.GetString(&quot;lastname&quot;); _context.Entry(RequestFormMaster).State = EntityState.Modified; SLAInformation.RequestID = RequestFormMaster.RequestID; SLAInformation.SalesDateOfSubmission = DateTime.Now; SLAInformation.LastModifiedTimeStamp = DateTime.Now; _context.Entry(SLAInformation).State = EntityState.Modified; YTDRevenue.RequestID = RequestFormMaster.RequestID; YTDRevenue.PricingOwnership = RequestFormMaster.PricingAssignee; YTDRevenue.LastModifiedTimeStamp = DateTime.Now; _context.Entry(YTDRevenue).State = EntityState.Modified; ImplementationInfo.RequestID = RequestFormMaster.RequestID; ImplementationInfo.CPAID = RequestFormMaster.CPAID; ImplementationInfo.LastModifiedTimeStamp = DateTime.Now; _context.Entry(ImplementationInfo).State = EntityState.Modified; //if (LanesRequestingReductionList.Any()) //{ // for (var i = 0; i &lt;= LanesRequestingReductionList.Count(); i++) // { // LanesRequestingReduction.RequestID = RequestFormMaster.RequestID; // LanesRequestingReduction.Counter = i; // _context.Entry(LanesRequestingReduction).State = EntityState.Added; // } //} await _context.SaveChangesAsync(); TempData[&quot;ReqSubmitted&quot;] = &quot;Submitted&quot;; var foldername = RequestFormMaster.RequestID.ToString(); var DirectoryPath = Path.Combine(_env.WebRootPath, &quot;Documents&quot;, foldername); if (!System.IO.Directory.Exists(DirectoryPath)) { System.IO.Directory.CreateDirectory(DirectoryPath); } if (ReqSupportingFiles != null || ReqSupportingFiles.Count &gt; 0) { int i = 0; foreach (IFormFile upload in ReqSupportingFiles) { i++; // Upload file to server folder string ext = Path.GetExtension(upload.FileName).ToLower(); if ((ext == &quot;.ppt&quot;) || (ext == &quot;.pptx&quot;) || (ext == &quot;.xls&quot;) || (ext == &quot;xlsx&quot;)) { var filesave = Path.Combine(_env.WebRootPath, &quot;Documents&quot;, foldername, i + &quot;_&quot; + upload.FileName); using (var stream = System.IO.File.Create(filesave)) { await upload.CopyToAsync(stream); } } } } //SendEmailAsync(); //OnPostUploadFiles(fileData, RequestID); return RedirectToPage(&quot;/RequestSummary&quot;); //return Page(); } </code></pre> <p>Is this a correct approach?</p>
3
2,086
How to write and read text in txt file from internal storage of android vitual
<p>i am learning by myself, without training in school. i need yours help, because i got a stuff and founding all question in the website but i can not solve it. it's very simple with you i think that. i also knew i get the wrong path(connect link).</p> <p>this's my code below</p> <p>Please help me find the path for internal storage. i am using genymothion with android 9 API 28. and Amaze file manager.</p> <p>'enter code here' Activity main:</p> <pre><code> &lt;Button android:id=&quot;@+id/btnwrite&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;26dp&quot; android:text=&quot;WRITE&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/edtnhap&quot; /&gt; &lt;EditText android:id=&quot;@+id/edtnhap&quot; android:layout_width=&quot;366dp&quot; android:layout_height=&quot;48dp&quot; android:layout_marginStart=&quot;10dp&quot; android:layout_marginTop=&quot;10dp&quot; android:layout_marginEnd=&quot;10dp&quot; android:ems=&quot;10&quot; android:hint=&quot;Nhập dữ liệu tại đây&quot; android:inputType=&quot;textPersonName&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;Button android:id=&quot;@+id/btndoc&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginStart=&quot;162dp&quot; android:layout_marginTop=&quot;30dp&quot; android:layout_marginEnd=&quot;161dp&quot; android:text=&quot;READ&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/btnwrite&quot; /&gt; &lt;TextView android:id=&quot;@+id/tvdocdulieu&quot; android:layout_width=&quot;395dp&quot; android:layout_height=&quot;363dp&quot; android:layout_marginTop=&quot;27dp&quot; android:text=&quot;TextView&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/btndoc&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; ''' ''' MainActivity public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private static final String INTERNAL_PATH = Environment.getDataDirectory().getPath()+&quot;/sdcard/&quot;; private static final String ACCOUNT_FILE = &quot;WRITING AND READ TESTING.txt&quot;; Button doc,ghi; EditText nhap; TextView hienthi; Boolean w; @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_main ); init(); } public void init(){ doc = findViewById( R.id.btndoc ); ghi = findViewById( R.id.btnwrite ); nhap = findViewById( R.id.edtnhap ); hienthi = findViewById( R.id.tvdocdulieu ); doc.setOnClickListener( this); ghi.setOnClickListener( this ); } @Override public void onClick( View v ) { switch (v.getId()){ case R.id.btnwrite: xulyviet(); break; case R.id.btndoc: xulydoc(); break; } } private void xulyviet() { try { String path = INTERNAL_PATH + ACCOUNT_FILE; File file = new File( path ); if(!file.exists()) { w = file.createNewFile(); } FileOutputStream fileOutputStream = new FileOutputStream( file, true ); OutputStreamWriter outputStreamWriter = new OutputStreamWriter( fileOutputStream, &quot;UTF-8&quot; ); outputStreamWriter.append( nhap.getText() ); outputStreamWriter.close(); fileOutputStream.close(); Toast.makeText( MainActivity.this, &quot;đã nhập&quot;, Toast.LENGTH_SHORT ).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText( this, &quot;Không thể ghi&quot;, Toast.LENGTH_SHORT ).show(); } } public void xulydoc(){ } } </code></pre> <p><code>enter code here</code></p>
3
2,214
Django and React: csrf cookie is not being set in request header
<p>To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided:</p> <p>settings.py:</p> <pre><code>ALLOWED_HOSTS = ['*'] ACCESS_CONTROL_ALLOW_ORIGIN = '*' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_CREDENTIALS = True ACCESS_CONTROL_ALLOW_METHODS = '*' ACCESS_CONTROL_ALLOW_HEADERS = '*' ''' SESSION_COOKIE_SECURE = True ''' CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' CSRF_TRUSTED_ORIGINS = [ &quot;http://127.0.0.1:3000&quot;,'http://127.0.0.1:8000','http://localhost:3000'] </code></pre> <p>setting SAMESITE protocol to anything else haven't made any change</p> <p>in views.py, we have login view (class based):</p> <pre><code>class LoginView(views.APIView): permission_classes = [AllowAny,] serializer_class = serializer.LoginSerializer def post(self,request): data = serializer.LoginSerializer(data=request.data) print(data.is_valid()) if data.is_valid(): email = data.data['email'] password = data.data['password'] auth = authenticate(username=email,password=password) if auth: login(request,auth) return HttpResponse(&quot;Success&quot;,status=200) else: print(password == &quot;&quot;) if email == &quot;&quot; and password ==&quot;&quot;: return HttpResponse('Both email and password field are empty',status=400) elif email == &quot;&quot;: return HttpResponse('Email field is empty',status=400) elif password == &quot;&quot;: return HttpResponse('Passowrd field is empty',status = 400) else: return HttpResponse(&quot;Both email and password fields are empty&quot;,status=400) </code></pre> <p>in serializer.py, we got the login serializer:</p> <pre><code>class LoginSerializer(serializers.Serializer): email = serializers.CharField(required=False) password = serializers.CharField(required=False,allow_null=True,allow_blank=True) </code></pre> <p>in react (frontend side), here is how i am making a post request:</p> <pre><code>function Login(){ const [login,setLogin] = useState({'email':'','password':''}) const {email,password} = login const navigate = useNavigate() let handleChange = (e)=&gt;{ setLogin( { ...login, [e.target.name]:e.target.value } ) } let handleSubmit = (e)=&gt;{ e.preventDefault() axios.post('http://127.0.0.1:8000/login/',login,{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then( (res)=&gt;{ console.log(res) console.log(Cookies.get('csrftoken')) //undefined here } ).catch((e)=&gt;{ console.log(e) } }) } } </code></pre> <p>this is part of the code btw ^.</p> <p>edit: I have a csrf view too, not sure how to use it:</p> <pre><code>class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] def get(self, request, format=None): return Response({ 'success': 'CSRF cookie set' }) </code></pre> <p>any help is welcomed.</p>
3
1,562
Strange chars after decoding with java.util.Base64.getDecoder()
<p>Im trying to encrypt some user data in the DB then decrepit it back when showing it to users</p> <p>Im doing this using JPA, Eclipse link 2.7.1, and MYSql 5.6 </p> <p>the User entity looks like that:</p> <pre><code>@Entity @Cacheable(false) @Table(name = "user_table") public class User implements Serializable { // some fields @Lob @Column(name = "about_me") @Convert(converter = EncryptorConverter.class) String aboutMe; // setters and getters } </code></pre> <p>and here under is the EncryptorConverter.class</p> <pre><code>import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import java.util.*; @Converter public class EncryptorConverter implements javax.persistence.AttributeConverter&lt;String, String&gt; { String key = "************"; // 128 bit key String initVector = "**************"; // 16 bytes IV IvParameterSpec iv; SecretKeySpec skeySpec; static Cipher cipher; static Cipher deipher; private static final Logger LOG = Logger.getLogger( EncryptorConverter.class.getName()); public EncryptorConverter() { try { iv = new IvParameterSpec(initVector.getBytes("UTF-8")); skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); deipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); deipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } } @Override public String convertToDatabaseColumn(String attribute) { if (attribute == null) { return ""; } try { byte[] encrypted = cipher.doFinal(attribute.getBytes("UTF-8")); return java.util.Base64.getEncoder().encodeToString(encrypted); } catch (BadPaddingException e) { // do nothing } catch (javax.crypto.IllegalBlockSizeException e) { // do nothing } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return ""; } @Override public String convertToEntityAttribute(String dbData) { if (dbData == null) { return ""; } try { byte[] original = deipher.doFinal(java.util.Base64.getDecoder().decode(dbData.getBytes("UTF-8"))); return new String(original, "UTF-8"); } catch (javax.crypto.IllegalBlockSizeException e) { // do nothing } catch (BadPaddingException e) { // do nothing } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return ""; } } </code></pre> <p>My problem is sometimes when I read the decoded <code>aboutMe</code> field from the <code>user</code> entity it looks like having strange chars like this "��t����a:i3��5�o" and sometimes it'll look just fine without any strange chars. </p> <p>Do I do anything wrong with the decoding steps?</p> <p>I really appreciate your help. </p>
3
1,383
How to correctly set values from JSON API response into Google Spreadsheet
<p>I am trying to get data into my google sheets from this API, I want to set the values each one in one row and if possible split them in columns.</p> <p>I tried this code below but what I get is that the script set the values each one in one column and whithout spliting the data.</p> <p><a href="https://i.stack.imgur.com/cvhiq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cvhiq.png" alt="spreadsheet screenshot" /></a></p> <pre><code>function myFunction() { } var urlRequest = 'https://www.presupuestoabierto.gob.ar/api/v1/credito?format=json' var body = { &quot;title&quot;: &quot;Credito devengado&quot;, &quot;ejercicios&quot;:[2020], &quot;columns&quot;: [ &quot;impacto_presupuestario_mes&quot;, &quot;ejercicio_presupuestario&quot;, &quot;jurisdiccion_id&quot;, &quot;jurisdiccion_desc&quot;, &quot;servicio_desc&quot;, &quot;inciso_id&quot;, &quot;principal_desc&quot;, &quot;credito_devengado&quot;, &quot;ultima_actualizacion_fecha&quot;], &quot;filters&quot;: [ { &quot;column&quot;: &quot;inciso_id&quot;, &quot;operator&quot;: &quot;equal&quot;, &quot;value&quot;: &quot;1&quot; }, { &quot;column&quot;: &quot;jurisdiccion_id&quot;, &quot;operator&quot;: &quot;equal&quot;, &quot;value&quot;: &quot;30&quot; } ] } var options = { muteHttpExceptions: true, method: 'POST', headers: {Authorization:'a......e','Content-Type':'application/json'}, payload: JSON.stringify(body) } var response = UrlFetchApp.fetch(urlRequest, options); var json = response.getContentText(); var dataAll = JSON.parse(json); var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheets = ss.getSheets(); var sheet = ss.getActiveSheet(); // I modified below. var rows = [Object.keys(dataAll)]; // Retrieve headers. var temp = []; for (var i = 0; i &lt; rows[0].length; i++) { temp.push(dataAll[rows[0][i]]); // Retrieve values. } rows.push(temp); sheet.getRange(1,1,rows.length,rows[0].length).setValues(rows); // Put values to Spreadsheet. </code></pre>
3
1,107
LNK 2001 : unresolved external symbol while initializing static member
<p>I am trying to implement a vitual Keyboard class for that I am having different keyboard layouts as shown.</p> <p>KeyBoard.hpp</p> <pre><code> class CKeyBoard { public: enum eKeyBoardLayout { UPPER_CASE_ALPHABETS, LOWER_CASE_ALPHABETS, UPPER_CASE_NUMBERS, LOWER_CASE_NUMBERS, MAX_KEYBOARDLAYOUTS, }; CKeyBoard(); void hideCharacters(bool hide); // for password void setDisplayBufferLength(UNSIGNED8_T maxCharToDisplay); virtual ~CKeyBoard(); static const UNSIGNED8_T const_noOfRows = 0x03; // 3 rows for character keys struct SLayout { UNSIGNED8_T noOfColumns[const_noOfRows]; ///&lt; noofcolumns in each row may be different TypedText textAreaFont; const KeyMapping* pKeyMapping; }; static const SLayout m_KeyBoardLayouts[MAX_KEYBOARDLAYOUTS]; private: /*methods*/ void setKeyBoardLayout(eKeyBoardLayout); void backspacePressedHndlr(); void letterCasePressedHndlr(); void alphabetNumberToggleHndlr(); /*members*/ static const UNSIGNED8_T const_maxNoOfKeysSupprtd = 26; CKey m_keyArray[const_maxNoOfKeysSupprtd]; CMenuItem m_KeySpaceBar; CMenuToggle m_KeyCaseSwitch; CMenuToggle m_KeyAlphaNum; CMenuItem m_keyBackSpace; eKeyBoardLayout m_eCurrentKeyLayout; CKeyBoardDisplayArea m_DisplayArea; </code></pre> <p>};</p> <p>I am initialising the static member as follows in cpp file. KeyBoard.cpp</p> <pre><code>static const CKeyBoard::SLayout m_KeyBoardLayouts[CKeyBoard::MAX_KEYBOARDLAYOUTS] = \ { // UPPER_CASE_ALPHABETS, { { 10, 9, 7 }, TypedText(T_KEYBOARD), &amp;keyMappingsAlphaUpper[0], }, // LOWER_CASE_ALPHABETS, { { 10, 9, 7 }, TypedText(T_KEYBOARD), &amp;keyMappingsAlphaLower[0], }, // UPPER_CASE_NUMBERS, { { 10, 10, 5 }, TypedText(T_KEYBOARD), &amp;keyMappingsNumLower[0], }, // LOWER_CASE_NUMBERS, { { 10, 10, 5 }, TypedText(T_KEYBOARD), &amp;keyMappingsNumLower[0] }, }; // Other function definitions CKey::CKey() : m_pCallback(NULL) { } </code></pre> <p>But still I am getting unresolved external symbol as linker error. What am I doing wrong here?</p> <p>Error Details: * error LNK2001: unresolved external symbol "public: static struct CKeyBoard::SLayout const * const CKeyBoard::m_KeyBoardLayouts" (?m_KeyBoardLayouts@CKeyBoard@@2QBUSLayout@1@B) *</p>
3
1,082
Getting stuck with rspec 3 on windows
<p>I'm following a <a href="https://www.coursera.org/learn/rails-with-active-record/" rel="nofollow noreferrer">course</a> on Coursera and I have to submit an assignment and validate it with rspec. So far I avoided all problems with rspec by simple copying the .rspec and spec folder provided with the sample code in my projects and it seems to work but now I have a spec file with following code:</p> <pre><code>require 'rails_helper' feature "Module #3" do before :all do $continue = true end around :each do |example| if $continue $continue = false example.run $continue = true unless example.exception else example.skip end end #helper method to determine if Ruby class exists as a class def class_exists?(class_name) eval("defined?(#{class_name}) &amp;&amp; #{class_name}.is_a?(Class)") == true end #helper method to determine if two files are the same def files_same?(file1, file2) if (File.size(file1) != File.size(file2)) then return false end f1 = IO.readlines(file1) f2 = IO.readlines(file2) if ((f1 - f2).size == 0) then return true else return false end end context "rq01" do context "Generate Rails application" do it "must have top level structure of a rails application" do expect(File.exists?("Gemfile")).to be(true) expect(Dir.entries(".")).to include("app", "bin", "config", "db", "lib", "public", "log", "test", "vendor") expect(Dir.entries("./app")).to include("assets", "controllers", "helpers", "mailers", "models", "views") end end end # check that TodoItem exists with fields and migration/db exists context "rq02" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end context "Scaffolding generated" do it "must have at least one controller and views" do expect(Dir.entries("./app/controllers")).to include("todo_items_controller.rb") expect(Dir.entries("./app/views/")).to include("todo_items") expect(Dir.entries("./app/views/todo_items")).to include("index.html.erb") end end context "TodoItem Model" do it "TodoItem class" do expect(class_exists?("TodoItem")) expect(TodoItem &lt; ActiveRecord::Base).to eq(true) end end context "TodoItem class properties added" do subject(:todoItem) { TodoItem.new } it { is_expected.to respond_to(:due_date) } it { is_expected.to respond_to(:title) } it { is_expected.to respond_to(:completed) } it { is_expected.to respond_to(:description) } it { is_expected.to respond_to(:created_at) } it { is_expected.to respond_to(:updated_at) } end it "TodoItem database structure in place" do # rails g model todo_item due_date:date title description:text # rake db:migrate expect(TodoItem.column_names).to include "due_date", "title", "description", "completed" expect(TodoItem.column_types["due_date"].type).to eq :date expect(TodoItem.column_types["title"].type).to eq :string expect(TodoItem.column_types["description"].type).to eq :text expect(TodoItem.column_types["created_at"].type).to eq :datetime expect(TodoItem.column_types["updated_at"].type).to eq :datetime expect(TodoItem.column_types["completed"].type).to eq :boolean end end context "rq03" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end # Check that database has been initialized with seed file prior to test it "has the file that seeded the database" do expect(File).to exist("#{Rails.root}/db/seeds.rb") end it "must have TodoItems as provided by assignment seed file" do expect(TodoItem.all.length).to eq(3) expect(TodoItem.all.map{ |x| x.title }).to include("Task 1", "Task 2", "Task 3") end end context "rq04" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "todo_items URI should return a valid page" do visit todo_items_path expect(page.status_code).to eq(200) end end context "rq05" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" # start at main page... visit todo_items_path end scenario "Main page displays all items" do expect(page).to have_content "Task 1" expect(page).to have_content "Task 2" expect(page).to have_content "Task 3" end scenario "New action from index and create action to generate a new item" do expect(page).to have_link("New Todo item") click_link("New Todo item") expect(page).to have_content "Title" item = TodoItem.new(title:'Random', description:'', completed:true, due_date:Date.today) fill_in "Title", with: item.title select item.due_date.year, from: 'todo_item[due_date(1i)]' select item.due_date.strftime("%B"), from: 'todo_item[due_date(2i)]' select item.due_date.day, from: 'todo_item[due_date(3i)]' fill_in 'todo_item[title]', with: item.title fill_in 'todo_item[description]', with: item.description click_button 'Create Todo item' new_task = TodoItem.find_by! title: "Random" expect(TodoItem.count).to eq 4 expect(page).to have_content "Todo item was successfully created." end =begin scenario "Show link takes user to detail page about an item" do task2 = TodoItem.find_by title: "Task 2" expect(page).to have_link("Show", href: "#{todo_item_path(task2)}") click_link("Show", href: "#{todo_item_path(task2)}") expect(page).to have_content task2.due_date.strftime("%F") expect(page).to have_content task2.title expect(page).to have_content task2.description expect(page.current_path).to eq(todo_item_path(task2.id)) end scenario "Edit and update action" do new_task = TodoItem.create!(:title =&gt; "Random", :description =&gt; "", :completed =&gt; true, :due_date =&gt; Date.today) visit edit_todo_item_path(new_task) expect(page).to have_content "Description" expect(page).to have_field("Title", with: "Random") fill_in "Description", with: "fascinating" click_button "Update Todo item" new_task = TodoItem.find_by! title: "Random" expect(new_task.description).to_not be_blank expect(page).to have_content "Todo item was successfully updated." end scenario "Delete action" do new_task = TodoItem.create!(:title =&gt; "Random", :description =&gt; "", :completed =&gt; true, :due_date =&gt; Date.today) visit todo_items_path expect(page).to have_link("Destroy", href: "#{todo_item_path(new_task)}") click_link("Destroy", href: "#{todo_item_path(new_task)}") expect(TodoItem.count).to eq 3 expect(TodoItem.find_by title: "Random").to be_nil end =end end context "rq06" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "after creating an item should go to listing page" do visit new_todo_item_path fill_in "Title", with: "some title" click_button "Create Todo item" expect(page).to have_content "Listing Todo Items" expect(page.current_path).to eq(todo_items_path) end end context "rq07" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "remove edit link from listing page" do visit todo_items_path expect(page).to_not have_content('Edit') end end context "rq08" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "only display completed checkbox in the form when editing" do visit new_todo_item_path expect(page).to_not have_content('Completed') item = TodoItem.all.to_a[0] expect(item.id).to_not be_nil visit edit_todo_item_path(item.id) expect(page).to have_content('Completed') end end context "rq09" do before :each do TodoItem.destroy_all load "#{Rails.root}/db/seeds.rb" end scenario "display somewhere on the listing page number of completed todos" do # seed the page with random items so test is specific to each run TodoItem.destroy_all numCompleted = 0; (0..15).each do |i| random_boolean = [true, false].sample if (random_boolean) then numCompleted = numCompleted + 1 end TodoItem.create!(title: "Task #{i}", due_date: Date.today, description: "description #{i}", completed: random_boolean) end visit todo_items_path expect(page).to have_content "Number of Completed Todos: #{numCompleted}" TodoItem.create! [ { title: "Task xyz", due_date: Date.today, completed: false }, { title: "Task zyx", due_date: Date.tomorrow, completed: true}, ] numCompleted = numCompleted + 1 visit todo_items_path expect(page).to have_content "Number of Completed Todos: #{numCompleted}" end end end </code></pre> <p>When I run it as is with requre 'rails_helper' I get:</p> <pre><code>D:/RailsInstaller/Ruby2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- rails_helper (LoadError) </code></pre> <p>When I remove it I get: </p> <pre><code>todolists/spec/features/module3_action_pack_spec.rb:1:in `&lt;top (required)&gt;': undefined method `feature' for main:Object (NoMethodError) </code></pre> <p>This is my spec_helper.rb:</p> <pre><code>require 'rspec' require 'capybara' require 'capybara/dsl' require 'capybara/poltergeist' RSpec.configure do |config| config.include Capybara::DSL end </code></pre> <p>I tried everything I can come across on the net like downgrading to rspec 3.0.0 from 3.1.0 and changing the DirectoryMaker.rb under RailsInstaller\Ruby2.2.0\lib\ruby\gems\2.2.0\gems\rspec-support-3.5.0\lib\rspec\support as mentioned in <a href="https://github.com/rspec/rspec-support/pull/109" rel="nofollow noreferrer">https://github.com/rspec/rspec-support/pull/109</a> but I still get the error when I try to run rails generate rspec:install like this:</p> <pre><code> create spec/C:/Users/Zeeshan Haider/AppData/Local/Temp/d20161116-10536-1962r60/spec/spec_helper.rb D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:252:in `mkdir': Invalid argument @ dir_s_mkdir - F:/Zeeshan Haider/Coursera/Rails with Active Record and Action Pack/todolists/spec/C: (Errno::EINVAL) from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:252:in `fu_mkdir' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:226:in `block (2 levels) in mkdir_p' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:224:in `reverse_each' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:224:in `block in mkdir_p' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:210:in `each' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/fileutils.rb:210:in `mkdir_p' from D:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/lib/thor/actions/create_file.rb:61:in `block in invoke!' </code></pre>
3
4,734
How do I get the log-in section to disappear when users are logged in?
<p>I want the "log in block" to be hidden to my users once they are logged in. It is very confusing to still see the log in section. My users think that their log in didn't work when in actuality, they are successfully logged in. I have tried inserting the following into my CSS block, but I need a condition to make it visible when users are NOT logged in.</p> <pre><code>display: none; </code></pre> <p>Here is my HTML code for this section:</p> <pre><code> &lt;DIV id="hp-content"&gt; &lt;DIV id="hp-left-column"&gt; &lt;DIV id="hp-sign-header"&gt; &lt;/DIV&gt; &lt;DIV id="hp-sign"&gt; &lt;input type="textbox" class="ui-txt-general medium required" id="swsignin-txt-username" /&gt; &lt;input type="password" class="ui-txt-general medium required" id="swsignin-txt-password" /&gt; &lt;a title="Sign into my site." onclick="joelSignIn();" class="" id="swsignin-btn-submit"&gt;&lt;img src="/cms/lib06/CA01000567/Centricity/Template/2/signin.png" alt="Sign In" /&gt;&lt;/a&gt; &lt;/DIV&gt; </code></pre> <p>Here is my CSS code for this section:</p> <pre><code> #hp-sign-header{ width: 288px; height: 27px; margin: 20px 0px 10px 0px; background: transparent url(/cms/lib06/CA01000567/Centricity/Template/2/sign-header.png) no-repeat scroll top center; } #hp-sign{ width: 218px; height: auto; margin-left: 35px; } #swsignin-txt-username, #swsignin-txt-password { border: 1px solid #0C304E; color: #6994B9; font-family: "Trebuchet MS",Arial,Helvetica,sans-serif; font-weight: bold; font-size: 15px; line-height: 15px; height: 47px; margin: 0px 0px 10px 0px; padding: 0px; text-align: center; width: 221px; } #swsignin-txt-username { background: transparent url(/cms/lib06/CA01000567/Centricity/Template/2/username.png) no-repeat scroll top left; } #swsignin-txt-password { background: transparent url(/cms/lib06/CA01000567/Centricity/Template/2/password.png) no-repeat scroll top left; } </code></pre> <p>Here is the JAVASCRIPT code for this section:</p> <pre><code> function joelSignIn(){ var data = "{Username: '" + addslashes($('#swsignin-txt-username').val()) + "',Password: '" + addslashes($('#swsignin-txt-password').val()) + "'} "; var success = "window.location.reload()"; var failure = "if (result[0].reason === 'TOU') { DisplayTOU(); } else { CallControllerFailure(result[0].errormessage); }"; var callPath = "../site/SiteController.aspx/SignIn"; CallController(callPath, data, success, failure); } </code></pre> <p>So my question is, do I need to insert HTML code, CSS code and/or JAVASCRIPT code to make this work? And what is the code that I need to insert and where? I have tried researching and playing around, but to no avail. Any advice would be MUCH appreciated. Thank you!</p>
3
1,300
PHP- getting the value of a cell for use with an api
<p>Sorry if this is a stupid question, I'm pretty new at PHP. </p> <p>So first, here is what I'm trying to do:</p> <p>I am pulling information from MYSQL and displaying the info on a page. specifically this bit:</p> <pre><code>while($rowsID = mysql_fetch_assoc($sIDD)) { echo '&lt;tr&gt;'; foreach($rowsID as $key =&gt; $cell){ print '&lt;td&gt;'.$cell.'&lt;/td&gt;'; } </code></pre> <p>This works fine and displays the info I want.</p> <p>The information from that cell, I want to plug into:</p> <pre><code>$sid = $rowsID['steamID']; $key = '&lt;yoink&gt;'; $slink =file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $key . '&amp;steamids=' . $sid . '&amp;format=json'); $myarray = json_decode($slink, true); print '&lt;img src='; print $myarray['response']['players'][0]['avatarmedium']; print '&gt;'; ` </code></pre> <p>This does not work. It won't pull the actual number from the cell and put it into $sid. I've at a loss here. I'm googled for days, and most of my code is frankenstiened from bits I've found around here, so I'm not even sure I'm on the right track. I hope I've clearly explained my problem and provided enough info. Thanks for any help.</p> <p>The full code: </p> <pre><code>&lt;?php $hostname = ""; // eg. mysql.yourdomain.com (unique) $username = ""; // the username specified when setting-up the database $password = ""; // the password specified when setting-up the database $database = ""; // the database name chosen when setting-up the database (unique) $imgR = "&lt;td&gt;&lt;img src='/images/red-dot2.png".$cell['red-dot2.png']."'&gt;&lt;/td&gt;"; $imgG = "&lt;td&gt;&lt;img src='/images/green-dot2.png".$cell['green-dot2.png']."'&gt;&lt;/td&gt;"; setlocale(LC_MONETARY, 'en_US'); // Line 10 $_GET['id']; $name = $_GET['id']; $link = mysql_connect($hostname,$username,$password); mysql_select_db($database) or die("Unable to select database"); $sql = "SELECT Members.PID, Members.ID, Members.Steam_Name, Members.SG_ID\n" . "FROM Members WHERE Members.PID = '$name%' "; //Line 20 $gas = "SELECT Giveaways.title, Giveaways.cv, Members_1.Page, Giveaways.B, Giveaways.entries\n" . "FROM Members_1 INNER JOIN (Members INNER JOIN Giveaways ON Members.SG_ID = Giveaways.giver) ON Members_1.SG_ID = Giveaways.status\n" . "WHERE (((Members.PID)='$name'))"; $cvGiven = "SELECT Members.PID, Sum(Giveaways.cv) AS SumOfcv\n" . "FROM Members INNER JOIN Giveaways ON Members.SG_ID = Giveaways.giver\n" . "GROUP BY Members.PID\n" . "HAVING (((Members.PID)=$name)) "; //Line 30 $winResults = "SELECT Giveaways.title, Members_1.Page, Giveaways.cv, Giveaways.B, Giveaways.entries\n" . "FROM Members INNER JOIN (Members_1 INNER JOIN Giveaways ON Members_1.SG_ID = Giveaways.giver) ON Members.SG_ID = Giveaways.status\n" . "WHERE (((Members.PID)=$name)) "; $cvWon = "SELECT Members.PID, Sum(Giveaways.cv) AS SumOfcvW\n" . "FROM Members INNER JOIN Giveaways ON Members.SG_ID = Giveaways.status\n" . "GROUP BY Members.PID\n" . "HAVING (((Members.PID)=$name)) "; $sID = "SELECT Members.ID\n" . "FROM Members\n" . "WHERE (((Members.PID)=$name))"; $get = "SELECT Members.PID, Members.SG_ID\n" . "FROM Members"; //Line 40 $result = mysql_query($sql,$link) or die("Unable to select: ".mysql_error()); $result2 = mysql_query($gas,$link) or die("Unable to select: ".mysql_error()); $cvTotal = mysql_query($cvGiven,$link) or die("Unable to select: ".mysql_error()); $cvTotalW = mysql_query($cvWon,$link) or die("Unable to select: ".mysql_error()); $wins = mysql_query($winResults,$link) or die("Unable to select: ".mysql_error()); $sIDD = mysql_query($sID,$link) or die("Unable to select: ".mysql_error()); $getN= mysql_query($get,$link) or die("Unable to select: ".mysql_error()); if (!$result) { die("Query to show fields from table failed"); } if (!$result2) { die("Query to show fields from table failed"); } if (!$cvTotal) { die("Query to show fields from table failed"); } if (!$sIDD) { die("Query to show fields from table failed"); } if (!$getN) { die("Query to show fields from table failed"); } //Line 60 if (!$cvTotalW) { die("Query to show fields from table failed"); } if (!$wins) { die("Query to show fields from table failed"); } /////////////////////////////////////////////////////////////////////////////////// //////////////////////////Start Structure////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// //Display name echo '&lt;h2&gt;[[Breadcrumbs?showHomeCrumb = 0 ]]&lt;/h2&gt;'; //Display Steam ID $sid = $rowsID['steamID']; $key = ''; $slink = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $key . '&amp;steamids=' . $sid . '&amp;format=json'); $myarray = json_decode($slink, true); print $myarray['response']['players'][0]['avatarmedium']; // print '&gt;'; print $sid; echo '&lt;table&gt;'; while($rowsID = mysql_fetch_assoc($sIDD)) { echo '&lt;tr&gt;'; foreach($rowsID as $key =&gt; $cell){ print '&lt;th&gt;Steam ID:&lt;/th&gt;'.'&lt;td&gt;'.$cell.'&lt;/td&gt;'; } echo'&lt;/tr&gt;'; } echo '&lt;/table&gt;'; //CV totals $row = mysql_fetch_assoc($cvTotal); $sum = $row['SumOfcv']; $rowW = mysql_fetch_assoc($cvTotalW); $sumW = $rowW['SumOfcvW']; //Start CV table echo '&lt;div class=cv&gt;'; echo '&lt;table&gt;'; echo '&lt;tr&gt;'; echo '&lt;td&gt;Total CV Given:&lt;/td&gt;'; echo '&lt;td&gt; $'. number_format ($sum,2). '&lt;/td&gt;'; echo '&lt;tr&gt;'; echo "&lt;td&gt;Total CV Won:&lt;/td&gt;"; echo '&lt;td&gt; $'. number_format ($sumW,2). '&lt;/td&gt;'; echo '&lt;/tr&gt;'; echo "&lt;/tr&gt;\n\n"; echo '&lt;/table&gt;'; echo '&lt;/div&gt;'; //Start Giveaways List echo '&lt;h3&gt;Giveaways&lt;/h3&gt;'; echo '&lt;div class=llamatable&gt;'; echo"&lt;table&gt;\n"; echo'&lt;th&gt;Game&lt;/th&gt;&lt;th&gt;CV&lt;/th&gt;&lt;th&gt;Winner&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;NB?&lt;/th&gt;&lt;th&gt;Entries&lt;/th&gt;'; while($row = mysql_fetch_assoc($result2)) { print "&lt;tr&gt;\n"; //Is it a bundle? foreach($row as $key =&gt; $cell){ if ($key == 'B' &amp;&amp; strpos($cell,'1') !== false){ $cell = str_replace('1',$cell,$imgR); } elseif($key == 'B' &amp;&amp; $cell == "0"){ $cell= $imgG; } //Set cv format if($key == 'cv'){ $cell= '$'. number_format ($cell,2); //Line 80 } //set breaks if multiple winners if (strpos($cell,',') !== false){ $cell= str_replace(',','&lt;br /&gt;',$cell); } if($key == 'status' &amp;&amp; strpos($cell, $nameName)){ $cell = $test; } echo"&lt;td&gt;$cell&lt;/td&gt;\n"; } print "&lt;/tr&gt;\n"; //print "&lt;/br&gt;\n"; }// End Giveaways list ////////////////////////////////////////////////////////////////////////////////////////// print "&lt;/table&gt;\n"; print "&lt;/div&gt;"; //Start Wins List echo '&lt;h3&gt;Wins&lt;/h3&gt;'; echo '&lt;div class=llamatable&gt;'; //$fields_num = mysql_num_fields($results); echo"&lt;table&gt;\n"; echo'&lt;th&gt;Game&lt;/th&gt;&lt;th&gt;Contributor&lt;/th&gt;&lt;th&gt;cv&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;th&gt;NB?&lt;/th&gt;&lt;th&gt;Entries&lt;/th&gt;'; while($row = mysql_fetch_assoc($wins)) { print "&lt;tr&gt;\n"; //Is it a bundle? foreach($row as $key =&gt; $cell){ if ($key == 'B' &amp;&amp; strpos($cell,'1') !== false){ $cell = str_replace('1',$cell,$imgR); } //Line 110 elseif($key == 'B' &amp;&amp; $cell == "0"){ $cell= $imgG; } //Set cv amount if($key == 'cv'){ $cell= '$'. number_format ($cell,2); } //set breaks if multiple winners if (strpos($cell,',') !== false){ $cell= str_replace(',','&lt;br /&gt;',$cell); } echo"&lt;td&gt;$cell&lt;/td&gt;\n"; } print "&lt;/tr&gt;\n"; }// End wins list print "&lt;/table&gt;\n"; echo "&lt;/div&gt;"; //echo '&lt;/table&gt;'; //echo '&lt;/div&gt;'; mysql_close($link); ?&gt; </code></pre> <p>I realize the code is probably a disaster, I plan on cleaning it up once I have it working and understand more fully what I'm looking at. I've copie and patched together code from a lot of different sources, as well as attempted my own. Don't hate me. :-)</p>
3
3,645
highcharts stacked area
<p>So I think I may have encountered a Highcharts bug in terms of stacked area:</p> <p><a href="http://jsfiddle.net/dRL6t/2/" rel="nofollow">JSFiddle Highcharts Example</a></p> <p>In this example, the "Social" has a start point before the "Online Video" and seems to render the points of the stacked areas erratically. If you were to deselect the charts from left to right, and then select them from right to left, the charts will render correctly. Has anyone else encountered this?</p> <pre><code>$('#container').highcharts({ "xAxis": [ { "name": "Date", "unitType": "DATE", "title": { "text": null } } ], "yAxis": [ { "name": "Currency", "unitType": "CURRENCY", "title": { "text": null } } ], "series": [ { "yAxis": 0, "xAxis": 0, "data": [ { "x": 1329724800000, "y": 9523.873333333333 }, { "x": 1330329600000, "y": 12646.573333333334 }, { "x": 1330934400000, "y": 12028.853333333333 }, { "x": 1331535600000, "y": 14016.48895104895 }, { "x": 1332140400000, "y": 16497.35533466533 }, { "x": 1332745200000, "y": 17799.29238095238 }, { "x": 1333350000000, "y": 21495.82333333334 }, { "x": 1333954800000, "y": 20261.55833333333 }, { "x": 1334559600000, "y": 22963.80833333332 }, { "x": 1335164400000, "y": 20498.47333333335 }, { "x": 1335769200000, "y": 23846.87499999998 }, { "x": 1336374000000, "y": 26080.86166666669 }, { "x": 1336978800000, "y": 25838.83666666667 }, { "x": 1337583600000, "y": 25501.14666666666 }, { "x": 1338188400000, "y": 23663.95 }, { "x": 1338793200000, "y": 31292.4716666667 }, { "x": 1339398000000, "y": 32823.2983333333 }, { "x": 1340002800000, "y": 33355.595 }, { "x": 1340607600000, "y": 35104.4816666667 }, { "x": 1341212400000, "y": 32984.61190476187 }, { "x": 1341817200000, "y": 34481.88142857143 }, { "x": 1342422000000, "y": 35663.83 }, { "x": 1343026800000, "y": 39744.7383333333 }, { "x": 1343631600000, "y": 37313.0559523810 }, { "x": 1344236400000, "y": 38950.5057142857 }, { "x": 1344841200000, "y": 43884.575 }, { "x": 1345446000000, "y": 43548.8683333333 }, { "x": 1346050800000, "y": 45227.9250000000 }, { "x": 1346655600000, "y": 38555.2130952382 }, { "x": 1347260400000, "y": 46228.5085714285 }, { "x": 1347865200000, "y": 50614.2016666666 }, { "x": 1348470000000, "y": 50058.0150000000 }, { "x": 1349074800000, "y": 53320.6133333333 }, { "x": 1349679600000, "y": 49347.0885714286 }, { "x": 1350284400000, "y": 49264.8047619050 }, { "x": 1350889200000, "y": 54185.2733333332 }, { "x": 1351494000000, "y": 55563.9733333333 }, { "x": 1352102400000, "y": 55708.3243786982 }, { "x": 1352707200000, "y": 48733.7656213019 }, { "x": 1353312000000, "y": 58758.0033333332 }, { "x": 1353916800000, "y": 61759.9366666667 }, { "x": 1354521600000, "y": 63097.59 }, { "x": 1355126400000, "y": 62201.8799999998 }, { "x": 1355731200000, "y": 54752.3342857144 }, { "x": 1356336000000, "y": 64890.0257142858 }, { "x": 1356940800000, "y": 69159.9916666666 }, { "x": 1357545600000, "y": 69436.6916666667 } ], "name": "Online Video", "unitType": "CURRENCY", "type": "area" }, { "yAxis": 0, "xAxis": 0, "data": [ { "x": 1328515200000, "y": 47191.90571428572 }, { "x": 1329120000000, "y": 34517.37428571429 }, { "x": 1329724800000, "y": 29077.13374999999 }, { "x": 1330329600000, "y": 31860.52625 }, { "x": 1330934400000, "y": 33656.41 }, { "x": 1331535600000, "y": 29916.92209424082 }, { "x": 1332140400000, "y": 28745.66540575918 }, { "x": 1332745200000, "y": 33738.3710714285 }, { "x": 1333350000000, "y": 31722.8264285715 }, { "x": 1333954800000, "y": 31198.835 }, { "x": 1334559600000, "y": 33476.54857142855 }, { "x": 1335164400000, "y": 33601.01892857145 }, { "x": 1335769200000, "y": 30943.41749999996 }, { "x": 1336374000000, "y": 30949.72500000004 }, { "x": 1336978800000, "y": 34241.68125 }, { "x": 1337583600000, "y": 30031.54875 }, { "x": 1338188400000, "y": 29886.5087500001 }, { "x": 1338793200000, "y": 34003.4012499999 }, { "x": 1339398000000, "y": 32008.1424999999 }, { "x": 1340002800000, "y": 31957.5975000000 }, { "x": 1340607600000, "y": 33813.8885714286 }, { "x": 1341212400000, "y": 33055.4214285715 }, { "x": 1341817200000, "y": 30489.5225000001 }, { "x": 1342422000000, "y": 30702.0503571428 }, { "x": 1343026800000, "y": 32966.3821428571 }, { "x": 1343631600000, "y": 29196.9012500001 }, { "x": 1344236400000, "y": 32688.0837499999 }, { "x": 1344841200000, "y": 33855.33 }, { "x": 1345446000000, "y": 28549.045 }, { "x": 1346050800000, "y": 30542.815 }, { "x": 1346655600000, "y": 32192.9671428571 }, { "x": 1347260400000, "y": 30028.8653571429 }, { "x": 1347865200000, "y": 28983.9975 }, { "x": 1348470000000, "y": 32102.2757142857 }, { "x": 1349074800000, "y": 34292.6042857143 }, { "x": 1349679600000, "y": 31773.625 }, { "x": 1350284400000, "y": 32021.5964285715 }, { "x": 1350889200000, "y": 32087.5610714285 }, { "x": 1351494000000, "y": 29137.7275 }, { "x": 1352102400000, "y": 32548.594404145 }, { "x": 1352707200000, "y": 34536.862738712 }, { "x": 1353312000000, "y": 32442.137857143 }, { "x": 1353916800000, "y": 30339.53125 }, { "x": 1354521600000, "y": 32420.4666071429 }, { "x": 1355126400000, "y": 32267.5671428571 }, { "x": 1355731200000, "y": 30140.21625 }, { "x": 1356336000000, "y": 31462.2751785714 }, { "x": 1356940800000, "y": 35181.4085714286 }, { "x": 1357545600000, "y": 32100.06375 }, { "x": 1358150400000, "y": 30464.51625 }, { "x": 1358755200000, "y": 32761.15 }, { "x": 1359360000000, "y": 30037.86625 } ], "name": "Social", "unitType": "CURRENCY", "type": "area" }, { "yAxis": 0, "xAxis": 0, "data": [ { "x": 1327910400000, "y": 71932.20333333334 }, { "x": 1328515200000, "y": 71015.56999999998 }, { "x": 1329120000000, "y": 64489.10809523810 }, { "x": 1329724800000, "y": 59054.29357142863 }, { "x": 1330329600000, "y": 59434.56785714285 }, { "x": 1330934400000, "y": 60617.94047619045 }, { "x": 1331535600000, "y": 57584.68013972055 }, { "x": 1332140400000, "y": 61606.9281936127 }, { "x": 1332745200000, "y": 55198.8326190476 }, { "x": 1333350000000, "y": 60385.3257142858 }, { "x": 1333954800000, "y": 54881.3528571429 }, { "x": 1334559600000, "y": 50847.6321428571 }, { "x": 1335164400000, "y": 50746.7521428572 }, { "x": 1335769200000, "y": 46697.2161904761 }, { "x": 1336374000000, "y": 48913.2923809524 }, { "x": 1336978800000, "y": 48944.0592857142 }, { "x": 1337583600000, "y": 49093.3221428572 }, { "x": 1338188400000, "y": 47704.8195238095 }, { "x": 1338793200000, "y": 49798.9383333334 }, { "x": 1339398000000, "y": 43637.2907142858 }, { "x": 1340002800000, "y": 46993.1742857142 }, { "x": 1340607600000, "y": 36354.43 }, { "x": 1341212400000, "y": 45646.7442857143 }, { "x": 1341817200000, "y": 38892.2640476190 }, { "x": 1342422000000, "y": 40631.3088095237 }, { "x": 1343026800000, "y": 36735.4161904764 }, { "x": 1343631600000, "y": 38958.0166666666 }, { "x": 1344236400000, "y": 33788.2871428572 }, { "x": 1344841200000, "y": 35576.4728571428 }, { "x": 1345446000000, "y": 33276.48 }, { "x": 1346050800000, "y": 32337.60 }, { "x": 1346655600000, "y": 27020.6400000002 }, { "x": 1347260400000, "y": 31333.0899999998 }, { "x": 1347865200000, "y": 28894.44 }, { "x": 1348470000000, "y": 30565.8733333333 }, { "x": 1349074800000, "y": 28436.5023809525 }, { "x": 1349679600000, "y": 23404.8109523810 }, { "x": 1350284400000, "y": 25939.9719047618 }, { "x": 1350889200000, "y": 22661.6014285714 }, { "x": 1351494000000, "y": 20579.0985714286 }, { "x": 1352102400000, "y": 22585.2552906402 }, { "x": 1352707200000, "y": 18785.2475665026 }, { "x": 1353312000000, "y": 19557.5735714284 }, { "x": 1353916800000, "y": 18670.1550000002 }, { "x": 1354521600000, "y": 15432.11 }, { "x": 1355126400000, "y": 18287.7600000002 }, { "x": 1355731200000, "y": 12086.7666666666 }, { "x": 1356336000000, "y": 13091.7819047619 }, { "x": 1356940800000, "y": 10996.8747619046 } ], "name": "Affiliate", "unitType": "CURRENCY", "type": "area" } ], "plotOptions": { "line": { "type": "lineOptions", "stacking": null }, "area": { "type": "areaOptions", "stacking": "normal" }, "column": { "type": "columnOptions", "stacking": "normal" } }, "title": { "text": null }, "chart": null } ); </code></pre>
3
12,124
Is it possible to add boolean conditions into a Binary Search Tree?
<p>I am trying to implement a Decision tree which from my understanding , a Decision Tree is a Binary Tree with boolean conditions , feel free to correct me if i am wrong. I am trying to implement an Add() function with a parameter of a template where i want to add a boolean conditions. I am using this link : <a href="http://csharpexamples.com/c-binary-search-tree-implementation/" rel="nofollow noreferrer">http://csharpexamples.com/c-binary-search-tree-implementation/</a> for help.I was trying to compare a boolean value with an int value knowing it won't work so i switched to using a template . This is my first time trying to implement a Binary Search Tree.</p> <p>Here is the code for my node class:</p> <pre><code> using System.Collections; using System.Collections.Generic; public class BST_NodeClass&lt;E&gt; { public BST_NodeClass&lt;E&gt; LeftNode { get; set; } public BST_NodeClass&lt;E&gt; RightNode { get; set; } public BST_NodeClass&lt;E&gt; Data { get; set; } }; </code></pre> <p>Here is the code for my Binary Search Tree :</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BST&lt;E&gt; where E : System.IComparable&lt;E&gt; { public BST_NodeClass&lt;E&gt; Root { get; set; } public bool Add (E condition) { BST_NodeClass&lt;E&gt; before = null, after = this.Root; while (after!= null) { before = after; if(condition &lt; after.Data)//Is new node in the left tree? { after = after.LeftNode; } else if (condition &gt; after.Data)//Is the new node in the right tree? { after = after.RightNode; } else { //Exist same value return false; } BST_NodeClass&lt;E&gt; newNode = new BST_NodeClass&lt;E&gt;(); newNode.Data = condition; if (this.Root == null)//Tree is empty this.Root = newNode; else { if (condition &lt; before.Data) before.LeftNode = newNode; else before.RightNode = newNode; } return true; } } }; </code></pre>
3
1,079
How to search for Specific item in User's Quick.db Inventory
<p>Pretty much, I'm having difficulty being able to find a role in a user's Quick.db inventory. I'd like to do this to: allow them to only buy a role once; allow them to equip an owned role only <em>if</em> it's found in their inventory. Problem is that the user is able to buy a role more than once, and able to equip a role even if it's not owned. I believe the line I'm having trouble with is <code>if(db.has(message.author.id + '.items' + 'hot rod red'))</code> (possibly because I'm searching for a role and not a plain text item?), but it could be something else.</p> <p>I'm completely lost and run out of ideas at this point, any help is appreciated!</p> <p><strong>Code for Equipping a Role:</strong></p> <pre><code> let user = message.guild.members.cache.get(message.author.id) let items = await db.fetch(message.author.id); if(items === null) items = &quot;Nothing&quot; let author = db.get(`items_${message.guild.id}_${user.id}`) if (args[0] == 'red') { let rejectEmbed = new Discord.MessageEmbed() .setDescription('You do not own this role!'); if(db.has(message.author.id + '.items' + 'hot rod red')){ if (message.member.roles.cache.some(role =&gt; role.name === 'hot rod red')) { let embed = new Discord.MessageEmbed().setDescription('You already have this role!'); return message.channel.send(embed); } else { await message.guild.members.cache.get(user.id).roles.add('733373020491481219'); let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`); message.channel.send(embed); user.roles.remove(user.roles.highest); } } else return message.channel.send(rejectEmbed) } </code></pre> <p><strong>Code for Buy Command:</strong></p> <pre><code> let Embed = new Discord.MessageEmbed() .setColor(&quot;#FFFFFF&quot;) .setDescription(`&gt; :no_entry_sign: You need 20,000 credits to purchase ${message.guild.roles.cache.get('733373020491481219')}`); if (message.member.roles.cache.some(role =&gt; role.name === &quot;level 25&quot;) ||(message.member.roles.cache.some(role =&gt; role.name === &quot;frequent flyers&quot;))){ if (console.log(db.has(message.author.id, 'hot rod red'))){ let EmbedError = new Discord.MessageEmbed() .setColor('#FFFFFF') .setDescription(`:no_entry_sign: You already own ${message.guild.roles.cache.get('733373020491481219')} !`); return message.channel.send(EmbedError) }else if (amount &lt; 20000) return message.channel.send(Embed) let Embed3 = new Discord.MessageEmbed() .setColor(&quot;#FFFFFF&quot;) .setDescription(`:white_check_mark: You bought ${message.guild.roles.cache.get('733373020491481219')} for 20,000 credits!`); message.channel.send(Embed3) db.subtract(`money_${message.guild.id}_${user.id}`, 20000) db.push(message.author.id, `${message.guild.roles.cache.get('733373020491481219')}`); db.fetch(`hot_rod_red${message.guild.id}_${user.id}`); db.set(`hot_rod_red_${message.guild.id}_${user.id}`, true) }else {return message.channel.send('You do not have the required level to buy this role!')} } </code></pre>
3
1,448
I have two i2c devices. Both alone work well, but when I read from one, and then write to the other, the second one is not an ancknowledging
<p>I have two devices MPU6050 and EEPROM 24C256. I can write and read from both alone. But when I try to read from MPU6050 and than write data to EEPROM in the same session, the EEPROM does not respond. I am using mbed OS libraries. And my question is.. Is it library, code or hardware problem?</p> <p>MPU6050 read sequence: <a href="https://i.stack.imgur.com/gRo9U.png" rel="nofollow noreferrer">enter image description here</a></p> <p>EEPROM write page sequance: <a href="https://i.stack.imgur.com/DTYYP.png" rel="nofollow noreferrer">enter image description here</a></p> <p>//CODE</p> <pre><code>const char imuAddress = 0x68&lt;&lt;1; const char imuDataAddress = 0x3B; const char eepAddress = 0xA0; const char data[3] = {1.1, 2.2, 3.3}; char acc[3]; //reading acceleration data from IMU while(true){ i2c.start(); if(i2c.write(imuAddress) != 1){ i2c.stop(); continue; } if(i2c.write(imuDataAddress) != 1){ i2c.stop(); continue; } i2c.start(); if(i2c.write(imuAddress | 0x01) != 1){ i2c.stop(); continue; } for (int i = 0; i &lt; 2; i++){ i2c.read(1); //read and respond ACK to continue } i2c.read(0); //read and respond NACK to stop reading i2c.stop(); break; } //write data to EEPROM while(true){ i2c.start(); if(i2c.write(eepAddress) != 1){ //here is the problem (EEPROM does not respond) i2c.stop(); continue; } if(i2c.write(0x00) != 1){ i2c.stop(); continue; } if(i2c.write(0x00) != 1){ i2c.stop(); continue; } bool ack = true; for(int i = 0; i &lt; 3; i++){ if(i2c.write(data[i]) != 1){ i2c.stop(); ack = false; break; } } if (ack == true){ i2c.stop(); break; } } </code></pre>
3
1,235
How to avoid object references for spawned objects in Unity 2D?
<p>At the moment I am programming a Unity 2D game. When the game is running the cars start moving and respawn continuously. I added kind of a life system to enable the possibility to shoot the cars. My issue is that my health bar as well as my score board need references to the objects they refer to, but I am unable to create a reference to an object which is not existing before the game starts. Another issue is that I don't know how to add a canvas to a prefab in order to spawn it with the cars continuously and connect them to the car. Is there a way to avoid these conflicts or how is it possible to set the references into prefabs. I will add the code of the spawner, the car and the the scoreboard. Already thank you in advance</p> <p>Spawner:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public GameObject carPrefab; public GameObject enemyCarPrefab; public GameObject kugel; public float respawnTime = 10.0f; public int counterPlayer1=0; public int counterPlayer2=0; public int counterEnergy=0; // Use this for initialization void Start () { StartCoroutine(carWave()); } private void spawnPlayerCars(){ GameObject a = Instantiate(carPrefab) as GameObject; a.transform.position = new Vector2(-855f, -312.9426f); counterPlayer1++; } private void SpawnEnemyCars(){ GameObject b = Instantiate(enemyCarPrefab) as GameObject; b.transform.position = new Vector2(853,-233); counterPlayer2++; } private void SpawnEnergy(){ GameObject c = Instantiate(kugel) as GameObject; c.transform.position = new Vector2(-995,-192); counterEnergy++; } IEnumerator carWave(){ while(true){ yield return new WaitForSeconds(respawnTime); if(counterPlayer1&lt;3){ spawnPlayerCars(); Debug.Log(counterPlayer1); } if(counterPlayer2&lt;3){ SpawnEnemyCars(); Debug.Log(counterPlayer2); } if(counterEnergy&lt;3){ SpawnEnergy(); } } } } </code></pre> <p>Car:</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyCar : MonoBehaviour { public float speed = 3f; int zählerAuto1=0; private Vector2 screenBounds; public AnzeigePunktzahlPlayer2 points; public Spawner sp; public int maxHealth=100; public int currentHealth; public HealthBar healthbar; void Start () { screenBounds = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)); points= GetComponent&lt;AnzeigePunktzahlPlayer2&gt;(); sp= GetComponent&lt;Spawner&gt;(); currentHealth=maxHealth; healthbar.SetMaxHealth(maxHealth); } void Update() { Vector2 pos = transform.position; if(pos.x&gt;-855f){ pos = transform.position; pos.x-= speed* Time.deltaTime; transform.position=pos; zählerAuto1++; }else{ points.counter++; Debug.Log(points.counter); sp.counterPlayer2--; Debug.Log(sp.counterPlayer2); Destroy(this.gameObject); } } private void OnCollisionEnter2D(Collision2D other) { if (other.collider.tag=="Kugel"){ takeDamage(40); //sp.counterPlayer2--; if(currentHealth&lt;=0) { Destroy(this.gameObject); } } } public void takeDamage(int damage){ currentHealth-= damage; healthbar.SetHealth(currentHealth); } public void getHealed(int heal){ currentHealth+= heal; healthbar.SetHealth(currentHealth); } } </code></pre> <p>Scoreboard(one part of it(the other one is almost the same)):</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class AnzeigePunktzahlPlayer1 : MonoBehaviour { public int counter; public TextMeshProUGUI textPlayer1; void Start() { // counter=0; textPlayer1= GetComponent&lt;TextMeshProUGUI&gt;(); } // Update is called once per frame void Update() { textPlayer1.SetText( counter.ToString()); } } </code></pre>
3
1,677
How to update content in Fragment of ViewPager using AsyncTaskLoader?
<p>I try to use <code>AsyncTaskLoader</code> in <code>Fragment</code> that is a child of <code>ViewPager</code>. Below a code of my <code>DayFragment</code>:</p> <pre><code>public class DayFragment extends Fragment implements LoaderManager.LoaderCallbacks&lt;DayAdapter.DayItem[]&gt; { private static final int CONTENT_LOADER = 0; private DayAdapter mAdapter = null; private int mWeekNumber = 1; private int mDayCode = 1; private Table.Timetable mTimetable; private RecyclerView mRVContent; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final MainActivity mainActivity = (MainActivity) getActivity(); View v = inflater.inflate(R.layout.content, container, false); mRVContent = (RecyclerView) v.findViewById(R.id.rvContent); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mainActivity); mRVContent.setLayoutManager(layoutManager); mAdapter = new DayAdapter(getActivity()); mRVContent.setAdapter(mAdapter); //Initialize the cursor loader getLoaderManager().initLoader(CONTENT_LOADER, null, this).forceLoad(); return v; } @Override public Loader&lt;DayAdapter.DayItem[]&gt; onCreateLoader(final int id, Bundle args) { if(CONTENT_LOADER == id) { return new ContentLoader(getContext(), mWeekNumber, mDayCode, mTimetable); } return null; } @Override public void onLoadFinished(Loader loader, DayAdapter.DayItem[] items) { if(CONTENT_LOADER == loader.getId()) { mAdapter.setIs24HourFormat(SettingsManager.is24HourFormat(getContext())); mAdapter.clear(); for (DayAdapter.DayItem item : items) { mAdapter.add(item); } mAdapter.notifyDataSetChanged(); if (items.length == 0) { mRVContent.setBackgroundResource(R.drawable.bg_lesson_empty); } else { mRVContent.setBackgroundColor(0xFFFFFFFF); } } } @Override public void onLoaderReset(Loader loader) { } private static final class ContentLoader extends AsyncTaskLoader&lt;DayAdapter.DayItem[]&gt; { private final int mWeekNumber; private final int mDayCode; private final Table.Timetable mTimetable; public ContentLoader(Context context, final int weekNumber, final int dayCode, Table.Timetable timetable) { super(context); mWeekNumber = weekNumber; mDayCode = dayCode; mTimetable = timetable; } @Override public DayAdapter.DayItem[] loadInBackground() { DatabaseHandler db = new DatabaseHandler(getContext()); db.openReadable(); List&lt;Table.Lesson&gt; lessons = db.findLessons(mDayCode, mWeekNumber, mTimetable.getId()); DayAdapter.DayItem[] items = new DayAdapter.DayItem[lessons.size()]; for (int i = 0; i &lt; items.length; ++i) { Table.Lesson lesson = lessons.get(i); Table.Subject subject = db.getSubject(lesson.getSubjectId()); Table.Teacher teacher = db.getTeacher(lesson.getTeacherId()); if (teacher == null) { teacher = new Table.Teacher(""); //Empty name } items[i] = new DayAdapter.DayItem() .setId(lesson.getId()) .setTitle(subject.getTitle()) .setSubtitle(teacher.getName())); } db.close(); return items; } } } </code></pre> <p><strong><code>PageAdapater</code></strong></p> <pre><code>public class PageAdapter extends FragmentStatePagerAdapter { public static final int PAGE_COUNT = 7; private int mWeekNumber; private final int[] mDayCodes; private final String[] mDays; private final DayFragment[] mFragments = new DayFragment[7]; private Table.Timetable mTimetable; private boolean mIsRebuildMode = false; public PageAdapter(Context context, FragmentManager fm, Table.Timetable timetable, final int weekNumber) { super(fm); //Initialize class members } @Override public Fragment getItem(int position) { DayFragment dayFragment; if (mFragments[position] == null) { dayFragment = new DayFragment(); Bundle args = new Bundle(); args.putSerializable(Keys.TIMETABLE, mTimetable); dayFragment.setArguments(args); dayFragment.setWeekNumber(mWeekNumber); dayFragment.setDayCode(mDayCodes[position]); mFragments[position]= dayFragment; } else { dayFragment = mFragments[position]; } return dayFragment; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { //do nothing here! no call to super.restoreState(arg0, arg1); } public void setWeekNumber(final int weekNumber) { mWeekNumber = weekNumber; Arrays.fill(mFragments, null); } public void setIsRebuildMode(final boolean isRebuildMode) { mIsRebuildMode = isRebuildMode; } @Override public CharSequence getPageTitle(final int position) { return mDays[position]; } @Override public int getCount() { return PAGE_COUNT; } @Override public int getItemPosition(Object object) { if(mIsRebuildMode) { return POSITION_NONE; } return super.getItemPosition(object); } } </code></pre> <p>But it doesn't call <code>onLoadFinished</code> method. I checked <code>Log</code> output... <code>LoaderManager</code> calls <code>onCreateLoader</code> but it never calls <code>onLoadFinished</code> except first run (when app started and <code>ViewPager</code> shows a first page (<code>Fragment</code>)). It's all! After if I switch a page to a next and a next and return to a first page <code>LoaderManager</code> doesn't call <code>onLoadFinished</code> for the first page too. But it creates loader calling <code>onCreateLoader</code> and resets loader calling <code>onLoaderReset</code>. Is it a joke from Google?</p>
3
2,720
RegExp Not providing expected result with cURL
<p>Hi below is my code which is not providing expected result.</p> <p>First it should provide complete html content of page using <code>cURL</code> then using regexp which is providing expected result when I provide them direct <code>htmlcontent</code> but not providing same result using curl. </p> <p>Suppose When I pass below content to <code>htmlcontent</code> variable then <code>RegExp</code> providing proper result. </p> <pre><code>$htmlContent = '&lt;table id="ctl00_pageContent_ctl00_productList" class="product-list" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;"&gt; &lt;tr&gt; &lt;td class="product-list-item-container" style="width:100%;"&gt; &lt;div class="product-list-item" onkeypress="javascript:return WebForm_FireDefaultButton(event, &amp;#39;ctl00_pageContent_ctl00_productList_ctl00_imbAdd&amp;#39;)"&gt; &lt;a href="/W10542314D/WDoorGasketandLatchSt.aspx"&gt; &lt;img class="product-list-img" src="/images/products/display/applianceparts.jpg" title="W10542314 D/W Door Gasket &amp; Latch St " alt="W10542314 D/W Door Gasket &amp; Latch St " border="0" /&gt; &lt;/a&gt; &lt;div class="product-list-options"&gt; &lt;h5&gt;&lt;a href="/W10542314D/WDoorGasketandLatchSt.aspx"&gt;W10542314 D/W Door Gasket &amp;amp; Latch St&lt;/a&gt;&lt;/h5&gt; &lt;div class="product-list-cost"&gt;&lt;span class="product-list-cost-label"&gt;Online Price:&lt;/span&gt; &lt;span class="product-list-cost-value"&gt;$33.42&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; </code></pre> <p>Below is my complete code - </p> <pre><code>&lt;?php $url = "http://www.universalapplianceparts.com/search.aspx?find=W10130694"; $ch1= curl_init(); curl_setopt ($ch1, CURLOPT_URL, $url ); curl_setopt($ch1, CURLOPT_HEADER, 0); curl_setopt($ch1,CURLOPT_VERBOSE,1); curl_setopt($ch1, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)'); curl_setopt ($ch1, CURLOPT_REFERER,'http://www.google.com'); //just a fake referer curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch1,CURLOPT_POST,0); curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 20); $htmlContent= curl_exec($ch1); echo $htmlContent; $value=preg_match_all('/.*&lt;div.*class=\"product\-list\-options\".*&gt;.*&lt;a href="(.*)"&gt;.*&lt;\/a&gt;.*&lt;\/div&gt;/s',$htmlContent,$matches); print_r($matches); $value=preg_match_all('/.*&lt;div.*class=\"product\-list\-item\".*&gt;.*&lt;a href=\"(.*)\"&gt;.*&lt;img.*&gt;.*&lt;\/div&gt;/s',$htmlContent,$matches); print_r($matches); </code></pre> <p>In this code it echo htmlcontent of webpage then with regexp it should return <code>href</code> of anchor tag between div which class name is <code>product-list-options</code> and <code>product-list-item</code></p> <p>Current output is - </p> <pre><code>http://www.universalapplianceparts.com/termsofservice.aspx </code></pre> <h2>Here Regexp reading my html content from cURL in reverse order and returning first href value in anchor tag.</h2> <p>Expected output in array value - <code>/W10130694LatchAssyWhiteHandle.aspx</code></p> <p>Any help would be appreciated.</p> <p>Thanks </p>
3
1,424
Setting up https on Google Compute Engine running WordPress
<p>I have set up WordPress on GCE using the marketplace:</p> <p><a href="https://cloud.google.com/wordpress/" rel="nofollow noreferrer">https://cloud.google.com/wordpress/</a></p> <p>I have set up the domain name to worldbreakersgame.com and reserved a static IP. I then followed the instructions here to set up https:</p> <p><a href="https://onepagezen.com/free-ssl-certificate-wordpress-google-cloud-click-to-deploy/" rel="nofollow noreferrer">https://onepagezen.com/free-ssl-certificate-wordpress-google-cloud-click-to-deploy/</a></p> <p>One part of the tutorial that did not work, <code>/etc/apache2/sites-available/wordpress.conf</code> did not exist. I edited <code>/etc/apache2/sites-available/wordpress-http.conf</code> instead.</p> <p>However, when going to <a href="https://www.worldbreakersgame.com" rel="nofollow noreferrer">https://www.worldbreakersgame.com</a>, I still get the error message that &quot;Your connection is not private&quot;. I think that there is an issue with the certificate I issued through Let's Encrypt/certbot, but I am not sure.</p> <p>I tried restarting the apache server again but it does not seem to help.</p> <p>Here are the relevant WordPress settings:</p> <p><a href="https://i.stack.imgur.com/wYAaD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wYAaD.png" alt="WordPress Settings" /></a></p> <p>And some snippets from the terminal:</p> <pre><code>el_ad_david_amir@wordpress-1-vm:~$ lsb_release -a No LSB modules are available. Distributor ID: Debian Description: Debian GNU/Linux 10 (buster) Release: 10 Codename: buster </code></pre> <pre><code>el_ad_david_amir@wordpress-1-vm:~$ sudo ls /etc/letsencrypt/live/worldbreakersgame.com/ README cert.pem chain.pem fullchain.pem privkey.pem </code></pre> <pre><code>el_ad_david_amir@wordpress-1-vm:~$ sudo cat /etc/apache2/sites-available/wordpress-https.conf &lt;VirtualHost *:443&gt; ServerAdmin admin@example.com DocumentRoot /var/www/html SSLEngine on SSLCertificateFile &quot;/etc/letsencrypt/live/worldbreakersgame.com/cert.pem&quot; SSLCertificateKeyFile &quot;/etc/letsencrypt/live/worldbreakersgame.com/privkey.pem&quot; SSLCertificateChainFile &quot;/etc/letsencrypt/live/worldbreakersgame.com/chain.pem&quot; &lt;Directory /var/www/html&gt; Options -Indexes AllowOverride FileInfo &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <pre><code>el_ad_david_amir@wordpress-1-vm:~$ sudo cat /etc/apache2/sites-available/wordpress-http.conf &lt;VirtualHost *:80&gt; ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName www.worldbreakersgame.com ServerAlias worldbreakersgame.com Redirect permanent / https://www.worldbreakersgame.com/ &lt;Directory /&gt; Options FollowSymLinks AllowOverride None &lt;/Directory&gt; &lt;Directory /var/www/html/&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all &lt;/Directory&gt; ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ &lt;Directory &quot;/usr/lib/cgi-bin&quot;&gt; AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre> <p>Finally, here is <code>/etc/apache2/sites-available/default-ssl.conf</code>:</p> <pre><code>&lt;IfModule mod_ssl.c&gt; &lt;VirtualHost _default_:443&gt; ServerAdmin webmaster@localhost &lt;Directory /var/www/html/&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all &lt;/Directory&gt; DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with &quot;a2disconf&quot;. #Include conf-available/serve-cgi-bin.conf # SSL Engine Switch: # Enable/Disable SSL for this virtual host. SSLEngine on # A self-signed (snakeoil) certificate can be created by installing # the ssl-cert package. See # /usr/share/doc/apache2/README.Debian.gz for more info. # If both key and certificate are stored in the same file, only the # SSLCertificateFile directive is needed. #SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem #SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key SSLCertificateFile &quot;/etc/letsencrypt/live/worldbreakersgame.com/cert.pem&quot; SSLCertificateKeyFile &quot;/etc/letsencrypt/live/worldbreakersgame.com/privkey.pem&quot; SSLCertificateChainFile &quot;/etc/letsencrypt/live/worldbreakersgame.com/chain.pem&quot; # Server Certificate Chain: # Point SSLCertificateChainFile at a file containing the # concatenation of PEM encoded CA certificates which form the # certificate chain for the server certificate. Alternatively # the referenced file can be the same as SSLCertificateFile # when the CA certificates are directly appended to the server # certificate for convinience. #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt # Certificate Authority (CA): # Set the CA certificate verification path where to find CA # certificates for client authentication or alternatively one # huge file containing all of them (file must be PEM encoded) # Note: Inside SSLCACertificatePath you need hash symlinks # to point to the certificate files. Use the provided # Makefile to update the hash symlinks after changes. #SSLCACertificatePath /etc/ssl/certs/ #SSLCACertificateFile /etc/apache2/ssl.crt/ca-bundle.crt # Certificate Revocation Lists (CRL): # Set the CA revocation path where to find CA CRLs for client # authentication or alternatively one huge file containing all # of them (file must be PEM encoded) # Note: Inside SSLCARevocationPath you need hash symlinks # to point to the certificate files. Use the provided # Makefile to update the hash symlinks after changes. #SSLCARevocationPath /etc/apache2/ssl.crl/ #SSLCARevocationFile /etc/apache2/ssl.crl/ca-bundle.crl # Client Authentication (Type): # Client certificate verification type and depth. Types are # none, optional, require and optional_no_ca. Depth is a # number which specifies how deeply to verify the certificate # issuer chain before deciding the certificate is not valid. #SSLVerifyClient require #SSLVerifyDepth 10 # SSL Engine Options: # Set various options for the SSL engine. # o FakeBasicAuth: # Translate the client X.509 into a Basic Authorisation. This means that # the standard Auth/DBMAuth methods can be used for access control. The # user name is the `one line' version of the client's X.509 certificate. # Note that no password is obtained from the user. Every entry in the user # file needs this password: `xxj31ZMTZzkVA'. # o ExportCertData: # This exports two additional environment variables: SSL_CLIENT_CERT and # SSL_SERVER_CERT. These contain the PEM-encoded certificates of the # server (always existing) and the client (only existing when client # authentication is used). This can be used to import the certificates # into CGI scripts. # o StdEnvVars: # This exports the standard SSL/TLS related `SSL_*' environment variables. # Per default this exportation is switched off for performance reasons, # because the extraction step is an expensive operation and is usually # useless for serving static content. So one usually enables the # exportation for CGI and SSI requests only. # o OptRenegotiate: # This enables optimized SSL connection renegotiation handling when SSL # directives are used in per-directory context. #SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire &lt;FilesMatch &quot;\.(cgi|shtml|phtml|php)$&quot;&gt; SSLOptions +StdEnvVars &lt;/FilesMatch&gt; &lt;Directory /usr/lib/cgi-bin&gt; SSLOptions +StdEnvVars &lt;/Directory&gt; # SSL Protocol Adjustments: # The safe and default but still SSL/TLS standard compliant shutdown # approach is that mod_ssl sends the close notify alert but doesn't wait for # the close notify alert from client. When you need a different shutdown # approach you can use one of the following variables: # o ssl-unclean-shutdown: # This forces an unclean shutdown when the connection is closed, i.e. no # SSL close notify alert is send or allowed to received. This violates # the SSL/TLS standard but is needed for some brain-dead browsers. Use # this when you receive I/O errors because of the standard approach where # mod_ssl sends the close notify alert. # o ssl-accurate-shutdown: # This forces an accurate shutdown when the connection is closed, i.e. a # SSL close notify alert is send and mod_ssl waits for the close notify # alert of the client. This is 100% SSL/TLS standard compliant, but in # practice often causes hanging connections with brain-dead browsers. Use # this only for browsers where you know that their SSL implementation # works correctly. # Notice: Most problems of broken clients are also related to the HTTP # keep-alive facility, so you usually additionally want to disable # keep-alive for those clients, too. Use variable &quot;nokeepalive&quot; for this. # Similarly, one has to force some clients to use HTTP/1.0 to workaround # their broken HTTP/1.1 implementation. Use variables &quot;downgrade-1.0&quot; and # &quot;force-response-1.0&quot; for this. # BrowserMatch &quot;MSIE [2-6]&quot; \ # nokeepalive ssl-unclean-shutdown \ # downgrade-1.0 force-response-1.0 &lt;/VirtualHost&gt; &lt;/IfModule&gt; # vim: syntax=apache ts=4 sw=4 sts=4 sr noet </code></pre>
3
5,397
REST web application in Maven using Jersey
<p>I'm new in jersey and trying to create project that uses rest web service and response me the json. following is my pom.xml</p> <pre><code>&lt;project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;com.modaltestapp&lt;/groupId&gt; &lt;artifactId&gt;modaltestapp&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;groupId&gt;com.modaltestapp&lt;/groupId&gt; &lt;artifactId&gt;modaltestapp-api&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;modaltestapp-api Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;properties&gt; &lt;slf4j.version&gt;1.7.9&lt;/slf4j.version&gt; &lt;logback.version&gt;1.1.2&lt;/logback.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-server&lt;/artifactId&gt; &lt;version&gt;1.9&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;modaltestapp-api&lt;/finalName&gt; &lt;/build&gt; </code></pre> <p></p> <p>web.xml</p> <pre><code>&lt;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;display-name&gt;Restful Web Application&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;helloworld&lt;/servlet-name&gt; &lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;com.modaltestapp.service&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.api.json.POJOMappingFeature&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;helloworld&lt;/servlet-name&gt; &lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p></p> <p>And java file is:</p> <pre><code> @GET @Path("/print") @Produces({ MediaType.APPLICATION_JSON }) // add MediaType.APPLICATION_XML // if you want XML as well // (don't forget // @XmlRootElement) public List&lt;RegistrationDto&gt; getAllMessages() throws Exception { List&lt;RegistrationDto&gt; messages = new ArrayList&lt;RegistrationDto&gt;(); RegistrationDto m = new RegistrationDto(); m.setFirstName("Nabi"); m.setLastName("Zamani"); m.setAge(30); messages.add(m); System.out.println("getAllMessages(): found " + messages.size() + " message(s) on DB"); return messages; // do not use Response object because this causes // issues when generating XML automatically } </code></pre> <p>but when I build and run app it shows me error:</p> <pre><code> INFO: Starting Servlet Engine: Apache Tomcat/9.0.0.M21 Jul 03, 2017 11:12:24 AM org.apache.catalina.core.ApplicationContext log INFO: Marking servlet [helloworld] as unavailable Jul 03, 2017 11:12:24 AM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet [helloworld] in web application [/modaltestapp-api] threw load() exception java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:508) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:489) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:119) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1050) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4921) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5231) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1439) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1429) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1439) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1429) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.startup.Catalina.start(Catalina.java:656) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495) Jul 03, 2017 11:12:24 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-nio-8080"] Jul 03, 2017 11:12:24 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-nio-8009"] Jul 03, 2017 11:12:24 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 317 ms </code></pre> <p>How can I fix this? I'm using Apache Tomcat 9.</p>
3
3,088
requesting video from YouTube API to be played in HTML page
<p>I'm trying to request videos from YouTube API but I'm only getting the title of the video and its thumbnail. how can i play the video ? </p> <p><strong>Note</strong>: I'm using the YouTube documentation in html and JavaScript</p> <p>I've tried to use item.snippet.player.embedHtml and put it in but nothing were shown.</p> <p><strong>This is my code:</strong></p> <pre><code> &lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Search&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="buttons"&gt; &lt;label&gt; &lt;input id="query" type="text"/&gt;&lt;button id="search-button" onclick="keyWordsearch()"&gt;Search&lt;/button&gt;&lt;/label&gt; &lt;div id="container"&gt; &lt;h1&gt;Search Results&lt;/h1&gt; &lt;ul id="results"&gt;&lt;/ul&gt; &lt;/div&gt; &lt;script&gt; function keyWordsearch(){ gapi.client.setApiKey(''); gapi.client.load('youtube', 'v3', function() { makeRequest(); }); } function makeRequest() { var q = $('#query').val(); var request = gapi.client.youtube.search.list({ q: q, part: 'snippet', maxResults: 1 }); request.execute(function(response) { $('#results').empty() var srchItems = response.result.items; $.each(srchItems, function(index, item) { vidTitle = item.snippet.title; vidThumburl = item.snippet.thumbnails.default.url; vidThumbimg = '&lt;pre&gt;&lt;img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"&gt;&lt;/pre&gt;'; $('#results').append('&lt;pre&gt;' + vidTitle + vidThumbimg + '&lt;/pre&gt;'); }) }) } &lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
1,198
MS Access: filling in missing values and adding numbers
<p>I wasn't sure what a proper title would be, I hope this works.</p> <p>I'm having trouble converting rows to columns with a certain table, and found possible solutions online. However, I feel like I need to edit this table to enable me to actually convert the rows into columns.</p> <p>The table looks a little bit like this:</p> <pre><code>ID1 patientID patientname study_date echo_var 1 1234 Bob 01-01-2014 15 2 1234 01-01-2000 13 3 1234 Bob 08-08-2012 14 4 1234 Bob 13-02-2005 13 5 6625 Louie 12-11-2010 25 6 6625 08-10-1998 20 7 6625 Louie 19-04-2006 21 </code></pre> <p>This is information automatically harvested from an electronic patient system and normally contains a lot more variables per row, but I'm only interested in one (echo-var) right now. All the rows represent specific patient visits. Because of changes in the electronic system the tool I use can't properly extract all data from older records, which is why some of the names aren't filled in properly. Seeing as their patientID is unique for every patient I can fill the names in manually, but there's about 6000 records so I was hoping there would be a more elegant manner of doing so.</p> <p>This is not much of a bother though, the major thing is converting the rows into columns (see below). So I found a solution online for my problem, but I feel like I am hindered because the separate datapoints per patient aren't numbered uniquely for every patient, as below. I want every seperate datapoint to be numbered for each patient, so the first visit, chronologically, is numbered 1 for each patient individually, and the second is 2, etc.</p> <pre><code> ID1 patientID patientname study_date echo_var echo_number 1 1234 Bob 01-01-2014 15 4 2 1234 Bob 01-01-2000 13 1 3 1234 Bob 08-08-2012 14 3 4 1234 Bob 13-02-2005 13 2 5 6625 Louie 12-11-2010 25 3 6 6625 Louie 08-10-1998 20 1 7 6625 Louie 19-04-2006 21 2 </code></pre> <p>If I have this I think I know how to convert the rows to columns, which is what I ultimately want, like below.</p> <pre><code>patientID echo_number1 study_date1 echo_var1 echo_number2 study_date2 echo_var2 1234 1 01-01-2000 13 2 13-02-2005 13 6625 1 08-10-1998 20 2 19-04-2006 21 </code></pre> <p>There would be rows for date no. 3 and its respective measurement and so forth. I guess the echo_number(x) variables aren't crucial, but the dates and respective measurement would be.</p> <p>Does anyone know the proper way to go for this? As I've mentioned, I've tried searching for these particular problems but I'm having trouble finding a solution. If anything's unclear please let me know. If anyone knows how how to go from the first table to the last (without the steps in between), that would work as well.</p> <p>Many thanks in advance</p> <hr> <p>Using a table similar to the second one above, I've tried the following queries:</p> <pre><code>SELECT [patientID], "echo_number" &amp; [echo_number] &amp; "_" &amp; "echo_var" AS [ValueID], [echo_var] AS [ValueValue] FROM [TABLENAME] UNION ALL SELECT [patientID], "echo_number" &amp; [echo_number] &amp; "_" &amp; "study_date" AS [ValueID], [study_date] AS [ValueValue] FROM [TABLENAME]; </code></pre> <p>Followed by:</p> <pre><code>TRANSFORM Sum(NEWQUERY.ValueValue) AS SumOfValueValue SELECT NEWQUERY.patientID FROM NEWQUERY GROUP BY NEWQUERY.patientID PIVOT NEWQUERY.ValueID </code></pre>
3
1,365