title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
How to pass array of objects to an MVC Controller in Jquery?
|
<p>I'm trying to post an array of objects from js ajax to asp.net mvc controller. But controller parameter is always comes null. Is there a type mismatch or something else?</p>
<p><strong>Js ajax</strong></p>
<pre><code> var obj = {};
var arr = [];
obj = {
id: clicked.attr("name"),
name: clicked.text().trim()
}
if (clicked.hasClass("active")) {
clicked.removeClass("active");
clickedCount--;
arr.pop(obj);
}
else {
clicked.addClass("active");
clickedCount++;
arr.push(obj);
}
$.ajax({
url: "/Players/Shuffle",
type: "POST",
data: JSON.stringify({ list: arr }),
contentType: "json",
success: function (data) {}
});
</code></pre>
<p><strong>Controller</strong></p>
<pre><code> [HttpPost]
public ActionResult Shuffle(List<player> list)
{
return RedirectToAction("Shuffled", new { l = list });
}
</code></pre>
<p><strong>Error:</strong> list in controller is always null.</p>
<p><strong>UPDATE:</strong></p>
<p>In addition to the code above, why can't I see a new page with the list that posted to the <code>Shuffle</code>? <code>Shuffled</code> should be dealing with this.</p>
<pre><code>public ActionResult Shuffled(List<Player> list)
{
ViewData["PlayerList"] = list;
return View(list);
}
</code></pre>
<p><strong>cshtml</strong></p>
<pre><code>@model List<Player>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Shuffled";
}
<h1 id="test">
list: @ViewData["PlayerList"]
</h1>
</code></pre>
| 0 |
Spring Boot API with Multiple Controllers?
|
<p>I am starting to learn Spring Boot. I am struggling to find an example with multiple RestControllers, which indicates to me that I may be doing something wrong. I am trying a very simple example: The goal is to make calls like the following:</p>
<pre><code>localhost:8080/
localhost:8080/employees/bob
localhost:8080/departments
</code></pre>
<p>I can only get localhost:8080/ to display. The other calls return response: This application has no explicit mapping for /error, so you are seeing this as a fallback. </p>
<pre><code>com.demo.departments
Department.java
DepartmentController.java
com.demo.employees
Employee.java
EmployeeController.java
com.demo
BootDemoApplication.java
</code></pre>
<p>Code:</p>
<pre><code>package com.demo.departments
@RestController
@RequestMapping("/departments")
public class DepartmentController {
@RequestMapping("")
public String get(){
return "test..";
}
@RequestMapping("/list")
public List<Department> getDepartments(){
return null;
}
}
--------------------------------------------------------------------
package com.demo.employees
@RestController
@RequestMapping("/employees")
public class EmployeeController {
Employee e =new Employee();
@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public Employee getEmployeeInJSON(@PathVariable String name) {
e.setName(name);
e.setEmail("[email protected]");
return e;
}
}
-----------------------------------------------------------------------
package com.demo
@RestController
@SpringBootApplication
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class, args);
}
@RequestMapping("/")
String home(){
return "<html> This is the home page for Boot Demo.</html>";
}
</code></pre>
| 0 |
Bind a service property to a component property with proper change tracking
|
<p>Consider the utterly simple Angular 2 service:</p>
<pre><code>import { Injectable } from '@angular/core';
import {Category} from "../models/Category.model";
@Injectable()
export class CategoryService {
activeCategory: Category|{} = {};
constructor() {};
}
</code></pre>
<p>And then the component using this service:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import {CategoryService} from "../shared/services/category.service";
import {Category} from "../shared/models/Category.model";
@Component({
selector: 'my-selector',
template: `
{{categoryService.activeCategory.Name}}<br/>
{{category.Name}}<br/>
`,
})
export class MySelectorComponent implements OnInit {
category:Category|{} = {};
constructor(public categoryService:CategoryService){};
ngOnInit() {
this.category = this.categoryService.activeCategory;
};
}
</code></pre>
<p>Assume appropriately defined Category model and assume that another component somewhere sets the activeCategory on the service to a valid Category at some point. Assume that the categoryservice is set as provider at an appropriately higher level.</p>
<p>When that happens, the first line in the template will correctly display the category Name, but the second line will not. I've tried using getters and setters vs. raw access on the service; I've tried primitive types vs. objects vs. object properties; I can't believe that the first line is the appropriate paradigm for this type of access. Can someone tell me the simplest way to bind a service property to a component property that will properly do change tracking in angular two?</p>
<p><strong>CLARIFICATION:</strong> I know I could use observables that I create and push to for myself. What I am asking is if there is any kind of already-baked into the framework way of doing this (that doesn't require me to write the huge amount of boilerplate for an observable) that just makes a variable track between the service and component.</p>
| 0 |
readFileSync is not a function
|
<p>I am relatively new to Node.js and have been looking around but cannot find a solution. I did check the require javascript file and it does not seem to have a method for "readFileSync". Perhaps I don't have a proper require file? I had a hard time finding this file, everywhere talked about it but most people did not post where to get it.</p>
<p>I installed Node.js and have the require.js file. My current code is like this:</p>
<pre><code>fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');
</code></pre>
<p>I had a bit at first getting require to work however it seems to load the require JavaScript file. I have been following guides and I am not sure why I get this error:</p>
<blockquote>
<p>Uncaught TypeError: fs.readFileSync is not a function</p>
</blockquote>
<p>I have tried many fixes and cannot seem to figure this one out.</p>
| 0 |
can't add maven dependency - apache poi
|
<p>I created this maven project in Eclipse on my mac. The following two artifacts are in my pom. No problem on MAC.</p>
<pre><code><dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
</code></pre>
<p>However when I recently moved the code to Eclipse on my PC I got this weird error "Missing artifact org.apache.poi:poi:jar:3.14". And it points to both the dependency block and the first line of pom (see screenshot) <a href="https://i.stack.imgur.com/ztuUP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ztuUP.png" alt="enter image description here"></a>. Updated project many times and it did not help. </p>
<p>I have set up two repositories, one public and one institutional.</p>
<pre><code> <repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>repo</name>
<url>http://risdevtool01p.mdanderson.edu:8081/artifactory/repo</url>
</repository>
</repositories>
</code></pre>
<p>When I do "mvn clean install -U", it looks like it is trying to download poi and poi-ooxml from two different repositories.</p>
<pre><code>Downloading:http://repository.jboss.org/nexus/content/groups/public/org/apache/poi/poi-ooxml-schemas/3.14/poi-ooxml-schemas-3.14.jar
Downloading: http://repository.jboss.org/nexus/content/groups/public/org/apache/poi/poi/3.14/poi-3.14.jar
Downloading: http://risdevtool01p.mdanderson.edu:8081/artifactory/repo/org/apache/poi/poi/3.14/poi-3.14.jar
Downloading: http://risdevtool01p.mdanderson.edu:8081/artifactory/repo/org/apache/poi/poi-ooxml-schemas/3.14/poi-ooxml-schemas-3.14.jar
</code></pre>
| 0 |
PHP foreach loop inside foreach loop?
|
<p>I have two foreach loop. In first foreach loop menu list and second foreach loop is database fetch loop. So i want compare first foreach key to second foreach value first foreach array result is shown</p>
<pre><code> Array
(
[master/city] => City
[master/national_holiday] => National Holiday
[master/operator_comments] => Operator Comments
[master/sensors] => Sensors
)
</code></pre>
<p>and second foreach array result</p>
<pre><code> Array
(
[0] => Array
(
[menu_url] => monitoring/tickets
[menu_category] => monitoring
[read] => 1
[write] => 1
)
[1] => Array
(
[menu_url] => monitoring/serach_tickets
[menu_category] => monitoring
[read] => 1
[write] => 1
)
[2] => Array
(
[menu_url] => master/national_holiday
[menu_category] => monitoring
[read] => 1
[write] => 0
)
)
</code></pre>
<p>I try to use this code but not working fine</p>
<pre><code> foreach( $first_array as $key => $value) {
foreach( $second_array as $second ) {
if ($second['value'] == $key) {
echo "Hi";
}
}
}
</code></pre>
<p>can you suggest what is my mistake.</p>
<p>My real code using in view</p>
<pre><code><?php
$i = 1;
foreach($first_array as $k => $val) {
?>
<tr>
<td>{{ $i }}</td>
<td class="mailbox-name">{{ $val }}</td>
<?php
foreach ($edit_rights['role_rights'] as $rights) {
?>
<td><input type="checkbox" class="master_read" name="menu_master_read[]" <?php if ($rights['menu_url'] == $k) { echo 'checked'; } else {echo ''; }?> value="{{ $k }}"></td>
<td><input type="checkbox" class="master_write" name="menu_master_write[]" value="{{ $k }}"></td>
</tr>
<?php } $i++; } ?>
</tr>
</code></pre>
| 0 |
How to compile Windows Visual C++ code on Linux
|
<p><strong>Note: The intent of this question was to find if there exists a standard way of developing in VC for Windows and porting that code smoothly (meaning, making as few edits to the code as possible) over to a Linux system so that it can be compiled into an executable and run.</strong></p>
<p><strong>Based on the answers I've received I can see that there is a misunderstanding. Therefore, I'm going to break this question into two separate questions. One being my original (revised question) and the other being my specific issues and how to fix it. (I'll add the links to this question once they're posted).</strong></p>
<p><em>Note: I'm pretty new to C++ and compiling with makefiles.</em></p>
<p>I've been creating a C++ program that will run on a Linux server and so far I've been using Visual Studio (<strong><em>Window's current release</em></strong>) to write all the code. To be safe, before I started writing my program I attempted to create some basic C++ files in VC, transfer them over to my server then compile them with g++ and run the executable. Everything worked out so I thought:</p>
<p><em>"Hey, I can go ahead and write my <strong>entire</strong> program, follow the same process and everything will be fine!"</em></p>
<p>Clearly, I was <strong>wrong</strong> and that's why I'm here.</p>
<p>When I run my makefile I get dozens of errors and I'm not exactly sure how to approach the situation. A large number of the error messages seem to be hinting at my use of vectors (which of course, run fine when compiling with VC).</p>
<p>I've had a look at the following questions: </p>
<p><a href="https://stackoverflow.com/questions/9171414/how-to-compile-in-visual-studio-2010-for-linux">How to compile in Visual Studio 2010 for Linux</a></p>
<p><a href="https://stackoverflow.com/questions/3298053/port-visual-studio-c-to-linux?rq=1">Port Visual Studio C++ to Linux</a></p>
<p><a href="https://stackoverflow.com/questions/11183217/compiling-visual-c-code-in-linux">Compiling Visual C++ code in Linux?</a></p>
<p>But I can't really find a direct solution to my issue (for example I'd prefer to avoid installing VC on a Linux platform and just working from there).</p>
<p>I've also looked into (<em>and tried using</em>) <a href="https://www.winehq.org/docs/winegcc" rel="noreferrer">wineg++</a> but it didn't seem to change anything upon compilation.</p>
<p><strong>How should I go about this issue?</strong></p>
<p><strong>Meaning: Is it common practice to develop on Windows VC then port over to Linux? If so, is there a standard way of ensuring that everything goes smoothly? Or is it just a matter of knowing how your compiler on Linux works and coding appropriately so that no errors occur?</strong></p>
<p>Preferably a solution that allows me to keep developing on Windows and simply port over everything to Linux when I'm done. Also if possible, try to make any answers as simple as possible, I'm still very amateur when it comes to most of this stuff.</p>
<p><em>Edit: I'd also like to mention that I'm not really using any crazy libraries. Just <strong>math.h</strong> and <strong>vector</strong>.</em></p>
<p>Some examples of errors are:</p>
<p>Initializing a vector with some doubles:</p>
<p><a href="https://i.stack.imgur.com/2RL3E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2RL3E.png" alt="enter image description here"></a></p>
<p>Corresponding compilation error:</p>
<p><a href="https://i.stack.imgur.com/62LJS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/62LJS.png" alt="enter image description here"></a></p>
| 0 |
Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
|
<p>Using <code>pip install</code> for any module apparently on my Ubuntu 16.04 system with python 2.7.11+ throws this error:</p>
<pre><code>TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
</code></pre>
<p>What is wrong with pip? How could I reinstall it, if necessary?</p>
<p>Update: Full traceback is below</p>
<pre><code>sunny@sunny:~$ pip install requests
Collecting requests
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 328, in run
wb.build(autobuilding=True)
File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 748, in build
self.requirement_set.prepare_files(self.finder)
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 360, in prepare_files
ignore_dependencies=self.ignore_dependencies))
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 512, in _prepare_file
finder, self.upgrade, require_hashes)
File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 273, in populate_link
self.link = finder.find_requirement(self, upgrade)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 442, in find_requirement
all_candidates = self.find_all_candidates(req.name)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 400, in find_all_candidates
for page in self._get_pages(url_locations, project_name):
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 545, in _get_pages
page = self._get_page(location)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 648, in _get_page
return HTMLPage.get_page(link, session=self.session)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 757, in get_page
"Cache-Control": "max-age=600",
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get
return self.request('GET', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 378, in request
return super(PipSession, self).request(method, url, *args, **kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in request
resp = self.send(prep, **send_kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 576, in send
r = adapter.send(request, **kwargs)
File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 46, in send
resp = super(CacheControlAdapter, self).send(request, **kw)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 376, in send
timeout=timeout
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 610, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 228, in increment
total -= 1
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
</code></pre>
| 0 |
How to allow POST method with Flask?
|
<p>I'm doing a web Flask app with "sign up" and "log in" functions. I'd like to use a POST method for the "sign up" function, like this:</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Index"
@app.route("/signup/<username>,<password>" , methods = ['POST'])
def signup(username, password):
return "Hello %s ! Your pw is %s" % (username,password)
if __name__== "__main__":
app.run(debug=True)
</code></pre>
<p>But when I ran it, I received this error : "Method not allowed. The method is not allowed for the requested URL."</p>
<p>How can I do? Thanks in advance.</p>
| 0 |
Android Studio getting "Must implement OnFragmentInteractionListener"
|
<p>I'm getting a throw that says "Must implement OnFragmentInteractionListener, and I already have it...</p>
<p>I've looked at every question asked here, and no one helped me.</p>
<p>Could anyone please help me?</p>
<p>ERROR:</p>
<pre><code>FATAL EXCEPTION: main
Process: com.example.android.navigationdrawer, PID: 5916
java.lang.RuntimeException: com.example.android.navigationdrawer.MainActivity@3aefae64 must implement OnFragmentInteractionListener
at com.example.android.navigationdrawer.FragmentCamera.onAttach(FragmentCamera.java:83)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
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:5930)
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:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
</code></pre>
<p>MAINACTIVITY (extending to OnFragmentInteractionListener)</p>
<pre><code>package com.example.android.navigationdrawer;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentCamera.OnFragmentInteractionListener {
</code></pre>
<p>MAINACTIVITY (FragmentCamera @Override)</p>
<pre><code>@Override
public void onFragmentInteraction(Uri uri) {
}
</code></pre>
<p>MAINACTIVITY (ONCREATE)</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
</code></pre>
<p>MAINACTIVITY (FRAGMENT TRANSACTION)</p>
<pre><code> boolean FragmentTransaction = false;
Fragment fragment = null;
//Camera
if (id == R.id.nav_camera) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
ImageView mImageView = (ImageView) findViewById(R.id.Galley1);
//Galley
} else if (id == R.id.nav_gallery) {
fragment = new FragmentCamera();
FragmentTransaction = true;
}
</code></pre>
<p>...</p>
<pre><code> if(FragmentTransaction) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.drawer_layout, fragment)
.commit();
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
}
</code></pre>
<p>FRAGMENTCAMERA</p>
<pre><code>package com.example.android.navigationdrawer;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link FragmentCamera.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FragmentCamera#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentCamera 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";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentCamera() {
// 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 FragmentCamera.
*/
// TODO: Rename and change types and number of parameters
public static FragmentCamera newInstance(String param1, String param2) {
FragmentCamera fragment = new FragmentCamera();
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
return inflater.inflate(R.layout.fragment_camera, container, false);
}
// 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.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
</code></pre>
<p>If you need some more code, comment and I will add it!</p>
| 0 |
Why doesn't C++ use std::nested_exception to allow throwing from destructor?
|
<p>The main problem with throwing exceptions from destructor is that in the moment when destructor is called another exception may be "in flight" (<code>std::uncaught_exception() == true</code>) and so it is not obvious what to do in that case. "Overwriting" the old exception with the new one would be the one of the possible ways to handle this situation. But it was decided that <code>std::terminate</code> (or another <code>std::terminate_handler</code>) must be called in such cases.</p>
<p>C++11 introduced nested exceptions feature via <code>std::nested_exception</code> class. This feature could be used to solve the problem described above. The old (uncaught) exception could be just nested into the new exception (or vice versa?) and then that nested exception could be thrown. But this idea was not used. <code>std::terminate</code> is still called in such situation in C++11 and C++14.</p>
<p>So the questions. Was the idea with nested exceptions considered? Are there any problems with it? Isn't the situation going to be changed in the C++17?</p>
| 0 |
Why isn't the command "cmake ." generating a makefile?
|
<p>I run <code>cmake .</code> in terminal and it says it generated something, then I run <code>make</code> and it says </p>
<pre><code>make: *** No targets specified and no makefile found. Stop.
</code></pre>
<p>I'm guessing I've missed something else that I need to do but I can't figure out what. It should have created a make file that I can then build and then install.</p>
<p>If I'm being too vague please let me know what more I can add to this question.</p>
<p><strong>* edit *</strong></p>
<pre><code>$ cmake .
-- Configuring done
CMake Warning (dev):
Policy CMP0042 is not set: MACOSX_RPATH is enabled by default. Run "cmake
--help-policy CMP0042" for policy details. Use the cmake_policy command to
set the policy and suppress this warning.
MACOSX_RPATH is not specified for the following targets:
freeglut
This warning is for project developers. Use -Wno-dev to suppress it.
-- Generating done
-- Build files have been written to: /Users/nicholasl/Downloads/freeglut-3.0.0
</code></pre>
<p>**** contents of build directory ****</p>
<pre><code>$ ls
AUTHORS android
Build android_toolchain.cmake
CMakeCache.txt blackberry.toolchain.cmake
CMakeFiles cmake_install.cmake
CMakeLists.txt config.h
CMakeScripts config.h.in
COPYING doc
ChangeLog freeglut.pc
README freeglut.pc.in
README.android freeglut.rc.in
README.blackberry freeglut.xcodeproj
README.cmake include
README.cygwin_mingw mingw_cross_toolchain.cmake
README.mingw_cross progs
README.win32 src
</code></pre>
| 0 |
Does the C standard explicitly indicate truth value as 0 or 1?
|
<p>We know that any numbers that are not equal to <code>0</code> are viewed as <code>true</code> in C, so we can write:</p>
<pre><code>int a = 16;
while (a--)
printf("%d\n", a); // prints numbers from 15 to 0
</code></pre>
<p>However, I was wondering whether true / false are defined as <code>1</code>/<code>0</code> in C, so I tried the code below:</p>
<pre><code>printf("True = %d, False = %d\n", (0 == 0), (0 != 0)); // prints: True = 1, False = 0
</code></pre>
<p>Does C standard explicitly indicate the truth values of true and false as <code>1</code> and <code>0</code> respectively?</p>
| 0 |
Is it correct to return null shared_ptr?
|
<p>For example, there is a function that finds an object and returns shared_ptr if object is found, and must indicate somehow that no object was found.</p>
<pre><code>std::vector<std::shared_ptr> Storage::objects;
std::shared_ptr<Object> Storage::findObject()
{
if (objects.find)
{
return objects[x];
}
else
{
return nullptr;
}
}
std::shared_ptr<Object> obj = Storage::findObject();
if (obj)
{
print("found");
}
else
{
print("not found");
}
</code></pre>
<ol>
<li><p>Is it correct to return shared_ptr implicitly initialized with nullptr like in upper example? It will work, but can be it done this way? Or should I return shared_ptr default constructed instead?</p></li>
<li><p>What in case it would be weak_ptr? What is proper way to check that empty weak_ptr has been returned? by weak_ptr::expired function or are there other ways? If checking by weak_ptr::expired is the only way then how can I distinguish that function returned empty pointer, or object was just deleted(multi-thread environment)?</p></li>
</ol>
| 0 |
Telnet - Connection to host lost - on port 1099 in local machine
|
<p>My jBoss server is running on the port 1099. While I am trying to telnet the port from the local machine, getting the "Connection to host lost" message. I was doing</p>
<blockquote>
<p>telnet 192.168.200.150 1099</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/8dExl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8dExl.png" alt="enter image description here" /></a></p>
<p>Its showing some other port as 8083. What this error message means?</p>
| 0 |
Python error importing dateutil
|
<p>I try to execute marathon-lb.py and it throws the next error:</p>
<pre><code>Traceback (most recent call last):
File "./marathon_lb.py", line 46, in <module>
import dateutil.parser
ImportError: No module named 'dateutil'
</code></pre>
<p>I just install python with apt and with pip.
I have run:</p>
<pre><code>sudo apt-get install python-pip
pip install python-dateutil
</code></pre>
<p>I compile the script with: python -m py_compile script.py</p>
<p>python application:</p>
<pre><code>from operator import attrgetter
from shutil import move
from tempfile import mkstemp
from wsgiref.simple_server import make_server
from six.moves.urllib import parse
from itertools import cycle
from common import *
from config import *
from lrucache import *
from utils import *
import argparse
import json
import logging
import os
import os.path
import stat
import re
import requests
import shlex
import subprocess
import sys
import time
import dateutil.parser
</code></pre>
| 0 |
Is using an outdated C compiler a security risk?
|
<p>We have some build systems in production which no one cares about and these machines run ancient versions of GCC like GCC 3 or GCC 2.</p>
<p>And I can't persuade the management to upgrade it to a more recent: they say, "if ain't broke, don't fix it". </p>
<p>Since we maintain a very old code base (written in the 80s), this C89 code compiles just fine on these compilers. </p>
<p>But I'm not sure it is good idea to use these old stuff.</p>
<p>My question is:</p>
<p>Can using an old C compiler compromise the security of the compiled program? </p>
<p>UPDATE:</p>
<p>The same code is built by Visual Studio 2008 for Windows targets, and MSVC doesn't support C99 or C11 yet (I don't know if newer MSVC does), and I can build it on my Linux box using the latest GCC. So if we would just drop in a newer GCC it would probably build just as fine as before.</p>
| 0 |
-ms-transform not working with IE 11
|
<p>Adding <code>-ms-transform:rotate(90deg)</code> dynamically using jQuery to the element. But, its not working in IE 11. However, <code>-webkit-transform:rotate(90deg)</code> is working in Chrome. </p>
<p>No transformation is happening on page. </p>
<p>Added meta :</p>
<pre><code><meta http-equiv=X-UA-Compatible content="IE=9;IE=10;IE=11;IE=Edge,chrome=1">
</code></pre>
<p><a href="https://i.stack.imgur.com/YNgnj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YNgnj.png" alt="enter image description here"></a></p>
| 0 |
Getting "SSL_connect returned=1 errno=0 state=error: certificate verify failed" when connecting to S3
|
<p>I have been trying to upload a photo to my AWS bucket, but running into the error mentioned in the title. I understand that it most likely has to do with my OpenSSL certificates, but any suggested solution that I have tried has failed thus far.</p>
<p>I am running into this issue with ruby 2.3.1, Rails 4.1.8, aws-sdk-core 2.3.4, and carrierwave 0.11.0 on OSX Yosemite.</p>
<p>I have tried all available found at this similar issue as well, as others (this one being with Windows): <a href="https://github.com/aws/aws-sdk-core-ruby/issues/166#issuecomment-111603660" rel="noreferrer">https://github.com/aws/aws-sdk-core-ruby/issues/166#issuecomment-111603660</a></p>
<p>Here are some of my files:</p>
<p>carrierwave.rb</p>
<pre><code>CarrierWave.configure do |config| # required
config.aws_credentials = {
access_key_id: Rails.application.secrets.aws_access_key_id, # required
secret_access_key: Rails.application.secrets.aws_access_key, # required
region: 'eu-west-2' # optional, defaults to 'us-east-1'
}
config.aws_bucket = Rails.application.secrets.aws_bucket # required
config.fog_attributes = { 'Cache-Control' => "max-age=#{365.day.to_i}" } # optional, defaults to {}
end
</code></pre>
<p>avatar_uploader.rb</p>
<pre><code>class AvatarUploader < CarrierWave::Uploader::Base
storage :aws
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
</code></pre>
<p>EDIT (more info):</p>
<pre><code>stack trace:
Seahorse::Client::NetworkingError - SSL_connect returned=1 errno=0 state=error: certificate verify failed:
/Users/stevenharlow/.rbenv/versions/2.3.1/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock'
/Users/stevenharlow/.rbenv/versions/2.3.1/lib/ruby/2.3.0/net/http.rb:933:in `connect'
/Users/stevenharlow/.rbenv/versions/2.3.1/lib/ruby/2.3.0/net/http.rb:863:in `do_start'
/Users/stevenharlow/.rbenv/versions/2.3.1/lib/ruby/2.3.0/net/http.rb:858:in `start'
/Users/stevenharlow/.rbenv/versions/2.3.1/lib/ruby/2.3.0/delegate.rb:83:in `method_missing'
aws-sdk-core (2.3.4) lib/seahorse/client/net_http/connection_pool.rb:292:in `start_session'
aws-sdk-core (2.3.4) lib/seahorse/client/net_http/connection_pool.rb:104:in `session_for'
aws-sdk-core (2.3.4) lib/seahorse/client/net_http/handler.rb:109:in `session'
</code></pre>
<p>Solutions tried:</p>
<ul>
<li>Aws.use_bundled_cert!</li>
<li>Download cert and reference manually</li>
<li>I tried using Fog instead of carrierwave-aws</li>
<li>Tried reinstalling ruby after upgrading rbenv</li>
</ul>
<p>Here's the result of </p>
<pre><code>CONNECTED(00000003)
depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Baltimore CA-2 G2
verify error:num=20:unable to get local issuer certificate
verify return:0
---
Certificate chain
0 s:/C=US/ST=Washington/L=Seattle/O=Amazon.com Inc./CN=*.s3-us-west-2.amazonaws.com
i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Baltimore CA-2 G2
1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert Baltimore CA-2 G2
i:/C=IE/O=Baltimore/OU=CyberTrust/CN=Baltimore CyberTrust Root
---
<certificate info>
No client certificate CA names sent
---
SSL handshake has read 2703 bytes and written 456 bytes
---
New, TLSv1/SSLv3, Cipher is AES128-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1
Cipher : AES128-SHA
Session-ID: <session-id>
Session-ID-ctx:
Master-Key: <master-key>
Key-Arg : None
Start Time: 1463697130
Timeout : 300 (sec)
Verify return code: 0 (ok)
</code></pre>
| 0 |
How to generate very Large random number in c++
|
<p>I want to generate very large random number in range of 0 - 2^64 using c++. I have used the rand() function but it is not generating very large number. Can any one help?</p>
| 0 |
Why does C not allow concatenating strings when using the conditional operator?
|
<p>The following code compiles without problems:</p>
<pre><code>int main() {
printf("Hi" "Bye");
}
</code></pre>
<p>However, this does not compile:</p>
<pre><code>int main() {
int test = 0;
printf("Hi" (test ? "Bye" : "Goodbye"));
}
</code></pre>
<p>What is the reason for that?</p>
| 0 |
Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUs
|
<p>I've been racking my brain for a week trying to complete this assignment and I'm hoping someone here can lead me toward the right path. Let me start with the instructor's instructions:</p>
<blockquote>
<p>Your assignment is the opposite of our first lab assignment, which was to optimize a prime number program. Your purpose in this assignment is to pessimize the program, i.e. make it run slower. Both of these are CPU-intensive programs. They take a few seconds to run on our lab PCs. You may not change the algorithm.</p>
<p>To deoptimize the program, use your knowledge of how the Intel i7 pipeline operates. Imagine ways to re-order instruction paths to introduce WAR, RAW, and other hazards. Think of ways to minimize the effectiveness of the cache. Be diabolically incompetent.</p>
</blockquote>
<p>The assignment gave a choice of Whetstone or Monte-Carlo programs. The cache-effectiveness comments are mostly only applicable to Whetstone, but I chose the Monte-Carlo simulation program:</p>
<pre><code>// Un-modified baseline for pessimization, as given in the assignment
#include <algorithm> // Needed for the "max" function
#include <cmath>
#include <iostream>
// A simple implementation of the Box-Muller algorithm, used to generate
// gaussian random numbers - necessary for the Monte Carlo method below
// Note that C++11 actually provides std::normal_distribution<> in
// the <random> library, which can be used instead of this function
double gaussian_box_muller() {
double x = 0.0;
double y = 0.0;
double euclid_sq = 0.0;
// Continue generating two uniform random variables
// until the square of their "euclidean distance"
// is less than unity
do {
x = 2.0 * rand() / static_cast<double>(RAND_MAX)-1;
y = 2.0 * rand() / static_cast<double>(RAND_MAX)-1;
euclid_sq = x*x + y*y;
} while (euclid_sq >= 1.0);
return x*sqrt(-2*log(euclid_sq)/euclid_sq);
}
// Pricing a European vanilla call option with a Monte Carlo method
double monte_carlo_call_price(const int& num_sims, const double& S, const double& K, const double& r, const double& v, const double& T) {
double S_adjust = S * exp(T*(r-0.5*v*v));
double S_cur = 0.0;
double payoff_sum = 0.0;
for (int i=0; i<num_sims; i++) {
double gauss_bm = gaussian_box_muller();
S_cur = S_adjust * exp(sqrt(v*v*T)*gauss_bm);
payoff_sum += std::max(S_cur - K, 0.0);
}
return (payoff_sum / static_cast<double>(num_sims)) * exp(-r*T);
}
// Pricing a European vanilla put option with a Monte Carlo method
double monte_carlo_put_price(const int& num_sims, const double& S, const double& K, const double& r, const double& v, const double& T) {
double S_adjust = S * exp(T*(r-0.5*v*v));
double S_cur = 0.0;
double payoff_sum = 0.0;
for (int i=0; i<num_sims; i++) {
double gauss_bm = gaussian_box_muller();
S_cur = S_adjust * exp(sqrt(v*v*T)*gauss_bm);
payoff_sum += std::max(K - S_cur, 0.0);
}
return (payoff_sum / static_cast<double>(num_sims)) * exp(-r*T);
}
int main(int argc, char **argv) {
// First we create the parameter list
int num_sims = 10000000; // Number of simulated asset paths
double S = 100.0; // Option price
double K = 100.0; // Strike price
double r = 0.05; // Risk-free rate (5%)
double v = 0.2; // Volatility of the underlying (20%)
double T = 1.0; // One year until expiry
// Then we calculate the call/put values via Monte Carlo
double call = monte_carlo_call_price(num_sims, S, K, r, v, T);
double put = monte_carlo_put_price(num_sims, S, K, r, v, T);
// Finally we output the parameters and prices
std::cout << "Number of Paths: " << num_sims << std::endl;
std::cout << "Underlying: " << S << std::endl;
std::cout << "Strike: " << K << std::endl;
std::cout << "Risk-Free Rate: " << r << std::endl;
std::cout << "Volatility: " << v << std::endl;
std::cout << "Maturity: " << T << std::endl;
std::cout << "Call Price: " << call << std::endl;
std::cout << "Put Price: " << put << std::endl;
return 0;
}
</code></pre>
<p>The changes I have made seemed to increase the code running time by a second but I'm not entirely sure what I can change to stall the pipeline without adding code. A point to the right direction would be awesome, I appreciate any responses.</p>
<hr />
<h2>Update: <a href="https://meta.stackoverflow.com/a/323690/224132">the professor who gave this assignment posted some details</a></h2>
<p>The highlights are:</p>
<ul>
<li>It's a second semester architecture class at a community college (using the Hennessy and Patterson textbook).</li>
<li>the lab computers have Haswell CPUs</li>
<li>The students have been exposed to the <code>CPUID</code> instruction and how to determine cache size, as well as intrinsics and the <code>CLFLUSH</code> instruction.</li>
<li>any compiler options are allowed, and so is inline asm.</li>
<li>Writing your own square root algorithm was announced as being outside the pale</li>
</ul>
<p>Cowmoogun's comments on the meta thread indicate that <a href="https://meta.stackoverflow.com/questions/323603/is-it-possible-for-some-too-broad-questions-to-be-exceptions-to-the-rule/323690#comment347466_323612">it wasn't clear compiler optimizations could be part of this, and assumed <code>-O0</code></a>, and that a 17% increase in run-time was reasonable.</p>
<p>So it sounds like the goal of the assignment was to get students to re-order the existing work to reduce instruction-level parallelism or things like that, but it's not a bad thing that people have delved deeper and learned more.</p>
<hr />
<p>Keep in mind that this is a computer-architecture question, not a question about how to make C++ slow in general.</p>
| 0 |
Create an exe file in assembly with NASM on 32-bit Windows
|
<p>I'm making a hello world program in assembly language with <em>NASM</em> on 32-bit <em>Windows 7</em>. My code is:</p>
<pre><code>section .text
global main ;must be declared for linker (ld)
main: ;tells linker entry point
mov edx,len ;message length
mov ecx,msg ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db 'Hello, world!', 0xa ;our dear string
len equ $ - msg ;length of our dear string
</code></pre>
<p>I save this program as <strong>hello.asm</strong>. Next, I created <strong>hello.o</strong> with: </p>
<pre><code>nasm -f elf hello.asm
</code></pre>
<p>Now I'm trying to create the <strong>exe</strong> file with this command: </p>
<pre><code>ld -s -o hello hello.o
</code></pre>
<p>But now I receive this error:</p>
<blockquote>
<p>ld is not recognized as an internal or external command, operable program or batch</p>
</blockquote>
<p>Why am I getting this error, and how can I fix it?</p>
| 0 |
Type 'uint32_t' could not be resolved
|
<p>I am working on a C++ program in Eclipse (3.8.1) CDT. I am using the gcc compiler on Debian 8. I'm also using an open source library called opendnp3 written in C++, which requires <strong>uint32_t</strong> to resolve as it's a parameter in several method calls and constructors.</p>
<p>In the opendnp objects, intellisense doesnt list </p>
<p><code>__uint32_t</code> however, DOES resolve.</p>
<p>The type is defined in <code><cstdint></code> (<code><cstdint></code> resolves just fine). I can open the declaration and clearly see '<code>using ::uint32_t;</code>' in there.</p>
<p>In my searching, I've added <code>-std=c++11</code> to 'All options' under 'C/C++ Build --> Settings -> Tool Settings -> GCC C++ Compiler' and I've also rebuilt the project index and restarted Eclipse, but it still doesn't resolve. </p>
<p>Here's the code so far: <strong>Edited to a simple HelloWorld project to help diagnose problem</strong></p>
<pre><code>#include <iostream>
#include <cstdint> //has uint32_t defined
using namespace std;
int main() {
__uint32_t t = 0; //resolves just fine
uint32_t i = 0; //Type could not be resolved
auto x = "123"; //C++ 11 working
cout << "Foo!" << endl; // prints Foo!
return 0;
}
</code></pre>
<p>CDT Console after a build attempt:</p>
<p>23:10:52 **** Incremental Build of configuration Debug for project FOO ****
make all
make: Nothing to be done for 'all'.</p>
<p>23:10:52 Build Finished (took 133ms)</p>
| 0 |
how does visual foxpro handle date calculation? (comming from java) result for date()-day(date())+1 operation?
|
<p>what is the correct value for the formula date()-day(date())+1?</p>
<p>if date() returns '2016/5/5'</p>
<p>is it, 2016/5/1? or 2016/4/29?</p>
<p>because when converting code from visual foxpro to java?</p>
<p>following code produces different result.</p>
<pre><code>Calendar today2 = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE));
endDate.add(Calendar.DATE, 1);
</code></pre>
<p>above code produces 2016/5/1, while:</p>
<pre><code>Calendar today2 = Calendar.getInstance();
today2.add(Calendar.DATE, 1);
Calendar endDate = Calendar.getInstance();
endDate.add(Calendar.DATE, -1 * today2.get(Calendar.DATE));
</code></pre>
<p>above code produces 2016/4/29.</p>
<p>not sure which conversion is correct?</p>
| 2 |
NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier MealTableViewCell - must register a nib
|
<p>I was doing the apple guide for <strong>Swift</strong>, and I came across an error saying:</p>
<pre><code> "NSInternalInconsistencyException', reason: 'unable to dequeue a
cell with identifier MealTableViewCell - must register a nib or
a class for the identifier or connect a prototype cell in a storyboard".
</code></pre>
<p>How do I fix it?</p>
| 2 |
InstallShield LE - relative paths for files in solution folder That are not part of content files
|
<p>I am creating a setup from InstallShield LE. My setup contains files that are in solution folder but not part of content files.
E.g. My solution Folder is <em>C:\MyProject\Project1\Dev</em>
And Files I want to add too InstallShield LE setup is at: <em>C:\MyProject\CommonFiles\Libraries</em>
So the path <strong>C:\MyProject</strong> is common and some developer can have this path as <strong>D:\MyProject</strong>. So I want to add relative path for <em>C:\MyProject\CommonFiles\Libraries</em> (Something like <em>....\CommonFiles\Libraries</em>). I tried editing .isl file of InstallShield LE but its not working.
There is a table named "ISPathVariable" but I am not sure that about how to use it for relative path.
Anyone got any ideas?</p>
| 2 |
Symfony3 Export To Production
|
<p>I have a server running on apache2 with some virtual hosts and I want to deploy a Symfony3 application on it. However, I cannot deploy it correctly to the production environment, it works perfectly on development environment. Whenever I do execute</p>
<pre><code>sudo composer install --no-dev --optimize-autoloader
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>PHP Fatal error: Class 'Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle' not found in /my/path/app/AppKernel.php on line 25
Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-install-cmd event terminated with an exception</p>
</blockquote>
<pre><code>[RuntimeException]
An error occurred when executing the "'cache:clear --no-warmup'" command: PHP Fatal error: Class 'Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle'not found in /my/path/app/AppKernel.php on line 25.
</code></pre>
<p>After getting this error I went to read the documentation again and it said that I need to export this the Symfony environment to production. So I did that:</p>
<pre><code>export SYMFONY_ENV=prod
</code></pre>
<p>After that I executed the <code>composer install</code> command again but, same results.</p>
<p>Some people on Stackoverflow (and other sources) said that I need to clear my cache by executing</p>
<pre><code>sudo bin/console cache:clear --env=prod
</code></pre>
<p>So I did that but same results. Anyone any idea?</p>
<p>Other solutions tried:
Actually it works great whenever I execute the command this way:</p>
<pre><code>sudo SYMFONY_ENV=prod composer install --no-dev --optimize-autoloader
</code></pre>
<p>However, whenever everything was installed correctly, I went to try to visit the URL and I got a 500. So I went to the Apache2 logs to check if something was wrong and I saw the same <code>RuntimeException</code> again.</p>
<p><strong>EDIT</strong></p>
<p>So I've also followed the instructions of this <a href="http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup" rel="nofollow noreferrer">link</a> but unfortunately, same results. I also checked if I've got everything installed correctly such as ACL and I did.</p>
<p>I also did an <code>getfacl /my/path/var/cache</code> and it showed the correct information based on this <a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-a-symfony-application-to-production-on-ubuntu-14-04" rel="nofollow noreferrer">link</a>.</p>
<p><strong>EDIT #2</strong></p>
<p>I've also already run <code>php bin/symfony_requirements</code> and it showed me that 'My system is ready to run Symfony Projects', even after <code>php bin/console cache:clear --env=prod --no-debug</code></p>
| 2 |
Espresso openActionBarOverflowOrOptionsMenu causes NoMatchingViewException
|
<p>I have just started experimenting with the Espresso testing framework for Android and the first thing I wanted to do was click the "Settings" button in an activity's options menu. However, when I try to call <code>openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext())</code> the test crashes with this exception</p>
<pre><code>android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: ((is displayed on the screen to the user and with content description: is "More options") or (is displayed on the screen to the user and with class name: a string ending with "OverflowMenuButton"))
View Hierarchy:
+>DecorView{id=-1, visibility=VISIBLE, width=800, height=1232, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->LinearLayout{id=-1, visibility=VISIBLE, width=800, height=1232, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
+-->ViewStub{id=16909074, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
|
+-->FrameLayout{id=16908290, res-name=content, visibility=VISIBLE, width=800, height=1207, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=25.0, child-count=1}
|
+--->RelativeLayout{id=-1, visibility=VISIBLE, width=800, height=1207, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=9}
|
+---->ImageView{id=2131361813, res-name=main_logo, desc=logo, visibility=VISIBLE, width=768, height=158, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=16.0, y=36.0}
|
+---->Button{id=2131361814, res-name=main_new_button, visibility=INVISIBLE, width=210, height=48, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=295.0, y=232.0, text=New forest, input-type=0, ime-target=false, has-links=false}
|
+---->Button{id=2131361815, res-name=main_load_button, visibility=VISIBLE, width=210, height=48, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=true, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=295.0, y=310.0, text=Load forest, input-type=0, ime-target=true, has-links=false}
|
+---->Button{id=2131361816, res-name=satform_download_button, visibility=VISIBLE, width=210, height=48, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=295.0, y=388.0, text=Download, input-type=0, ime-target=false, has-links=false}
|
+---->Button{id=2131361817, res-name=main_resume_button, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=Continue, input-type=0, ime-target=false, has-links=false}
|
+---->ToggleButton{id=2131361818, res-name=marking_mode_toggle, visibility=VISIBLE, width=223, height=48, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=288.0, y=466.0, text=Auto Marking RFID mode, input-type=0, ime-target=false, has-links=false, is-checked=false}
|
+---->ProgressBar{id=2131361819, res-name=progress_bar, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
|
+---->TextView{id=2131361820, res-name=progress_text, visibility=GONE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, text=Please wait…, input-type=0, ime-target=false, has-links=false}
|
+---->TextView{id=2131361821, res-name=version_text, visibility=VISIBLE, width=210, height=25, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=295.0, y=1128.0, text=version:0.7.0, input-type=0, ime-target=false, has-links=false}
|
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:579)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:82)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:53)
at android.support.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:184)
at android.support.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:115)
at android.support.test.espresso.ViewInteraction.perform(ViewInteraction.java:87)
at android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu(Espresso.java:214)
at com.treemetrics.treedegrees.TestBluetoothPeripheralDialog.openOverflowMenu(TestBluetoothPeripheralDialog.java:28)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:257)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:54)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:240)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1710)
</code></pre>
<p>The options menu is initialised in the activity like this</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_comp_activity, menu);
this.menu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_rfid:
toggleRfid(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MainApplication.debugOut(true, 2, TAG, getString(R.string.called_on_prepare_options_menu));
if (RfidBtService.isRunning){
menu.findItem(R.id.action_rfid).setTitle(R.string.action_rfid_off);
menu.findItem(R.id.action_rfid).setIcon(R.drawable.bt_rfid);
}else{
menu.findItem(R.id.action_rfid).setTitle(R.string.action_rfid_on);
menu.findItem(R.id.action_rfid).setIcon(R.drawable.bt_rfid_on);
}
return true;
}
</code></pre>
<p>and here is the XML for the menu</p>
<pre><code><menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menuitem_saveforest"
android:onClick="saveForest"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_save_forest"/>
<item
android:id="@+id/action_sendforest"
android:onClick="sendForest"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_send_forest"/>
<item
android:id="@+id/action_settings"
android:onClick="launchSettings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/action_saveforest"
android:icon="@drawable/ic_menu_save"
android:onClick="saveForest"
android:showAsAction="always"
android:title="@string/action_save_forest"/>
<item
android:id="@+id/action_rfid"
android:icon="@drawable/bt_rfid_on"
android:onClick="toggleRfid"
android:showAsAction="ifRoom"
android:title="@string/action_rfid_on"/>
</menu>
</code></pre>
<p>Here is my test class</p>
<pre><code>@RunWith(AndroidJUnit4.class)
@SmallTest
public class TestBluetoothPeripheralDialog {
@Rule
public ActivityTestRule<ForestActivity> mActivityRule
= new ActivityTestRule<>(ForestActivity.class);
@Test
public void openOverflowMenu() {
// Open the overflow menu OR open the options menu,
// depending on if the device has a hardware or software overflow menu button.
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
// Click the item.
onView(withText("Settings"))
.perform(click());
}
}
</code></pre>
| 2 |
c# Outlook Add-in get Sent date after email is in Sent mailbox
|
<p>I have made an Outlook Add-In (Outlook 2013 and 2016 VSTO Add-In) for business purposes to save the email details to our database. The add-in is launched when a new email is composed, but closes when the email is sent.</p>
<p>The sent date of the email is only added after the email is moved to the Sent mailbox. Is there a way to use my current add-in (or another add-in) can be used to get that sent date after it has been closed without letting the user wait for it to be moved to the sent mailbox?</p>
<p>I know it can easily be done in VBA, but I want to preferably use an Add-in so that it can be easily loaded to all users with exchange server.</p>
| 2 |
Assign function return object to variable and pass it to a component as a prop
|
<p>I am having trouble doing one last thing here. I need to take the object that gets returned from the _request method and assign it to the propVals variable in the render method and then pass that variable to the channelValues prop on the SingleChannel component as you can see. My problem is that propVals is undefined when I return the SingleChannel component. I know the if statements are returning what they should be so the problem is that the SingleChannel component is being rendered before propVals recieves the object. I really have no idea what else to do. I have also tried calling the method directly from the SingleChannel component like channelValues={this._request(channel.name)}.</p>
<pre><code>_request(name) {
HTTP.call('GET', `https://api.twitch.tv/kraken/streams/${name}`,
{headers: {Accept: 'application/vnd.twitchtv.v3+json'} },
function(error, response) {
if(error) {
console.log(error)
} else {
if(response.data.stream === null) {
return {streaming: false, game: "Not playing anything"}
} else {
return {streaming: true, game: response.data.stream.game}
}
}
});
}
renderChannels() {
const channels = this.props.channels;
console.log(channels)
return channels.map((channel) => {
const propVals = this._request(channel.name);
//console.log(propVals);
return <SingleChannel key={channel._id} channel={channel} channelValues={propVals}/>
});
}
</code></pre>
| 2 |
Avoid to save an instance in a pre_save Signal without using raise Exception
|
<p>I have <strong>two models</strong>. When I save an instance from the first I need to send a field value from this Model into the other one's field.</p>
<p>First Model:</p>
<pre><code>class ModelOne(models.Model):
# fields...
quantity = models.FloatField()
</code></pre>
<p>Second Model:</p>
<pre><code>class ModelTwo(models.Model):
# fields...
quantity = models.FloatField()
</code></pre>
<p>pre_save signal:</p>
<pre><code>@receiver(pre_save, sender=ModelOne)
def verify(sender, instance, **kwargs):
# Stuff
quantity = instance.quantity
founded_model_two = ModelTwo.objects.get("""Something""")
future_result = founded_model_two.quantity - quantity
if future_result < 0:
raise Exception("Cannot be less than zero")
</code></pre>
<p><strong>I want to avoid to save the instance, but I don't want to raise an Exception</strong></p>
| 2 |
How would I format data in a PrettyTable?
|
<p>I'm getting the text from the title and href attributes from the HTML. The code runs fine and I'm able to import it all into a PrettyTable fine. The problem that I face now is that there are some titles that I believe are too large for one of the boxes in the table and thus distort the entire PrettyTable made. I've tried adjusting the hrules, vrules, and padding_width and have not found a resolution. </p>
<pre><code>from bs4 import BeautifulSoup
from prettytable import PrettyTable
import urllib
r = urllib.urlopen('http://www.genome.jp/kegg-bin/show_pathway?map=hsa05215&show_description=show').read()
soup = BeautifulSoup((r), "lxml")
links = [area['href'] for area in soup.find_all('area', href=True)]
titles = [area['title'] for area in soup.find_all('area', title=True)]
k = PrettyTable()
k.field_names = ["ID", "Active Compound", "Link"]
c = 1
for i in range(len(titles)):
k.add_row([c, titles[i], links[i]])
c += 1
print(k)
</code></pre>
<p>How I would like the entire table to display as: </p>
<pre><code>print (k.get_string(start=0, end=25))
</code></pre>
<p>If PrettyTable can't do it. Are there any other recommended modules that could accomplish this? </p>
| 2 |
How to get the directory path of a script in the shebang line
|
<p>Currently I can run a script only from the containing directory since the shebang line includes a path relative to the current directory</p>
<pre><code>#!/usr/bin/env xcrun swift -F ./Rome/ -framework Swiftline
</code></pre>
<p>How is it possible to modify the <code>"."</code> to an absolute path?</p>
<p><code>./Rome/</code> to something that will work from any directory? I've tried the following:</p>
<p><code>$0/Rome/</code> doesn't work</p>
<p><code>dirname $0</code> /Rome/ doesn't work</p>
<p><code>$1/Rome/</code> doesn't work</p>
| 2 |
How to retain Spark executor logs in Yarn after Spark application is crashed
|
<p>I am trying to find the root cause of recent Spark application failure in production. When the Spark application is running I can check NodeManager's yarn.nodemanager.log-dir property to get the Spark executor container logs.</p>
<p>The container has logs for both the running Spark applications </p>
<p>Here is the view of the container logs:
drwx--x--- 3 yarn yarn 51 Jul 19 09:04 application_1467068598418_0209
drwx--x--- 5 yarn yarn 141 Jul 19 09:04 application_1467068598418_0210</p>
<p>But when the application is killed both the application logs are automatically deleted. I have set all the log retention setting etc in Yarn to a very large number. But still these logs are deleted as soon as the Spark applications are crashed.</p>
<p>Question: How can we retain these Spark application logs in Yarn for debugging when the Spark application is crashed for some reason.</p>
| 2 |
How to add a specific item's image as a background image in rails
|
<p>This one is frustrating me. I'm using paperclip for the images, and adding them to the model <code>offer</code> That's fine. My problem is adding them in as a background image on the index page for <code>offer</code> So my code looks like this:</p>
<pre><code><div class="product-image"></div>
<style>
.product-image {
width: 50%;
height: 200px;
margin-left: 25%;
border-radius: 50%;
background-image: url(<%= image_tag offer.image %>);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
</style>
</code></pre>
<p>When I inspect it on chrome, the code looks like this: </p>
<pre><code>background-image: url(<img src="/system/offers/images/000/000/033/original/headphones.jpg?1468610654" alt="Headphones" />);
</code></pre>
<p>Anybody know a fix? Like I said, the images are working fine. If I simply put a line of code in as <code><%= image_tag offer.image %></code>, the image shows. Help is very much appreciated.</p>
| 2 |
Protractor: browser.wait function, isElementPresent times out
|
<p>Here is my code. For some reason it cannot detect the element present, and just times out. Site is in angular. I have tried isPresent, as well as ExpectedConditions and it times out nonetheless. For some reason, it just cannot detect the element no matter how I try to locate it. I have tried multiple elements as well. I'm open to any ideas.</p>
<pre><code> browser.wait(function()
{
return browser.isElementPresent(by.xpath('//[@id="ngdialog1"]/div[2]/div/div')).then(function(present)
{
console.log('\n' + 'looking for element')
if(present)
{
console.log('\n' + 'recognized dialog');
var jccSelect = element(by.xpath('//*[@id="ghId_GameSelectBottomRow"]/div[1]'));
jccSelect.click();
return true;
}
})}, 50000);
</code></pre>
<p>});</p>
| 2 |
Mix python output and markdown in jupyter
|
<p>I want to be able to show the result of a python computation and have some explanation of it in Markdown. This seems like a fairly simple operation, but I can't figure out how to do it.
Is there any way to do this without installing any extensions to Jupyter?</p>
| 2 |
pickadate.js not working at all
|
<p>Trying to learn how to use this plugin, but I can't seem to make anything work at all. Can someone point me in the right direction? This is a laravel project, but that shouldn't make much difference. </p>
<p>Here is my html:</p>
<pre><code><p><input id="date" class="form-control" ng-model="currentWimDate" placeholder="Date..." type="text"></p>
</code></pre>
<p>and my index.blade.php:</p>
<pre><code><html lang="en" ng-app="wim">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WIM(afy)</title>
<link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="css/wimmain.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="bower_components/pickadate/lib/themes/default.css" id="theme_base">
<link rel="stylesheet" href="bower_components/pickadate/lib/themes/default.date.css" id="theme_date">
<link rel="stylesheet" href="bower_components/pickadate/lib/themes/default.time.css" id="theme_time">
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/ng-file-upload-shim/ng-file-upload-shim.min.js"></script>
<script src="bower_components/ng-file-upload/ng-file-upload.min.js"></script>
<script src="bower_components/lodash/lodash.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="bower_components/angular-local-storage/dist/angular-local-storage.min.js"></script>
<script src="bower_components/restangular/dist/restangular.min.js"></script>
<script src = "js/app.js"></script>
<script src = "js/services.js"></script>
<script src = "js/controllers.js"></script>
<script src = "js/checkPass.js"></script>
<script src = "js/signupValidation.js"></script>
<script src = "js/dropdown.js"></script>
<script src = "js/profileActions.js"></script>
<style>
li {
padding-bottom: 8px;
}
</style>
</head>
<body style="background-color: #ef5350;">
<div ng-view></div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="bower_components/pickadate/lib/picker.js"></script>
<script src="bower_components/pickadate/lib/picker.date.js"></script>
<script src="bower_components/pickadate/lib/picker.time.js"></script>
<script type="text/javascript">
// PICKADATE FORMATTING
$('#date').pickadate({
format: 'mmmm d, yyyy', // Friendly format displayed to user
formatSubmit: 'mm/dd/yyyy', // Actual format used by application
hiddenName: true // Allows two different formats
});
</script>
</body>
</code></pre>
<p></p>
<p>What am I doing wrong here? </p>
| 2 |
How do I specify an index for Elasticsearch using NEST?
|
<p>If I run the code below it will create a mapping on ALL indices, which I don't want. I am unable to find the documentation for specifying just the index I want.<br>
How do I specify which index to apply this mapping to?</p>
<pre><code>var client = new ElasticClient();
var response = client.Map<Company>(m => m
.Properties(props => props
.Number(n => n
.Name(p => p.ID)
.Type(NumberType.Integer)
)
)
);
</code></pre>
| 2 |
Change text style programmatically
|
<p>I want to change the text style to bold when user checks the bold checkbox but I am unable to do that. Text appears normally even after selecting the checkbox.</p>
<pre><code><EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:gravity="top"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bold"
android:id="@+id/bold"
android:layout_alignBottom="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="57dp"
android:checked="false" />
</RelativeLayout>
</code></pre>
<p>MainActivity</p>
<pre><code>public class MainActivity extends AppCompatActivity {
CheckBox checkBox;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText= (EditText) findViewById(R.id.editText);
checkBox=(CheckBox)findViewById(R.id.bold);
if(checkBox.isChecked())
editText.setTypeface(editText.getTypeface(), Typeface.BOLD);
}
...
}
</code></pre>
| 2 |
How do I display a title on mouse hover on an angularjs expression rendered on html page?
|
<p>I have a section in my HTML page as follows:</p>
<pre><code><div ng-app="" ng-init="patient={firstName:'John',lastName:'Doe'}">
<p>{{ patient.firstName}} | {{ patient.lastName }}</p>
</div>
</code></pre>
<p>It is displayed in the form of a tile and needs to display the rendered text on mouse hover in a tooltip.</p>
<p>I have used <code>text-overflow: ellipsis</code>, in my CSS to display <code>(...)</code> in case the text length exceeds my span size.</p>
<p>Any suggestions are highly appreciated. Thanks in advance.</p>
| 2 |
Run TextView marquee after some time
|
<p>How can I run a text marquee in the <code>TextView</code> with delay before start?<br>
At this moment I use the next code to start:</p>
<pre><code>mTVTitle.postDelayed(new Runnable() {
@Override
public void run() {
mTVTitle.setFocusableInTouchMode(true);
mTVTitle.invalidate();
}
}, 1000);
</code></pre>
<p><code>TextView</code> xml:</p>
<pre><code><TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:marqueeRepeatLimit="2"
android:scrollHorizontally="true"
android:singleLine="true"
android:textAppearance="?attr/titleTextAppearance"
android:textColor="@color/white"/>
</code></pre>
<p>But it doesn't work although if I set this property in xml then all right. How to fix it to I can start a marquee programmatically?</p>
| 2 |
Prevent Android Ionic App from Reloading on Resume
|
<p>I have an ionic app running on android that reloads everytime I put the app into the background and resume it?
The reload is causing issues with some bluetooth devices I'm interacting with.</p>
<p>I know I can listen for the resume here, but not quite sure what I need to put in there to prevent the reload.</p>
<pre><code>$ionicPlatform.on('resume', function(){
...
})
</code></pre>
<p>What can I do to prevent app reload on resume?</p>
| 2 |
Cannot convert value of type NSSet? to expected argument type Set<HKSampleType>
|
<p>I just started learning swift 2 days ago so I apologise in advance if this may sound like a dumb question.</p>
<p>I'm working on getting the basic user data from HealthKit following this tutorial: <a href="https://www.natashatherobot.com/healthkit-getting-fitness-data/" rel="nofollow">https://www.natashatherobot.com/healthkit-getting-fitness-data/</a>
but when I compile it, I get the following error:</p>
<blockquote>
<p>Cannot convert value of type NSSet? to expected argument type
Set <'HKSampleType></p>
</blockquote>
<pre><code>func requestHealthKitAuthorization(dataTypesToWrite: NSSet?, dataTypesToRead: NSSet?) {
healthStore?.requestAuthorizationToShareTypes(dataTypesToWrite, readTypes: dataTypesToRead, completion: { (success, error) -> Void in
if success {
println("success")
} else {
println(error.description)
}
})
}
</code></pre>
<p>I have tried various answers that I found online but without success.</p>
<p>Any tip/idea would be greatly appreciated!</p>
| 2 |
Provider is not supported, or was incorrectly entered
|
<p>I have installed gerrit server setup in localhost. And after making the successful connection the Web UI has been launched. There i have registered with my gmail id in "Sign in with a Launchpad ID" option.<br>
Its worked earlier, but now it shows the error "Provider is not supported, or was incorrectly entered." when i try to login. I had searched a lot and found some solution regarding the security issues in the installed java in the system. I have Oracle Jdk8 not OpenJdk in my system. so should i have to switch to Open Jdk. Here is my error log messages from log file.</p>
<pre><code>Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:90)
at sun.security.validator.Validator.getInstance(Validator.java:179)
at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:312)
at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:171)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:184)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
... 66 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200)
at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120)
at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104)
at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:88)
... 78 more
</code></pre>
| 2 |
UWP app targeted only to Desktop/Tablet?
|
<p>I'm trying to understand how UWP apps work. I'm looking at some third party libraries on NuGet, but some of them won't work with UWP due, I presume to missing dependencies. </p>
<p>For example, some PDF drawers need System.Drawing.dll which I presume may not be accessible on Windows Phone.</p>
<p>Given my app doesn't need to work on Phones, and it's arguably not even required for tablets... it's primarily a Desktop app... how can I get around these dependency issues?</p>
<p>Is there some way for me to still use these third party libraries; perhaps by choosing a setting to say not to target Windows Phone at all?</p>
| 2 |
Microsoft access project (ADP) in access 2016
|
<p>I would like to make an access application that ms access is FE and sql server is BE, what i remember in access 2003 there was access project file could do this job.
I read in some where in google there is not ADP in new version of ms access.
Please help
is there any way yet to do Ms access as a FE and sql server as a BE?</p>
<p>Is there ADP yet?</p>
<p>If there is not ADP yet , what is the replacement way for doing this job?</p>
| 2 |
Merge two time-series in pandas & extract observations within threshold time difference
|
<p>I have two time series in pandas that have observations at seemingly-random times. The code below will create some example time series:</p>
<pre><code>import numpy as np
import pandas as pd
s1 = pd.Series(data=np.arange(5), index=['2014-05-06 09:15:34', '2014-05-06 09:34:00',
'2014-05-06 11:20:43', '2014-05-07 12:13:00',
'2014-05-07 17:29:19'])
s1.index = pd.DatetimeIndex(s1.index)
s2 = pd.Series(data=np.arange(6)*10, index=['2014-05-03 10:20:09', '2014-05-06 09:13:26',
'2014-05-06 09:23:38', '2014-05-06 11:09:52',
'2014-05-07 12:14:08', '2014-05-07 17:35:19'])
s2.index = pd.DatetimeIndex(s2.index)
</code></pre>
<p>Giving <code>s1</code>:</p>
<pre><code>2014-05-06 09:15:34 0
2014-05-06 09:34:00 1
2014-05-06 11:20:43 2
2014-05-07 12:13:00 3
2014-05-07 17:29:19 4
dtype: int64
</code></pre>
<p>and <code>s2</code>:</p>
<pre><code>2014-05-03 10:20:09 0
2014-05-06 09:13:26 10
2014-05-06 09:23:38 20
2014-05-06 11:09:52 30
2014-05-07 12:14:08 40
2014-05-07 17:35:19 50
dtype: int64
</code></pre>
<p>I want to merge these time series and extract the rows where there are observations in each time series <em>within 10 minutes of each other</em>. So, using the data above:</p>
<ul>
<li>The first element of <code>s2</code> wouldn't match anything at all in <code>s1</code>.</li>
<li>The second element of <code>s2</code> is within about 2 minutes of the first element of <code>s1</code>, so these would match.</li>
<li>and so on...</li>
</ul>
<p>Ideally, I'd end up with a <code>DataFrame</code> with columns of <code>s1_time</code>, <code>s1_value</code>, <code>s2_time</code>, <code>s2_value</code>, but I'm not really fussed about the exact format of the output.</p>
<p>I've tried loads of different approaches to this, using <code>pd.merge</code>, trying to use <code>asof</code> and so on - but I've ended up confusing myself entirely. I'm sure this is a problem that has been solved before, but I can't seem to find much online that relates to randomly-spaced time-series (a lot is based on things being hourly or daily).</p>
<p>What is the best way to do this in pandas?</p>
| 2 |
Plot points and lines on the same plot with ggplot2
|
<p>I want to plot two scatter plots with lines on the same plot using <code>ggplot2</code>. I also want to specify the colors.</p>
<pre><code>dat <- data.frame(x = 1:10, y1 = 2:11, y2 = 3:12)
ggplot(dat, aes(x)) + geom_line(aes(y = y1, color = "y1"), color = "blue") + geom_line(aes(y = y2, color = "y2"), color = "red") + geom_point(aes(y = y1), color = "blue") + geom_point(aes(y = y2), color = "red")
</code></pre>
<p>Two questions:</p>
<ol>
<li>How do I make the legend appear?</li>
<li>I am new to ggplot2. I believe there must be an easier way to do this. Please show me. Thanks.</li>
</ol>
<p><a href="https://i.stack.imgur.com/njSuD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/njSuD.png" alt="enter image description here"></a></p>
| 2 |
reactjs.net - are react-text tags required when rendered?
|
<p>I have been following this tutorial <a href="http://reactjs.net/getting-started/tutorial.html" rel="nofollow">http://reactjs.net/getting-started/tutorial.html</a> and all works great. However in the final output source, I get the following comment tags, why is the text wrapped around the <code>react-text</code> tags, are they required tags? Why are they in comment tags? Can they be removed somehow?</p>
<pre><code><!-- react-text: 6 -->Hello ReactJS.NET World!<!-- /react-text -->
<!-- react-text: 9 -->This is one comment<!-- /react-text -->
</code></pre>
| 2 |
Signed Hmac/sha1 message using Go different result than node.js or Python
|
<p>I am trying to generate a Hmac/SHA1 signature using Go, but I'm getting different results than when I test with Node.js or Python.</p>
<p>Here's my code in Go:</p>
<pre><code>signature := hmac.New(sha1.New, []byte(signKey))
signature.Write([]byte(buffer))
return hex.EncodeToString(signature.Sum(nil))
</code></pre>
<p>Here's my code in Node.js:</p>
<pre><code>return crypto.createHmac('sha1', signKey).update(buffer).digest('hex');
</code></pre>
<p>Python:</p>
<pre><code>return hmac.new(signKey, buffer, sha1).hexdigest()
</code></pre>
<p>Can you help figure out what I'm doing wrong?</p>
<p>Thanks!</p>
| 2 |
Missing an assembly reference when using Mono.Data.Sqlite
|
<p>I'm trying to use SQLite in unity for scoring purposes by following this tutorial <a href="https://www.youtube.com/watch?v=9SHz8mm-4Pw" rel="nofollow">https://www.youtube.com/watch?v=9SHz8mm-4Pw</a>.
I'm using UNITY 5.3.5, Visual Studio 2015 and .Net framework: 4.6.</p>
<p>This error appeared when I add:<code>using Mono.Data.Sqlite;</code></p>
<blockquote>
<p>Assets/Scripts/DataBaseManager.cs(4,12): error CS0234: The type or namespace name Data' does not exist in the namespace Mono'. Are you missing an assembly reference?</p>
</blockquote>
<p>The Mono.Data.Sqlite DLL file had been put into the Assets>Plugins folder and Assets folder but the error is still the same.</p>
<p>*This dll can work previously, until I installed modules: Web Player, Microsoft Visual Studio Tools for Unity, Windows Build Support using Download Assistant to solve other issues.</p>
<p>Hope to hear any of your advise on how to solve this issue. Thank you very much!</p>
<p><a href="http://i.stack.imgur.com/X2j8V.png" rel="nofollow">Screenshoot of Visual Studio and Unity</a></p>
| 2 |
Intermittent "Pool wait interrupted. java.sql.SQLException: Pool wait interrupted." Java server connecting to Mysql
|
<p>I've not found any good information about what "Pool wait interrupted" means. I'm attempting to connect from Tomcat (6 at the moment, upgrading to 8 soon) to MySql 5.6 and generally all works fine. Over the past year we've gone through two periods of time (about two weeks long or so) where this error: </p>
<blockquote>
<p>Pool wait interrupted. java.sql.SQLException: Pool wait interrupted.</p>
</blockquote>
<p>appears at least once per day. The server application is a read-only application where fast request-time performance is essential.</p>
<p>Here's my Connector/J configuration information:</p>
<pre><code><Resource
name="connectionJNDIName"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
initialSize="10"
maxActive="100"
maxIdle="50"
minIdle="10"
suspectTimeout="60"
timeBetweenEvictionRunsMillis="30000"
minEvictableIdleTimeMillis="60000"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"
testWhileIdle="true"
maxWait="10000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="username"
password="password123"
driverClassName="com.mysql.jdbc.Driver"
url="<databaseConnectionURL>"/>
</code></pre>
<p>Because the application works so much of the time, I don't think the problem is caused in the server app itself, but I would like to be more resilient. The DBA team tells me that the MySql server is clean (when they get to it to check), but the server is not returning data as it should even so. I looked at setting <code>autoReconnectForPools='true'</code> but have read documentation indicating some concerns about using that -- and I don't know that would solve the issue in any case.</p>
| 2 |
If condition with Eval value on aspx page in asp.net
|
<p>I'am using ASP.NET Web Forms, and I have to do something like this:</p>
<pre><code> <asp:Panel runat="server" CssClass="cellContent" Visible='<%# (bool)Eval("IsFolder")? false:true %>'>
<% if(Eval("Type").ToString() == "0"){ %>
<asp:Image runat="server" ImageUrl="~/Content/Icon/analiza.png" Width="30px" Height="30px" ImageAlign="Left" />
<% } else if(Eval("Type").ToString() == "1") {%>
<asp:Image runat="server" ImageUrl="~/Content/Icon/raport.png" Width="30px" Height="30px" ImageAlign="Left" />
<% } %>
</asp:Panel>
</code></pre>
<p>but I'am getting error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.". How can I achieve that? "Type" can have 3 values: 0, 1, 2. In MVC something like this is very easy, but I was forced to use Web Forms and Devexpress TreeList control, and cant find answer how to do such simple think :/</p>
| 2 |
Python turtle : Create a redo function
|
<p>I know how to undo a drawing step in python turtle with <code>turtle.undo()</code>. But how can I make a Redo function ?</p>
<pre><code>from tkinter import *
...#Just some other things
def undoStep():
turtle.undo()
def redoStep():
#What to put here
root.mainloop()
</code></pre>
| 2 |
JSF Richfaces PopupPanel refresh form not working
|
<p>I have a problem with the data on a rich:popupPanel not being refreshed in the following case:</p>
<ol>
<li>When the user first opens the popup panel the values are brought from the bean and are displaye.</li>
<li>The user changes some values then decides not to save the changes and hits the close button.</li>
<li>Then he opens the popup again. When the dialog is opened again, in the backing bean , the values for the relevances are correctly changed back to the previous values(load() is called) but this update is not reflected in the UI.
The user can see the values that he has chosen just before (step 2.), not the ones that are on the backing bean.</li>
</ol>
<p>Do you happen to know any solution for forcing an update for the components of the popup panel with values from the backing bean once it is opened in the browser?
I don't have this problem if the data is displayed on a separate page, not on a popupPanel, but i need to use popup Panel from the requirements.</p>
<p>Here is the code:
1. Component that opens the popuppanel</p>
<pre><code><a4j:commandLink id="config" value="open" action="#{bean.load()}"
oncomplete="#{rich:component('configPopUp:pp')}.show();" execute="@this">
</a4j:commandLink>
</code></pre>
<ol start="2">
<li><p>popuppanel</p>
<pre><code> <rich:popupPanel id="ConfigPopUp" width="800" height="350" title=" ">
<h:form id="ConfigForm">
<div class="row " style="margin: 0px">
<div >
<a4j:commandButton styleClass="pull-right" id="ConfigSave"
actionListener="#{bean.saveConfiguration()}"
value="#{text['Configuration.save']}" immediate="true">
</a4j:commandButton>
</div>
</div>
<ui:repeat
value="#{bean.selectedValues}" var="current" varStatus="i">
<div class="row" style="margin: 0px">
<div class="col-sm-4 col-sm-offset-1 ">
<h:outputText value="#{current.text}" />
</div>
<div class="col-sm-4 ">
<rich:select value="#{current.relevance}">
<f:selectItems
value="#{bean.relevanceOptions}"/>
<f:ajax event="change" render="@form" execute="@this" />
</rich:select>
</div>
</div>
</ui:repeat>
</h:form>
</rich:popupPanel>
</code></pre></li>
</ol>
| 2 |
Dynamic importing modules results in an ImportError
|
<p>So I've been trying to make a simple program that will dynamically import modules in a folder with a certain name. I cd with <code>os</code> to the directory and I run <code>module = __import__(module_name)</code> as I'm in a for loop with all of the files names described being iterated into the variable module_name.</p>
<p>My only problem is I get hit with a: </p>
<pre><code>ImportError: No module named "module_name"
</code></pre>
<p>(saying the name of the variable I've given as a string). The file exists, it's in the directory mentioned and <code>import</code> works fine in the same directory. But normal even import doesn't work for modules in the cd directory. The code looks as follows. I'm sorry if this is an obvious question. </p>
<pre><code>import os
class Book():
def __init__(self):
self.name = "Book of Imps"
self.moduleNames = []
# configure path
def initialize(self):
path = os.getcwd() + '/Imp-pit'
os.chdir(path)
cwd = os.walk(os.getcwd())
x, y, z = next(cwd)
# Build Modules
for name in z:
if name[:3] == 'Imp':
module_name = name[:len(name) - 3]
module = __import__(module_name)
def start_sim():
s = Book()
s.initialize()
if __name__ == '__main__':
start_sim()
</code></pre>
| 2 |
Elasticsearch how to configure language analyzer (German) or build a custom normalizer
|
<p>I am using the german language analyzer to tokenize some content. I know that it is basically a macro filter for "lowercase","german_stop", "german_keywords", "german_normalization", "german_stemmer".</p>
<p>My problem has to do with the nomalization filter. Here is the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-normalization-tokenfilter.html" rel="nofollow">Elasticsearch Documentation</a> and the <a href="http://lucene.apache.org/core/4_9_0/analyzers-common/org/apache/lucene/analysis/de/GermanNormalizationFilter.html" rel="nofollow">Lucene Implementation</a> of the filter. The problem is that ae ue and oe are treated as the german letters ä,ö and ü and therefore transformed to a,o,u. </p>
<p>The second transformation is good but the first leads to more problems than it solves. There is usually no ae,ue,oe in german texts that really represents ä, ü, ö. Most of the times they actually appear are inside foreign words, derived from latin or english like 'Aearodynamik' (aerodynamics). The filter then interprets 'Ae' as 'Ä' then transforns it to 'A'. This yields 'arodynamik' as token. Normally this is not a problem since the search word is also normalized with that filter. This does however become a problem if combined with wildcard search:</p>
<p>Imagine a word like 'FooEdit', this will be tokenized to 'foodit'. A search for 'edit OR *edit*' (which is my normal search when the user searches for 'edit') will not yield a result since the 'e' of 'edit' got lost. Since my content has a lot of words like that and people are searching for partial words it's not as much of an edge case as it seems. </p>
<p>So my question is is there any way to get rid of the 'ae -> a' transformations? My understanding is that this is part of the <a href="http://snowball.tartarus.org/algorithms/german2/stemmer.html" rel="nofollow">German2 snowball algorithm</a> so probably this can't be changed. Does that mean I would have to get rid of the whole normalization step or can I provide my own version of the snowball algorithm where I just strip the parts that I don't like (didn't find any documentation on how to use a custom snowball algorithm for normalization)?</p>
<p>Cheers </p>
<p>Tom</p>
| 2 |
Wordpress media library don't show files manually added in upload folder
|
<p>I'm very new to Wordpress. I just started working locally (using XAMPP on Ubuntu 14.04) when my HD crashed and i had to reinstall everything.
I'm pretty sure that before crash i was able to "upload" media simply by moving files into <code>upload</code> folder using a file manager (i'm sure i also added an <code>upload/bg</code> subfolder using shell). To see the new files into the media library i just had to refresh the media-upload page.</p>
<p>Now, after startover (ubuntu 16.04, lamp instead of XAMPP, WP 4.5.3 - can't remember old version) i cannot see copied media files anymore in media library.
Of course files are there (in the upload folder), both uploaded and copied, and i can see them using any browser (url like localhost/mysite/wp-content/uploads/myimg.jpg is working fine), but in media library i only see the uploaded ones.</p>
<p>Maybe in my old setting i installed a plugin that i forgot?</p>
| 2 |
score for matching query_string documents
|
<p>i'm currently working on a pretty annoying query i need from ES.
my documents are nested docs, their index looks like something like this:</p>
<pre><code>"mydocs" : {
"properties" : {
"doc" : {
"type" : "nested",
"properties" : {
"name" : {"type" : "string", "store" : "yes", "index" : "analyzed"},
"tagln" : {"type" : "string", "store" : "yes", "index" : "analyzed"},
"tags" : {"type" : "string", "store" : "yes", "index" : "analyzed"},
"featured" : {"type" : "integer", "store" : "yes", "index" : "not_analyzed"}
"blkd" : {"type" : "integer", "store" : "yes", "index" : "not_analyzed"},
... etc ...
}
</code></pre>
<p>i'm trying to boost the name, tagln and tags fields by a special score algo that adds the scores of featured*10000 + [is found in name]*1000 + [is found in tagln]*10 + [is found in tags]*10. my query is as follows:</p>
<pre><code>{
"from" : 0,
"size" : 10,
"query" : {
"nested" : {
"query" : {
"filtered" : {
"query" : {
"bool" : {
"must" : [ {
"term" : {
"doc.blkd" : 0
}
} ],
"should" : [ {
"function_score" : {
"functions" : [ {
"field_value_factor" : {
"field" : "doc.featured",
"factor" : 10000.0
}
} ],
"score_mode" : "sum",
"boost_mode" : "sum"
}
}, {
"constant_score" : {
"filter" : {
"query_string" : {
"query" : "featured*",
"fields" : [ "doc.name^1000.0" ]
}
},
"boost" : 1000.0
}
}, {
"constant_score" : {
"filter" : {
"query_string" : {
"query" : "featured*",
"fields" : [ "doc.tags^10.0" ],
"boost" : 10.0
}
}
}
}, {
"constant_score" : {
"filter" : {
"query_string" : {
"query" : "featured*",
"fields" : [ "doc.tagln^10.0" ],
"boost" : 10.0
}
}
}
} ],
"minimum_should_match" : "0"
}
}
}
},
"path" : "doc",
"score_mode" : "sum"
}
},
"explain" : false,
"sort" : [ {
"_score" : { }
} ]
}
</code></pre>
<p>the score doesn't take the boosting into account as it should have, the score of the featured works as expected but the boost in the query_string doesn't work,
docs with "aaa" in their names get a tiny score of 5 or 0. something while the featured=1 returns scores of 4000/6000/7500 etc..</p>
<p>first of all the score isn't 10000+ which is weird (might be due to many factors of the score) but the matching query string inside the name doesn't have any visible affect on the scores..</p>
<p>how can i solve this problem or atleast debug it better(to see how the score is being built)?
tried changing explain to true but all i get is this pretty useless(or probably unreadable for me) explanation:</p>
<pre><code>"_explanation": {
"value": 4000.0024,
"description": "sum of:",
"details": [
{
"value": 4000.0024,
"description": "Score based on child doc range from 387 to 387",
"details": []
},
{
"value": 0,
"description": "match on required clause, product of:",
"details": [
{
"value": 0,
"description": "# clause",
"details": []
},
{
"value": 0.0009999962,
"description": "-ConstantScore(_type:.percolator) #(+*:* -_type:__*), product of:",
"details": [
{
"value": 1,
"description": "boost",
"details": []
},
{
"value": 0.0009999962,
"description": "queryNorm",
"details": []
}
]
}
]
}
]
}
</code></pre>
<p><strong>* edited *</strong></p>
<p>thanks to keety i'm able to provide more info:
after adding disable_coord-true and inner_hits explain-true
i've tried "boosting" the query_string in any way i could.. the query is as follows:</p>
<pre><code>{
"from" : 0,
"size" : 10,
"query" : {
"nested" : {
"query" : {
"filtered" : {
"query" : {
"bool" : {
"must" : [ {
"term" : {
"doc.blkd" : 0
}
} ],
"should" : [ {
"function_score" : {
"functions" : [ {
"field_value_factor" : {
"field" : "doc.featured",
"factor" : 10000.0
}
} ],
"score_mode" : "sum",
"boost_mode" : "sum"
}
}, {
"constant_score" : {
"filter" : {
"query_string" : {
"query" : "*featured*",
"fields" : [ "doc.name^1000.0" ]
}
},
"boost" : 1000.0
}
}, {
"query_string" : {
"query" : "*featured*",
"fields" : [ "doc.tags^100.0" ],
"boost" : 100.0
}
}, {
"constant_score" : {
"filter" : {
"query_string" : {
"query" : "*featured*",
"fields" : [ "doc.tagln^10.0" ],
"boost" : 10.0
}
}
}
} ],
"disable_coord" : true,
"minimum_should_match" : "0"
}
},
"filter" : {
"bool" : {
"should" : [ {
"query_string" : {
"query" : "*featured*",
"fields" : [ "doc.name^1000000.0", "doc.tags^10.0", "doc.tagln^10.0" ],
"boost" : 1000.0
}
} ],
"minimum_should_match" : "0"
}
}
}
},
"path" : "doc",
"score_mode" : "sum",
"inner_hits" : {
"explain" : "true"
}
}
},
"explain" : false,
"sort" : [ {
"_score" : { }
} ]
}
</code></pre>
<p>as you can see i've added the query_string to the filter and changed one of the query-shoulds to not be constant_score</p>
<p>the explanation of the doc now looks like this:</p>
<pre><code>"max_score": 10001,
"hits": [
{
"_index": "myindex",
"_type": "mydocs",
"_id": "1111",
"_score": 10001,
"_ttl": 86158563,
"_source": {
"meta": {
"id": "1111",
"rev": "35-14602ccf5c3d429e0000000002000000",
"expiration": 0,
"flags": 33554432
},
"doc": {
"featured": 1,
"tagln": "hello location 1",
"blkd": 0,
"tags": [
"UsLocTaglinefeat"
],
"name": "hello US location featured"
}
},
"inner_hits": {
"doc": {
"hits": {
"total": 1,
"max_score": 10001,
"hits": [
{
"_shard": 1,
"_node": "YIXx2rrKR2O5q9519FIr_Q",
"_index": "myindex",
"_type": "mydocs",
"_id": "1111",
"_nested": {
"field": "doc",
"offset": 0
},
"_score": 10001,
"_source": {
"featured": 1,
"tagln": "hello location 1",
"blkd": 0,
"tags": [
"UsLocTaglinefeat"
],
"name": "hello US location featured"
},
"_explanation": {
"value": 10001,
"description": "sum of:",
"details": [
{
"value": 10001,
"description": "sum of:",
"details": [
{
"value": 0.0041682906,
"description": "weight(doc.blkd:`\b\u0000\u0000\u0000\u0000 in 0) [PerFieldSimilarity], result of:",
"details": [
{
"value": 0.0041682906,
"description": "score(doc=0,freq=1.0), product of:",
"details": [
{
"value": 0.0020365636,
"description": "queryWeight, product of:",
"details": [
{
"value": 2.0467274,
"description": "idf(docFreq=177, maxDocs=507)",
"details": []
},
{
"value": 0.0009950341,
"description": "queryNorm",
"details": []
}
]
},
{
"value": 2.0467274,
"description": "fieldWeight in 0, product of:",
"details": [
{
"value": 1,
"description": "tf(freq=1.0), with freq of:",
"details": [
{
"value": 1,
"description": "termFreq=1.0",
"details": []
}
]
},
{
"value": 2.0467274,
"description": "idf(docFreq=177, maxDocs=507)",
"details": []
},
{
"value": 1,
"description": "fieldNorm(doc=0)",
"details": []
}
]
}
]
}
]
},
{
"value": 10000.001,
"description": "sum of",
"details": [
{
"value": 0.0009950341,
"description": "*:*, product of:",
"details": [
{
"value": 1,
"description": "boost",
"details": []
},
{
"value": 0.0009950341,
"description": "queryNorm",
"details": []
}
]
},
{
"value": 10000,
"description": "min of:",
"details": [
{
"value": 10000,
"description": "field value function: none(doc['doc.featured'].value * factor=10000.0)",
"details": []
},
{
"value": 3.4028235e+38,
"description": "maxBoost",
"details": []
}
]
}
]
},
{
"value": 0.9950341,
"description": "ConstantScore(doc.name:*featured*), product of:",
"details": [
{
"value": 1000,
"description": "boost",
"details": []
},
{
"value": 0.0009950341,
"description": "queryNorm",
"details": []
}
]
}
]
},
{
"value": 0,
"description": "match on required clause, product of:",
"details": [
{
"value": 0,
"description": "# clause",
"details": []
},
{
"value": 0.0009950341,
"description": "((doc.name:*featured*)^1000000.0 | (doc.tags:*featured*)^10.0 | (doc.tagln:*featured*)^10.0), product of:",
"details": [
{
"value": 1,
"description": "boost",
"details": []
},
{
"value": 0.0009950341,
"description": "queryNorm",
"details": []
}
]
}
]
}
]
}
}
]
}
}
}
},
</code></pre>
<p>it seems like the only query_string affecting the score in any way is the one inside the filter but i can't seem to be able to boost it's score...
any tips are welcome :) thanks</p>
| 2 |
Python get web page screenshot color palette
|
<p>I am using Python 2.7 to try to get 5-color palette from screenshots of web pages.</p>
<p>The methods I have tried so far are not producing satisfactory results. </p>
<p>The palettes converge on a greens, grays and blues when web pages have other maybe not dominant but thematically important colors that should be in a palette.</p>
<p>A sample of output is included here. I have put a 5 cell table above each image thumbnail, each showing one of the 5 colors. </p>
<p><a href="https://i.stack.imgur.com/wpkmn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wpkmn.png" alt="enter image description here"></a></p>
<p>My code with methods commented out is below but to summarize I have been using <code>Pillow</code> and a promising module called <code>colorthief</code>.</p>
<p>I think that most of these color palette exercises work on photograph or graphics of scenes and objects which are full of colors give or take. Web pages are different. They have loads of white space and black text.</p>
<p>The best results, though far from satisfactory, were a method that changed white pixels to transparent. This allowed a few screenshots to exhibit palettes with more than blue, gray, greens.</p>
<p>I suspect that if I could remove all white and black pixels from screenshot first, and perhaps all other pixels within a related % to white and black (eg off-whites, dark grays) then I the palette could be generated from set of pixels with just colors.</p>
<p>Web search hasn't revealed any techniques specifically dealing with web page or document palette generation. </p>
<p>I might have to rethink palette generation and get it from HTML directly. But want to try to make the image method work if possible.</p>
<p>So the question is how can I get color palette from a screenshot of a web page that excludes white, black and is based on only colors in image?</p>
<pre><code>import os, os.path
from PIL import Image
import psycopg2
from colorthief import ColorThief
conn_string = \
"host='localhost' \
dbname='databasename' \
user='username' \
password='password'"
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
## dev paths
screenshots_path = 'path/to/screenshots/'
screenshots_dir = os.listdir(screenshots_path)
for screenshot in screenshots_dir:
if screenshot != 'Thumbs.db':
try:
img_orig = Image.open(screenshots_path + screenshot)
## method 1 replace white pixels with transparent
# img = img_orig.convert("RGBA")
# datas = img.getdata()
# newData = []
# for item in datas:
# if item[0] == 255 and item[1] == 255 and item[2] == 255:
# newData.append((255, 255, 255, 0))
# else:
# newData.append(item)
# img.putdata(newData)
## method 2 - pillow
img = img_orig.convert('P', palette=Image.ADAPTIVE, colors=5)
width, height = img.size
height = img.size[1]
quantized = img.quantize(colors=5, kmeans=3)
palette = quantized.getpalette()[:15]
convert_rgb = quantized.convert('RGB')
colors = convert_rgb.getcolors(width*height)
color_str = str(sorted(colors, reverse=True))
color_str = str([x[1] for x in colors])
print screenshot + ' ' + color_str
## method 3 - colorthief
# try:
# img = Image.open(screenshots_path + screenshot)
# color_thief = ColorThief(screenshots_path + screenshot)
## get the dominant color
# dominant_color = color_thief.get_color(quality=1)
# build a color palette
# color_str = color_thief.get_palette(color_count=5)
# print screenshot + ' ' + str(height) + ' ' + str(color_str)
cur.execute("UPDATE screenshots set color_palette = %s, height = %s WHERE filename like %s", (str(color_str), height, '%' + screenshot + '%',))
conn.commit()
except:
continue
cur.close()
conn.close()
</code></pre>
| 2 |
iOS-Charts - yAxis labels not start exactly at bottom
|
<p>I use Charts swift library in my project.I use two datasets in line chart, but the labels of Yaxis not start exactly at bottom.I want the first label on the yAxis to be exactly at bottom-left corner of chart. I try to set minimum of yAxis but it didn't help.</p>
<p>Following is example image.</p>
<p><img src="https://i.imgur.com/kt7kE7j.png" alt="Image"></p>
| 2 |
JSON: Adding missing quotes and commas automatically in WebStorm
|
<p>I get from a service json-like-data with several hundred different structures:</p>
<pre><code>{
car112: {
n: Audi
type: A4 20 TDI ultra daylight
sd: 01.07.2016
p: 34216
st: false
}
car113: {
n: BMW
type: not known
st: true
}
}
</code></pre>
<p>and want to get quotes and commas automatically added in WebStorm, so that I have a valid JSON file afterwards:</p>
<pre><code>{
"car112": {
"n": "Audi",
"type": "A4 2,0 TDI ultra daylight",
"sd": "01.07.2016",
"p": 34216,
"st": false
},
"car113": {
"n": "BMW",
"type": "not known",
"st": true
}
}
</code></pre>
<p>How could I do that easily?</p>
| 2 |
Is it possible to specify the WRITETIME in a Cassandra INSERT command?
|
<p>I am having a problem where a few INSERT commands are viewed as being send simultaneously on the Cassandra side when my code clearly does not send them simultaneously. (When you get a little congestion on the network, then the problem happens, otherwise, everything works just fine.)</p>
<p>What I am thinking would solve this problem is a way for me to be able to specify the WRITETIME myself. From what I recall, that was possible in thrift, but maybe not (i.e. we could read it for sure.)</p>
<p>So something like this (to simulate the TTL):</p>
<pre><code>INSERT INTO table_name (a, b, c) VALUES (1, 2, 3) USING WRITETIME = 123;
</code></pre>
<p>The problem I'm facing is overwriting the same data and once in a while the update is ignored because it ends up with the same or even an older timestamp (probably because it is sent to a different node and the time of each node is slightly different and since the C++ process uses threads, it can be send before/after without your control...)</p>
| 2 |
How to select a row from any hstore values?
|
<p>I've a table <code>Content</code> in a PostgreSQL (9.5) database, which contains the column <code>title</code>. The <code>title</code> column is a <code>hstore</code>. It's a <code>hstore</code>, because the <code>title</code> is translated to different languages. For example:</p>
<pre><code>example=# SELECT * FROM contents;
id | title | content | created_at | updated_at
----+---------------------------------------------+------------------------------------------------+----------------------------+----------------------------
1 | "de"=>"Beispielseite", "en"=>"Example page" | "de"=>"Beispielinhalt", "en"=>"Example conten" | 2016-07-17 09:20:23.159248 | 2016-07-17 09:20:23.159248
(1 row)
</code></pre>
<p>My question is, how can I select the <code>content</code> which <code>title</code> contains <code>Example page</code>?</p>
<pre><code>SELECT * FROM contents WHERE title = 'Example page';
</code></pre>
<p>This query unfortunately doesn't work. </p>
<pre><code>example=# SELECT * FROM contents WHERE title = 'Example page';
ERROR: Syntax error near 'p' at position 8
LINE 1: SELECT * FROM contents WHERE title = 'Example page';
</code></pre>
| 2 |
Open port for outbound and inbound traffic
|
<p>I want to send push notifications to devices through the Apple push service server (APNS). Now the APNS requires an unproxied connection to them with some ports open.</p>
<p>To quote Apple from this link - Push providers, iOS devices, and Mac computers are often behind firewalls. To send notifications, you will need to allow inbound and outbound TCP packets over port 2195.</p>
<p>Now the security team is asking why we need to open both inbound and outbound when we will only sending (outwards) the request to APNS.</p>
<p>Now I am no networking guy. My basic web brain tells me we will be sending a POST request (outwards as seen from my server) to APNS, and this POST request will have a response. For this response, I will need to open inbound traffic for that same port i.e. 2195. Am i right?</p>
| 2 |
case statement to return node property and true if relationship exist
|
<p>I want to return true or false if relationship exist between between two nodes and also return a property if rel exist otherwise return only false. I tried this query - It works when rel exist but doesn't return anything if rel doesn't exist</p>
<pre><code>MATCH (n:User {username: 'user'})-[r:HAS_CAR]-(m:Car)
RETURN SIGN(COUNT(r)), CASE SIGN(COUNT(r)) WHEN 1 THEN m.name END as name
</code></pre>
| 2 |
Qt error: undefined reference to 'QDebug::~QDebug()'
|
<p>I am compiling my code with caffe, opencv 3.1 and Qt5.6. Following is my .pro file. I have not included the actual source and header file names here.</p>
<pre><code>QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = outsideSituationDetection
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp \
<and others>
HEADERS += mainwindow.h \
< and others >
FORMS += mainwindow.ui
DEFINES += CPU_ONLY
QMAKE_CXXFLAGS += -std=c++11 -Wall -D_REENTRANT -D__STDC_CONSTANT_MACROS -pthread
QMAKE_CXXFLAGS += -DQT_COMPILING_QSTRING_COMPAT_CPP -DQT_COMPILING_QIMAGE_COMPAT_CPP
CONFIG += link_pkgconfig
PKGCONFIG += opencv
INCLUDEPATH += /usr/local/include /usr/local/lib /usr/lib
DEPENDPATH += /usr/local/include
LIBS += -L/usr/local/lib/ -lopencv_imgproc
LIBS += -lm -lglib-2.0 -lgthread-2.0 -lxml2 -pthread
INCLUDEPATH += /usr/include/glib-2.0
INCLUDEPATH += /usr/lib/x86_64-linux-gnu/glib-2.0/include
INCLUDEPATH += /usr/include/libxml2
INCLUDEPATH += /usr/include/ \
/usr/lib/x86_64-linux-gnu/ \
LIBS += -L/usr/lib/x86_64-linux-gnu/ -lglog -lpthread -lm -lrt -ldl -lnsl
DEPENDPATH += /usr/lib/x86_64-linux-gnu/
# BOOST Library
LIBS += -L/usr/lib/x86_64-linux-gnu/ -lboost_system
INCLUDEPATH += /usr/lib/x86_64-linux-gnu
#Caffe for CPU System
INCLUDEPATH += $$PWD/../../../../../src/caffe/build/include \
$$PWD/../../../../../src/caffe/include \
$$PWD/../../../../../src/caffe/build
unix:!macx: LIBS += -L$$PWD/../../../../../src/caffe/build/lib/ -lcaffe -lglog
INCLUDEPATH += $$PWD/../../../../../src/caffe/build
DEPENDPATH += $$PWD/../../../../../src/caffe/build
RESOURCES += icons.qrc
</code></pre>
<p>Problem - When I compile the code, I get a bunch of 'error: undefined reference to 'QDebug::~QDebug()'' errors along with 'error: undefined reference to `QDebug::putString(QChar const*, unsigned long)'' against all of my .cpp files. (I have successfully built and executed another application without errors using Qt5.6 and Qt5.7.)</p>
<pre><code>(.qtversion[qt_version_tag]+0x0):-1: error: undefined reference to `qt_version_tag' File not found (.qtversion[qt_version_tag]+0x0) in main.o
</code></pre>
<p>What I have tried - Check Qt version to make sure I am using Qt5.6. Deleted the installed qt5-default by doing 'sudo apt-get remove qt5-default'. Downgraded from Qt5.7 to Qt5.6 although it didn't make any difference. I have deleted qt4 and qt5 folders from /usr/include and /usr/share. </p>
<p>Can you please suggest what I might be missing?</p>
| 2 |
node.js timing: process.hrtime() vs new Date().getTime()?
|
<p>I'm trying to troubleshoot an issue where requests from node.js to remote http api take too long. To start with, i've decided to add timing to my node application:</p>
<pre><code>'use strict';
let logger = require('./logger');
let request = require('request');
module.exports = function(uri, done) {
// set full url.
let options = {
uri: `http://example.org/${uri}`,
timeout: 60000,
json: true,
gzip: true,
encoding: null
};
const startDate = new Date().getTime();
const start = process.hrtime();
request(options, function(error, response, body) {
const endDate = new Date().getTime();
const end = process.hrtime(start);
const durationDate = endDate - startDate;
const duration = end[1] / 1000000;
const diff = Math.abs(Math.round(durationDate - duration));
logger.debug(`${uri} hrtime: ${duration} ms, date: ${durationDate} ms, diff: ${diff}`);
if (!error && response.statusCode === 200) {
done(error, response, body, body);
} else {
done(error, response, body);
}
});
};
</code></pre>
<p>And this is the output i get:</p>
<pre><code><....>
2016-06-29T10:26:59.230Z /account hrtime: 41.567354 ms, date: 41 ms, diff: 1
2016-06-29T10:27:06.369Z /account hrtime: 42.052154 ms, date: 42 ms, diff: 0
2016-06-29T10:27:13.368Z /account hrtime: 51.582807 ms, date: 5052 ms, diff: 5000
2016-06-29T10:27:14.971Z /account hrtime: 40.705936 ms, date: 40 ms, diff: 1
2016-06-29T10:27:22.490Z /account hrtime: 45.953398 ms, date: 5046 ms, diff: 5000
2016-06-29T10:27:29.669Z /account hrtime: 42.504256 ms, date: 5043 ms, diff: 5000
2016-06-29T10:27:31.622Z /account hrtime: 39.405575 ms, date: 39 ms, diff: 0
<....>
2016-06-29T10:27:45.135Z /account hrtime: 40.594642 ms, date: 41 ms, diff: 0
2016-06-29T10:27:52.682Z /account hrtime: 40.290881 ms, date: 40 ms, diff: 0
2016-06-29T10:28:05.115Z /account hrtime: 50.81821 ms, date: 10050 ms, diff: 9999
2016-06-29T10:28:13.555Z /account hrtime: 52.061123 ms, date: 52 ms, diff: 0
<.....>
2016-06-29T10:29:45.052Z /account hrtime: 44.252486 ms, date: 44 ms, diff: 0
2016-06-29T10:29:46.829Z /account hrtime: 39.652963 ms, date: 40 ms, diff: 0
2016-06-29T10:29:49.101Z /account hrtime: 40.841915 ms, date: 41 ms, diff: 0
2016-06-29T10:29:55.097Z /account hrtime: 44.161802 ms, date: 5044 ms, diff: 5000
2016-06-29T10:30:01.784Z /account hrtime: 47.732807 ms, date: 47 ms, diff: 1
2016-06-29T10:30:04.309Z /account hrtime: 40.151299 ms, date: 40 ms, diff: 0
2016-06-29T10:30:06.926Z /account hrtime: 39.933368 ms, date: 40 ms, diff: 0
2016-06-29T10:30:14.440Z /account hrtime: 53.610396 ms, date: 5054 ms, diff: 5000
</code></pre>
<p>So sometimes the difference between hrtime and getTime() is huge.<br>
And this is not just some misreporting, but rather actual behaviour - if look at the remote http server logs, i see that all requests actually took time reported by hrtime, and time reported by getTime() is actually how long the node.js application responds. So it seems that there is some kind of delay on node.js application itself. Any hits on why this is happening ?</p>
<p>Node v4.4.6</p>
| 2 |
Minecraft Plugin Prefix (Java)
|
<p>I just want to create simple prefix plugin for minecraft server,which is shows each player points in chatbox.</p>
<p>The API i used = <code>PlayerPoints</code> & <code>Spigot 1.9.4</code> shaded.
About <code>PlayerPoints API</code> : <a href="http://dev.bukkit.org/bukkit-plugins/playerpoints/pages/api/" rel="nofollow noreferrer">Click here</a></p>
<p>As console Show problem is here on <code>PlayerListener.java</code>:</p>
<pre><code>package points.prefix;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.black_ixx.playerpoints.PlayerPoints;
public class PlayerListener implements Listener {
Main plugin;
public PlayerListener(Main instance){
this.plugin = instance;
}
public PlayerPoints getPlayerPoints() {
return getPlayerPoints();
}
//OnPlayer Join
@EventHandler
public void playerjoin(PlayerJoinEvent e){
Player p = e.getPlayer();
String pname = p.getName();
int points = getPlayerPoints().getAPI().look("Player");
//Begin
if (p.hasPermission("prefix.point")){
String member = "" + ChatColor.WHITE + "[" + ChatColor.GREEN + points + ChatColor.WHITE + "]" + ChatColor.RESET + ChatColor.WHITE + pname + ChatColor.RESET + "";
p.setDisplayName(member);
}
} }
</code></pre>
<p>error log from spigot console:</p>
<blockquote>
<p>points.prefix.PlayerListener.getPlayerPoints(PlayerListener.java:19)
~[?:?] [20:57:40]</p>
</blockquote>
<p>error log from eclipse:</p>
<blockquote>
<p>The method look(String) from the type PlayerPointsAPI is deprecated</p>
</blockquote>
<p>Here an other note:
In <code>PlayerpointsAPI</code> page mentioned to use:</p>
<pre><code>int balance = playerPoints.getAPI().look("Player");
</code></pre>
<p>for showing balance! but it is not working!</p>
<p>Any one know what's wrong?</p>
<p>Thank U.</p>
| 2 |
I am trying to make a responsive rectangle with an image to the left inside and text centered
|
<p>I am trying to make a responsive tweet <code>button</code> with the twitter bird <code>float</code>ed left, the text next to it and centered. </p>
<p>My 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-css lang-css prettyprint-override"><code>.flex-rectangle {
float: left;
margin: 0 5px;
max-width: 500px;
text-align: center;
width: 200%;
background: #FFFFFF;
border: 7px solid #00A5EF;
}
/* Styles Twitter Bird png */
.image-wrapper {
padding-top: 10%;
position: relative;
width: 100%;
padding-bottom: 10%;
}
img .tweet {
float: left;
}
/* Tweet This: */
.span-content {
display: block;
color: #00A5EF;
}
.span {
display: block;
text-align: center;
font-family: OpenSans;
font-size: 36px;
color: #00A5EF;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-rectangle">
<div class="image-wrapper">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/281152/Twitter_bird_logo_2012.svg" class="tweet" />
</div>
</div>
<div id="buttons">
<div class="span-content">
<span>Tweet This</span>
</div>
</div>
CSS</code></pre>
</div>
</div>
</p>
<p>I've tried pretty much everything under the sun.</p>
<p>I can't seem to get the rectangle to shrink and widen when I resize the page or go into Dev Tools and use the mobile device pane.</p>
<p>I understand CSS less than I do JavaScript at this point. Not sure if I should use <code>flexbox</code> in this instance or how I would do that.</p>
<p>Here is the <a href="http://codepen.io/twhite96/pen/aZmrXO?editors=1100" rel="nofollow">CodePen</a></p>
| 2 |
Solr: Index csv file
|
<p>I am trying to index the CSV file in Solr using command prompt but it gives the Not found error.</p>
<p>Here is the command:</p>
<pre><code>E:\...\solr-6.1.0\example\exampledocs>java -Dtype=text/csv -Dc
=gettingstarted -jar post.jar E:\cross-over\dataset\dataset.csv
</code></pre>
<p><a href="https://i.stack.imgur.com/9m0Gh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9m0Gh.png" alt="Here is the error" /></a></p>
<p>Do I need to define schema for the data set first or is this something else?</p>
<p>Kindly assist me.</p>
| 2 |
Make Custom Url In codeigniter
|
<p><strong>Model</strong></p>
<pre><code>function get_footer_pages(){
$query=$this->db->where('section','footer');
$query=$this->db->get('pages');
if($query->num_rows()>0){
$result=$query->result_array();
return $result;
}else{
return false;
}
}
function get_url($row){
$title=$row['title'];
$not_allowed=array('/','?','\"','&','"',':','%','\'',',');
$title=str_replace($not_allowed,'',$title);
$title=str_replace(' ','-',$title);
$title=$title."_".$row['id'];
return $title;
}
</code></pre>
<p><strong>Controller:</strong></p>
<pre><code>$data['footer_pages']=$this->Home_model->get_footer_pages();
</code></pre>
<p><strong>View:</strong></p>
<pre><code><?php foreach($footer_pages as $f_pages){ ?>
<li><a href="<?php echo $f_pages['url'] ?>"><?php echo $f_pages['name'] ?></a></li>
<?php } ?>
</code></pre>
<p>I want to create a <code>url</code> combination of <code>title</code> and <code>id</code> as i performed in function <code>get_url()</code>.</p>
<p><strong>Now problem:</strong></p>
<p>is how can i call this <code>get_url()</code> in <code>get_footer_pages()</code> to make the url of all the results of <code>get_footer_pages()</code> and use this url in my <code>VIEW</code> in <code>href</code>?</p>
| 2 |
Error in using Typed.js Typewriter effect
|
<p>I am creating a Typing effect using HTML5 , CSS ,Javascript,Typed.js.
This is my code=</p>
<pre><code> <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body>
<p class ="TypeWirter_effect"></p>
<script src="jquery-ui.min.js>"></script> //This is downloaded from jquery's Website n pasted in same folder
<script src="jquery.js"></script> //This is downloaded from jquery's Website n pasted in same folder
<script src="typed.min.js"></script> //This is downloaded from Typed.js main Website n pasted in same folder
<script>
$(function() {
$("#TypeWirter_effect").typed({
strings: ["Want to learn Coding ?", "Want to learn C++","Java","Python"],
typeSpeed: 0,
loop: true,
backSpeed: 30,
showCursor: true,
backDelay: 500,
startDelay: 1000,
contentType: 'text',
backspace: function(curString, curStrPos) {
setTimeout(function () {
// check string array position
// on the first string, only delete one word
// the stopNum actually represents the amount of chars to
// keep in the current string. In my case it's 3.
if (curString.arrayPos == 20) {
curString.stopNum = 14;
}
//every other time, delete the whole typed string
else {
self.stopNum = 14;
}
}
)
}
});
});
</script>
</body>
</html>
</code></pre>
<p>1) When i run this the cursor always appear in the bottom <a href="https://www.dropbox.com/s/fe66bhw108bvfpt/1%20cursor%20prob.png?dl=0" rel="nofollow">cursor problem</a>, i want the cursor right next to the ? mark at the end of this line but it always stays down.</p>
<p>2) I want the second sentence "Want to learn C++" not to be erased completely and c++ 2 be erased and java to be appended to it .</p>
<p>I have read the documentation .But nothing seems to work Out .Help
Link of Documentation==(<a href="https://github.com/mattboldt/typed.js/blob/master/README.md" rel="nofollow">https://github.com/mattboldt/typed.js/blob/master/README.md</a>)</p>
| 2 |
R, how to add an unlist (and other) function inside an apply function?
|
<p>Context: I am working with genes and ontology, but my question concerns R script writing.</p>
<p>I would like to replace the GO:ID in my data frame by their corresponding terms extracted form a database.</p>
<p>So, this is my source data frame. it is a genes list (v1) and associated GO:ID (v2):</p>
<pre><code>>gene_list_and_Go_ID
V1 V2
2563 Gene1 GO:0003871, GO:0008270, GO:0008652, GO:0009086
2580 Gene2 GO:0003871, GO:0008270, GO:0008652, GO:0009086
12686 Gene3 GO:0003871, GO:0008270, GO:0008652, GO:0009086
14523 Gene4 GO:0004489, GO:0006555, GO:0055114
</code></pre>
<p>The request to the database looks very simple:</p>
<pre><code>>select(GO.db, my_Go_id, "TERM", "GOID")
</code></pre>
<p>I tried the following lines to address manually the database, it worked well: </p>
<pre><code>>my_Go_id = unlist(strsplit("GO:0008270, GO:0008652, GO:0009086", split=", "))
>select(GO.db, my_Go_id, "TERM", "GOID")
GOID TERM
1 GO:0008270 zinc ion binding
2 GO:0008652 cellular amino acid biosynthetic process
3 GO:0009086 methionine biosynthetic process
</code></pre>
<p>My problem: I cannot make this process automatic!
Precisely, for each row, I need to transform each string from column n°2 in my data frame to a vector in order to question the database.
And then I need to replace the GO:ID in the data frame by the result of the request.</p>
<p>1/ To start, I tried to put the "unlist" function in a "apply" function to my data frame: </p>
<pre><code>apply(gene_list_and_Go_ID,1,unlist(strsplit(gene_list_and_Go_ID[,2], split=", ")))
</code></pre>
<p>I got : </p>
<pre><code>Error in strsplit(ok, split = ", ") : non-character argument
</code></pre>
<p>2/ Then, can I add also the request to the database inside the apply function?</p>
<p>3/ Finally, I do not know how to replace column n°2 by the result of the database request.</p>
<p>This is an example of an excepted “ideal” result:</p>
<pre><code> V1 V2
2563 Gene1 GOID TERM
1 GO:0008270 zinc ion binding
2 GO:0008652 cellular amino acid biosynthetic process
3 GO:0009086 methionine biosynthetic process
</code></pre>
<p>Thanks for your help.</p>
| 2 |
Convert dta files in csv
|
<p>I want to convert several dta files into csv.
So far my code is (to be honest I used an answer I found on stackoverflow...)</p>
<pre><code>library(foreign)
setwd("C:\Users\Victor\Folder")
for (f in Sys.glob('*.dta'))
write.csv(read.dta(f), file = gsub('dta$', 'csv', f))
</code></pre>
<p>It works, but if my folder contains sub-folders they are ignored.
My problem is that I have 11 sub-folders (which may contain sub-folders themselves) I would like to find a way to loop my folder and sub-folders, because right now I need to change my working directory for each sub-folders and. </p>
<p>I'm using R now, I tried to use pandas (python) but it seems that the quality of the conversion is debatable...</p>
<p>Thank you</p>
| 2 |
Git track a remote branch but push to a different branch?
|
<p>Lets assume I have a branch called 'my-local-changes', which is a local branch, that was created from a branch called 'some-remote-branch', which is a remote branch.</p>
<p>Let's also assume there is a third branch called 'develop', which is the remote branch where code is pulled into from multiple branches ('some-remote-branch' is one of them, I also have a local branch called 'develop' that tracks the remote develop branch)</p>
<p><strong>My question is how can i set up 'my-local-changes' to track the 'develop' branch, but push to the branch 'some-remote-branch'?</strong> </p>
<p>For those curious, as to why I want to do this, I would like to be able to run git status and see if I am behind 'develop' while not having to switch to that branch, and easily still be able to push to 'some-remote-branch'</p>
<p>My current process is as follows (I'd love any suggestions for improving this as well)</p>
<pre><code>git checkout -b my-local-branch some-remote-branch
</code></pre>
<p>(make some changes and add them)</p>
<pre><code>git fetch origin
git checkout develop
git status
</code></pre>
<p>(do this to see if any changes on develop that I need to merge, if not run)</p>
<pre><code>git push origin my-local-branch some-remote-branch
</code></pre>
| 2 |
Keep a reference of a DOM node when mounting / unmounting a React component in a non-React application
|
<p>I'm using webpack to use react components in a non-react applications. The idea is to export these in a way so they can be mounted and dismounted on any DOM.</p>
<p>This is the html page where I'm testing the component:</p>
<pre class="lang-php prettyprint-override"><code><script type="text/javascript" src="<?php echo base_url('assets/javascripts/build/component.js') ?>"></script>
<button onclick="showComponent()" />show component</button>
<button onclick="hideComponent()" />hide component</button>
<div id='mainContainer'></div>
<script >
function showComponent() {
MyComponent.mount(document.getElementById('mainContainer'))
}
function hideComponent() {
MyComponent.unmount()
}
</script>
</code></pre>
<p>This is the webpack entry point:</p>
<pre class="lang-jsx prettyprint-override"><code>import React from 'react'
import MyComponent from '/path/to/MyComponent'
import ComponentMounter from '/path/to/ComponentMounter'
let componentMounter = new ComponentMounter(<MyComponent />)
export let mount = componentMounter.mount
export let unmount = componentMounter.unmount
</code></pre>
<p>In the webpack config, I'm exporting the bundle as a library, using:</p>
<pre class="lang-json prettyprint-override"><code>output: {
path: './assets/javascripts/build/',
filename: 'component.js',
libraryTarget: 'var',
library: 'MyComponent'
}
</code></pre>
<p>The ComponentMounter class:</p>
<pre class="lang-jsx prettyprint-override"><code>import ReactDOM from 'react-dom'
class ComponentMounter {
constructor(component) {
this.component = component
}
mount = (element) => {
// This renders the react 'component', mounting it in the DOM 'element'
this.element = ReactDOM.render(this.component, element)
}
unmount = () => {
// This unmounts the react 'component', removing the DOM 'element'
ReactDOM.unmountComponentAtNode(this.element)
}
}
export default ComponentMounter
</code></pre>
<p>Hopefully you can see what I'm trying to do there. When clicking on the show button, the component mounts without problems.</p>
<p>But when I try to unmount it, it seems the element is not a valid DOM element, as I get this warning:</p>
<p><code>invariant.js:38 Uncaught Invariant Violation: unmountComponentAtNode(...): Target container is not a DOM element.</code></p>
<p>How can I keep a reference to a React component mounted in a DOM node within ComponentMounter object so I can easily unmount it when needed?</p>
| 2 |
How do I install OpenCV 3 on Centos 6.8?
|
<p>I'm working on a CentOS cluster right now and have Python2.7 installed. I've managed to get OpenCV 2.4 installed (using <a href="https://superuser.com/questions/678568/install-opencv-in-centos">these</a> helpful instructions) but it does not have all of the functionality of 3 (I need the connectedComponents function and a couple others not available). Omitting the "checkout tags" step results in errors during "cmake". Something else to note is when I attempt to install the ffmpeg package it tells me no such package is available. Error:</p>
<pre><code>CMake Error at 3rdparty/ippicv/downloader.cmake:77 (message):
ICV: Failed to download ICV package: ippicv_linux_20151201.tgz.
Status=6;"Couldn't resolve host name"
Call Stack (most recent call first):
3rdparty/ippicv/downloader.cmake:110 (_icv_downloader)
cmake/OpenCVFindIPP.cmake:237 (include)
...
</code></pre>
| 2 |
How to remove Python tools for Visual Studio (June 2016) update notification? It's already installed
|
<p>I have updated VS 2015 Community to Update 3. According to the installer, this includes Python tools 2.2.4.</p>
<p>However, Visual Studio still reports that update is available (from 2.2.3 to 2.2.4) and when I choose to do that, VS Setup starts, but Update button is disabled. </p>
<p>It enables if I uncheck Python tools (due the fact that in that case it would be removed). </p>
<p>VS Update 3 is installed and in Help / About I can see that Python tools is 2.2.4.</p>
<p>How can I remove notification from VS?</p>
| 2 |
Sampling from a pandas dataframe non-repetitively within a loop
|
<p>I've simplified the code as much as I can but it's still quite long, it should illustrate the problem. </p>
<p>I'm sampling weather data from a dataframe:</p>
<pre><code>import numpy as np
import pandas as pd
#dataframe
dates = pd.date_range('19510101',periods=16000)
data = pd.DataFrame(data=np.random.randint(0,100,(16000,1)), columns =list('A'))
data['date'] = dates
data = data[['date','A']]
#create year and season column
def get_season(row):
if row['date'].month >= 3 and row['date'].month <= 5:
return '2'
elif row['date'].month >= 6 and row['date'].month <= 8:
return '3'
elif row['date'].month >= 9 and row['date'].month <= 11:
return '4'
else:
return '1'
data['Season'] = data.apply(get_season, axis=1)
data['Year'] = data['date'].dt.year
</code></pre>
<p>I want to choose a random year using predetermined year/season tuples:</p>
<pre><code>#generate an index of year and season tuples
index = [(1951L, '1'),
(1951L, '2'),
(1952L, '4'),
(1954L, '3'),
(1955L, '1'),
(1955L, '2'),
(1956L, '3'),
(1960L, '4'),
(1961L, '3'),
(1962L, '2'),
(1962L, '3'),
(1979L, '2'),
(1979L, '3'),
(1980L, '4'),
(1983L, '2'),
(1984L, '2'),
(1984L, '4'),
(1985L, '3'),
(1986L, '1'),
(1986L, '2'),
(1986L, '3'),
(1987L, '4'),
(1991L, '1'),
(1992L, '4')]
</code></pre>
<p>and sample from this in the following way:</p>
<p>generate 4 lists with the years in each season (one list for spring, one for summer etc.)</p>
<pre><code>coldsample = [[],[],[],[]] #empty list of lists
for (yr,se) in index:
coldsample[int(se)-1] += [yr] #function which gives the years which have extreme seasons [[1],[2],[3],[4]]
coldsample
</code></pre>
<p>choose a random year from this list</p>
<pre><code>cold_ctr = 0 #variable to count from (1 is winter, 2 spring, 3 summer, 4 autumn)
coldseq = [] #blank list
for yrlist in coldsample:
ran_yr = np.random.choice(yrlist, 1) #choose a randomly sampled year from previous cell
cold_ctr += 1 # increment cold_ctr variable by 1
coldseq += [(ran_yr[0], cold_ctr)] #populate coldseq with a random year and a random season (in order)
</code></pre>
<p>then generate a new dataframe which chooses multiple random years </p>
<pre><code>df = []
for i in range (5): #change the number here to change the number of output years
for item in coldseq: #item is a tuple with year and season, coldseq is cold year and season pairs
df.append(data.query("Year == %d and Season == '%d'" % item))
</code></pre>
<p>The problem is that this selects from <code>coldseq</code> (which has the same year/season combination) every time, and doesn't generate a new coldseq. I need to reset coldseq to empty and generate a new one for each iteration of the final for loop, but can't see a way of doing this. I've tried embedding code within the loop in multiple ways but it doesn't seem to work.</p>
| 2 |
Skeleton Tracking on Raspberry Pi using Kinect
|
<p>I'm trying to do some skeleton tracking on Raspberry Pi.
I installed libfreenect and OpenNI. I can't find NITE ARM binaries anywhere as it is acquired by Apple and no support is provided now. Where can I find the other required binaries and how to install them on Raspberry Pi?</p>
| 2 |
crontab script fail: end of file unexpected (expecting ")") when call $(date)
|
<p>I want to add</p>
<pre><code>0 5 1 * * goaccess -f /var/log/nginx/access.log -a > /home/xan/reports/report-week-$(date +%Y.%m.%d).html
</code></pre>
<p>but crontab always complains about that:</p>
<pre><code>Subject: Cron <root@deimos> goaccess -f /var/log/nginx/access.log -a > /home/xan/reports/report-week-$(date +
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
Message-Id: <E1bIogT-0001FX-9n@deimos>
Date: Fri, 01 Jul 2016 05:00:01 +0200
/bin/sh: 1: Syntax error: end of file unexpected (expecting ")")
</code></pre>
<p>What the proper syntax to do that?</p>
| 2 |
Setting a default layout in the controller (Laravel 5.2)
|
<p>I'd like to set a default layout in my BaseController, so that it is used for every view I have. I don't want to use "@extends" in every single view.</p>
<p>In Laravel 4 this was easy to do. Now I can't find any way to do this in Laravel 5.2 .</p>
<p>Does anyone have an idea?</p>
<p>BTW: this is my first question on stackoverflow, I hope i'm following the rules.</p>
| 2 |
Android: Firebase Update Issue When the app is in background
|
<p>Hey I m going to develop an location tracker app in which, this app in client device which constantly send it location to the firebase db.
Here the problem is that it will send the data to firebase only first 3 minutes then it wont. I don't know whats happening. ?
For that even i put a log message that log message is printed perfectly even after three minutes
Any one please help on this........!
Here i attached 3 file One BackgroundLocation: Which is the service in background which will extract the device location and call the LocationReceiver which extends broadcast receiver where it will print log message and send the data to firebase through FBSender.</p>
<p>Thanks in advance</p>
<p>BackgroundLocation.java
Which runs in Background to get the location details and call the broadcast Reveiver. LocationReveiver.java</p>
<pre><code> /**
* Created by geekyint on 1/7/16.
*/
public class BackgroundLocation extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
IBinder mBinder = new LocalBinder();
private GoogleApiClient mGoogleApiClient;
private PowerManager.WakeLock mWakeLock;
private LocationRequest mlocationRequest;
//Flag for boolean request
private boolean mInProgress;
private boolean serviceAvailabe = false;
public class LocalBinder extends Binder {
public BackgroundLocation getServerInstance() {
return BackgroundLocation.this;
}
}
@Override
public void onCreate() {
super.onCreate();
mInProgress = false;
//Create the lcoation request object
mlocationRequest = LocationRequest.create();
//Use the acurecy
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//The INTERVAL
mlocationRequest.setInterval(Constants.UPDATE_INTERVAL);
//The FAST INTERVAL
mlocationRequest.setFastestInterval(Constants.FAST_INTERVAL);
serviceAvailabe = serviceConnected();
setUpALocationClientIfNeeded();
ComponentName receiver = new ComponentName(this, LocationReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
/*ComponentName receiver1 = new ComponentName(this, FireBaseSender.class);
PackageManager pm1 = this.getPackageManager();
pm1.setComponentEnabledSetting(receiver1,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
}
private void setUpALocationClientIfNeeded() {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
}
//Create the new Connection to the client
private void buildGoogleApiClient() {
this.mGoogleApiClient = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
private boolean serviceConnected() {
//Check the google Play service availibility
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
//IF AVAILABLE
if (resultCode == ConnectionResult.SUCCESS) {
return true;
} else {
return false;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (this.mWakeLock == null) {
this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
}
if (!this.mWakeLock.isHeld()) {
this.mWakeLock.acquire();
}
if (!serviceAvailabe || mGoogleApiClient.isConnected() || mInProgress) {
return START_STICKY;
}
setUpALocationClientIfNeeded();
if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() || !mInProgress) {
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
mInProgress = true;
mGoogleApiClient.connect();
}
return START_STICKY;
}
@Override
public void onLocationChanged(Location location) {
String msg = Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Log.d("debug", msg);
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ":" + msg, Constants.LOCATION_FILE);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onDestroy() {
// Turn off the request flag
this.mInProgress = false;
if (this.serviceAvailabe && this.mGoogleApiClient != null) {
this.mGoogleApiClient.unregisterConnectionCallbacks(this);
this.mGoogleApiClient.unregisterConnectionFailedListener(this);
this.mGoogleApiClient.disconnect();
// Destroy the current location client
this.mGoogleApiClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ":
// Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
if (this.mWakeLock != null) {
this.mWakeLock.release();
this.mWakeLock = null;
}
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Stopped", Constants.LOG_FILE);
ComponentName receiver = new ComponentName(this, LocationReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
/*
ComponentName receiver1 = new ComponentName(this, FireBaseSender.class);
PackageManager pm1 = this.getPackageManager();
pm1.setComponentEnabledSetting(receiver1,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);*/
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Intent intent = new Intent (this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(this, 54321, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
mlocationRequest, pendingIntent);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onConnectionSuspended(int i) {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mGoogleApiClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected", Constants.LOG_FILE);
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
</code></pre>
<p>}</p>
<p>Here The LocationReceiver Code:</p>
<pre><code>public class LocationReceiver extends BroadcastReceiver {
private String TAG = this.getClass().getSimpleName();
private LocationResult mLocationResult;
private double latitude;
private double longitude;
private double speed;
private String time;
@Override
public void onReceive(Context context, Intent intent) {
// Need to check and grab the Intent's extras like so
if(LocationResult.hasResult(intent)) {
this.mLocationResult = LocationResult.extractResult(intent);
//new SaveToFireB().insertToFireBase(mLocationResult.getLastLocation());
new FBSender().put(mLocationResult.getLastLocation());
Log.i(TAG, "Location Received: " + this.mLocationResult.toString());
String msg = String.valueOf(mLocationResult.getLastLocation().getLongitude()) + " " +
String.valueOf(mLocationResult.getLastLocation().getLatitude());
// appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ":" + msg, Constants.LOCATION_FILE);
}
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre>
<p>Here Which will call FBSender to send the data to firebase.
Ther real problems comes here.
It will send the data only in first three minutes then it wont send the data to firebase
For confirmation whether the control going there or not i put log message there that log message will be printed perfectly even after 3 minutes from the start of the app </p>
<p>Here is FBSender.Java</p>
<pre><code>public class FBSender extends Service {
private String TAG = "FBSender";
private double latitude;
private double longitude;
private double speed;
private String time;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void put (Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
speed = location.getSpeed();
time = DateFormat.getTimeInstance().format(new Date());
Log.e(TAG, "Entering the run ()");
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference reference = database.getReference("users/" + user.getUid() + "/vehicles");
Log.e(TAG, "I M in the middle");
Map mLocations = new HashMap();
mLocations.put("latitude", latitude);
mLocations.put("longitude", longitude);
mLocations.put("speed", speed);
mLocations.put("time", time);
reference.setValue(mLocations);
Log.e(TAG, "Exiting The run ()");
}
}
</code></pre>
| 2 |
Visual Studio Professional 2013 and .NET Framework 4.6.1
|
<p>I've got a copy of Visual Studio Professional 2013, trying to load up a project targeting .NET Framework version 4.6.1. I have installed the actual framework, the targeting pack, and the clickonce bootstrapper, all from Microsoft directly.</p>
<p>For whatever reason, the project can't sense that 4.6.1 is installed, and keeps asking me to download it (which, to my frustration, just leads to microsoft.com/en-us), or to re-target to 4.5, the version my machine apparently believes is the most current.</p>
<p>I'm not sure how to get around this, but it seems to be a known issue for machines running OS versions prior to Windows 8.1. I have no issues on my Windows 10 device running 2015 Community (different version, I know).</p>
<p>Either way, need to resolve this on the Win 7 machine. </p>
| 2 |
Magnific-Popup close callback does not execute
|
<p>For each <code><a></code> that has <code>mfp-ajax</code> class will be executed as a pop-up box, and this pop-up box use the plugin in Magnific-Popup.</p>
<p><strong>HTML:</strong> </p>
<pre><code><a href="/target" class="mfp-ajax multiselect-modal">View List</a>
</code></pre>
<p><strong>Javascript:</strong></p>
<pre><code>magnificSetting: {
type: 'ajax',
mainClass: 'mfp-fade',
ajax: {
settings: {
cache: false
}
}
},
modals: function () {
var self = this;
$('a.mfp-ajax').each(function () {
var $this = $(this);
$this.magnificPopup(self.settings.magnificSetting);
});
}
</code></pre>
<p>The codes works fine, however <code><a></code> is sometimes dynamically generated in the DOM and I have to create a separate script for Magnific-Popup callbacks. So what I did is I followed what is in the documentation, see the codes below:</p>
<pre><code>$(document).on('mfpClose', '.multiselect-modal', function () {
console.log('test');
});
</code></pre>
<p>I tried this code but this does not get executed, how do I attach this in an element that is being generated dynamically in the DOM and when the pop-up opens and the user close it, it will go to the above code. Am I missing something here?</p>
| 2 |
nix: install derivation directly from master branch
|
<p>I was wondering, why some packages appear in older versions than in the github repo when querying them via nix-env -qa .. .
I learned that this is due to the fact that the master branch has not been merged to the unstable-channel.</p>
<p>How would I manually install a derivation from the master branch, in order to get the latest version?</p>
| 2 |
Is it possible to log spock feature method names and clause labels?
|
<p>I'd like to be able to log the spock feature names and clause labels when running some automated tests. This would help with debugging test issues when using a headless browser for automation, specifically phantomjs. Reason being, phantomjs does not always behave the same way as when using the chrome WebDriver. It would also be nice to have if this is even possible. </p>
<pre><code>def "Login logout test"(){
given: "Go to login page"
...
when: "Submit username and password"
...
then: "Dashboard page displayed"
...
when: "logout"
...
then: "Returned to login page"
...
}
</code></pre>
<p>For example, It would be cool if I could get the above sample spock feature method to log the labels like this.</p>
<pre><code>Login logout test
Go to login page
Submit username and password
logout
Returned to login page
</code></pre>
| 2 |
How to get contacts in alphabetical order using $cordovaContacts plugin of IONIC Framework
|
<p>I'm trying to build an app in Ionic Framework which fetches phone contacts using <code>$cordovaContacts</code> plugin. And everything works fine but how can I arrange these fetched contacts in alphabetical order i.e from A to Z. I know fetching contacts as per search keyword, but I'm not able to fetch the contacts in alphabetical order.... </p>
<pre><code>$cordovaContacts.find({filter : '', fields: ['displayName']}).then(function(allContacts) {
for (var i = 0; i < allContacts.length ; i++) {
$scope.Contacts.push({
cid : allContacts[i]['id'],
cname: allContacts[i]['displayName'],
numbers: allContacts[i]['phoneNumbers']
});
}
});
</code></pre>
| 2 |
WSO2 esb access node from xml in property
|
<p>i stored an XML document in a property:</p>
<pre><code><property expression="$body//*" name="InDoc"
scope="default" type="OM"/>
</code></pre>
<p>in a later step of the proxy a want to access the XML doucment.</p>
<p>This</p>
<pre><code> <log level="custom">
<property name="InDoc" expression="get-property('InDoc')"/>
</log>
</code></pre>
<p>gives the whole XML document. But I would like to access only some parts of the XML e.g. only one value in a later step of the proxy. I already tried </p>
<pre><code> <log level="custom">
<property name="InDoc" expression="get-property('InDoc')//AAA"/>
</log>
</code></pre>
<p>or this</p>
<pre><code><log level="custom">
<property name="InDoc" expression="$ctx:InDoc//AAA"/>
</log>
</code></pre>
<p>But both do not work. Is there another way?
Thanks in advance.</p>
<p>Roland</p>
| 2 |
Passing model from view to controller using Html.RenderAction results in model being null
|
<p>I have following model:</p>
<pre><code>public class Foo
{
public List<Employee> Employees{ get; set; }
public List<Company> Companies{ get; set; }
public List<Admin> Admins{ get; set; }
}
</code></pre>
<p>Then I have my controller actions:</p>
<pre><code>public ActionResult Index()
{
Foo model = GetFooFromSomewhere();
return PartialView("Index", model);
}
public ActionResult Employees(List<Employee> model)
{
return PartialView("Employees", model);
}
public ActionResult Companies(List<Company> model)
{
return PartialView("Companies", model);
}
public ActionResult Admins(List<Admin> model)
{
return PartialView("Admins", model);
}
</code></pre>
<p>Then I have my views</p>
<p>Index.cshml:</p>
<pre><code>@model Foo
@if(Model.Employees.Count > 0)
{
@{Html.RenderAction("Employees", "Config", Model.Employees);}
}
@if(Model.Companies.Count > 0)
{
@{Html.RenderAction("Companies", "Config", Model.Companies);}
}
@if(Model.Admins.Count > 0)
{
@{Html.RenderAction("Admins", "Config", Model.Admins);}
}
</code></pre>
<p>Employees.cshtml:</p>
<pre><code>@model List<Employee>
//Display model here
</code></pre>
<p>Companies.cshtml</p>
<pre><code>@model List<Company>
//Display model here
</code></pre>
<p>Admins.cshtml</p>
<pre><code>@model List<Admin>
//Display model here
</code></pre>
<p>As you can see, I use Index.cshtml to get a object that contains multiple lists. This is because I need to hide the actions if no items are found in the list/s. However, when I pass them to the controller again using @Html.RenderAction(...), I get null inside the controller action when I am expecting a List. Why?</p>
| 2 |
R markdown: problems with Latex headers
|
<p>When I setup a header by using a custom .sty file and the fancyhdr package, the header text is automatically formatted and the text is taken from the first header defined in the .Rmd file, and I cannot override this behavior. For instance, I have the following R markdown file</p>
<pre><code>---
output:
pdf_document:
includes:
in_header: report.sty
keep_tex: yes
geometry: tmargin=2cm, bmargin=2.5cm
classoption: a4paper
---
\pagenumbering{gobble}
# Behavioural profile of your dog
blah... blah...
```{r echo}
# Some R code here...
```
</code></pre>
<p>And this is the .sty file:</p>
<pre><code>%
% This file must be saved with UTF-8 encoding, otherwise pandoc will complain
% for instance about nordic characters.
%
\usepackage{palatino}
\renewcommand{\familydefault}{\sfdefault} % sans serif
\fontfamily{ppl}\selectfont
\usepackage{blindtext}
\usepackage{eso-pic, rotating, graphicx, calc}
\usepackage[nomessages]{fp}
% Code to add a vertical gray band in the inner margin :
\usepackage{eso-pic}
\definecolor{colorMarge}{RGB}{242,242,245}
\newlength{\distance}
\setlength{\distance}{0.0in} % 0.5in
\newlength{\rulethickness}
\setlength{\rulethickness}{0.3in} % 1pt
\newlength{\ruleheight}
\setlength{\ruleheight}{11in} % Longueur de la ligne
\newlength{\xoffset}
\newlength{\yoffset}
\setlength{\yoffset}{0.5\dimexpr\paperheight-\ruleheight}
\AddToShipoutPicture{%
\ifodd\value{page}%
\setlength{\xoffset}{\distance}%
\else
\setlength{\xoffset}{\dimexpr\paperwidth-\rulethickness-\distance}%
\fi
\AtPageLowerLeft{\put(\LenToUnit{\xoffset},\LenToUnit{\yoffset}){\color{colorMarge}\rule{\rulethickness}{\ruleheight}}}%
}
\newcommand{\sidewaysText}{R Development Core Team (2008). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. ISBN 3-900051-07-0, URL http://www.R-project.org.}
%\newlength{\swtLen}
%\setlength{\swtLen}{\widthof{\sidewaysText}}
%\newlength{\swtPos}
%\setlength{\swtPos}{\yoffset}
%\addtolength{\swtPos}{0.5\swtLen}
%\newlength{\swtPos}
%\setlength{\swtPos}{350em}
\AddToShipoutPicture{\put(5,10){\rotatebox{90}{\scalebox{0.8}{\sidewaysText}}}}
\usepackage{fancyhdr}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}
\chead{I want this header}
\lfoot{\scriptsize
Here is some footer text.}
</code></pre>
<p>But this is the output:</p>
<p><a href="https://i.stack.imgur.com/spRHb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/spRHb.png" alt="enter image description here"></a></p>
<p>As you can see, the "THIS IS SOME HEADER" appears as part of the header in capital letters, italics and aligned to the right. How can avoid this?</p>
<p>Thanks in advance!</p>
| 2 |
Carousel slide with Swipe jQuery Bootstrap 3
|
<p>i'm trying to do this with the solution of this thread:</p>
<p><a href="https://stackoverflow.com/questions/21349984/how-to-make-bootstrap-carousel-slider-use-mobile-left-right-swipe">How to make Bootstrap carousel slider use mobile left/right swipe</a></p>
<p>But dont work for me, this is my code:</p>
<pre><code><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<link href="assets/css/bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="assets/js/jquery.mobile-1.4.5.js"></script>
<script src="assets/js/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<section class="wrap" id="month" >
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="" alt="Chania">
</div>
<div class="item">
<img src="" alt="Chania2">
</div>
<div class="item">
<img src="" alt="Flower1">
</div>
<div class="item">
<img src="" alt="Flower2">
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</section>
<script src="assets/js/bootstrap.min.js"></script>
<SCRIPT>
$(document).ready(function() {
$("#myCarousel").swiperight(function() {
$("#myCarousel").carousel('prev');
});
$("#myCarousel").swipeleft(function() {
$("#myCarousel").carousel('next');
});
});
</SCRIPT>
</body>
</code></pre>
| 2 |
Plot of the L0 norm penalty function in matlab
|
<p>I am interested to plot the <code>L0-norm</code> penalty function in matlab.</p>
<p>In fact, I know that the <code>L0-norm</code> of a vector <strong>x</strong>, ||<strong>x</strong>||_0, returns a value which designates the total number of nonzero elements in <strong>x</strong>. In other terms, ||<strong>x</strong>||_0 = #(i | xi !=0).</p>
<p>For example, for the L1-norm of <strong>x</strong>, it returns the sum of the absolute values of the elements in <strong>x</strong>. The matlab code to plot the L_1 norm penalty function is:</p>
<pre><code>clear all;
clc;
x = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5];
penal = zeros (length(x),1);
lambda = 2; % the tuning parameter
for ii = 1 : length(x)
penal(ii) = lambda*abs(x(ii));
end
figure
plot(x(:), penal(:), 'r');
</code></pre>
<p>But now what about the L_0 norm??</p>
<p>Any help will be very appreciated!</p>
| 2 |
How do you draw a sector in matplotlib?
|
<p>I would like just a pure sector line, not a wedge. I am trying to use it to represent the uncertainty of a vector's direction, at the tip of the vector arrow. I am using plt.arrow to plot the arrow over a basemap in matplotlib. </p>
<p>I haven't been able to find any way to express this uncertainty other than with a wedge. I was wondering if it is possible to plot just a sector line at the tip of the arrow. </p>
| 2 |
Difference between gcc "-Xlinker" and "-Wl," options?
|
<p>According to the <a href="https://gcc.gnu.org/onlinedocs/gcc-6.1.0/gcc/Link-Options.html#Link-Options" rel="nofollow">GCC 6.1 manual on Link Options</a>:</p>
<blockquote>
<p><strong>-Wl, option</strong></p>
<p><strong><em>Pass option as an option to the linker.</em></strong> If option contains commas, it is split into multiple options at the commas. </p>
<p><strong>-Xlinker option</strong></p>
<p><strong><em>Pass option as an option to the linker.</em></strong> You can use this to supply system-specific linker options that GCC does not recognize.</p>
</blockquote>
<p>Why we need 2 of them?</p>
<h2>ADD 1</h2>
<p>Similarly, why we need both <code>-Xassembler</code> and <code>-Wa</code> for assembler options?</p>
<p>Quote from <a href="https://gcc.gnu.org/onlinedocs/gcc-6.1.0/gcc/Assembler-Options.html#index-Wa-1113" rel="nofollow">GCC 6.1 doc on Assembler Options</a>:</p>
<blockquote>
<p><strong>-Wa,option</strong></p>
<p><strong><em>Pass option as an option to the assembler.</em></strong> If option contains commas, it is split into multiple options at the commas.</p>
<p><strong>-Xassembler option</strong></p>
<p><strong><em>Pass option as an option to the assembler.</em></strong> You can use this to supply system-specific assembler options that GCC does not recognize.</p>
</blockquote>
| 2 |
In angular how can I test a scope function is being called in my directive?
|
<p>In angular how can I test a scope function is being called in my directive?</p>
<p>I'm using jasmine, karma runner and js unit tests with Angular version 1.</p>
<p><strong>This is my directive code:</strong></p>
<pre><code>angular.module("myApp.directives")
.directive("test", ["$rootScope", function($rootScope) {
return {
restrict: "E",
scope: {
"figures": "="
},
templateUrl: "templates/components/test.html",
link: function(scope) {
scope.init = function() {
if (scope.figures !== undefined) {
for (let i = 0; i < scope.figures.length; i++) {
scope.figures[i].isModalVisible = false;
}
}
};
scope.init ();
}
};
}]);
</code></pre>
<p><strong>This is my unit test:</strong></p>
<pre><code>describe("test", function () {
var element,
scope,
otherScope
mockData = [
{
isModalVisible: true
},
{
isModalVisible: false
}
];
beforeEach(angular.mock.module("myApp.directives"));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
scope.agg = mockData;
element = "<test figures=\"agg\"></test>";
element = $compile(element)(scope);
angular.element(document.body).append(element);
scope.$digest();
otherScope = element.isolateScope();
spyOn(otherScope, "init");
}));
//This one doesn't work
it("should close all modals by default", function () {
expect(otherScope.init).toHaveBeenCalled();
});
});
</code></pre>
<p><strong>This is the error I currently get: " Expected spy init to have been called."</strong></p>
| 2 |
How to fix the error "Rename refactoring can't be applied in this context" in Netbeans?
|
<p>I'm currently working on a HTML5 projects in netbeans and wanted to change a variable name with multiple occurrence. However, when I clicked refactor and then rename, the IDE tells me that:</p>
<blockquote>
<p>Rename refactoring can't be applied in this context.</p>
</blockquote>
<p>So is it possible to refactor variable names in HTML5 projects in Netbeans? </p>
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.