title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
Firebase: Query to exclude data based on a condition
<p>I'm able to get the data for a particular value in the child using <code>orderByChild</code> and <code>equalTo</code> (cool that it works for nested child as well) </p> <pre><code>private void getData() { try { final DatabaseReference database = FirebaseDatabase.getInstance().getReference(); database.child(Constants.TABLE_TASKS).orderByChild("user/id") .equalTo("somevalue") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Timber.d(dataSnapshot.toString()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } catch (Exception ex) { ex.printStackTrace(); } } </code></pre> <p>Is there an easy way to get the data where a particular value is not found, basically something like a <code>notEqualTo("somevalue")</code> ? </p>
0
How to load gif image in placeholder of Glide/Picasso/Ion etc
<p>Not able to find perfect solution for loading a gif image in placeholder</p> <pre><code>Glide .with(context) .load("imageUrl") .asGif() .placeholder(R.drawable.gifImage) .crossFade() .into(imageView) </code></pre> <p>Tried asGif() property of Glide version 3.7.0 too. But no Luck!</p>
0
How to create nested object in MongoDB schema
<p>I currently have the following schema for a MongoDB document which is supposed to save user data:</p> <pre><code>var userSchema = new mongoose.Schema({ username: {type: String, unique : true}, password: {type: String}, firstname: String, lastname: String, sketches: [ {name: String, sketch: Array} ] </code></pre> <p>The sketches attribute needs to be an array objects where each object associates the name of a sketch and an array which holds the sketch data. For some reason, the schema ends up being created as the following:</p> <pre><code>{ &quot;__v&quot; : 1, &quot;_id&quot; : ObjectId(&quot;57c4d7693aa85cea2acf4d4d&quot;), &quot;firstname&quot; : &quot;test&quot;, &quot;lastname&quot; : &quot;name&quot;, &quot;password&quot; : &quot;password123&quot;, &quot;sketches&quot; : [ { &quot;sketch&quot; : [] } ], &quot;username&quot; : &quot;testname&quot; } </code></pre> <p>I'm not exactly sure the correct format for creating nested objects in MongoDB but I was assuming that it would be the same as it would for JSON. How should the schema be structured to yield an array of objects.</p> <h2>EDIT:</h2> <p><strong>web service to insert into document from PUT request:</strong></p> <pre><code>app.route(&quot;/addSketch/:username&quot;).put(function(req, res, next) { var user_name = req.params.username; User.findOne({username:user_name},function(err,foundObject){ if(err){ console.log(&quot;error&quot;); res.status(500).send(); } else{ if(!foundObject){ res.status(404).send(); } else{ if(req.body.strokes &amp;&amp; req.body.sketchName){ var sketchObj = []; sketchObj[req.body.sketchName] = req.body.strokes; foundObject.sketches.push(req.body.sketchData); } foundObject.save(function(err,updatedObject){ if(err){ console.log(err); res.status(500).send(); } else{ res.send(updatedObject); } }); } } }); console.log('saving on server'); var form = formidable.IncomingForm(); console.log(form); console.log('the type of the request received is', (typeof req)); form.parse(req, function(err, fields, files) { res.writeHead(200, {&quot;content-type&quot;: &quot;text/plain&quot;}); res.write('received upload:\n\n'); var name = fields.name; var newSketch = new SavedSketch(); newSketch.name = name; newSketch.sketchData = fields.value; newSketch.save(function(err,savedObject){ if(err){ console.log(err); res.status(500).json({status:'failure'}) } else{ console.log(&quot;ID: &quot; + fields.value.id + &quot; strokeData:&quot; + fields.value.strokes); res.json({status: 'success'}); } }); res.end(); }); }); </code></pre>
0
Set and get using tag a fragment in android
<p>I've created a tab layout with viewpager. Everything was alright, except that I need to run a method in a specific moment. So I need to get fragment instance and run their method. I create in this way:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); activateToolbarWithNavigationView(HomeActivity.this); // Tabs Setup TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); final ViewPager viewPager = (ViewPager) findViewById(R.id.home_pager); if (tabLayout != null) { tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.favorites_label_fragment)).setTag(getString(R.string.fragment_favorite_tag))); tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.air_today_label_fragment)).setTag(getString(R.string.fragment_airing_today_tag))); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); final HomePageAdapter adapter = new HomePageAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); if (viewPager != null) { viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } } public void refreshFavorites(){ FavoritesFragment favoritesFragment = (FavoritesFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_favorite_tag)); if(favoritesFragment != null) favoritesFragment.executeFavoriteList(); } </code></pre> <p>I don't know if i'm doing it in wrong way, or there some mistake that they return null from findFragmentByTag... I can't figure out. In case, I've checked some others answers but I can't understand what I really need to do.</p> <p>viewpager adapter:</p> <pre><code>public class HomePageAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public HomePageAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: FavoritesFragment favoritesFragment = new FavoritesFragment(); return favoritesFragment; case 1: AirTodayFragment airTodayFragment = new AirTodayFragment(); return airTodayFragment; default: return null; } } @Override public int getCount() { return mNumOfTabs; } } </code></pre> <p>my xml:</p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/ad_view_home"&gt; &lt;android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?actionBarSize" android:theme="@style/ActionBarThemeOverlay"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="?actionBarSize" app:layout_scrollFlags="scroll|enterAlways" app:logo="@mipmap/ic_launcher_initials" app:popupTheme="@style/AppTheme.PopupOverlay" app:theme="@style/ActionBarThemeOverlay" app:titleTextAppearance="@style/ActionBar.TitleText"&gt; &lt;/android.support.v7.widget.Toolbar&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/app_bar_layout" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/home_pager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p><strong>EDIT 1: HOW I SOLVED:</strong></p> <pre><code>public void refreshFavorites(){ List&lt;Fragment&gt; allFragments = getSupportFragmentManager().getFragments(); for (Fragment fragmento: allFragments) { if (fragmento instanceof FavoritesFragment){ ((FavoritesFragment) fragmento).executeFavoriteList(); } } } </code></pre> <p><strong>EDIT 2: WHERE I USE:</strong></p> <p>I didn't use refreshFavoretes inside my Activity but actually in Fragments that are inside of it:</p> <pre class="lang-cs prettyprint-override"><code>@Override public void onClick(View v) { ... // Refresh Favorites if (getActivity() instanceof MainActivity) ((MainActivity) getActivity()).refreshFavorites(); } </code></pre> <p>You can see more at:</p> <p><a href="https://github.com/adleywd/WhatsNextSeries/blob/d5a4232a51596bda43ccbe40424e93d0929b1a33/app/src/main/java/br/com/adley/whatsnextseries/activities/MainActivity.java" rel="nofollow noreferrer">GitHub/MainActivity.Java</a> </p> <p>and</p> <p><a href="https://github.com/adleywd/WhatsNextSeries/blob/45fc08cee60fe5cb75d5aad7009df2492e54d91a/app/src/main/java/br/com/adley/whatsnextseries/fragments/PopularFragment.java" rel="nofollow noreferrer">GitHub/PopularFragment.Java -- Fragment from MainActivity</a> </p>
0
Getting list of class fields
<p>I am trying to create a generic method for my search, but I don't know how to return list of fields from my class.</p> <p>Let's say I've got a class: </p> <pre><code>public class Table { [Key] public int ID { get; set; } public string Name { get; set; } public string Address { get; set; } } </code></pre> <p>And now I want to return a list that would look like this:</p> <pre><code>"ID" "Name" "Address" </code></pre> <p>How do I do that?</p> <p>tried something like this:</p> <pre><code> FieldInfo[] fields = typeof(T).GetFields( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); string[] names = Array.ConvertAll&lt;FieldInfo, string&gt;(fields, delegate(FieldInfo field) { return field.Name; }); </code></pre> <p>But it has some unnecessary text after field names</p> <h2><strong>EDIT</strong></h2> <p>It's not duplicate because in my situation GetProperties()<strong>.Select(f => f.Name)</strong> made a difference</p>
0
Pagination for search results laravel 5.3
<h2>Pagination search results</h2> <p>I have just started with Laravel and I am trying to make a search function with proper pagination. The function works for page one but on page two it doesn't. I think it's not giving the results to the next page but I can't seem to find an answer.</p> <hr> <p><em>this is my search function inside IndexController:</em></p> <pre><code>public function search() { $q = Input::get('search'); # going to next page is not working yet $product = Product::where('naam', 'LIKE', '%' . $q . '%') -&gt;orWhere('beschrijving', 'LIKE', '%' . $q . '%') -&gt;paginate(6); return view('pages.index', compact('product')); } </code></pre> <p><em>this is my route:</em></p> <pre><code>Route::post('search{page?}', 'IndexController@search'); </code></pre> <p><em>this is the URL of page two:</em></p> <pre><code>/search?page=2 </code></pre> <p><em>this is how I show my pagination:</em></p> <pre><code>{{ $product-&gt;appends(Request::get('page'))-&gt;links()}} </code></pre> <p><em>the error:</em></p> <pre><code>MethodNotAllowedHttpException in RouteCollection.php line 218: </code></pre> <hr> <p>Get error on request.</p> <p>Route:</p> <pre><code>Route::get('search/{page?}', 'IndexController@search'); </code></pre> <p>Error:</p> <pre><code>MethodNotAllowedHttpException in RouteCollection.php line 218: in RouteCollection.php line 218 at RouteCollection-&gt;methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php line 205 at RouteCollection-&gt;getRouteForMethods(object(Request), array('GET', 'HEAD')) in RouteCollection.php line 158 at RouteCollection-&gt;match(object(Request)) in Router.php line 780 at Router-&gt;findRoute(object(Request)) in Router.php line 610 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 53 </code></pre> <hr> <p>I hope my question is clear and in the right format. Thank you in advance (sorry for my bad English)</p> <hr> <p><strong>Answer:</strong></p> <p>I ended up using the answer of this post in combination with some help of <a href="https://stackoverflow.com/questions/35212580/laravel-5-route-pagination-url-encoding-issue?rq=1">this</a> post</p> <p>I used a post function for the initial search and a get function for the following pages. This was possible because I'm now giving my search to the URL.</p> <hr> <p><strong>EDIT:</strong></p> <ul> <li>added the initial error.</li> <li>added the <code>Route::get</code> error</li> <li>added answer</li> </ul>
0
“href” value in HTML to open video in youtube app or market (Google Play) on Android
<p>I'm making a Web Page that shows 360 videos, but i recently noticed that 360 functionality in the android browser is not supported, and because of this the video wont shows correctly, so after searching a lot i found that the best option is to try to open the video in the YouTube app making use of an "Android Intent" explained in this developer tutorial:</p> <p><a href="https://developer.chrome.com/multidevice/android/intents" rel="nofollow noreferrer">https://developer.chrome.com/multidevice/android/intents</a></p> <p>So i need to construct the href address for a YouTube video, but unfortunately i don't know android programming and also can't find the YouTube App xml manifest to fill the options, can anyone help me?</p> <pre><code>intent: HOST/URI-path &lt;-- I think here needs to be the video URL? #Intent; package=com.google.android.youtube.player.YouTubeIntents; &lt;-- Is this the correct package? or should i use com.google.android.youtube.player? action=createPlayVideoIntentWithOptions(context, UUweNrpFTwA, true, true); &lt;-- Dont know what to put in context field category=[string]; &lt;-- Is category needed? if so what category should i place here? component=[string]; &lt;-- Is component needed? scheme=youtube; &lt;-- Is this the correct scheme? end; </code></pre> <p>Any help or tutorial will be greatly appreciated... Thanks!!</p>
0
How to map exisiting sql server view with EF code first
<p>i am fairly new in EF and learning EF code first. i am looking for a knowledge to map exisiting sql server view with EF code first. i have map my view with POCO but getting the below error.</p> <p>when i try to fetch data from view then got the below error thrown</p> <blockquote> <p>Additional information: The model backing the 'TestDBContext' context has changed since the database was created. Consider using Code First Migrations to update the database</p> </blockquote> <h2>my full code as follow</h2> <pre><code>public class TestDBContext : DbContext { public TestDBContext() : base("name=TestDBContext") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new vwCustomerConfiguration()); } public DbSet&lt;vwCustomer&gt; vwCustomer { get; set; } } public class vwCustomerConfiguration : EntityTypeConfiguration&lt;vwCustomer&gt; { public vwCustomerConfiguration() { this.HasKey(t =&gt; t.CustomerID); this.ToTable("vwCustomer"); } } public class vwCustomer { public int CustomerID { get; set; } public string FirstName { get; set; } } </code></pre> <h2>this way i am trying to load data.</h2> <pre><code> using (var db = new TestDBContext()) { var listMyViews = db.vwCustomer.ToList(); } </code></pre> <p>guide me what i am missing in code for which error is throwing. thanks</p> <h2>UPDATE1</h2> <p>When i issue Add-Migration "My_vwCustomer" then i saw new migration code added as below one. it seems there is no migration is pending.</p> <pre><code> public partial class My_vwCustomer : DbMigration { public override void Up() { CreateTable( "dbo.vwCustomers", c =&gt; new { CustomerID = c.Int(nullable: false, identity: true), FirstName = c.String(), }) .PrimaryKey(t =&gt; t.CustomerID); } public override void Down() { DropTable("dbo.vwCustomers"); } } </code></pre>
0
Play multiple sounds at the same time in python
<p>I have been looking into a way to play sounds from a list of samples, and I found some modules that can do this.</p> <p>I am using <strong>AudioLazy</strong> module to play the sound using the following script:</p> <pre><code>from audiolazy import AudioIO sound = Somelist with AudioIO(True) as player: player.play(sound, rate=44100) </code></pre> <p>The problem with this code is that it stop the whole application till the sound stop playing and I can't play multiple sound at the same time.</p> <p>My program is interactive so what I want is to be able to play multiple sound at the same time,So for instance I can run this script which will play a 5 second sound then at the second 2 I can play a 5 second sound again.</p> <p>And I don't want the whole program to stop till the sound finish playing.</p>
0
Jenkins Workflow java.io.NotSerializableException: groovy.json.internal.LazyMap in Closure
<p>I've got the following function in a workflow script that results in the error <code>java.io.NotSerializableException: groovy.json.internal.LazyMap</code></p> <pre><code>def getParentTagForCurrentBranch(appWorkspace) { def parentTag = null dir("${appWorkspace.getPath()}") { parentTag = bat(script:"git describe --abbrev=0 --tags", returnStdout:true) } return parentTag } </code></pre> <p>What I don't understand about the error is where I am using a LazyMap?</p> <p>I've tried quite a few different variations of this block but all result in the error, I've also tried using the <code>@NonCPS</code> but that just results in the whole method being skipped.</p> <p>Can anyone help me understand why this produces the error and how to resolve it?</p>
0
Alexa Skill not recognized when tested on Echo
<p>I was doing one of the tutorials (HelloWorld) to make a skill for the Echo and I followed the directions. When I tested the skill using the Service Simulator, I typed in </p> <pre><code>Alexa, tell Greeter to say hello </code></pre> <p>and that returned the following JSON response:</p> <pre><code>{ "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": "Hello World!" }, "card": { "content": "Hello World!", "title": "Greeter", "type": "Simple" }, "shouldEndSession": true }, "sessionAttributes": {} } </code></pre> <p>I think that is the correct output. However, when I tried testing the skill on my Echo, Alexa replies "Sorry, I didn't your question." I went on the history and Alexa interpreted my command as "alexa tell greeter to say hello." It seems that Alexa is not recognizing the skill? </p> <p>I am using Amazon Lambda to execute the code, so I checked the logs and the code was not executed when I spoke the command to above. </p> <p>I replaced the app_id in the javascript file to the one that corresponds to my skill. I have also put the amazon skills kit as a trigger. </p> <p>I also tried the other tutorials (ChemistryFlashCards and HistoryBuff), and Alexa replies "I'm not sure what you meant by that." </p> <p>Not sure what is happening! Any guidance is appreciated!!</p>
0
spring-boot - Which piece of code actually register dispatcher servlet for springMVC?
<p>I am trying to find out in <code>spring-boot</code>, which implementation of <code>WebApplicationInitializer</code> actually register the dispatcher servlet.</p> <p>I didn't found any piece code from <code>SpringBootServletInitializer</code> or its parent types did that.</p> <p>Instead, <code>AbstractDispatcherServletInitializer</code> does the job, but it's abstract, I can't find any of its concrete implementation with help of Eclipse.</p> <p>So, which piece of code from which class is actually invoked to register the dispatcher servlet for springMVC?</p> <p><em>This is a subsequent question of: <a href="https://stackoverflow.com/questions/39192943/how-does-spring-boot-able-to-serve-specific-url">How does spring-boot able to serve specific url?</a></em></p>
0
How to call a function from HTML to a Javascript file, in Node.JS
<p>I am using Node.JS with Express. The following line fails, and I need help fixing it. </p> <pre><code>var routines = require("myJsRoutines.js"); </code></pre> <p>When I run index.html and click <code>MenuItem</code>, I get the first alert, but not the second one. I have both files in the same directory. Thanks</p> <p>index.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="javascript:myMenuFunc('Level 1');"&gt;MenuItem&lt;/a&gt; &lt;script&gt;function myMenuFunc(level) { alert("myMenuFunc1:" + level); var routines = require("myJsRoutines.js"); alert("myMenuFunc:2" + level); routines.processClick(level); alert("myMenuFunc:3" + level); }&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>myJsRoutines.js:</p> <pre><code>exports.processClick = function processClick (param1) { console.log(param1) } </code></pre>
0
Error converting data type nvarchar to numeric - SQL Server
<p>I am trying to take an average of a column in my database. The column is <code>AMOUNT</code> and it is stored as <code>NVARCHAR(300),null</code>.</p> <p>When I try to convert it to a numeric value I get the following error: </p> <blockquote> <p>Msg 8114, Level 16, State 5, Line 1<br> Error converting datatype NVARCHAR to NUMBER</p> </blockquote> <p>Here is what I have right now. </p> <pre><code>SELECT AVG(CAST(Reimbursement AS DECIMAL(18,2)) AS Amount FROM Database WHERE ISNUMERIC(Reimbursement) = 1 AND Reimbursement IS NOT NULL </code></pre>
0
Get Azure Active Directory application users and roles
<p>I've setup an application in Azure AD Premium and made user assignment required to access the application. I've added custom app roles to the application manifest. I can assign users with a role to the application.</p> <p>How can you get a list of all users that are assigned to the application and their assigned role?</p>
0
How to upload file using angular 2?
<p>I need to upload file using angular 2,I used it at client side,And I used Web Api At server side.How can i use this combination to implement </p>
0
How to keep active bootstrap tooltip without hover or click
<p><strong>This is example which i am using for keep open tooltip without hover or click but its not working any other suggestion</strong></p> <pre><code>&lt;a href="#" title="Download Excel" class="tool_tip"&gt;Download Excel&lt;/a&gt; </code></pre> <p>my jquery for tooltip keep active</p> <pre><code>&lt;script&gt; $('.tool_tip').tooltip({trigger: 'manual'}).tooltip('show'); &lt;/script&gt; </code></pre>
0
Postgres GROUP BY on jsonb inner field
<p>I am using Postgresql 9.4 and have a table <code>test</code>, with <code>id::int</code> and <code>content::jsonb</code>, as follows:</p> <pre class="lang-sql prettyprint-override"><code> id | content ----+----------------- 1 | {"a": {"b": 1}} 2 | {"a": {"b": 1}} 3 | {"a": {"b": 2}} 4 | {"a": {"c": 1}} </code></pre> <p>How do I <code>GROUP BY</code> on an inner field in the <code>content</code> column and return each group as an array? Specifically, the results I am looking for are:</p> <pre class="lang-sql prettyprint-override"><code> content --------------------------------- [{"a": {"b": 1}},{"a": {"b": 1}}] [{"a": {"b": 2}}] (2 rows) </code></pre> <p>Trying:</p> <pre class="lang-sql prettyprint-override"><code>SELECT json_agg(content) as content FROM test GROUP BY content -&gt;&gt; '{a,b}'; </code></pre> <p>Yields:</p> <pre class="lang-sql prettyprint-override"><code> content ---------------------------------------------------------------------- [{"a": {"b": 1}}, {"a": {"b": 1}}, {"a": {"b": 2}}, {"a": {"c": 1}}] (1 row) </code></pre>
0
java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
<p>I am using hibernate-search 5.5.4.Final with hibernate-entitymanager 5.0.9 (matched with hibernate-core 5.0.9). But when i deployed the ejb maven module on glassfish 4.1. I obtained the following exception:</p> <pre><code>Grave: java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:34) at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:165) at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:160) at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:135) at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199) at org.glassfish.persistence.jpa.PersistenceUnitLoader.&lt;init&gt;(PersistenceUnitLoader.java:107) at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223) at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510) at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230) at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:925) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:434) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:360) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534) at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224) at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at com.sun.enterprise.v3.server.AppLibClassLoaderServiceImpl$URLClassFinder.findClass(AppLibClassLoaderServiceImpl.java:168) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) </code></pre> <p>I checked that this class exists on hibernate core. the pom file has the correct configuration according to the official website<a href="http://hibernate.org/search/documentation/getting-started/" rel="nofollow noreferrer"> hibernate search get started</a></p> <p>The POM configuration is the following</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.sergio.sanchez&lt;/groupId&gt; &lt;artifactId&gt;ejercicio4mb-ejb&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;ejb&lt;/packaging&gt; &lt;name&gt;ejercicio4mb-ejb&lt;/name&gt; &lt;properties&gt; &lt;endorsed.dir&gt;${project.build.directory}/endorsed&lt;/endorsed.dir&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;hibernate.version&gt;5.0.9.Final&lt;/hibernate.version&gt; &lt;hibernate.search.version&gt;5.5.4.Final&lt;/hibernate.search.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-search-orm&lt;/artifactId&gt; &lt;version&gt;${hibernate.search.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;single&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;descriptorRefs&gt; &lt;descriptorRef&gt;jar-with-dependencies&lt;/descriptorRef&gt; &lt;/descriptorRefs&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;compilerArguments&gt; &lt;endorseddirs&gt;${endorsed.dir}&lt;/endorseddirs&gt; &lt;/compilerArguments&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-ejb-plugin&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;ejbVersion&gt;3.1&lt;/ejbVersion&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;validate&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${endorsed.dir}&lt;/outputDirectory&gt; &lt;silent&gt;true&lt;/silent&gt; &lt;artifactItems&gt; &lt;artifactItem&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-endorsed-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;type&gt;jar&lt;/type&gt; &lt;/artifactItem&gt; &lt;/artifactItems&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p><a href="https://i.stack.imgur.com/DCC2y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DCC2y.png" alt="Dependencies tree"></a></p>
0
How to POST a DateTime value to a Web API 2 controller
<p>I have an example controller:</p> <pre><code>[RoutePrefix("api/Example")] public class ExampleController : ApiController { [Route("Foo")] [HttpGet] public string Foo([FromUri] string startDate) { return "This is working"; } [Route("Bar")] [HttpPost] public string Bar([FromBody] DateTime startDate) { return "This is not working"; } } </code></pre> <p>When I issue a GET request to: <code>http://localhost:53456/api/Example/Foo?startDate=2016-01-01</code> it works.</p> <p>When I POST to <code>http://localhost:53456/api/Example/Bar</code> I receive a <code>HTTP/1.1 400 Bad Request</code> error.</p> <p>This is my POST data:</p> <pre><code>{ "startDate":"2016-01-01T00:00:00.0000000-00:00" } </code></pre> <p>What am I doing wrong?</p>
0
Getting 'dict_keys' object does not support indexing despite casting to list
<p>I am using Python 3 and despite of casting to list, I cannot seem to run my program.</p> <p>This is the function calling:</p> <pre><code>path = euleriancycle(edges) </code></pre> <p>And this is where I have used the keys method:</p> <pre><code>def euleriancycle(e): currentnode = list[e.keys()[0]] path = [currentnode] </code></pre> <p>I tried to run it without type-casting to list and got this error. After rummaging about this site and similar queries, I followed the solutions suggested and type-cast to list but to no avail. I got the same error. </p> <p>This is the error track:</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-56-356b905111a9&gt; in &lt;module&gt;() 45 edges[int(edge[0])] = [int(edge[1])] 46 ---&gt; 47 path = euleriancycle(edges) 48 print(path) &lt;ipython-input-56-356b905111a9&gt; in euleriancycle(e) 1 def euleriancycle(e): ----&gt; 2 currentnode = list[e.keys()[0]] 3 path = [currentnode] 4 5 while true: TypeError: 'dict_keys' object does not support indexing </code></pre>
0
Update multiple records using stored procedure
<p>Being a novice, I had a question that is helping me troubleshoot something I'm working on.</p> <p>With the table created below, is there a way to modify the stored procedure to update multiple rows in the table</p> <pre><code>CREATE TABLE AccountTable ( RowID int IDENTITY(1, 1), AccountID varchar(2), AccountName varchar(50), SeqNum int, SeqDate datetime ) CREATE PROCEDURE [ACCOUNTTABLE_UPDATE] ( @SeqNum int, @SeqDate datetime, @Account_ID varchar(2) ) AS SET NOCOUNT ON BEGIN UPDATE AccountTable SET SeqNum = @SeqNum, SeqDate = @SeqDate WHERE AccountID = @AccountID END EXEC ACCOUNTTABLE_UPDATE SeqNumValue, SeqDateValue, AccountIDValue </code></pre> <p>Running the stored procedure manually will of course edit one row, adding more values will lead to a too many arguments error. I just wanted to see if this stored procedure can in fact update more than one row in the table or if this should be modified to in fact handle providing more than the 3 parameters.</p>
0
PostgreSQL slow JOIN with CASE statement
<p>In my database I have a table that contains ~3500 records and as a part of more complicated query I've tried to perform inner join on itself using "CASE" condition just as you can see below.</p> <pre><code>SELECT * FROM some_table AS t1 JOIN some_table AS t2 ON t1.type = t2.type AND CASE WHEN t1.type = 'ab' THEN t1.first = t2.first WHEN t1.type = 'cd' THEN t1.second = t2.second -- Column type contains only one of 2 possible varchar values END; </code></pre> <p>The problem is this query is performed for 3.2 - 4.5 seconds while next request is performed in 40 - 50 milliseconds.</p> <pre><code>SELECT * FROM some_table AS t1 JOIN some_table AS t2 ON t1.type = t2.type AND (t1.first = t2.first OR t1.second = t2.second) </code></pre> <p>Also according to the execution plan in first case database processes ~5.8 millions of records while table contains only ~3500. There are next indexes on this table: (id), (type), (type, first), (type, second). </p> <p>We are using next version: PostgreSQL 9.4.5 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120 313 (Red Hat 4.4.7-16), 64-bit</p> <p>Any ideas why PostgreSQL works so weird in this case?</p>
0
how to remove last comma from line in bash using "sed or awk"
<p>Hi I want to remove last comma from a line. For example:</p> <p>Input:</p> <pre><code>This,is,a,test </code></pre> <p>Desired Output:</p> <pre><code>This,is,a test </code></pre> <p>I am able to remove last comma if its also the last character of the string using below command: (However this is not I want)</p> <pre><code>echo "This,is,a,test," |sed 's/,$//' This,is,a,test </code></pre> <p>Same command does not work if there are more characters past last comma in line.</p> <pre><code>echo "This,is,a,test" |sed 's/,$//' This,is,a,test </code></pre> <p>I am able to achieve the results using dirty way by calling multiple commands, any alternative to achieve the same using awk or sed regex ?(This is I want)</p> <pre><code>echo "This,is,a,test" |rev |sed 's/,/ /' |rev This,is,a test </code></pre>
0
Converting time from AM/PM format to military time in Python
<p>Without using any libraries, I'm trying to solve the Hackerrank problem "<a href="https://www.hackerrank.com/challenges/time-conversion?h_r=next-challenge&amp;h_v=zen" rel="noreferrer">Time Conversion</a>", the problem statement of which is copied below.</p> <p><a href="https://i.stack.imgur.com/YRr6p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YRr6p.png" alt="enter image description here"></a></p> <p>I came up with the following:</p> <pre><code>time = raw_input().strip() meridian = time[-2:] # "AM" or "PM" time_without_meridian = time[:-2] hour = int(time[:2]) if meridian == "AM": hour = (hour+1) % 12 - 1 print ("%02d" % hour) + time_without_meridian[2:] elif meridian == "PM": hour += 12 print str(hour) + time_without_meridian[2:] </code></pre> <p>However, this fails on one test case:</p> <p><a href="https://i.stack.imgur.com/yQLb9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yQLb9.png" alt="enter image description here"></a></p> <p>Since the test cases are hidden to the user, however, I'm struggling to see where the problem is occurring. "12:00:00AM" is correctly converted to "00:00:00", and "01:00:00AM" to "01:00:00" (with the padded zero). What could be wrong with this implementation?</p>
0
is "from flask import request" identical to "import requests"?
<p>In other words, is the flask request class identical to the requests library?</p> <p>I consulted:</p> <p><a href="http://flask.pocoo.org/docs/0.11/api/" rel="noreferrer">http://flask.pocoo.org/docs/0.11/api/</a></p> <p><a href="http://docs.python-requests.org/en/master/" rel="noreferrer">http://docs.python-requests.org/en/master/</a></p> <p>but cannot tell for sure. I see code examples where people seem to use them interchangeably.</p>
0
Attempt to invoke virtual method 'android.content.Context.getResources()' on a null object reference
<p>I try to use a fragment to open a database, however, when I click the button to begin searching, the program unexpectedly terminates and it show the error like this: </p> <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.widget.Toast.&lt;init&gt;(Toast.java:102) at android.widget.Toast.makeText(Toast.java:259) at com.example.nkwpy.myapplication.MainFragment.query(MainFragment.java:176) at com.example.nkwpy.myapplication.MainFragment.access$000(MainFragment.java:46) at com.example.nkwpy.myapplication.MainFragment$queryListener.onClick(MainFragment.java:161) at android.view.View.performClick(View.java:5207) at android.view.View$PerformClick.run(View.java:21177) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5458) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) </code></pre> <p>MainFragment:</p> <pre><code>package com.example.nkwpy.myapplication; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.view.View.OnClickListener; import android.widget.Toast; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link MainFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link MainFragment#newInstance} factory method to * create an instance of this fragment. */ public class MainFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; MainActivity parent=(MainActivity) getActivity(); SQLiteDatabase test; DBManager dbHelper; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private EditText N; private EditText Z; private EditText R_A; private Button queryBtn; private OnFragmentInteractionListener mListener; public MainFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MainFragment. */ // TODO: Rename and change types and number of parameters public static MainFragment newInstance(String param1, String param2) { MainFragment fragment = new MainFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view =inflater.inflate(R.layout.fragment_main, container, false); N=(EditText)view.findViewById(R.id.neuton); Z=(EditText)view.findViewById(R.id.proton); queryBtn = (Button)view.findViewById(R.id.query); queryBtn.setOnClickListener(new queryListener()); R_A=(EditText)view.findViewById(R.id.result); dbHelper = new DBManager(getActivity()); dbHelper.openDatabase(); dbHelper.closeDatabase(); return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * &lt;p/&gt; * See the Android Training lesson &lt;a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * &gt;Communicating with Other Fragments&lt;/a&gt; for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } class queryListener implements OnClickListener{ @Override public void onClick(View v) { // query(); test.close(); } } private void query() { try { String string1 = N.getText().toString(); String string2 = Z.getText().toString(); String sql = "select * from sly4 where N=" + string1 + " and Z=" + string2; Cursor cursor =test.rawQuery(sql, null); cursor.moveToFirst(); String r = cursor.getString(cursor.getColumnIndex("value")); R_A.setText(r); } catch (Exception e) { Toast.makeText(parent, "Please check the number you entered", Toast.LENGTH_LONG).show(); } } } </code></pre> <p>class DBManager:</p> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import android.util.Log; public class DBManager { private final int BUFFER_SIZE = 400000; public static final String DB_NAME = "main.db"; public static final String PACKAGE_NAME = "com.example.nkwpy.myapplication"; public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME; private SQLiteDatabase database; private Context context; DBManager(Context context) { this.context = context; } public void openDatabase() { this.database = this.openDatabase(DB_PATH + "/" + DB_NAME); } private SQLiteDatabase openDatabase(String dbfile) { try { if (!(new File(dbfile).exists())) { InputStream is = this.context.getResources().openRawResource(R.raw.main); FileOutputStream fos = new FileOutputStream(dbfile); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = is.read(buffer)) &gt; 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null); return db; } catch (FileNotFoundException e) { Log.e("Database", "File not found"); e.printStackTrace(); } catch (IOException e) { Log.e("Database", "IO exception"); e.printStackTrace(); } return null; } public void closeDatabase() { this.database.close(); } } </code></pre> <p>By the way,I have used code about DBManager in MainAcitivity,and it succeeded.After I copy the code to the fragment like the one above,it failed.How should I do?</p>
0
Logstash output plugin for JDBC/mySQL
<p>I am collecting Twitter and Instagram data using Logstash and I want to save it to Elasticsearch, MongoDB, and MySQL. There are Logstash output plugins available for Elasticsearch and MongoDB but not for MySQL (it is a requirement to save this data to multiple databases). Any workaround for this? Thanks!</p>
0
RGB to HSL conversion
<p>I'm creating a Color Picker tool and for the HSL slider, I need to be able to convert RGB to HSL. When I searched SO for a way to do the conversion, I found this question <a href="https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion">HSL to RGB color conversion</a>.</p> <p>While it provides a function to do conversion from RGB to HSL, I see no explanation to what's really going on in the calculation. To understand it better, I've read the <a href="https://en.wikipedia.org/wiki/HSL_and_HSV" rel="noreferrer">HSL and HSV</a> on Wikipedia.</p> <p>Later, I've rewritten the function from the "HSL to RGB color conversion" using the calculations from the "HSL and HSV" page.</p> <p>I'm stuck at the calculation of hue if the R is the max value. See the calculation from the "HSL and HSV" page:</p> <p><a href="https://i.stack.imgur.com/c6FL6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/c6FL6.jpg" alt="enter image description here"></a></p> <p>This is from another <a href="https://nl.wikipedia.org/wiki/HSL_(kleurruimte)#Omzetting_van_RGB_naar_HSL" rel="noreferrer">wiki page</a> that's in Dutch:</p> <p><a href="https://i.stack.imgur.com/VJrSc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/VJrSc.jpg" alt="enter image description here"></a></p> <p>and this is from the <a href="https://stackoverflow.com/a/9493060/2202732">answers</a> to "HSL to RGB color conversion":</p> <pre><code>case r: h = (g - b) / d + (g &lt; b ? 6 : 0); break; // d = max-min = c </code></pre> <p>I've tested all three with a few RGB values and they seem to produce similar (if not exact) results. What I'm wondering is are they performing the same thing? Will get I different results for some specific RGB values? Which one should I be using?</p> <pre><code>hue = (g - b) / c; // dutch wiki hue = ((g - b) / c) % 6; // eng wiki hue = (g - b) / c + (g &lt; b ? 6 : 0); // SO answer </code></pre> <p></p> <pre><code>function rgb2hsl(r, g, b) { // see https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation // convert r,g,b [0,255] range to [0,1] r = r / 255, g = g / 255, b = b / 255; // get the min and max of r,g,b var max = Math.max(r, g, b); var min = Math.min(r, g, b); // lightness is the average of the largest and smallest color components var lum = (max + min) / 2; var hue; var sat; if (max == min) { // no saturation hue = 0; sat = 0; } else { var c = max - min; // chroma // saturation is simply the chroma scaled to fill // the interval [0, 1] for every combination of hue and lightness sat = c / (1 - Math.abs(2 * lum - 1)); switch(max) { case r: // hue = (g - b) / c; // hue = ((g - b) / c) % 6; // hue = (g - b) / c + (g &lt; b ? 6 : 0); break; case g: hue = (b - r) / c + 2; break; case b: hue = (r - g) / c + 4; break; } } hue = Math.round(hue * 60); // ° sat = Math.round(sat * 100); // % lum = Math.round(lum * 100); // % return [hue, sat, lum]; } </code></pre>
0
Intellij Java 2016 & Maven : how to embed dependencies in JAR?
<p>I'm using Intellij Java 2016.2.2 and Maven to create a very simple Java console application.</p> <p>I want to add an external library, so I add my dependency in Maven like this:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jline&lt;/groupId&gt; &lt;artifactId&gt;jline&lt;/artifactId&gt; &lt;version&gt;2.12&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>It works fine when I run it in the IDE, but not in an external console (I have the following error: <em>java.lang.NoClassDefFoundError</em>).</p> <p>I checked and for some reason, the external JAR is not added in the JAR I just generated. I also tried many things in "File -> Project Structure", but still not working...</p> <p>I just want to build my JAR with my dependencies in it, so I can simply run my application in a console using:</p> <pre><code>java -jar myproject.jar </code></pre> <p>How can I do that? Thanks for your help!</p>
0
Retrofit Returning Null Response Body
<p>I am trying to make a call to the FlickR API and am having difficulty as the response.body() is returning null.</p> <p>I am not sure if it relates to my JSON/POJO mapping, but I cannot figure out how to access the response from Retrofit when I make the call to FlickR. I know that my call is being completed successfully as I am actually able to view the JSON through the logging interceptor.</p> <p><strong>Model:</strong></p> <pre><code>public class Model { Photos photos; int code; String stat; String message; // when you text = null public class Photos { @SerializedName("page") @Expose private int page; @SerializedName("pages") @Expose private int pages; @SerializedName("perpage") @Expose private int perpage; @SerializedName("total") @Expose private String total; @SerializedName("photo") @Expose private List&lt;Photo&gt; photo = new ArrayList&lt;Photo&gt;(); /** * @return The page */ public int getPage() { return page; } /** * @param page The page */ public void setPage(int page) { this.page = page; } /** * @return The pages */ public int getPages() { return pages; } /** * @param pages The pages */ public void setPages(int pages) { this.pages = pages; } /** * @return The perpage */ public int getPerpage() { return perpage; } /** * @param perpage The perpage */ public void setPerpage(int perpage) { this.perpage = perpage; } /** * @return The total */ public String getTotal() { return total; } /** * @param total The total */ public void setTotal(String total) { this.total = total; } /** * @return The photo */ public List&lt;Photo&gt; getPhoto() { return photo; } /** * @param photo The photo */ public void setPhoto(List&lt;Photo&gt; photo) { this.photo = photo; } } public class Photo { @SerializedName("id") @Expose private String id; @SerializedName("owner") @Expose private String owner; @SerializedName("secret") @Expose private String secret; @SerializedName("server") @Expose private String server; @SerializedName("farm") @Expose private int farm; @SerializedName("title") @Expose private String title; @SerializedName("ispublic") @Expose private int ispublic; @SerializedName("isfriend") @Expose private int isfriend; @SerializedName("isfamily") @Expose private int isfamily; @SerializedName("url_m") @Expose private String urlM; @SerializedName("height_m") @Expose private String heightM; @SerializedName("width_m") @Expose private String widthM; public Photo(){ } /** * @return The id */ public String getId() { return id; } /** * @param id The id */ public void setId(String id) { this.id = id; } /** * @return The owner */ public String getOwner() { return owner; } /** * @param owner The owner */ public void setOwner(String owner) { this.owner = owner; } /** * @return The secret */ public String getSecret() { return secret; } /** * @param secret The secret */ public void setSecret(String secret) { this.secret = secret; } /** * @return The server */ public String getServer() { return server; } /** * @param server The server */ public void setServer(String server) { this.server = server; } /** * @return The farm */ public int getFarm() { return farm; } /** * @param farm The farm */ public void setFarm(int farm) { this.farm = farm; } /** * @return The title */ public String getTitle() { return title; } /** * @param title The title */ public void setTitle(String title) { this.title = title; } /** * @return The ispublic */ public int getIspublic() { return ispublic; } /** * @param ispublic The ispublic */ public void setIspublic(int ispublic) { this.ispublic = ispublic; } /** * @return The isfriend */ public int getIsfriend() { return isfriend; } /** * @param isfriend The isfriend */ public void setIsfriend(int isfriend) { this.isfriend = isfriend; } /** * @return The isfamily */ public int getIsfamily() { return isfamily; } /** * @param isfamily The isfamily */ public void setIsfamily(int isfamily) { this.isfamily = isfamily; } /** * @return The urlM */ public String getUrlM() { return urlM; } /** * @param urlM The url_m */ public void setUrlM(String urlM) { this.urlM = urlM; } /** * @return The heightM */ public String getHeightM() { return heightM; } /** * @param heightM The height_m */ public void setHeightM(String heightM) { this.heightM = heightM; } /** * @return The widthM */ public String getWidthM() { return widthM; } /** * @param widthM The width_m */ public void setWidthM(String widthM) { this.widthM = widthM; } } } </code></pre> <p><strong>JSON Response:</strong></p> <pre><code>{ photos: { page: 1, pages: 3683, perpage: 100, total: "368270", photo: [ { id: "29264707352", owner: "84316756@N02", secret: "9ed355a86e", server: "8603", farm: 9, title: "Tercer Patio de los Claustros de la Compañía/ Arequipa", ispublic: 1, isfriend: 0, isfamily: 0, url_m: "https://farm9.staticflickr.com/8603/29264707352_9ed355a86e.jpg", height_m: "500", width_m: "333" }, { id: "29339070436", owner: "146617764@N02", secret: "b52f1e9914", server: "8509", farm: 9, title: "2016-04-17 09.24.07", ispublic: 1, isfriend: 0, isfamily: 0, url_m: "https://farm9.staticflickr.com/8509/29339070436_b52f1e9914.jpg", height_m: "281", width_m: "500" }, </code></pre> <p><strong>LOGCAT</strong></p> <pre><code>09-03 15:11:33.037 1846-1846/com.troychuinard.flickr_test E/AndroidRuntime: FATAL EXCEPTION: main Process: com.troychuinard.flickr_test, PID: 1846 java.lang.NullPointerException: println needs a message at android.util.Log.println_native(Native Method) at android.util.Log.v(Log.java:118) at com.troychuinard.flickr_test.MainActivity$1$1.onResponse(MainActivity.java:72) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) 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:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 09-03 15:14:21.858 1846-1846/com.troychuinard.flickr_test I/Process: Sending signal. PID: 1846 SIG: 9 </code></pre> <p><strong>Line 72</strong></p> <pre><code> Log.v("RESPONSE_BODY", response.body().getTotal()); </code></pre> <p><strong>Activity</strong></p> <pre><code>public class MainActivity extends AppCompatActivity { private EditText mSearchTerm; private Button mRequestButton; private Button mSearchButton; private String mQuery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSearchTerm = (EditText) findViewById(R.id.ediText_search_term); mRequestButton = (Button) findViewById(R.id.request_button); mSearchButton = (Button) findViewById(R.id.search_button_flickr); mRequestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mQuery = mSearchTerm.getText().toString(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.flickr.com/services/rest/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); ApiInterface apiInterface = retrofit.create(ApiInterface.class); Call&lt;Photos&gt; call = apiInterface.getImages(mQuery); call.enqueue(new Callback&lt;Photos&gt;() { @Override public void onResponse(Call&lt;Photos&gt; call, Response&lt;Photos&gt; response) { Log.v("RESPONSE_CALLED", "ON_RESPONSE_CALLED"); String didItWork = String.valueOf(response.isSuccessful()); Log.v("SUCCESS?", didItWork); Log.v("RESPONSE_CODE", String.valueOf(response.code())); Photos photos = response.body(); Log.v("RESPONSE_BODY", "response:" + photos); String total = response.body().getTotal(); Log.v("Total", total); List&lt;Photos.Photo&gt; photoResults = response.body().getPhoto(); for (Photos.Photo photo : photoResults) { Log.v("PHOTO_URL:", photo.getTitle() ); } } @Override public void onFailure(Call&lt;Photos&gt; call, Throwable t) { } }); } }); mSearchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent toSearch = new Intent(MainActivity.this, FlickRActivity.class); startActivity(toSearch); } }); } //Synchronous vs. Asynchronous public interface ApiInterface { @GET("?method=flickr.photos.search&amp;api_key=1c448390199c03a6f2d436c40defd90e&amp;format=json&amp;nojsoncallback=1&amp;extras=url_m") Call&lt;Photos&gt; getImages(@Query("text") String query); } </code></pre> <p>}</p>
0
"jcenter.bintray.com:443 failed to respond" error in Android Studio
<p>I am trying to build a project in Android Studio, and Android's default build tool, Gradle, ALWAYS gives me an error when it attempts to build my project. The following is the result of using the "gradlew build" command:</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'MyFirstApp'. &gt; Could not resolve all dependencies for configuration ':classpath'. &gt; Could not resolve com.android.tools.build:gradle:2.1.3. Required by: :MyFirstApp:unspecified &gt; Could not resolve com.android.tools.build:gradle:2.1.3. &gt; Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/ gradle/2.1.3/gradle-2.1.3.pom'. &gt; Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle /2.1.3/gradle-2.1.3.pom'. &gt; jcenter.bintray.com:443 failed to respond </code></pre> <p>I have tried using an http proxy, vpn, turning off my firewall, deleting the cache in the .gradle foler, and even completely reinstalling Android Studio, but nothing seems to be working.</p> <p>I am new to Android development, so any information is appreciated!</p> <p>Here is the error when the proxy is implemented:</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'MyFirstApp'. &gt; Could not resolve all dependencies for configuration ':classpath'. &gt; Could not resolve com.android.tools.build:gradle:2.1.3. Required by: :MyFirstApp:unspecified &gt; Could not resolve com.android.tools.build:gradle:2.1.3. &gt; Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/ gradle/2.1.3/gradle-2.1.3.pom'. &gt; Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle /2.1.3/gradle-2.1.3.pom'. &gt; Remote host closed connection during handshake </code></pre> <p>I was able to add the HTTPS certificate to the keystore for jcenter.bintray.com, but now I am getting a JVM error whenever I start android studio: <a href="http://i.stack.imgur.com/i0274.jpg" rel="noreferrer">Android Studio JVM Error</a></p> <p>I have checked my environment variables, tried changing them, and the error persists. My java environment variables are set as follows:</p> <pre><code>User Variables: PATH: %JAVA_HOME%\bin JAVA_HOME: C:\Program Files\Java\jdk1.8.0_101 System Variables: CLASSPATH: C:\Program Files\Java\jre1.8.0_101 JAVA_HOME: C:\Program Files\Java\jdk1.8.0_101\bin </code></pre> <p>EDIT: After setting my Java home path in the gradle.properties file, I am now getting a different error when I attempt to build my project.</p> <pre><code>Downloading https://services.gradle.org/distributions/gradle-2.14.1-all.zip Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed </code></pre> <p>EDIT: I just wanted to let everyone know that I figured it out! Apparently my parents put some insanely powerful parental control software on my computer a few years ago and I forgot it was there. After uninstalling, Android Studio now works flawlessly. The software basically blocked all unknown traffic coming in and out of most of the ports. Anyway, thank you to everyone for the help. I can finally start developing!</p>
0
visualization of convolutional layer in keras model
<p>I created a model in Keras (I am a newbie) and somehow managed to train it nicely. It takes 300x300 images and try to classify them in two groups.</p> <pre><code># size of image in pixel img_rows, img_cols = 300, 300 # number of classes (here digits 1 to 10) nb_classes = 2 # number of convolutional filters to use nb_filters = 16 # size of pooling area for max pooling nb_pool = 20 # convolution kernel size nb_conv = 20 X = np.vstack([X_train, X_test]).reshape(-1, 1, img_rows, img_cols) y = np_utils.to_categorical(np.concatenate([y_train, y_test]), nb_classes) # build model model = Sequential() model.add(Convolution2D(nb_filters, nb_conv, nb_conv, border_mode='valid', input_shape=(1, img_rows, img_cols))) model.add(Activation('relu')) model.add(Convolution2D(nb_filters, nb_conv, nb_conv)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax')) # run model model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) </code></pre> <p>Now I would like to visualize the second convolutional layer and if possible also the first dense layer. "Inspiration" was taken from <a href="https://blog.keras.io/how-convolutional-neural-networks-see-the-world.html" rel="noreferrer">keras blog</a>. By using <code>model.summary()</code> I found out the name of the layers. Then I created the following frankenstein code:</p> <pre><code>from __future__ import print_function from scipy.misc import imsave import numpy as np import time #from keras.applications import vgg16 import keras from keras import backend as K # dimensions of the generated pictures for each filter. img_width = 300 img_height = 300 # the name of the layer we want to visualize # (see model definition at keras/applications/vgg16.py) layer_name = 'convolution2d_2' #layer_name = 'dense_1' # util function to convert a tensor into a valid image def deprocess_image(x): # normalize tensor: center on 0., ensure std is 0.1 x -= x.mean() x /= (x.std() + 1e-5) x *= 0.1 # clip to [0, 1] x += 0.5 x = np.clip(x, 0, 1) # convert to RGB array x *= 255 if K.image_dim_ordering() == 'th': x = x.transpose((1, 2, 0)) x = np.clip(x, 0, 255).astype('uint8') return x # load model loc_json = 'my_model_short_architecture.json' loc_h5 = 'my_model_short_weights.h5' with open(loc_json, 'r') as json_file: loaded_model_json = json_file.read() model = keras.models.model_from_json(loaded_model_json) # load weights into new model model.load_weights(loc_h5) print('Model loaded.') model.summary() # this is the placeholder for the input images input_img = model.input # get the symbolic outputs of each "key" layer (we gave them unique names). layer_dict = dict([(layer.name, layer) for layer in model.layers[1:]]) def normalize(x): # utility function to normalize a tensor by its L2 norm return x / (K.sqrt(K.mean(K.square(x))) + 1e-5) kept_filters = [] for filter_index in range(0, 200): # we only scan through the first 200 filters, # but there are actually 512 of them print('Processing filter %d' % filter_index) start_time = time.time() # we build a loss function that maximizes the activation # of the nth filter of the layer considered layer_output = layer_dict[layer_name].output if K.image_dim_ordering() == 'th': loss = K.mean(layer_output[:, filter_index, :, :]) else: loss = K.mean(layer_output[:, :, :, filter_index]) # we compute the gradient of the input picture wrt this loss grads = K.gradients(loss, input_img)[0] # normalization trick: we normalize the gradient grads = normalize(grads) # this function returns the loss and grads given the input picture iterate = K.function([input_img], [loss, grads]) # step size for gradient ascent step = 1. # we start from a gray image with some random noise if K.image_dim_ordering() == 'th': input_img_data = np.random.random((1, 3, img_width, img_height)) else: input_img_data = np.random.random((1, img_width, img_height, 3)) input_img_data = (input_img_data - 0.5) * 20 + 128 # we run gradient ascent for 20 steps for i in range(20): loss_value, grads_value = iterate([input_img_data]) input_img_data += grads_value * step print('Current loss value:', loss_value) if loss_value &lt;= 0.: # some filters get stuck to 0, we can skip them break # decode the resulting input image if loss_value &gt; 0: img = deprocess_image(input_img_data[0]) kept_filters.append((img, loss_value)) end_time = time.time() print('Filter %d processed in %ds' % (filter_index, end_time - start_time)) # we will stich the best 64 filters on a 8 x 8 grid. n = 8 # the filters that have the highest loss are assumed to be better-looking. # we will only keep the top 64 filters. kept_filters.sort(key=lambda x: x[1], reverse=True) kept_filters = kept_filters[:n * n] # build a black picture with enough space for # our 8 x 8 filters of size 128 x 128, with a 5px margin in between margin = 5 width = n * img_width + (n - 1) * margin height = n * img_height + (n - 1) * margin stitched_filters = np.zeros((width, height, 3)) # fill the picture with our saved filters for i in range(n): for j in range(n): img, loss = kept_filters[i * n + j] stitched_filters[(img_width + margin) * i: (img_width + margin) * i + img_width, (img_height + margin) * j: (img_height + margin) * j + img_height, :] = img # save the result to disk imsave('stitched_filters_%dx%d.png' % (n, n), stitched_filters) </code></pre> <p>After executing it I get:</p> <pre><code>ValueError Traceback (most recent call last) /home/user/conv_filter_visualization.py in &lt;module&gt;() 97 # we run gradient ascent for 20 steps /home/user/.local/lib/python3.4/site-packages/theano/compile/function_module.py in __call__(self, *args, **kwargs) 857 t0_fn = time.time() 858 try: --&gt; 859 outputs = self.fn() 860 except Exception: 861 if hasattr(self.fn, 'position_of_error'): ValueError: CorrMM images and kernel must have the same stack size Apply node that caused the error: CorrMM{valid, (1, 1)}(convolution2d_input_1, Subtensor{::, ::, ::int64, ::int64}.0) Toposort index: 8 Inputs types: [TensorType(float32, 4D), TensorType(float32, 4D)] Inputs shapes: [(1, 3, 300, 300), (16, 1, 20, 20)] Inputs strides: [(1080000, 360000, 1200, 4), (1600, 1600, -80, -4)] Inputs values: ['not shown', 'not shown'] Outputs clients: [[Elemwise{add,no_inplace}(CorrMM{valid, (1, 1)}.0, Reshape{4}.0), Elemwise{Composite{(i0 * (Abs(i1) + i2 + i3))}}[(0, 1)](TensorConstant{(1, 1, 1, 1) of 0.5}, Elemwise{add,no_inplace}.0, CorrMM{valid, (1, 1)}.0, Reshape{4}.0)]] Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer): File "/home/user/.local/lib/python3.4/site-packages/keras/models.py", line 787, in from_config model.add(layer) File "/home/user/.local/lib/python3.4/site-packages/keras/models.py", line 114, in add layer.create_input_layer(batch_input_shape, input_dtype) File "/home/user/.local/lib/python3.4/site-packages/keras/engine/topology.py", line 341, in create_input_layer self(x) File "/home/user/.local/lib/python3.4/site-packages/keras/engine/topology.py", line 485, in __call__ self.add_inbound_node(inbound_layers, node_indices, tensor_indices) File "/home/user/.local/lib/python3.4/site-packages/keras/engine/topology.py", line 543, in add_inbound_node Node.create_node(self, inbound_layers, node_indices, tensor_indices) File "/home/user/.local/lib/python3.4/site-packages/keras/engine/topology.py", line 148, in create_node output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0])) File "/home/user/.local/lib/python3.4/site-packages/keras/layers/convolutional.py", line 356, in call filter_shape=self.W_shape) File "/home/user/.local/lib/python3.4/site-packages/keras/backend/theano_backend.py", line 862, in conv2d filter_shape=filter_shape) </code></pre> <p>I guess I am having some bad dimensions, but don't even know where to start. Any help would be appreciated. Thanks.</p>
0
How to solve 'libcurl' not found with Rails on Windows
<p>This is giving me a headache. I'm continuing a Rails project that started on Linux and I keep getting this when I run Puma on Ruby Mine:</p> <pre><code>Error:[rake --tasks] DL is deprecated, please use Fiddle rake aborted! LoadError: Could not open library 'libcurl': The specified module could not be found. Could not open library 'libcurl.dll': The specified module could not be found. Could not open library 'libcurl.so.4': The specified module could not be found. Could not open library 'libcurl.so.4.dll': The specified module could not be found. C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/ffi-1.9.14-x86-mingw32/lib/ffi/library.rb:147:in `block in ffi_lib' [...] </code></pre> <p><strong>Now, what have I tried?</strong></p> <ul> <li>I installed Puma successfully on Windows following <a href="https://github.com/hicknhack-software/rails-disco/wiki/Installing-puma-on-windows" rel="noreferrer">this steps</a></li> <li>I downloaded <code>curl-7.50.1-win32-mingw</code> and put it on "C:/curl"</li> <li>I added C:/curl/bin and C:/curl/include to PATH</li> <li>I installed successfully curb gem with <code>gem install curb --platform=ruby -- --with-curl-lib=C:/curl/bin --with-curl-include=C:/curl/include</code></li> <li>I put the .dll files in Ruby bin folder, installed the certificate in curl/bin and even run the curl.exe just in case.</li> </ul> <p>I rebooted the machine but I keep seeing the same error.</p> <p>I do not know what to do. <strong>How to successfully install libcurl on Windows for use with Rails</strong></p>
0
How to open PDF file in vb.net?
<p>Our system is progressing so far so good then I (the programmer) hit a wall again. I tried to convert all the ordinances into .pdf files; here's what I code:</p> <pre><code>Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked e.Link.Visited = True Dim data1 As String = CType(e.Link.LinkData, String) Process.Start(data1) End Sub Private Sub FullText_Load(sender As Object, e As EventArgs) Handles MyBase.Load LinkLabel1.Links.Add(13, 13, "C:\Users\Bagiuz\Desktop\CAPSTONE\Data\PDF\City Ordinance No. 2010-215.pdf") End Sub </code></pre> <p>( The code above is my first try, it work but it will open pdf reader if I click the link label; it's okay but what I want is to open the pdf file inside the vb.net not just linking it to a pdf reader)</p> <hr> <p>The next step I did was watch a video abour=t merging pdf into vb.net and I didn't really understand it cause the user (in the video) use a "SaveFileDialog" and inserted a "Image Viewer CP Gold ActiveX Control" this thing can be found in the COM Components after right clicking the SaveFileDialog Control. So as I was saying I tried it and it work but nothing happens, I conclude that it didn't display because he use SaveFileDialog.</p> <hr> <p>The last step I did was using a "OpenFileDialog"</p> <pre><code>Dim OpenFileDialog As New OpenFileDialog OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments OpenFileDialog.Filter = "PDF Files (*.pdf) |*.pdf|All Files (*.*)|*.*" If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then Dim FileName As String = OpenFileDialog.FileName Process.Start(OpenFileToolStripMenuItem.Text) End If </code></pre> <p>it work but I can't open the file. </p> <hr> <p>Im getting confused on what should I do, Can someone please help me with this? I'll gladly appreciate it :) Someone suggested that I should check out .net pdf viewers but I don't get it Language used: Vb.Net 2013 </p>
0
How do you control the size of the output file?
<p>In spark, what is the best way to control file size of the output file. For example, in log4j, we can specify max file size, after which the file rotates. </p> <p>I am looking for similar solution for parquet file. Is there a max file size option available when writing a file?</p> <p>I have few workarounds, but none is good. If I want to limit files to 64mb, then One option is to repartition the data and write to temp location. And then merge the files together using the file size in the temp location. But getting the correct file size is difficult.</p>
0
401 Unauthorized error when accessing webapi from angular
<p>I need to capture a user's domain\username when they access my webapi app. On my dev machine I have my webapi at <code>localhost:10570</code> and my angularjs website which makes calls to the webservice at <code>localhost:34575</code>.</p> <p>If I make a call directly to my webapi app everything works fine. I can see the users domain and username and the service returns the requested data as JSON. But if I access my angularjs site and angular makes the call to webapi then I get 401 unauthorized for every call against the service.</p> <p>In my WebApi app's web.config I have:</p> <pre><code>&lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.5.2" /&gt; &lt;httpRuntime targetFramework="4.5.2" /&gt; &lt;authentication mode="Windows" /&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;httpProtocol&gt; &lt;customHeaders&gt; &lt;add name="Access-Control-Allow-Origin" value="http://localhost:34575" /&gt; &lt;add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" /&gt; &lt;add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" /&gt; &lt;add name="Access-Control-Allow-Credentials" value="true" /&gt; &lt;/customHeaders&gt; &lt;/system.webServer&gt; </code></pre> <p>I have this in IIS Express for Visual Studio 2015's applicationhost.config file:</p> <pre><code>&lt;location path="MyNamespace.WebAPI"&gt; &lt;system.webServer&gt; &lt;security&gt; &lt;authentication&gt; &lt;windowsAuthentication enabled="true" /&gt; &lt;anonymousAuthentication enabled="false" /&gt; &lt;/authentication&gt; &lt;/security&gt; &lt;/system.webServer&gt; &lt;/location&gt; </code></pre> <p>My angularjs site is part of the same solution at "MyNamespace.Client".</p> <p>Why does accessing the web service directly work fine, but accessing it via the angular app fail?</p>
0
WritableStringObjectInspector cannot be cast to BooleanObjectInspector
<p>Every time i run a hive query which has an OR condition from my java program, I get the following error,</p> <blockquote> <p>Caused by: java.lang.ClassCastException: org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableStringObjectInspector cannot be cast to org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector at org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr.initialize(GenericUDFOPOr.java:53) at org.apache.hadoop.hive.ql.udf.generic.GenericUDF.initializeAndFoldConstants(GenericUDF.java:117) at org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc.newInstance(ExprNodeGenericFuncDesc.java:232) at org.apache.hadoop.hive.ql.parse.TypeCheckProcFactory$DefaultExprProcessor.getXpathOrFuncExprNodeDesc(TypeCheckProcFactory.java:958) at org.apache.hadoop.hive.ql.parse.TypeCheckProcFactory$DefaultExprProcessor.process(TypeCheckProcFactory.java:1175) at org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher.dispatch(DefaultRuleDispatcher.java:90) at org.apache.hadoop.hive.ql.lib.DefaultGraphWalker.dispatchAndReturn(DefaultGraphWalker.java:94) at org.apache.hadoop.hive.ql.lib.DefaultGraphWalker.dispatch(DefaultGraphWalker.java:78) at org.apache.hadoop.hive.ql.lib.DefaultGraphWalker.walk(DefaultGraphWalker.java:132) at org.apache.hadoop.hive.ql.lib.DefaultGraphWalker.startWalking(DefaultGraphWalker.java:109) at org.apache.hadoop.hive.ql.parse.TypeCheckProcFactory.genExprNode(TypeCheckProcFactory.java:192) at org.apache.hadoop.hive.ql.parse.TypeCheckProcFactory.genExprNode(TypeCheckProcFactory.java:145) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genAllExprNodeDesc(SemanticAnalyzer.java:10650) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genExprNodeDesc(SemanticAnalyzer.java:10606) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genExprNodeDesc(SemanticAnalyzer.java:10577) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genFilterPlan(SemanticAnalyzer.java:2736) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genFilterPlan(SemanticAnalyzer.java:2717) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genBodyPlan(SemanticAnalyzer.java:8972) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genPlan(SemanticAnalyzer.java:9884) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genPlan(SemanticAnalyzer.java:9777) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.genOPTree(SemanticAnalyzer.java:10250) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.analyzeInternal(SemanticAnalyzer.java:10261) at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.analyzeInternal(SemanticAnalyzer.java:10141) at org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.analyze(BaseSemanticAnalyzer.java:222) at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:430) at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:305) at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1123) at org.apache.hadoop.hive.ql.Driver.compileAndRespond(Driver.java:1110) at org.apache.hive.service.cli.operation.SQLOperation.prepare(SQLOperation.java:99) ... 26 more</p> </blockquote> <p>But when i tried to run the following java program just to test the casting, it is cast successfully.</p> <pre><code>import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.WritableStringObjectInspector; public class MyClass { public static void main(String[] args) { ObjectInspector[] arguments = new ObjectInspector[2]; BooleanObjectInspector boi0 = (BooleanObjectInspector) arguments[0]; BooleanObjectInspector boi1 = (BooleanObjectInspector) arguments[1]; System.out.println(boi1); } } </code></pre> <p>I have only one jar file which is hive-exec-5.5.4 in my classpath. So i dont see any jar conflicts. Any other solutions?</p>
0
How to validate white spaces/empty spaces? [Angular 2]
<p>I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?</p>
0
nginx udp proxy pass ip
<p>Looking for some guidance on NGINX and passing the source IP address to backend servers. So far I have found config on how to do this for http/s requests but not for TCP/UDP load balancing to non http/s ports. </p> <p>I have an UDP proxy setup and working with NGINX but the source IP in my application (syslog server) is showing as that of NGINX and not the devices passing syslog messages to it.</p> <p>Below is my config - so far I am coming up empty handed on how to pass the source IP from the originating servers.</p> <pre><code> stream { server { listen 514 udp; proxy_pass syslog_standard; } upstream syslog_standard { server syslog1.ars.com:10514 max_fails=1 fail_timeout=10s; server syslog2.ars.com:10514 max_fails=1 fail_timeout=10s; } } </code></pre> <p>Any input would be appreciated!</p>
0
Unable to start Hybris Tomcat Server due to Solr Server
<p>I am not able to start the Hybris server due to the starting issue with SOLR server.</p> <p>Kindly help me in this regard so that I can start the Hybris tomcat server.</p> <h2>error log:</h2> <pre><code>INFO [localhost-startStop-1] [DefaultSolrServerService] Starting Solr server for instance: [name: default, port: 8983] Waiting up to 30 seconds to see Solr running on port 8983 [/] Started Solr server on port 8983 (pid=8405). Happy searching! . . . INFO [localhost-startStop-1] [AbstractSolrServerController] Solr server not yet started for instance: [name: default, port: 8983] [retry: 7, interval: 5000ms] INFO: (Enh120375): AspectJ attempting reweave of 'org/tanukisoftware/wrapper/WrapperSimpleApp' INFO: (Enh120375): AspectJ attempting reweave of 'org/apache/catalina/startup/Catalina' INFO: (Enh120375): AspectJ attempting reweave of 'org/tanukisoftware/wrapper/WrapperManager' INFO: (Enh120375): AspectJ attempting reweave of 'org/apache/catalina/util/LifecycleBase' INFO: (Enh120375): AspectJ attempting reweave of 'org/apache/catalina/core/StandardContext' . . INFO [localhost-startStop-1] [AbstractSolrServerController] Solr server not yet started for instance: [name: default, port: 8983] [retry: 10, interval: 5000ms] ERROR [localhost-startStop-1] [AbstractSolrServerController] Solr server is still not running after calling start command for instance: [name: default, port: 8983] ERROR [localhost-startStop-1] [DefaultSolrServerService] de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] WARN [localhost-startStop-1] [CloseAwareApplicationContext] Exception encountered during context initialization - cancelling refresh attempt org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: InvINFO | jvm 1 | main | 2016/08/16 14:14:10.627 | ERROR [localhost-startStop-1] [AbstractSolrServerController] Solr server is still not running after calling start command for instance: [name: default, port: 8983] INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | ERROR [localhost-startStop-1] [DefaultSolrServerService] de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | WARN [localhost-startStop-1] [CloseAwareApplicationContext] Exception encountered during context initialization - cancelling refresh attempt INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.core.HybrisContextFactory.refreshContext(HybrisContextFactory.java:98) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:176) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.cache.impl.RegionCacheAdapter.getController(RegionCacheAdapter.java:76) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | at de.hybris.platform.cache.impl.RegionCacheAdapter.getOrAddUnit(RegionCacheAdapter.java:206) INFO | jvm 1 | main | 2016/08/16 14:14:10.627 | atocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) . . . at de.hybris.platform.core.Registry.setCurrentTenant(Registry.java:544) at de.hybris.platform.core.Registry.activateMasterTenant(Registry.java:607) at de.hybris.platf de.hybris.platform.cache.AbstractCacheUnit.get(AbstractCacheUnit.java:180) INFO | jvm 1 | main | 2016/08/16 14:14:10.628 | WARN [localhost-startStop-1] [CloseAwareApplicationContext] Exception encountered during context initialization - cancelling refresh attempt INFO | jvm 1 | main | 2016/08/16 14:14:10.628 | org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] INFO | jvm 1 |orm.core.Registry.startup(Registry.java:422) at de.hybris.platform.spring.HybrisContextLoaderListener.startRegistry(HybrisContextLoaderListener.java:237) at de.hybris.platform.spring.HybrisContextLoaderListener.doInitWebApplicationContext(HybrisContextLoaderListener.java:135) at de.hybris.platform.spring.HybrisContextLoaderListener.initWebApplicationContext(HybrisContextLoaderListener.java:125) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at de.hybris.platform.spring.HybrisContextLoaderListener.contextInitialized(HybrisContextLoaderListener.java:80) at org.apache.catalina.core.StandardContext.null(Unknown Source) at org.apache.catalina.core.StandardContext.null(Unknown Source) at org.apache.catalina.util.LifecycleBase.null(Unknown Source) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at de.hybris.platform.solrserver.impl.AbstractSolrServerController.retryGetStatusUntilConditionIsTrue(AbstractSolrServerController.java:378) at de.hybris.platform.solrserver.impl.AbstractSolrServerController.ensureToStartSolr(AbstractSolrServerController.java:122) at de.hybris.platform.solrserver.impl.AbstractSolrServerController.start(AbstractSolrServerController.java:99) at de.hybris.platform.solrserver.impl.DefaultSolrServerService.startServer(DefaultSolrServerService.java:107) at de.hybris.platform.solrserver.impl.DefaultSolrServerService.startServers(DefaultSolrServerService.java:132) 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:497) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1702) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1641) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) ... 53 more . . . INFO | jvm 1 | main t.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:497) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1702) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1641) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) ... 53 more ERROR [localhost-startStop-1] [DeploymentMigrationUtil] Error while migrating deployments of extension core org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:317) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:189) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:175) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059) at de.hybris.platform.cache.impl.RegionCacheAdapter.getController(RegionCacheAdapter.java:76) at de.hybris.platform.cache.impl.RegionCacheAdapter.removeUnit(RegionCacheAdapter.java:259) at de.hybris.platform.cache.AbstractCacheUnit.get(AbstractCacheUnit.java:199) at de.hybris.platform.persistence.type.ComposedType_HJMPWrapper$FindByCodeExact1FinderResult.getFinderResult(ComposedType_HJMPWrapper.java:1811) at de.hybris.platform.persistence.type.ComposedType_HJMPWrapper.ejbFindByCodeExact(ComposedType_HJMPWrapper.java:1870) 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:497) at de.hybris.platform.util.Utilities.callMethod(Utilities.java:1069) at de.hybris.platform.util.Utilities.callMethod(Utilities.java:1059) at de.hybris.platform.persistence.framework.HomeInvocationHandler.invoke(HomeInvocationHandler.java:93) at com.sun.proxy.$Proxy17.findByCodeExact(Unknown Source) at de.hybris.platform.persistence.type.TypeManagerEJB.findByCodeExact(TypeManagerEJB.java:271) at de.hybris.platform.persistence.type.TypeManagerEJB.getComposedType(TypeManagerEJB.java:459) at de.hybris.platform.util.migration.DeploymentMigrationUtil.migrateSelectedDeployments(DeploymentMigrationUtil.java:458) at de.hybris.platform.core.AbstractTenant.migrateCoreTypes(AbstractTenant.java:910) at de.hybris.platform.core.Abst| 2016/08/16 14:14:11.231 | at de.hybris.platform.persistence.type.ComposedType_HJMPWrapper$FindByCodeExact1FinderResult.getFinderResult(ComposedType_HJMPWrapper.java:1811) . . . Caused by: org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start cINFO | jvm 1 | main | 2016/08/16 14:14:11.732 | INFO [localhost-startStop-1] [HybrisContextFactory] Initializing &lt;&lt;global&gt;&gt; Spring ApplicationContext took: (34.50 μs) INFO | jvm 1 | main | 2016/08/16 14:14:11.732 | de.hybris.platform.core.UninstantiableCoreApplicationContextException: Error creating Spring application context. INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | Caused by: org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | Error creating Spring application context. Shutting down hybris platform since the system cannot be used without working Spring context... INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | shutting down hybris registry.. INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | INFO [Thread-2] [HybrisContextFactory] Initializing &lt;&lt;global&gt;&gt; Spring ApplicationContext took: (44.32 μs) INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | ERROR [Thread-2] [JMXBeanLoader] Can't unregister jmxbeans on shutdown of the tenant &lt;&lt;master&gt;&gt; INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] . . . INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | at de.hybommand for instance: [name: default, port: 8983] at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:317) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:189) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:175) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) at de.hybris.platform.core.HybrisContextHolder.getAppCtxFactory(HybrisContextHolder.java:164) at de.hybris.platform.core.HybrisContextHolder.getApplicationInstance(HybrisContextHolder.java:90) at de.hybris.platform.core.AbstractTenant.createCoreApplicationContext(AbstractTenant.java:686) at de.hybris.platform.core.AbstractTenant.doStartupSafe(AbstractTenant.java:724) ... 20 more Error creating Spring application context. Shutting down hybris platform since the system cannot be used without working Spring context... shutting down hybris registry.. INFO [Thread-2] [HybrisContextFactory] Initializing &lt;&lt;global&gt;&gt; Spring ApplicationContext took: (44.32 μs) ERROR [Thread-2] [JMXBeanLoader] Can't unregister jmxbeans on shutdown of the tenant &lt;&lt;master&gt;&gt; org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:317) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:189) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:175) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059) at de.hybris.platform.core.JMXBeanLoader.getMBeanRegistry(JMXBeanLoader.java:155) at de.hybris.platform.core.JMXBeanLoader.beforeTenantShutDown(JMXBeanLoader.java:116) at de.hybris.platform.core.AbstractTenant.notifyTenantListenersBeforeShutdown(AbstractTenant.java:1236) at de.hybris.platform.core.AbstractTenant.doShutdown(AbstractTenant.java:987) at de.hybris.platform.core.AbstractTenant.doShutDown(AbstractTenant.java:948) at de.hybris.platform.core.Registry.destroy(Registry.java:309) at de.hybris.platform.util.RedeployUtilities.shutdown(RedeployUtilities.java:74) at de.hybris.platform.util.RedeployUtilities$1.run(RedeployUtilities.java:38) INFO [Thread-2] [HybrisContextFactory] Initializing &lt;&lt;global&gt;&gt; Spring ApplicationContext took: (61.35 μs) ERROR [Thread-2] [RegionCacheAdapter] Unable to clear cache. Failed on region null. Last key null null org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:317) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:189) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:175) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(ris.platform.util.RedeployUtilities.shutdown(RedeployUtilities.java:74) INFO | jvm 1 | main | 2016/08/16 14:14:11.733 | at de.hybris.platform.util.RedeployUtilities$1.run(RedeployUtilities.java:38) INFO | jvm 1 | main | 2016/08/16 14:14:12.035 | INFO [Thread-2] [HybrisContextFactory] Initializing &lt;&lt;global&gt;&gt; Spring ApplicationContext took: (61.35 μs) INFO | jvm 1 | main | 2016/08/16 14:14:12.035 | ERROR [Thread-2] [RegionCacheAdapter] Unable to clear cache. Failed on region null. Last key null null INFO | jvm 1 | main | 2016/08/16 14:14:12.035 | org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] . . INFO | jvm 1 | main |HybrisContextHolder.java:134) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059) at de.hybris.platform.cache.impl.RegionCacheAdapter.getController(RegionCacheAdapter.java:76) at de.hybris.platform.cache.impl.RegionCacheAdapter.clear(RegionCacheAdapter.java:288) at de.hybris.platform.core.AbstractTenant.shutdownCache(AbstractTenant.java:1061) at de.hybris.platform.core.AbstractTenant.doShutdown(AbstractTenant.java:1003) at de.hybris.platform.core.AbstractTenant.doShutDown(AbstractTenant.java:948) at de.hybris.platform.core.Registry.destroy(Registry.java:309) at de.hybris.platform.util.RedeployUtilities.shutdown(RedeployUtilities.java:74) at de.hybris.platform.util.RedeployUtilities$1.run(RedeployUtilities.java:38) org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:317) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:189) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:175) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059) at de.hybris.platform.cache.impl.RegionCacheAdapter.getController(RegionCacheAdapter.java:76) at de.hybris.platform.cache.impl.RegionCacheAdapter.clear(RegionCacheAdapter.java:288) at de.hybris.platform.core.AbstractTenant.shutdownCache(AbstractTenant.java:1061) at de.hybris.platform.core.AbstractTenant.doShutdown(AbstractTenant.java:1003) at de.hybris.platform.core.AbstractTenant.doShutDown(AbstractTenant.java:948) at de.hybris.platform.core.Registry.destroy(Registry.java:309) at de.hybris.platform.util.RedeployUtilities.shutdown(RedeployUtilities.java:74) at de.hybris.platform.util.RedeployUtilities$1.run(RedeployUtilities.java:38) INFO [Thread-2] [HybrisContextFactory] Initializing &lt;&lt;global&gt;&gt; Spring ApplicationContext took: (21.21 μs) ERROR [Thread-2] [RegionCacheAdapter] Unable to clear cache. Failed on region null. Last key null null org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spring.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Solr server is still not running after calling start command for instance: [name: default, port: 8983] at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:317) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:189) at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:175) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113) at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059) at de.hybris.platform.cache.impl.RegionCacheAdapter.getController(RegionCacheAdapter.java:76) at de.hybris.platform.cache.impl.RegionCacheAdapter.clear(RegionCacheAdapter.java:288) at de.hybris.platform.cache.impl.RegionCacheAdapter.destroy(Region 2016/08/16 14:14:12.036 | at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134) . . . INFO | jvm 1 | main | 2016/08/16 14:14:12.537 | STATUS | wrapper | main | 2016/08/16 14:14:14.169 | &lt;-- Wrapper Stopped </code></pre>
0
What happens if I rebase after pushing?
<p>I always hear that it's something scary and something I should never do. For example, here's how the pull dialog looks like in SourceTree:</p> <p><a href="https://i.stack.imgur.com/BjUmj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BjUmj.png" alt="enter image description here"></a></p> <p>So I'm curious, what would happen and how bad would it be if I had pushed changes, then rebased and pushed them again? And how to fix the repository if I'd break it this way?</p>
0
How to get a complex number as a user input in python?
<p>I'm trying to build a calculator that does basic operations of complex numbers. I'm using code for a calculator I found online and I want to be able to take user input as a complex number. Right now the code uses int(input) to get integers to evaluate, but I want the input to be in the form of a complex number with the format complex(x,y) where the user only needs to input x,y for each complex number. I'm new to python, so explanations are encouraged and if it's something that's just not possible, that'd be great to know. Here's the code as it is now:</p> <pre><code># define functions def add(x, y): """This function adds two numbers""" return x + y def subtract(x, y): """This function subtracts two numbers""" return x - y def multiply(x, y): """This function multiplies two numbers""" return x * y def divide(x, y): """This function divides two numbers""" return x / y # take input from the user print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice: 1, 2, 3, or 4: ") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input") </code></pre>
0
angularjs ui-select-choices dropdown aphabetical order depending on the input given
<p>I'm using <a href="https://github.com/angular-ui/ui-select" rel="nofollow noreferrer">https://github.com/angular-ui/ui-select</a> for the website I'm working on. Currently the code is as follows:</p> <pre><code> &lt;ui-select ng-model=&quot;model.states&quot;&gt; &lt;ui-select-match placeholder=&quot;State&quot;&gt; {{$item.Name}} &lt;/ui-select-match&gt; &lt;ui-select-choices repeat=&quot;item.Code as item in statesArray | filter:$select.search&quot;&gt; {{item.Name}} &lt;/ui-select-choices&gt; &lt;/ui-select&gt; </code></pre> <p>When I type anything in the input field, for example &quot;a&quot;, ui-select-choices shows all the fields containing &quot;a&quot; (by default). What I want to do is, I want to show all the states starting with &quot;a&quot; only. If nothing is typed in the input box, then show all the fields in alphabetical order. Can someone please propose a solution? I saw few other posts but no one has answered this question yet. Thanks in advance.</p> <h1>Example</h1> <p>Here's an example, suppose states array has states like California, Connecticut, Alaska, Arizona, New York.</p> <p>If nothing is typed in the input field, dropdown should show Alaska, Arizona, California, Connecticut, New York (which can be achieved using orderBy filter).</p> <p>If user types &quot;a&quot; in the input field, dropdown should show Alaska, Arizona and no other fields as Alaska and Arizona are only fields starting with &quot;a&quot;. If user types &quot;c&quot;, dropdown should show California, Connecticut. If user types &quot;ca&quot;, dropdown should show California only as it only matches the input string given.</p>
0
center text in bootstrap navbar
<p>I've seen several answers of this sort on StackOverflow, but none of them suit my purposes. What I'm trying to do is center <strong>text</strong> in the navbar. All of the other answers I've seen dealt with centering a nav <code>ul</code>. What I want to do is center a <code>.nav-text</code> in the navbar. I tried centering the text with <code>text-align: center</code> on pretty much every element in the navbar (<code>.navbar</code>, <code>.container</code>, <code>.navbar-collapse</code>) but none of them work.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div id="navbar" style="opacity: 0;"&gt; &lt;nav class="navbar navbar-default navbar-fixed-top" style="text-align: center;"&gt; &lt;div class="container" style="text-align: center;"&gt; &lt;div class="collapse navbar-collapse" style="text-align: center;"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="/"&gt;My Website&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p class='navbar-text text-center' style='text-align: center;'&gt;My Website&lt;/p&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;p class="navbar-btn"&gt;&lt;a href="checkout.php" class="btn btn-success"&gt;Continue to checkout &lt;span class='fa fa-arrow-right'&gt;&lt;/span&gt;&lt;/a&gt;&lt;/p&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; </code></pre> <p>How can this work?</p>
0
docker login not working with nexus 3 private registry
<p><a href="https://i.stack.imgur.com/nlGWN.png" rel="noreferrer">Nexus UI Config</a></p> <p>I am running Nexus Repository Manager OSS 3.0.1-01 on a linux VM On that VM, I have nginx working to reserve proxy http requests as https. My SSL key is signed by a trusted CA I created a maven repository, which works without issues, whenever I have a client machine publish to it.</p> <p>Also on this client machine, when I use my docker client, and do a docker login. I am receiving all kinds of errors.</p> <p>I am following these instructions <a href="https://books.sonatype.com/nexus-book/3.0/reference/docker.html#_accessing_repositories" rel="noreferrer">https://books.sonatype.com/nexus-book/3.0/reference/docker.html#_accessing_repositories</a> Specifically Section 9.2 and honestly, I've spent the last 2 days getting nowhere. </p> <p>I've read over everything that's mentioned here: <a href="https://stackoverflow.com/questions/33021350/trouble-connecting-to-docker-registry-stored-on-nexus-3-preview-on-azure-vm">Trouble connecting to Docker registry stored on Nexus 3 Preview on Azure VM</a> But that setup the user explains confuses me.</p> <p>For the setup we are trying to achieve insecure settings by adding <code>--insecure-registry</code> to <code>/etc/default/docker</code> file, is simply not an option.</p> <p>I've tried to follow multiple tutorials just to understand the inner workings of the docker registry but I haven't been able to piece it together. I've looked at following this to a certain extent:<a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-a-private-docker-registry-on-ubuntu-14-04" rel="noreferrer">https://www.digitalocean.com/community/tutorials/how-to-set-up-a-private-docker-registry-on-ubuntu-14-04</a></p> <p>I have used additional responses in stackoverflow to help me troubleshoot <a href="https://stackoverflow.com/questions/31599634/malformed-http-response-with-docker-private-registry-v2-behind-an-nginx-proxy">malformed HTTP response with docker private registry (v2) behind an nginx proxy</a></p> <p>But honestly I can't say I've found anything that's made understanding this straight forward. NGINX isn't reporting any error logs in <code>/var/log/nginx/errors.log</code>, the access logs look like basic 'GETS', each time I attempt a docker login. The docker logs in <code>/var/log/upstart/docker.log</code> report the same errors that I'm illustrating below with the 404 errors. Also followed this issue on github to see if that was any help github com/docker/docker/issues/8410 . Any assistance to get me to able to perform a successful docker login to this private nexus 3 repo would be amazing.</p> <p>Now maybe I'm a bit confused with everything I've been reading to get my docker client to work successfully with this nexus repo, but is it required that I setup a docker(group) repo and that is the source of my issue? Or is it okay for me to just have a docker(hosted) repo. Because as of right now I only have a docker(hosted) repo. The Nexus documentation didn't give me the impression that a group repo was also required to get things to work.</p> <p>Last but not least, I hope my question is specific enough, and I hope that you guys see I've made some effort here. I really did try!</p> <p>When I login, I am using the local admin user, with the default admin password. First let me present the issues:</p> <p>If I try without a port, i get the following --</p> <pre><code>root:~# docker login box.company.net Error response from daemon: Login: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;404 - Nexus Repository Manager&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/&gt; </code></pre> <p>With the HTTP port of 4444, i get the following</p> <pre><code>root:~# docker login box.company.net:4444 Error response from daemon: Get https://box.company.net:4444/v1/users/: `http: server gave HTTP response to HTTPS client` </code></pre> <p>If I add HTTPS in the Nexus UI to 4445, then I run</p> <pre><code>root:~# docker login box.company.net:4445 Error response from daemon: Get https://box.company.net:4445/v1/users/: dial tcp x.x.x.x:4445: getsockopt: connection refused </code></pre> <p>Here is my environment information:</p> <pre><code>#cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=14.04 DISTRIB_CODENAME=trusty DISTRIB_DESCRIPTION="Ubuntu 14.04.5 LTS" # uname -r 3.19.0-65-generic # nginx -v nginx version: nginx/1.4.6 (Ubuntu) ~# docker version Client: Version: 1.12.1 API version: 1.24 Go version: go1.6.3 Git commit: 23cf638 Built: Thu Aug 18 05:22:43 2016 OS/Arch: linux/amd64 Server: Version: 1.12.1 API version: 1.24 Go version: go1.6.3 Git commit: 23cf638 Built: Thu Aug 18 05:22:43 2016 OS/Arch: linux/amd64 cat /etc/nginx/conf.d/site.conf server { proxy_send_timeout 120; proxy_read_timeout 300; proxy_buffering off; tcp_nodelay on; server_tokens off; client_max_body_size 1G; listen 80; server_name box.company.net; location / { rewrite ^(.*) https://box.company.net$1 permanent; } } server { listen 443; server_name box.company.net; keepalive_timeout 60; ssl on; ssl_certificate /etc/nginx/conf.d/net.crt; ssl_certificate_key /etc/nginx/conf.d/net.key; ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH; ssl_session_cache shared:TLSSSL:16m; ssl_session_timeout 10m; ssl_prefer_server_ciphers on; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto "https"; proxy_pass http://x.x.x.x:8081; proxy_read_timeout 90; } } </code></pre> <p>here are some basic curl results for more info, if this will help at all.</p> <pre><code> root:~# curl -v https://box.company.net * Rebuilt URL to: https://box.company.net * Hostname was NOT found in DNS cache * Trying x.x.x.x... * Connected to box.company.net (x.x.x.x) port 443 (#0) * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * SSLv3, TLS handshake, Client hello (1): * SSLv3, TLS handshake, Server hello (2): * SSLv3, TLS handshake, CERT (11): * SSLv3, TLS handshake, Server key exchange (12): * SSLv3, TLS handshake, Server finished (14): * SSLv3, TLS handshake, Client key exchange (16): * SSLv3, TLS change cipher, Client hello (1): * SSLv3, TLS handshake, Finished (20): * SSLv3, TLS change cipher, Client hello (1): * SSLv3, TLS handshake, Finished (20): * SSL connection using ECDHE-RSA-AES256-GCM-SHA384 * Server certificate: * subject: OU=Domain Control Validated; CN=*.company.net * start date: 2016-04-01 14:01:38 GMT * expire date: 2018-04-14 15:15:04 GMT * subjectAltName: box.company.net matched * issuer: C=US; ST=Arizona; L=Scottsdale; O=GoDaddy.com, Inc.; OU=http://certs.godaddy.com/repository/; CN=Go Daddy Secure Certificate Authority - G2 * SSL certificate verify ok. &gt; GET / HTTP/1.1 &gt; User-Agent: curl/7.35.0 &gt; Host: box.company.net &gt; Accept: */* &gt; &lt; HTTP/1.1 200 OK * Server nginx/1.4.6 (Ubuntu) is not blacklisted &lt; Server: nginx/1.4.6 (Ubuntu) &lt; Date: Thu, 25 Aug 2016 13:39:14 GMT &lt; Content-Type: text/html &lt; Content-Length: 5077 &lt; Connection: keep-alive &lt; X-Frame-Options: SAMEORIGIN &lt; X-Content-Type-Options: nosniff &lt; Last-Modified: Thu, 25 Aug 2016 13:39:14 GMT &lt; Pragma: no-cache &lt; Cache-Control: post-check=0, pre-check=0 &lt; Expires: 0 </code></pre> <p>Any help to get docker login private.registry.net would be highly helpful thanks.</p>
0
JavaFX 8 - Tabpanes and tabs with separate FXML and controllers for each tab
<p>I hope to get some answers regarding having fx:include statements for each tab in a tabpane. I have managed with ease to get content to show up BUT referencing methods of the associated controller class simply gives me a nullpointerreference exception no matter how I structure it. The controllers of the included FXML layouts do not have neither constructor not initialize() methods, are they needed? I tried some different things but always got the same exception.</p> <p>What I simply did was add a change listener to the tabpane and when a tab was pressed I wanted to populate some textfields with some values gotten from a globally accessible arraylist. Note: the arraylist is not the issue, performing this operation using the main controller works fine. </p> <p>I'm going to add a code example shortly but cannot right now. Please let me know if you need more info, otherwise I'll post the code later today. </p> <p>*Edit, here is my code example, taken from another thread here on StackOverflow. <a href="https://stackoverflow.com/questions/19889882/javafx-tabpane-one-controller-for-each-tab">JavaFX TabPane - One controller for each tab</a></p> <p>TestApp.java:</p> <pre><code>public class TestApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Scene scene = new Scene(new StackPane()); FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/MainTestWindow.fxml")); scene.setRoot(loader.load()); MainTestController controller = loader.getController(); controller.init(); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } </code></pre> <p>Main controller, where I want to reference the sub controllers.</p> <pre><code>public class MainTestController { @FXML private TabPane tabPane; // Inject tab content. @FXML private Tab fooTabPage; // Inject controller @FXML private FooTabController fooTabPageController; // Inject tab content. @FXML private Tab barTabPage; // Inject controller @FXML private BarTabController barTabPageController; public void init() { tabPane.getSelectionModel().selectedItemProperty().addListener((ObservableValue&lt;? extends Tab&gt; observable, Tab oldValue, Tab newValue) -&gt; { if (newValue == barTabPage) { System.out.println("Bar Tab page"); barTabPageController.handleButton(); } else if (newValue == fooTabPage) { System.out.println("Foo Tab page"); fooTabPageController.handleButton(); } }); } } </code></pre> <p>Main view's .fxml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.control.TabPane?&gt; &lt;?import javafx.scene.control.Tab?&gt; &lt;TabPane fx:id="tabPane" fx:controller="controller.MainTestController" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://www.w3.org/2001/XInclude"&gt; &lt;tabs&gt; &lt;Tab fx:id="fooTabPage" text="FooTab"&gt; &lt;fx:include source="fooTabPage.fxml"/&gt; &lt;/Tab&gt; &lt;Tab fx:id="barTabPage" text="BarTab"&gt; &lt;fx:include source="barTabPage.fxml"/&gt; &lt;/Tab&gt; &lt;/tabs&gt; &lt;/TabPane&gt; </code></pre> <p>FooTab:</p> <pre><code>public class FooTabController { @FXML private Label lblText; public void handleButton() { lblText.setText("Byebye!"); } } </code></pre> <p>FooTab's .fxml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.layout.VBox?&gt; &lt;?import javafx.scene.control.Label?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;VBox xmlns:fx="http://www.w3.org/2001/XInclude" fx:controller="controller.FooTabController"&gt; &lt;Label fx:id="lblText" text="Helllo"/&gt; &lt;Button fx:id="btnFooTab" onAction="#handleButton" text="Change text"/&gt; &lt;/VBox&gt; </code></pre> <p>BarTab:</p> <pre><code>public class BarTabController { @FXML private Label lblText; public void handleButton() { lblText.setText("Byebye!"); } } </code></pre> <p>BarTab's .fxml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.layout.VBox?&gt; &lt;?import javafx.scene.control.Label?&gt; &lt;?import javafx.scene.control.Button?&gt; &lt;VBox xmlns:fx="http://www.w3.org/2001/XInclude" fx:controller="controller.BarTabController"&gt; &lt;Label fx:id="lblText" text="Helllo" /&gt; &lt;Button fx:id="btnBarTab" onAction="#handleButton" text="Change text"/&gt; &lt;/VBox&gt; </code></pre> <p>The above onAction for both FooTab and BarTab works with their respective buttons. When this method (handleButton) is references from the Main controller, that's when I get an exception.</p>
0
Search bar like google in HTML and CSS
<p>Iam learning <code>HTML</code>, <code>CSS</code> and i have problem with making search bar like google. Can you give me any advice, what am I doing wrong, especialy with size? Thanks :)</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-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en" xmlns="http://www.w3.org/1999/html" xmlns:th="http://www.thymeleaf.org"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;/link&gt; &lt;!-- Optional theme --&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"&gt; &lt;/link&gt; &lt;!-- Latest compiled and minified JavaScript --&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;link rel="shortcut icon" type="image/x-icon" href="https://image.freepik.com/photos-libre/courbe-de-vapeur-de-la-fumee-d&amp;-39;onde_19-123974.jpg" /&gt; &lt;style&gt; .container { width: 1000px; margin-top: 100px; text-align: center; } h2 { font-family: "Trebuchet MS", Helvetica, sans-serif; size: 150px; fill: #294F6D; } div { width: 500px; height: 50px; } h1 { text-align: center; fill: 02111 D; } .search input[type="search"] { width: 400px; height: 50px; } &lt;/style&gt; &lt;body&gt; &lt;div class="container" &lt;form action="/worldoffragrance"&gt; &lt;input name="search" /&gt; &lt;input type="submit" value="GO" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Thanks for your any suggestions :)</p>
0
Validate a base64 decoded image in laravel
<p>Im trying to get a image from a PUT request for update a user picture(using postman), and make it pass through a validation in Laravel 5.2, for making the call in postman use the following url: </p> <p><a href="http://localhost:8000/api/v1/users?_method=PUT" rel="noreferrer">http://localhost:8000/api/v1/users?_method=PUT</a></p> <p>and send the image string in the body, using a json like this: </p> <pre><code>{ "picture" : "data:image/png;base64,this-is-the-base64-encode-string" } </code></pre> <p>In the controller try a lot of differents ways for decode the image and try to pass the validation:</p> <ol> <li><p>First I tried this: </p> <pre><code>$data = request-&gt;input('picture'); $data = str_replace('data:image/png;base64,', '', $data); $data = str_replace(' ', '+', $data); $image = base64_decode($data); $file = app_path() . uniqid() . '.png'; $success = file_put_contents($file, $image); </code></pre></li> <li><p>Then I tried this:</p> <pre><code>list($type, $data) = explode(';', $data); list(, $data) = explode(',', $data); $data = base64_decode($data); $typeFile = explode(':', $type); $extension = explode('/', $typeFile[1]); $ext = $extension[1]; Storage::put(public_path() . '/prueba.' . $ext, $data); $contents = Storage::get(base_path() . '/public/prueba.png'); </code></pre></li> <li><p>Try to use the intervention image library (<a href="http://image.intervention.io/" rel="noreferrer">http://image.intervention.io/</a>) and don't pass: </p> <pre><code>$image = Image::make($data); $image-&gt;save(app_path() . 'test2.png'); $image = Image::make(app_path() . 'test1.png'); </code></pre></li> </ol> <p>This is the validation in the controller:</p> <pre><code> $data = [ 'picture' =&gt; $image, 'first_name' =&gt; $request-&gt;input('first_name'), 'last_name' =&gt; $request-&gt;input('last_name') ]; $validator = Validator::make($data, User::rulesForUpdate()); if ($validator-&gt;fails()) { return $this-&gt;respondFailedParametersValidation('Parameters failed validation for a user picture'); } </code></pre> <p>this is the validation in the User-model: </p> <pre><code>public static function rulesForUpdate() { return [ 'first_name' =&gt; 'max:255', 'last_name' =&gt; 'max:255', 'picture' =&gt; 'image|max:5000|mimes:jpeg,png' ]; } </code></pre>
0
Code or command to use embedded resource in Visual Studio
<p>Can somebody provide me a starting point or code to access an embedded resource using C#?</p> <p>I have successfully embedded a couple of batch files, scripts and CAD drawings which I would like to run the batch and copy the scripts and CAD files to a location specified in the batch file. </p> <p>I'm struggling to find how to specify what the item is and set the path within the EXE. The below code is what I thought would work, but it failed and the others I found online all related to XML files.</p> <pre><code>System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "\\Batchfile.bat"; p.Start(); </code></pre> <p>I honestly don't even know if I'm looking at the correct way to do this as this is my first time using either C# or Visual Studio.</p>
0
C# - Get value from a specific tag in XML document
<p>I have an xml document which looks like:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;cbn:PaidOrderNotification xmlns:cbn="http://xml.test.com/3.12.0.0/test.xsd"&gt; &lt;cbn:NotificationDate&gt;2016-08-01T07:28:46.679414Z&lt;/cbn:NotificationDate&gt; &lt;cbn:Purchase cbt:Id="95368158" xmlns:cbt="http://xml.test.com/3.12.0.0/testTypes.xsd"&gt; &lt;cbt:Status&gt;Test Order&lt;/cbt:Status&gt; &lt;cbt:Items&gt; &lt;cbt:Item cbt:RunningNo="1"&gt; &lt;cbt:ProductId&gt;178732&lt;/cbt:ProductId&gt; &lt;cbt:Payment cbt:SubscriptionId="S18767146"&gt; &lt;cbt:CancelUrl&gt;https://store.test.com/&lt;/cbt:CancelUrl&gt; &lt;cbt:ChangeUrl&gt;https://test.com/&lt;/cbt:ChangeUrl&gt; &lt;/cbt:Payment&gt; &lt;/cbt:Item&gt; &lt;/cbt:Items&gt; &lt;cbt:ExtraParameters /&gt; &lt;/cbn:Purchase&gt; &lt;/cbn:PaidOrderNotification&gt; </code></pre> <p>Using C#, I want to get the value inside <code>&lt;cbt:CancelUrl&gt;</code> tag. How can I do that?</p>
0
couldn't find file 'bootstrap' with type 'text/css'
<p>I got a problem when adding bootstrap into my rail project. The error message is given as:</p> <blockquote> <p>File to import not found or unreadable: bootstrap-sprockets.</p> </blockquote> <p><a href="https://i.stack.imgur.com/eu6s9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eu6s9.png" alt="Output"></a></p> <p>I have tried the following two solutions but none of them works for me.</p> <p><em>Solution 1</em>: <a href="https://stackoverflow.com/questions/25860638/couldnt-find-file-twitter-bootstrap-ror">Couldn&#39;t find file &#39;twitter/bootstrap&#39; (ROR)</a></p> <p><em>Solution 2</em>: <a href="https://stackoverflow.com/questions/36359801/sprocketsfilenotfound-couldnt-find-file-bootstrap-with-type-text-css">Sprockets::FileNotFound couldn&#39;t find file &#39;bootstrap&#39; with type &#39;text/css&#39;</a></p>
0
pandas read_csv and keep only certain rows (python)
<p>I am aware of the skiprows that allows you to pass a list with the indices of the rows to skip. However, I have the index of the rows I want to keep.</p> <p>Say that my cvs file looks like this for millions of rows:</p> <pre><code> A B 0 1 2 1 3 4 2 5 6 3 7 8 4 9 0 </code></pre> <p>The list of indices i would like to load are only 2,3, so</p> <pre><code>index_list = [2,3] </code></pre> <p>The input for the skiprows function would be [0,1,4]. However, I only have available [2,3].</p> <p>I am trying something like:</p> <pre><code>pd.read_csv(path, skiprows = ~index_list) </code></pre> <p>but no luck.. any suggestions?</p> <p>thank and I appreciate all the help,</p>
0
How can I compile my Typescript into a single JS file with no module loading system?
<p>I have a small Typescript project of about 10 <code>ts</code> files. I want to compile all my files into <code>es5</code> and into a single <code>es5</code> file called <code>all.js</code>.</p> <p>Currently, with my <code>tsconfig.json</code> set up as </p> <pre><code>{ "compilerOptions": { "module": "system", "target": "es5", "outFile": "./all.js" } </code></pre> <p>everything is getting compiled, but each file is being wrapped by </p> <pre><code>System.register("SomeTSFile", [], function(exports_4, context_4) { ... } </code></pre> <p>SystemJS looks cool but I am not in the mood to learn it now and I don't believe it is necessary. If I could get all my JS into one file, that will be perfectly sufficient for my needs. </p> <p>If I remove <code>"module": "system",</code>from my compiler options, my <code>all.js</code> file comes out completely blank. Apparently, this is because for some reason, <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html" rel="noreferrer">you cannot use <code>"modules": none</code> when outputting to one file</a>. (I don't get why)</p> <p><strong>How can I compile all the TS into one JS file without having to involve SystemJS or any other complications?</strong></p>
0
Passing parameters to a trait
<p>I want to model the game of chess. For that, I want to make an abstract class, <code>Piece</code> which takes a player and a position as arguments. From that, I want to extend to other classes such as <code>Pawn</code>:</p> <pre><code>trait Piece(player: Int, pos: Pos) = { def spaces(destination: Pos): List[Pos] } case class Pawn extends Piece = { //some other code } </code></pre> <p>However, I think I'm not allowed to pass parameters to a trait, like this <code>trait Piece(player: Int, pos: Pos)</code>.</p> <p>So how can I have an abstract class <code>Piece</code> that has fields?</p>
0
How to enforce TLS1.2 to Rest client using Rest Template
<p>I am consuming json webservice using Spring3.0 restTemplate by calling post method. </p> <pre><code> MultiValueMap&lt;String, String&gt; headers = new LinkedMultiValueMap&lt;String, String&gt;(); headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE); HttpEntity&lt;Object&gt; entity = new HttpEntity&lt;Object&gt;(requestAsString, headers); postForObject = restTemplate.postForObject(url, entity, responseClass ); </code></pre> <p>Our application is deployed in WAS server and trying to connect producer by creating socket connection with TLS1.0. However, now producer only supports TLS1.1 and TLS1.2.</p> <p>How to enforce restTempate to use TLS1.1 or TLS 1.2.</p> <p>Normally for apache httpclient code , create custom ProtocolSocketFactory and override createSocket method. However , in case of RestTemplate , how to achieve same.</p>
0
Git - what does CONFLICT (rename/delete) mean?
<p>I did not find much success in understanding what this means in other SO questions.</p> <p>this is for a ruby on rails project. it's probably really straightforward if you know what to do. I tried merging two branches and this was (part) of the result.</p> <pre><code>CONFLICT (rename/delete): db/migrate/20160705073411_create_building_employees.rb deleted in HEAD and renamed in user-authentication. Version user-authentication of db/migrate/20160705073411_create_building_employees.rb left in tree. Removing app/models/buildings_user.rb Automatic merge failed; fix conflicts and then commit the result. </code></pre> <ul> <li>There were a tonne of files which were marked as "modified"</li> <li>there was one 'unmerged' path. Namely:</li> </ul> <blockquote> <p>added by them: db/migrate/20160705073411_create_building_employees.rb</p> </blockquote> <p>when I opened up the file i saw nothing to really resolve. there were no asterix running across the page.</p> <ol> <li>What does the above mean? </li> <li>How do I resolve the issue?</li> </ol> <p>Any advice would be much appreciated.</p>
0
Grey square as notification icon using Firebase notifications
<p>I am attempting to integrate Firebase Cloud Messaging into my android app. But when the app is in the background or closed, Firebase notification is displayed with grey square icon instead of my application's launcher icon. </p> <p>How could I make the notification icon to be my application logo, without implementing Firebase server API and sending data messages? </p>
0
javascript get html timezone dropdown
<p>I want to make a html timezone dropdown which will give me result like:</p> <pre><code>&lt;select name="timezone"&gt; &lt;option value="Europe/London"&gt;(GMT) London&lt;/option&gt; .... .... &lt;/select&gt; </code></pre> <p>Is there any javascript library which will give me this result ?? Need help</p>
0
Get principal in Spring Boot resource server from JWT token
<p>I have a separate auth server and a resource server - both Spring Boot applications. I am using OAuth2 with JWT tokens for authentication and authorisation. </p> <p>I can get a token by accessing the auth server:</p> <pre><code>curl -X POST --user 'client:secret' -d 'grant_type=password&amp;username=john&amp;password=123' http://localhost:9000/auth-server/oauth/token </code></pre> <p>and use it when getting a resource from the resource server (running on different server) by attaching the token to the request header.</p> <p>What is unclear to me though, is to determine which user is logged in in the resource server.</p> <p>In the auth server, I can do something like this:</p> <pre><code>@RequestMapping("/user") public Principal user(Principal user) { return user; } </code></pre> <p>and this endpoint will get me the current user based on the token used. If I try to do the same thing in the resource server though, I only get empty response.</p> <p>I need to get the id of the authenticated user somehow in the resource server to decide whether I should return some data to him (I have some resources which can be accessed only by their owner). </p> <p>How could I do that? I thought that by using JWT, I don't need to share the same token store.</p> <p>I can provide code samples if my question is not clear.. I am just looking for a confirmation that my assumption is correct and this behaviour can be achieved - this is my first time experimenting with spring security.</p> <p>The resource server is linked to the auth server in the application.properties:</p> <pre><code>security.oauth2.resource.userInfoUri: http://localhost:9000/auth-server/user </code></pre>
0
How can I hide skipped tasks output in Ansible
<p>I have Ansible role, for example</p> <pre><code>--- - name: Deploy app1 include: deploy-app1.yml when: 'deploy_project == "{{app1}}"' - name: Deploy app2 include: deploy-app2.yml when: 'deploy_project == "{{app2}}"' </code></pre> <p>But I deploy only one app in one role call. When I deploy several apps, I call role several times. But every time there is a lot of <code>skipped tasks output</code> (from tasks which do not pass condition), which I do not want to see. How can I avoid it?</p>
0
Android WebView, err net::Name_Not_Resolved
<p>I have tried searching through the docs and other forums but no success.</p> <p>I have an android application that is simply a webView that opens up a website as soon as you open the app. However, when connecting to my website I receive an error, <strong>net::ERR_NAME_NOT_RESOLVED.</strong> Changed the loadUrl with a popular website like Google.com and it worked just fine.</p> <p>My website works fine from Google Chrome, on dekstop, etc.. just not in WebView.. Can anyone help explain why? </p> <p><strong>On Another note</strong>, I am also trying to find a way to manually enter the dns settings, hoping this would resolve the matter. Any tips or pointing me down the right path is very much appreciated.</p> <p>Thanks.</p>
0
Git hooks : applying `git config core.hooksPath`
<p>I have a git repository with a pre-commit hook set up :</p> <pre><code>my-repo |- .git |- hooks |- pre-commit # I made this file executable </code></pre> <p>Until there, everything works. The hook is running when I commit.</p> <p>=================================</p> <p>I now run <code>git config core.hooksPath ./git-config/hooks</code> in <code>my-repo</code>. </p> <p>The folder structure is this one : </p> <pre><code>my-repo |- .git |- hooks |- git-config |- hooks |- pre-commit # I made this file executable as well </code></pre> <p>What happens is :</p> <ul> <li>the new pre-commit script doesn't run on commit</li> <li>the old pre-commit script still runs on commit if I leave it in <code>my-repo/.git/hooks</code></li> <li>running <code>git config --get core.hooksPath</code> in <code>my-repo</code> outputs <code>./git-config/hooks</code></li> </ul> <p><strong>How can I make the new pre-commit hook run on commit ?</strong></p> <p>Here's the link to the docs I apparently don't understand well :<br> <a href="https://git-scm.com/docs/git-config" rel="noreferrer">https://git-scm.com/docs/git-config</a><br> <a href="https://git-scm.com/docs/githooks" rel="noreferrer">https://git-scm.com/docs/githooks</a> </p>
0
How to use X Windows with Emacs on Windows 10 Bash?
<p>I am using the Bash on Ubuntu on Windows program to use Emacs for C++. Right now, I can code everything using the keyboard shortcuts, however, I want to select text with my mouse or set the mark with my mouse instead of always having to use my keyboard. </p> <p>To get the X Windows System, I already did <code>sudo apt-get install xserver -xorg</code> but emacs still runs in a terminal editor. </p> <p>I don't know what other commands to use or how to get X Windows to start running.</p>
0
How to download multiple files in Google Cloud Storage
<p>Scenario: there are multiple folders and many files stored in storage bucket that is accessible by project team members. Instead of downloading individual files one at a time (which is very slow and time consuming), is there a way to download entire folders? Or at least multiple files at once? Is this possible without having to use one of the command consoles? Some of the team members are not tech savvy and need to access these files as simple as possible. Thank you for any help!</p>
0
What are the best practice for domain names (dev, staging, production)?
<p>With the rise of containers, Kuberenetes, 12 Factor etc, it has become easier to replicate an identical environment across dev, staging and production. However, what there appears to be no common standard to domain name conventions.</p> <p>As far as I can see it, there are two ways of doing it:</p> <ul> <li>Use subdomains: <ul> <li><code>*.dev.foobar.tld</code></li> <li><code>*.staging.foobar.tld</code></li> <li><code>*.foobar.tld</code></li> </ul></li> <li>Use separate domains: <ul> <li><code>*.foobar-dev.tld</code></li> <li><code>*.foobar-staging.tld</code></li> <li><code>*.foobar.tld</code></li> </ul></li> </ul> <p>I can see up and downs with both approaches, but I'm curious what the common practise is.</p> <p>As a side-note, Cloudflare will not issue you certificates for sub-sub domains (e.g. <code>*.stage.foobar.tld</code>).</p>
0
Docker MySQL: create new user
<p>In the <a href="https://hub.docker.com/_/mysql/" rel="nofollow">mysql docker hub page</a> there's a reference on how to create users with:</p> <pre><code>MYSQL_USER, MYSQL_PASSWORD </code></pre> <p>But how can you specify those parameters on the docker-compose.yml file?</p> <p>So far I have:</p> <pre><code>mysql: image: mysql:5.7 ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: R00t+ </code></pre> <p>Another question; how can I connect to the mysql host from outside the container? Inside the container I can connect using:</p> <pre><code>$user = 'root'; $pass = 'R00t+'; $server = 'mysql'; $dbh = new PDO( "mysql:host=$server", $user, $pass ); </code></pre>
0
didReceiveRemoteNotification not called, iOS 10
<p>In iOS 9.3, the <code>didReceiveRemoteNotification</code> method gets called on both of the following occasions. </p> <p>1) When the push notification is received 2) When the user launches the app by tapping on the notification.</p> <p>But on iOS 10, I notice that the <code>didReceiveRemoteNotification</code> method does <strong>NOT</strong> fire when the user launches the app by tapping on the notification. It's called only when the notification is received. Hence, I cannot do any further action after the app is launched from notification.</p> <p>What should be the fix for this? Any idea?</p>
0
Calling Oracle stored procedure using Entity Framework with output parameter?
<p>I have a simple Oracle stored procedure that gets three parameters passed in, and has one output parameter:</p> <pre><code>CREATE OR REPLACE PROCEDURE RA.RA_REGISTERASSET ( INPROJECTNAME IN VARCHAR2 ,INCOUNTRYCODE IN VARCHAR2 ,INLOCATION IN VARCHAR2 ,OUTASSETREGISTERED OUT VARCHAR2 ) AS BEGIN SELECT INPROJECTNAME || ', ' || INLOCATION || ', ' || INCOUNTRYCODE INTO OUTASSETREGISTERED FROM DUAL; END RA_REGISTERASSET; </code></pre> <p>I am trying to use Entity Framework 6.1 to get back the <code>OutAssetRegistered</code> value, however, I get a null after calling <code>SqlQuery</code> with no exception:</p> <pre><code>public class CmdRegisterAssetDto { public string inProjectName { get; set; } public string inCountryCode { get; set; } public string inLocation { get; set; } public string OutAssetRegistered { get; set; } } </code></pre> <p>//------------------------------------------------------------</p> <pre><code>string projectName = "EXCO"; string location = "ANYWHERE"; string countryCode = "XX"; using (var ctx = new RAContext()) { var projectNameParam = new OracleParameter("inProjectName", OracleDbType.Varchar2, projectName, ParameterDirection.Input); var countryCodeParam = new OracleParameter("inCountryCode", OracleDbType.Varchar2, countryCode, ParameterDirection.Input); var locationParam = new OracleParameter("inLocation", OracleDbType.Varchar2, location, ParameterDirection.Input); var assetRegisteredParam = new OracleParameter("OutAssetRegistered", OracleDbType.Varchar2, ParameterDirection.Output); var sql = "BEGIN RA.RA_RegisterAsset(:inProjectName, :inCountryCode, :inLocation, :OutAssetRegistered); END;"; var query = ctx.Database.SqlQuery&lt;CmdRegisterAssetDto&gt;(sql, projectNameParam, countryCodeParam, locationParam, assetRegisteredParam ); assetRegistered = (string)assetRegisteredParam.Value; } </code></pre> <p>I have been battling to get this to work to no avail, have checked different blogs, all the other crud operations work, can anyone please assist and direct me where I am going wrong?</p>
0
Loading Assemblies from NuGet Packages
<p>Sometimes in my PowerShell scripts, I need access to a specific DLL, using <code>Add-Type -AssemblyName</code>. However, the DLLs I need aren't always on the machine or in the GAC. For instance, I might want a quick script that uses Dapper to query a database. In these cases, I have been literally copying the DLLs along with the <code>ps1</code> file. I was wondering if this was common/a good idea and whether there was an existing extension that would load up NuGet packages, store then in a global or local folder and call <code>Add-Type -AssemblyName</code> automatically.</p> <p>It'd be a lot like using <code>npm</code> or <code>pip</code> in Node.js or Python, respectively.</p> <h2>Update</h2> <p>I did some research and there's nothing built-in to older versions of PowerShell. I made some progress trying to write one from scratch using the <code>nuget.exe</code></p> <pre><code>&amp;&quot;$(Get-Location)/nuget.exe&quot; install $packageName -Version $version -OutputDirectory &quot;$(Get-Location)/packages&quot; -NoCache -NoInteractive </code></pre> <p>This will download a given package/version under a &quot;packages&quot; folder in the current folder, along with any of its dependencies. However, it looks like it downloads every framework version, with no obvious way to tell which one to use for your given environment.</p> <p>Otherwise, you could just loop through the results and call Add-Type:</p> <pre><code>Get-ChildItem .\packages\ -Recurse -Filter &quot;*.dll&quot; | % { try { Add-Type -Path $_.FullName } catch [System.Exception] { } } </code></pre> <p>I tried using the <code>restore</code> command using a <code>project.json</code> file to see if I could control the framework version with no luck. This is just too hacky for me.</p> <p>I'll check out @crownedjitter's suggestion of using PowerShell 5.</p> <h2>Update</h2> <p>Using @crownedjitter's suggestion, I was able to eventually register the PackageManagement module with NuGet (see comments below). With the following command, I was able to reproduce what the <code>Nuget.exe</code> command above was doing:</p> <pre><code>Install-Package Dapper -Destination packages </code></pre> <p>Obviously, this is a lot shorter. Problem is it has the same limitation; it brings down every framework version of a package. If this includes .NET core, it brings down a good deal of the .NET core framework with it! There doesn't appear to be a way to specify a target framework (a.k.a, .NET 4.5.1 or below).</p> <p><a href="https://i.stack.imgur.com/poQ5g.png" rel="noreferrer"><img src="https://i.stack.imgur.com/poQ5g.png" alt="Install-Package grabbing dependencies for all .NET frameworks" /></a></p> <p>I am wondering if there is a way to determine which NuGet package folder(s) to load the DLLs from based on PowerShell's current <code>$PSVersionTable.CLRVersion</code> field.</p>
0
Jackson serializes a ZonedDateTime wrongly in Spring Boot
<p>I have a simple application with Spring Boot and Jetty. I have a simple controller returning an object which has a Java 8 <code>ZonedDateTime</code>:</p> <pre><code>public class Device { // ... private ZonedDateTime lastUpdated; public Device(String id, ZonedDateTime lastUpdated, int course, double latitude, double longitude) { // ... this.lastUpdated = lastUpdated; // ... } public ZonedDateTime getLastUpdated() { return lastUpdated; } } </code></pre> <p>In my <code>RestController</code> I simply have: </p> <pre><code>@RequestMapping("/devices/") public @ResponseBody List&lt;Device&gt; index() { List&lt;Device&gt; devices = new ArrayList&lt;&gt;(); devices.add(new Device("321421521", ZonedDateTime.now(), 0, 39.89011333, 24.438176666)); return devices; } </code></pre> <p>I was expecting the <code>ZonedDateTime</code> to be formatted according to the ISO format, but instead I am getting a whole JSON dump of the class like this:</p> <pre><code>"lastUpdated":{"offset":{"totalSeconds":7200,"id":"+02:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"zone":{"id":"Europe/Berlin","rules":{"fixedOffset":false,"transitionRules":[{"month":"MARCH","timeDefinition":"UTC","standardOffset":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"offsetBefore":{"totalSeconds":3600,"id":"+01:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"offsetAfter":{"totalSeconds":7200,"id":"+02:00", ... </code></pre> <p>I just have a <code>spring-boot-starter-web</code> application, using <code>spring-boot-starter-jetty</code> and excluding <code>spring-boot-starter-tomcat</code>.</p> <p>Why is Jackson behaving like this in Spring Boot?</p> <p>** UPDATE **</p> <p>For those looking for a full step by step guide how to solve this I found this after asking the question: <a href="http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/">http://lewandowski.io/2016/02/formatting-java-time-with-spring-boot-using-json/</a></p>
0
How to run an electron app with arguments?
<p>My app is electron with a <code>BrowserWindow</code> loading a local page index.html.<br> I call <code>npm run start</code> a script to run <code>electron main.js</code> , the app opens and the html loaded.<br> Can I add an argument to the script that will load different html file into the <code>BrowserWindow</code> ? </p> <p>In the main.js file the code is :</p> <pre class="lang-js prettyprint-override"><code>function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({ webPreferences:{ webSecurity:false }, fullscreen : false });//, alwaysOnTop : true , kiosk : true }) mainWindow.setMenu(null); // and load the index.html of the app. let url = `file://${__dirname}/index.html`; \\ index.html should be determined by argument passed at start. mainWindow.loadURL(url,loadOptions); // Open the DevTools. mainWindow.webContents.openDevTools(); // Emitted when the window is closed. mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); } </code></pre>
0
Python - Kivy: AttributeError: 'super' object has no attribute '__getattr__' when trying to get self.ids
<p>I wrote a code for a kind of android lock thing, whenever I try to get an specific ClickableImage using the id it raises the following error:</p> <pre><code>AttributeError: 'super' object has no attribute '__getattr__' </code></pre> <p>I've spent hours trying to look for a solution for this problem, I looked other people with the same issue, and people told them to change the site of the builder, because it needed to be called first to get the ids attribute or something like that, but everytime I move the builder, it raises the error "class not defined". Any clues?</p> <p>Here is my code:</p> <pre><code>from kivy.app import App from kivy.config import Config from kivy.lang import Builder from kivy.graphics import Line from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.widget import Widget from kivy.uix.image import Image from kivy.uix.floatlayout import FloatLayout from kivy.uix.behaviors import ButtonBehavior #Variables cords = () bld = Builder.load_file('conf.kv') class Manager(ScreenManager): pass class Principal(Screen): pass class ClickableImage(ButtonBehavior, Image): def on_press(self): self.source = 'button_press.png' def on_release(self): self.source = 'button.png' self.ids.uno.source = 'button_press.png' class canva(Widget): def on_touch_down(self, touch): global cords with self.canvas: touch.ud['line'] = Line(points=(touch.x, touch.y), width=1.5) cords = (touch.x, touch.y) def on_touch_move(self,touch): global cords touch.ud['line'].points = cords + (touch.x, touch.y) def on_touch_up(self,touch): self.canvas.clear() class Api(App): def build(self): return bld if __name__ == '__main__': Api().run() </code></pre> <p>and here is my .kv file:</p> <pre><code># conf to file: test.py &lt;Manager&gt;: Principal: &lt;Principal&gt;: GridLayout: size_hint_x: 0.5 size_hint_y: 0.6 width: self.minimum_width cols: 3 ClickableImage: id: 'uno' size: 10,10 source: 'button.png' allow_strech: True ClickableImage: id: 'dos' size: 30,30 source: 'button.png' allow_strech: True canva: </code></pre>
0
dataframe, set index from list
<p>Is it possible when creating a dataframe from a list, to set the index as one of the values?</p> <pre><code>import pandas as pd tmp = [['a', 'a1'], ['b',' b1']] df = pd.DataFrame(tmp, columns=["First", "Second"]) First Second 0 a a1 1 b b1 </code></pre> <p>And how I'd like it to look:</p> <pre><code> First Second a a a1 b b b1 </code></pre>
0
How can I use parameters in gradle tasks?
<p>There are many tasks that come with gradle which use parameters.</p> <pre><code>gradle test --tests *Test gradle dependencyInsight --dependency junit </code></pre> <p>How can I access parameters in my own custom tasks?</p>
0
How to check if a file exists in Laravel 5.2
<p>I have tried the following method to check if file exist:</p> <pre><code>@if(file_exists(public_path('/user_img/'.Auth::user()-&gt;id.'.jpg'))) </code></pre> <p>It returns <code>false</code> even when the file exists!</p> <p>What is wrong with it?</p>
0
Why is the TypeScript compiler ignoring tsconfig.json?
<p>I have this file, pasted from a tutorial (and let's face it, the disparity between docs, tuts, and examples is astounding):</p> <p>/scripts/tsconfig.json:</p> <pre><code>{ "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "module": "commonjs", "noEmitOnError": true, "noImplicitAny": false, "outDir": "../wwwroot/appScripts/", "removeComments": false, "sourceMap": true, "target": "es5", "moduleResolution": "node" }, "exclude": [ "node_modules", "typings/index", "typings/index.d.ts" ] } </code></pre> <p>Options are set to compile on save, but whenever I save a TypeScript file, the JavaScript output ends up 'under', or 'attached to', the source file:</p> <pre><code>TypeScript | --test.ts | --test.js </code></pre> <p>, and that is physically in the same directory as the source, <code>/TypeScript</code>. If <code>tsconfig.json</code> is missing, the compiler complains, but when it's present, and it definitely is, the compiler ignores the <code>"outDir": "../wwwroot/appScripts/"</code> setting.</p> <p>I am really to new to Gulp, but the Gulp task looks OK to me:</p> <pre><code>var tsProject = ts.createProject('scripts/tsconfig.json'); gulp.task('ts', function (done) { //var tsResult = tsProject.src() var tsResult = gulp.src([ "scripts/*.ts" ]) .pipe(ts(tsProject), undefined, ts.reporter.fullReporter()); return tsResult.js.pipe(gulp.dest('./wwwroot/appScripts')); }); </code></pre>
0
Restrict scipy.optimize.minimize to integer values
<p>I'm using <code>scipy.optimize.minimize</code> to optimize a real-world problem for which the answers can only be integers. My current code looks like this: </p> <pre><code>from scipy.optimize import minimize def f(x): return (481.79/(5+x[0]))+(412.04/(4+x[1]))+(365.54/(3+x[2]))+(375.88/(3+x[3]))+(379.75/(3+x[4]))+(632.92/(5+x[5]))+(127.89/(1+x[6]))+(835.71/(6+x[7]))+(200.21/(1+x[8])) def con(x): return sum(x)-7 cons = {'type':'eq', 'fun': con} print scipy.optimize.minimize(f, [1,1,1,1,1,1,1,0,0], constraints=cons, bounds=([0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7],[0,7])) </code></pre> <p>This yields: </p> <pre><code>x: array([ 2.91950510e-16, 2.44504019e-01, 9.97850733e-01, 1.05398840e+00, 1.07481251e+00, 2.60570253e-01, 1.36470363e+00, 4.48527831e-02, 1.95871767e+00] </code></pre> <p>But I want it optimized with integer values (rounding all <code>x</code> to the nearest whole number doesn't always give the minimum). </p> <p>Is there a way to use <code>scipy.optimize.minimize</code> with only integer values?</p> <p>(I guess I could create an array with all possible permutations of <code>x</code> and evaluate f(x) for each combination, but that doesn't seem like a very elegant or quick solution.)</p>
0
Application startup code in ASP.NET Core
<p>Reading over the <a href="https://docs.asp.net/en/latest/fundamentals/startup.html" rel="noreferrer">documentation for ASP.NET Core</a>, there are two methods singled out for Startup: Configure and ConfigureServices.</p> <p>Neither of these seemed like a good place to put custom code that I would like to run at startup. Perhaps I want to add a custom field to my DB if it doesn't exist, check for a specific file, seed some data into my database, etc. Code that I want to run once, just at app start.</p> <p>Is there a preferred/recommended approach for going about doing this?</p>
0
Rails: Unpermitted parameter in Rails 5
<p>First of all I want simply get an object inside the current object that I'm sending to my <em>backend</em>.</p> <p>I have this simple <code>JSON</code> (generated from a form):</p> <pre><code>{ "name": "Project 1", "project_criteria": [ { "name": "Criterium 1", "type": "Type 1", "benefit": "1" }, { "name": "Criterium 2", "type": "Type 2", "benefit": "3" } ] } </code></pre> <p>My <code>classes</code>:</p> <pre><code>class Project &lt; ApplicationRecord has_many :project_criteria accepts_nested_attributes_for :project_criteria end class ProjectCriterium &lt; ApplicationRecord belongs_to :project end </code></pre> <p><strong>ProjectsController:</strong></p> <pre><code>def project_params params.require(:project).permit(:name, project_criteria: [] ) end </code></pre> <p>But I still can't access <code>project_criteria</code> parameter as you can see below:</p> <pre><code>Started POST "/projects" for 127.0.0.1 at 2016-08-19 16:24:03 -0300 Processing by ProjectsController#create as HTML Parameters: {"project"=&gt;{"name"=&gt;"Project 1", "project_criteria"=&gt;{"0"=&gt;{"benefit"=&gt;"1", "name"=&gt;"Criterium 1", "type"=&gt;"Type 1"}, "1"=&gt;{"benefit"=&gt;"3", "name"=&gt;"Criterium 2", "type"=&gt;"Type 2"}}}} Unpermitted parameter: project_criteria # &lt;----------- </code></pre> <p><strong>Note:</strong></p> <p>By the way, I already tried to use <strong>criterium</strong> instead of <strong>criteria</strong>(which <strong>- in my opinion -</strong> is the correct since it should be pluralized) in <code>has_many</code> and <code>accepts_nested_attributes_for</code>, but it also doesn't work.</p> <p>Does someone have a solution for this?</p>
0
SocketTimeoutException in Retrofit
<p>I am trying to <strong>POST</strong> request to server for fetch data but sometime It's occure <code>SocketTimeoutException</code>!</p> <p>I used <code>Ok3Client</code> to resolve it but I facing the same Exception How can I resolve it?</p> <p>My code is below</p> <pre><code>public void getNormalLogin() { if (mProgressDialog == null) { mProgressDialog = ViewUtils.createProgressDialog(mActivity); mProgressDialog.show(); } else { mProgressDialog.show(); } if (Build.VERSION.SDK != null &amp;&amp; Build.VERSION.SDK_INT &gt; 13) { restadapter = new RestAdapter.Builder().setEndpoint(HOST).setLogLevel(RestAdapter.LogLevel.FULL).setClient(new Ok3Client(new OkHttpClient())).build(); mApi = restadapter.create(Api.class); mApi.SignIn(etEmail.getText().toString(), etPassword.getText().toString(), new Callback&lt;ArrayList&lt;SignUpMainBean&gt;&gt;() { @Override public void success(ArrayList&lt;SignUpMainBean&gt; signUpMainBeen, Response response) { mProgressDialog.dismiss(); LOGD("Status:: ::", String.valueOf(response.getStatus())); LOGD("Code:: ::", String.valueOf(signUpMainBeen.get(0).getCode())); if (signUpMainBeen != null &amp;&amp; signUpMainBeen.size() &gt; 0) { if (signUpMainBeen.get(0).getCode() == 1) { for (int i = 0; i &lt; signUpMainBeen.size(); i++) { for (int j = 0; j &lt; signUpMainBeen.get(i).getResult().size(); j++) { showToast(mActivity, getString(R.string.you_have_successfully_login), Toast.LENGTH_SHORT); LOGD("Success", "Success"); finish(); SignIn.mActivity.finish(); } } } else if (signUpMainBeen.get(0).getCode() == 0) { mProgressDialog.dismiss(); showToast(mActivity, getString(R.string.invalid_email_password), Toast.LENGTH_SHORT); LOGD("Invalid email or password", "Invalid email or password"); } else if (signUpMainBeen.get(0).getCode() == -1) { mProgressDialog.dismiss(); showToast(mActivity, getString(R.string.your_account_is_inactive), Toast.LENGTH_SHORT); LOGD("Your account is inactive", "Your account is inactive"); } } } @Override public void failure(RetrofitError error) { mProgressDialog.dismiss(); showToast(mActivity, getString(R.string.can_not_connect_to_server), Toast.LENGTH_SHORT); LOGD("Failure", "Failure"); } }); } } </code></pre> <p>My Error Log is</p> <pre><code>D/Retrofit: java.net.SocketTimeoutException at java.net.PlainSocketImpl.read(PlainSocketImpl.java:532) at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:40) at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:255) at okio.Okio$2.read(Okio.java:139) at okio.AsyncTimeout$2.read(AsyncTimeout.java:211) at okio.RealBufferedSource.indexOf(RealBufferedSource.java:306) at okio.RealBufferedSource.indexOf(RealBufferedSource.java:300) at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196) at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:185) at okhttp3.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:126) at okhttp3.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:723) at okhttp3.internal.http.HttpEngine.access$200(HttpEngine.java:81) at okhttp3.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.java:708) at okhttp3.internal.http.HttpEngine.readResponse(HttpEngine.java:563) at okhttp3.RealCall.getResponse(RealCall.java:241) at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160) at okhttp3.RealCall.execute(RealCall.java:57) at com.jakewharton.retrofit.Ok3Client.execute(Ok3Client.java:40) at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:326) at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220) at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278) at retrofit.CallbackRunnable.run(CallbackRunnable.java:42) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at retrofit.Platform$Android$2$1.run(Platform.java:142) at java.lang.Thread.run(Thread.java:818) </code></pre>
0
How to use onPress on a custom component?
<p>Let's assume I have this custom component:</p> <pre><code>export default class Button extends Component { render(){ return( &lt;TouchOpacity&gt; &lt;Text&gt; Button &lt;/Text&gt; &lt;/TouchOpacity&gt; ) } } </code></pre> <p>And I use it in a parent component like this :</p> <pre><code>export default class MainPage extends Component { render(){ return( &lt;Button onPress={ this.doSomething }&gt;&lt;/Button&gt; ) } } </code></pre> <p>For some reason (unknown to me at least) this onPress even won't happen. I'm pretty new to react-native btw. I believe I must find a way to enable this kind of event handling. </p> <p>Is it possible to get a small example how to achieve that based on my examples above ?</p>
0
Difference between $() and () in Bash
<p>When I type <code>ls -l $(echo file)</code> output from bracket (which is just simple echo'ing) is taken and passed to external <code>ls -l</code> command. It equals to simple <code>ls -l file</code>.</p> <p>When I type <code>ls -l (echo file)</code> we have error because one cannot nest <code>()</code> inside external command.</p> <p>Can someone help me understand the difference between <code>$()</code> and <code>()</code> ?</p>
0
How to get row value by just giving column name in DataTable
<p>Is it possible to get a row value by giving column name when DataTable holds a single row, without iteration.</p> <pre><code>foreach(DataRow row in dt.Rows) { string strCity = row["City"].ToString(); } </code></pre> <p><a href="http://i.stack.imgur.com/YZjr7.png" rel="noreferrer">Table</a></p> <p>I need Something like below without loop when we have only one row,</p> <pre><code>String cn=row["ColumnName"].ToString() </code></pre>
0
Netflix Ribbon and Hystrix Timeout
<p>We are using Spring cloud in our project. We have several micro services and each has its own .yml file.</p> <p>Below properies are only in zuul server</p> <pre><code>hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000 ribbon: ConnectTimeout: 3000 ReadTimeout: 60000 </code></pre> <p><strong>Test 1:</strong></p> <p><strong>Accounts Service:</strong></p> <p>This service is what I'm calling to test the timeout and I'm calling the request through zuul i.e., using the port 8006.</p> <pre><code>@RequestMapping(value = "/accountholders/{cardHolderId}/accounts", produces = "application/json; charset=utf-8", method = RequestMethod.GET) @ResponseBody public AllAccountsVO getAccounts(@PathVariable("cardHolderId") final String cardHolderId, @RequestHeader("userContextId") final String userContextId, @RequestParam final MultiValueMap&lt;String, String&gt; allRequestParams, final HttpServletRequest request) { return iAccountService.getCardHolderAccountsInfo(cardHolderId, userContextId, request, allRequestParams, ApplicationConstants.ACCOUNTHOLDER); } </code></pre> <p>The above service internally calls the below one using Spring RestTemplate. I started testing by adding a sleep time of 5000ms like below in <strong>Association Service</strong> and made a request to <strong>Accounts Service</strong> (getAccounts call).</p> <p><strong>Association Service:</strong></p> <pre><code>@RequestMapping(value = "/internal/userassociationstatus", produces = "application/json; charset=utf-8", consumes = "application/json", method = RequestMethod.GET) @ResponseBody public UserAssociationStatusVO getUserAssociationStatus(@RequestParam final Map&lt;String, String&gt; allRequestParams) { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return iUserAssociationsService.getUserAssociationStatus(allRequestParams); } </code></pre> <p>Below is the error I got in <strong>Association Service</strong></p> <pre><code>org.apache.catalina.connector.ClientAbortException: java.io.IOException: An established connection was aborted by the software in your host machine at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:393) ~[tomcat-embed-core-8.0.30.jar:8.0.30] at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:426) ~[tomcat-embed-core-8.0.30.jar:8.0.30] at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:342) ~[tomcat-embed-core-8.0.30.jar:8.0.30] </code></pre> <p>Below is the error I got in <strong>Accounts Service</strong></p> <pre><code>org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://USERASSOCIATIONS-V1/user/v1/internal/userassociationstatus?cardholderid=123&amp;usercontextid=222&amp;role=ACCOUNT": com.sun.jersey.api.client.ClientHandlerException: java.net.SocketTimeoutException: Read timed out; nested exception is java.io.IOException: com.sun.jersey.api.client.ClientHandlerException: java.net.SocketTimeoutException: Read timed out at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:607) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE] at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE] </code></pre> <p>If I keep the sleep time as 4500 it gives me response, but if is >=4800 it throws the above exception. I'm thinking this is not related to Ribbon Timeouts but something else. Any specific reason for the above exception after certain point. </p> <p><strong>Test 2</strong></p> <p>Then I tried keeping a sleep time of 75000 ms in <strong>Accounts Service</strong> directly and removed sleep time <strong>Association Service</strong>.</p> <pre><code>@RequestMapping(value = "/accountholders/{cardHolderId}/accounts", produces = "application/json; charset=utf-8", method = RequestMethod.GET) @ResponseBody public AllAccountsVO getAccounts(@PathVariable("cardHolderId") final String cardHolderId, @RequestHeader("userContextId") final String userContextId, @RequestParam final MultiValueMap&lt;String, String&gt; allRequestParams, final HttpServletRequest request) { try { Thread.sleep(75000); } catch (InterruptedException ex) { // TODO Auto-generated catch block ex.printStackTrace(); } return iAccountService.getCardHolderAccountsInfo(cardHolderId, userContextId, request, allRequestParams, ApplicationConstants.ACCOUNTHOLDER); } </code></pre> <p>In this case I got "exception": "com.netflix.zuul.exception.ZuulException",</p> <p>And in my APIGateway(Zuul application) log I see the below error.</p> <pre><code>com.netflix.zuul.exception.ZuulException: Forwarding error at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:134) ~[spring-cloud-netflix-core-1.1.0.M5.jar:1.1.0.M5] at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:76) ~[spring-cloud-netflix-core-1.1.0.M5.jar:1.1.0.M5] at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112) ~[zuul-core-1.1.0.jar:1.1.0] at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:197) ~[zuul-core-1.1.0.jar:1.1.0] Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: useraccounts-v1RibbonCommand timed-out and no fallback available. at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:806) ~[hystrix-core-1.4.23.jar:1.4.23] at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:790) ~[hystrix-core-1.4.23.jar:1.4.23] at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14] at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14] </code></pre> <p>I think this has nothing to do with Ribbon ConnectTimeout or ReadTimeout. This error is because of the property <strong>"execution.isolation.thread.timeoutInMilliseconds: 60000"</strong>. I have also reduced this property to 10000 ms to test the behavior and got the same exception if the sleep time is more(ex: 12000).</p> <p><strong>I want to understand Ribbon ConnectTimeout and Read-timeout vs Hystrix timeout and how to test ribbon timeouts in my application. Also if I want different timeouts for different microservices, Do I keep these properties in respective .yml files?.</strong> Any thoughts?</p> <p>I'm trying to create a document to be used by my team so that it is easy for a developer to know how these timeout options work in Spring cloud.</p> <p>(It's a lengthy description but to make it clearer I had to write in detail)</p>
0
How do I load a custom bundle in Swift 3
<p>In Objective-C I was doing this:</p> <pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"LUIImages" ofType:@"bundle"]; path = [[NSBundle bundleWithPath:path] pathForResource:_imageHash ofType:nil]; </code></pre> <p>But I can't seem to find equivalent in swift 3</p> <pre><code>let bundlePath: String = Bundle.main.path(forResource: "LiveUI", ofType: "bundle")! </code></pre> <p>But what is the next step? Or is there any better way to load a custom bundle?</p>
0
Woocommerce - Display single product attribute(s) with shortcodes in Frontend
<p>i've read many Q/A's here during the last few days, but unfortunately none of them solved my issue.</p> <p>I'm trying to fetch product attributes and display them on the frontend with a shortcode. I have managed to display ALL available attributes and display them in a list, but i need to select only one or two of them in different locations (thats why using shortcodes). For example like [shortcode_attribute name="brand"].</p> <p>Any help is highly appreciated!</p> <p>my code so far:</p> <pre><code>function tutsplus_list_attributes( $product ) { global $product; global $post; $attributes = $product-&gt;get_attributes(); if ( ! $attributes ) { return; } foreach ( $attributes as $attribute ) { // Get the taxonomy. $terms = wp_get_post_terms( $product-&gt;id, $attribute[ 'name' ], 'all' ); $taxonomy = $terms[ 0 ]-&gt;taxonomy; // Get the taxonomy object. $taxonomy_object = get_taxonomy( $taxonomy ); // Get the attribute label. $attribute_label = $taxonomy_object-&gt;labels-&gt;name; // Display the label followed by a clickable list of terms. echo get_the_term_list( $post-&gt;ID, $attribute[ 'name' ] , '&lt;div&gt;&lt;li class="bullet-arrow"&gt;' . $attribute_label . ': ' , ', ', '&lt;/li&gt;&lt;/div&gt;' ); } } add_action( 'woocommerce_product_meta_end', 'tutsplus_list_attributes' ); add_shortcode('display_attributes', 'tutsplus_list_attributes'); </code></pre>
0
AWS Lambda: Unable to import module
<p>please forgive me, I am totally new at Lambda and Node.</p> <p>I am trying to replicate <a href="https://gist.github.com/bhberson/7a2847888596e67fd69b" rel="noreferrer">this</a> git to order a pizza using an AWS IoT button.</p> <p>My current code is:</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>var pizzapi = require('dominos'); var myStore = new pizzapi.Store( { ID: 'Example' } ); var myAddress = new pizzapi.Address( { Street: 'Example', City: 'Example', Region: 'Example', PostalCode: 'Example' } ); var myCustomer = new pizzapi.Customer( { firstName: 'Example', lastName: 'Example', address: myAddress, phone: 'Example', email: '[email protected]' } ); var order = new pizzapi.Order( { customer: myCustomer, storeID: myStore.ID } ); var cardNumber='Example'; var cardInfo = new order.PaymentObject(); cardInfo.Amount = order.Amounts.Customer; cardInfo.Number = cardNumber; cardInfo.CardType = order.validateCC(cardNumber); cardInfo.Expiration = 'Example'; cardInfo.SecurityCode = 'Example'; cardInfo.PostalCode = 'Example'; order.Payments.push(cardInfo); function orderDominos(event, context) { var clickType = event.clickType; switch(clickType.toLowerCase()) { case "single": { order.addItem( new pizzapi.Item( { code: 'P_14SCREEN', options: {}, quantity: 1 } ) ); break; } case "double": { order.addItem( new pizzapi.Item( { code: 'P_14SCREEN', options: {}, quantity: 1 } ) ); break; } case "long": { order.addItem( new pizzapi.Item( { code: 'P_14SCREEN', options: {}, quantity: 1 } ) ); break; } } order.validate( function(result) { console.log("Order is Validated"); } ); order.price( function(result) { console.log("Order is Priced"); } ); order.place( function(result) { console.log("Price is", result.result.Order.Amounts, "\nEstimated Wait Time",result.result.Order.EstimatedWaitMinutes, "minutes"); console.log("Order placed!"); context.succeed(event); } ); } exports.handler = orderDominos;</code></pre> </div> </div> </p> <p>The file structure is:</p> <ul> <li>orderDominos.js</li> <li>node_modules/dominos</li> </ul> <p>I zipped the files, uploaded to Lambda, and pointed the header to "index.handler"</p> <p>What am I doing wrong?</p> <p>Edit: The error</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>Unable to import module 'orderDominos': Error at Function.Module._resolveFilename (module.js:325:15) at Function.Module._load (module.js:276:25) at Module.require (module.js:353:17) at require (internal/module.js:12:17) at Object.&lt;anonymous&gt; (/var/task/node_modules/dominos/src/http-json.js:1:74) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Module.require (module.js:353:17)</code></pre> </div> </div> </p>
0
Firebase connection with codeigniter in php
<p>I want to connect firebase database with my codeigniter project in php.</p> <p>I not able to find the exact solution and library..</p> <p>Please recommend the correct library with correct steps that I should follow to connect.</p> <p>Thanks in advance.</p>
0
SQL: join with OR in condition
<p>I have 2 tables:</p> <pre><code>Devices (id (PK)) Links (id (PK), device_id_1 (FK), device_id_2 (FK)) </code></pre> <p>Which represents devices connected by links.</p> <p>I need to select all devices connected with a given one (which can be device_id_1 or device_id_2). I tried to do it with the following query:</p> <pre><code>select d2.* from Devices as d1 left outer join Links as l on d1.id in (l.device_id_1, l.device_id_2) left outer join Devices as d2 on d2.id in (l.device_id_1, l.device_id_2) where d1.id = 398 and d2.id &lt;&gt; 398; </code></pre> <p>But as soon as I added second <code>JOIN</code> the query returns zero rows. What am I doing wrong?</p>
0
mysql_num_rows in laravel?
<p>im trying to use mysql_num_rows in laravel but laravel says it not the same way like in 'raw php'</p> <blockquote> <p>example:</p> </blockquote> <pre><code>$users = DB::table('users') -&gt;where('username', '=', $username) -&gt;where('password', '=', $password) -&gt;get(); </code></pre> <blockquote> <p>what i want to do:</p> </blockquote> <pre><code>$count = mysql_num_rows($users); if($count &gt; 0 ){ $user-&gt;login = $request-&gt;login; $user-&gt;email = $request-&gt;email; $user-&gt;password = $request-&gt;password; Auth::login($user); return redirect("/"); }else{ return "datos incorrectos"; } </code></pre> <blockquote> <p>what laravel says:</p> </blockquote> <pre><code>Call to undefined function App\Http\Controllers\Auth\mysql_num_rows() </code></pre> <p>PD: its not philosophy of code just make commets about that question, i dont want answers like "u gonna crypt that thing?", "why not use [insert my faborite ORM]" is just a simple question THANKS</p>
0
How to clone project from the GitHub in Android studio
<p>Hello all I am trying to clone the project from github. Is downloading the zip folder and loading it into the android studio the same as cloning from Github ?</p>
0
Why Angular2 routerLinkActive sets active class to multiple links?
<p>I'm trying to implement routerLinkActive to my app but i'm facing the issue that it's sets class active to multiple links. Here's how i'm doing it</p> <pre><code>&lt;ul class=&quot;nav nav-tabs&quot;&gt; &lt;li role=&quot;presentation&quot; [routerLinkActive]=&quot;['active']&quot;&gt;&lt;a [routerLink]=&quot;['/']&quot;&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li role=&quot;presentation&quot; [routerLinkActive]=&quot;['active']&quot;&gt;&lt;a [routerLink]=&quot;['/about']&quot;&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li role=&quot;presentation&quot; [routerLinkActive]=&quot;['active']&quot;&gt;&lt;a [routerLink]=&quot;['/contact']&quot; &gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Here it's how it looks</p> <p><a href="https://i.stack.imgur.com/Mvaer.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mvaer.png" alt="enter image description here" /></a> Here it's how it look in dev-tools <a href="https://i.stack.imgur.com/HyZHC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HyZHC.png" alt="enter image description here" /></a> And my address bar</p> <p><a href="https://i.stack.imgur.com/7OpbH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7OpbH.png" alt="enter image description here" /></a></p> <h2>Am i missing something because i'm doing as explained in <a href="https://angular.io/docs/ts/latest/guide/router.html#!#router-link-active" rel="noreferrer">angular docs</a>.</h2>
0
Call child component method from parent class - Angular
<p>I have created a child component which has a method I want to invoke.</p> <p>When I invoke this method it only fires the <code>console.log()</code> line, it will not set the <code>test</code> property??</p> <p>Below is the quick start Angular app with my changes.</p> <p><strong>Parent</strong></p> <pre><code>import { Component } from '@angular/core'; import { NotifyComponent } from './notify.component'; @Component({ selector: 'my-app', template: ` &lt;button (click)=&quot;submit()&quot;&gt;Call Child Component Method&lt;/button&gt; ` }) export class AppComponent { private notify: NotifyComponent; constructor() { this.notify = new NotifyComponent(); } submit(): void { // execute child component method notify.callMethod(); } } </code></pre> <p><strong>Child</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'notify', template: '&lt;h3&gt;Notify {{test}}&lt;/h3&gt;' }) export class NotifyComponent implements OnInit { test:string; constructor() { } ngOnInit() { } callMethod(): void { console.log('successfully executed.'); this.test = 'Me'; } } </code></pre> <p>How can I set the <code>test</code> property as well?</p>
0
Rolling Regression Estimation in Python dataframe
<p>I have a dataframe like this:</p> <pre><code> Date Y X1 X2 X3 22 2004-05-12 9.348158e-09 0.000081 0.000028 0.000036 23 2004-05-13 9.285989e-09 0.000073 0.000081 0.000097 24 2004-05-14 9.732308e-09 0.000085 0.000073 0.000096 25 2004-05-17 2.235977e-08 0.000089 0.000085 0.000099 26 2004-05-18 2.792661e-09 0.000034 0.000089 0.000150 27 2004-05-19 9.745323e-09 0.000048 0.000034 0.000053 ...... 1000 2004-05-20 1.835462e-09 0.000034 0.000048 0.000099 1001 2004-05-21 3.529089e-09 0.000037 0.000034 0.000043 1002 2004-05-24 3.453047e-09 0.000043 0.000037 0.000059 1003 2004-05-25 2.963131e-09 0.000038 0.000043 0.000059 1004 2004-05-26 1.390032e-09 0.000029 0.000038 0.000054 </code></pre> <p>I want to run a rolling 100-day window OLS regression estimation, which is: </p> <p>First for the 101st row, I run a regression of Y-X1,X2,X3 using the 1st to 100th rows, and estimate Y for the 101st row;</p> <p>Then for the 102nd row, I run a regression of Y-X1,X2,X3 using the 2nd to 101st rows, and estimate Y for the 102nd row;</p> <p>Then for the 103rd row, I run a regression of Y-X1,X2,X3 using the 2nd to 101st rows, and estimate Y for the 103rd row;</p> <p>......</p> <p>Until the last row.</p> <p>How to do this?</p>
0
Spring boot connect to MongoDB replica set running with an Arbiter
<p>My application is a Spring boot application and the application configuration properties file look like:</p> <pre><code>.... spring.data.mongodb.host=ip spring.data.mongodb.port=27017 spring.data.mongodb.admin.database=admin spring.data.mongodb.database=myDB spring.data.mongodb.username=su spring.data.mongodb.password=su1$ .... </code></pre> <p>Now the thing is for high availability MongoDB has been moved to a <em>Primary-Secondary-Arbiter</em> setup. What changes should I do in order to connect to this. Tried separating with comma but that did not help.</p>
0
How to resolve Nginx "proxy_pass 502 Bad Gateway" error
<p>I have trying to add proxy_set_header in my nginx.conf file. When I try to add proxy_pass and invoke the URL it throws 502 Bad Gateway nginx/1.11.1 error.</p> <p>Not sure how to resolve this error:</p> <pre><code>upstream app-server { # connect to this socket server unix:///tmp/alpasso-wsgi.sock; # for a file socket } server { server_name &lt;name&gt;; listen 80 default_server; # Redirect http to https rewrite ^(.*) https://$host$1 permanent; } server { server_name &lt;name&gt;; listen 443 ssl default_server; recursive_error_pages on; location /azure{ proxy_pass http://app-server; } ssl on; ssl_certificate /etc/nginx/server.crt; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/server.crt; ssl_verify_client optional; } </code></pre>
0
Get a value inside a Promise Typescript
<p>One of function inside a typescript class returns a <code>Promise&lt;string&gt;</code>. How do I unwrap/yield the value inside that promise.</p> <pre><code>functionA(): Promise&lt;string&gt; { // api call returns Promise&lt;string&gt; } functionB(): string { return this.functionA() // how to unwrap the value inside this promise } </code></pre>
0
ImportError: No module named azure.storage.blob (when doing syncdb)
<p>I recently cloned a Django project of mine in a brand new machine, and went about setting up its dependencies. One such dependency was azure storages, for which I followed the advice <a href="https://stackoverflow.com/questions/34405936/getting-importerror-no-module-named-azure-storage-blob-when-doing-python-manage">here</a> and simply did <code>sudo pip install azure</code>. </p> <p>However, upon `python manage.py syncdb', I keep getting the error:</p> <blockquote> <p>ImportError: No module named azure.storage.blob</p> </blockquote> <p>I've tried to solely do <code>sudo pip install azure-storage</code> as well, but this doesn't alleviate my problem either. This shouldn't have been this problematic. What do I do?</p>
0
applicationId manifest placeholder for multiple build flavors not working
<p>I am modifying current android project so it can be installed on same device for multiple flavors and build configs.</p> <p><strong>build.gradle:</strong></p> <pre><code>{ // ... defaultConfig { applicationId "com.myapp" manifestPlaceholders = [ manifestApplicationId: "${applicationId}", onesignal_app_id: "xxxx", onesignal_google_project_number: "xxxx" ] // ... } productFlavors { production { applicationId "com.myapp" // ... } dev { applicationId "com.myapp.dev" // ... } // ... } buildTypes { release { // ... } debug { applicationIdSuffix ".debug" // ... } } // ... } </code></pre> <p><strong>AndroidManifest.xml</strong>:</p> <pre><code>&lt;manifest ... &gt; &lt;uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" /&gt; &lt;permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt; &lt;!-- ... --&gt; &lt;receiver android:name="com.onesignal.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" &gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;category android:name="${applicationId}" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;!-- ... --&gt; &lt;/manifest&gt; </code></pre> <p>When I compile both debug and release version of the same flavor, I got error message:</p> <p>...</p> <p>INSTALL_FAILED_DUPLICATE_PERMISSION</p> <p>perm=com.myapp.permission.C2D_MESSAGE</p> <p>pkg=com.myapp.dev</p> <p>...</p> <p>manifestApplicationId placeholder came from AndroidManifest.xml on OneSignal library as instructed on <a href="https://documentation.onesignal.com/docs/android-sdk-setup" rel="noreferrer">https://documentation.onesignal.com/docs/android-sdk-setup</a></p> <p>Anybody have a clue how to fix this problem? Thank you.</p>
0