Menu
  • HOME
  • TAGS

Python time.sleep on line 2 happens before line 1

python,time,sleep

self.myTimer = QTimer() self.myTimer.singleShot(2000, lambda: self.output.clear()) ...

cannot find symbol, java, classloader

java,import,classloader

Your Java file is missing an import statement for java.util.List, which is why it's failing to compile. Unlike String and Integer, List is not in the java.lang package. You need to import java.util.List, not java.lang.List. If I'm understanding your scenario correctly, your other program is generating the import statements and...

mfp cli build: missing cordova on preview

mobilefirst,mobilefirst-cli

This is perfectly expected. From the preview URL it seems you are looking at the "Simple Preview" which actually only loads the web resources - and in this case Cordova is indeed not available, as Cordova is available only when previewing the actual app in either the Mobile Browser Simulator...

Convert MSB first to LSB first

c++,c,visual-c++

What was wrong is that you first assigned the value's MSB to the temp's LSB, then shifted it again to MSB and assigned value's LSB to LSB. Basically, you had interchanged *(m_pCurrent + 1) and *m_pCurrent so the whole thing had no effect. The simplified code: #include <iostream> using namespace...

Why can primitives not be stored in Java collections, but primitive arrays can?

java

Because Java arrays are objects, not primitives. And you can store references to objects in Java collections implemented as generic types. From the Java language specification, Chapter 10: Arrays: In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object...

std::is_copy/move_constructible fails even though copy/move constructors are defaulted

c++,copy-constructor,c++14,move-constructor

Your problem is that the static_assert is in the class declaration. The compiler can't know for sure when it reaches the static_assert whether the class is copy- or move-constructible, because the class hasn't been fully defined yet.

MarionetteJS - cannot reference this in template function

backbone.js,this,marionette

You can use underscore's bindAll to bind template to your marionetteItem View's this whenever its called . So something like : Backbone.Marionette.ItemView.extend({ initialize: function(){ _.bindAll(this, 'template'); }, template: function() { //this refers to the parent object scope. } }); ...

Slim framework get the data from a form

php,forms,slim

You can access to your posted data using post() method of request(): $app->post('/', function() use ($app){ $req = $app->request(); $email = $req->post('Email'); $subject = $req->post('Subject'); echo "Email: $email<br/>"; echo "Subject: $subject"; }); ...

Scalable way to stack in CSS

html,css

You can make your elements float and give them a negative margin for the desired effect. The <div class="nofloat">Floating box</div> is to make every annotation skip a line. The visibility is set to hidden so that the element still affects the layout. <div class="floating-box1">Floating box1</div> <div class="nofloat">Floating box</div> <div class="floating-box">Floating...

Why is there always a dash in my title tag

html,asp.net,vb.net

The proper format I think you need to remove runat from head tag. <head> <title runat="server" id="PageTitle"></title> </head> In the Code behind you can add: PageTitle.InnerHtml = "sdvd" ...

Scheduling an Unsampled Report via the API

google-analytics

I'd strongly recommend reading the developer overview of the unsampled reporting methods of the Management API. It'll give you a good sense of how the process works. To answer some of your specific questions: First off, is that a correct assumption? Does the insert trigger an unsampled report for immediate...

Expand button in TableRow

android,image,drawable

Use Layout_weight for Buttons <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000" > <TableLayout android:id="@+id/table1" android:layout_width="match_parent" android:layout_height="match_parent"...

Accessing individual objects that all have the same categoryBitMask

ios,sprite-kit,skphysicsbody,bitmask

Your if statements are all just checking if the child exists, which it seems they all do. What I think you want to check is if the collision node has the name you are looking for, so change: if ([_backgroundLayer childNodeWithName:@"bounds"]) to: if ([firstBody.node.name isEqualToString:@"bounds"]) ...

Speeding up sql inserts on postgresql with JDBC?

java,postgresql,jdbc

Are you calling first isMatchIdInDatabase then insertMatchId for many records? Possible duplicate: Efficient way to do batch INSERTS with JDBC It is an expensive operation to open a connection and query for a single record. If you do that thousands of times, it gets very slow. You should try to...

How to make use of Maven Classifier in an application with Gradle build system

java,maven,gradle

You didn't specify what kind of artifact you install and then deploy (jar, war), but but as you can see here jar has classifier property. Have you tried setting it?

Can't run iex in Windows command prompt or git bash

elixir,chocolatey

Neither Erlang nor Elixir are automatically added to your path by Chocolatey. So make sure you add both Erlang's and Elixir's bin directory to your path. Since you mention that you're not really used to Windows, try running this at the command prompt before you try to execute iex.bat: SET...

Cast to larger type in switch case

c,embedded

It looks like a slightly failed attempt to get rid of implicit integer promotions on a 8-bit or 16-bit microcontroller. First of all, there is no way integer promotion can cause harm here, so preventing it is overly pedantic and just reduces readability. At a glance it looks like nonsense....

Hosting a laravel project on openshift

ssh,laravel-5,openshift

You should try checking out the laravel 5 quickstart on the OpenShift Hub (https://hub.openshift.com/quickstarts/115-laravel-5-0), check out the source code and see what modifications were made to make it run correctly on OpenShift and then incorporate those changes into your application.

Error : Conversion failed when converting date and/or time from character string

c#,sql

Aside from the SQL Injection issues with sending in user variables directly to the database, I suggest using parameterized queries to simplify what you're trying to do. SqlCommand cmd7 = new SqlCommand("UPDATE Employees SET Designation = @designation, Employee_Subgroup = @subgroup, Date_Of_Birth = @dateofbirth, Date_Of_Joining = @dateofjoining Where Employee_Name = @employeename",...

Dynamically turn bSearchable option when hiding columns

datatable,datatables

Although I couldn't find it in documentation, I was able to find this post where Allan Jardine, creator of DataTables plug-in, recommends the method my answer is based on. However the method mentioned in the post is not complete and requires table invalidation/re-draw for new setting to take effect. Property...

MySQL - Consider multiple rows with equal value in two columns as one row

mysql,count,group-by,sum,distinct

I would start by getting distinct action_id and date pairs like this: SELECT DISTINCT action_id, date_of_action FROM myTable; Once you have that, you can get count using conditional aggregation: SELECT SUM(action_id = 1) AS 'count 1', SUM(action_id = 2) AS 'count 2' FROM( SELECT DISTINCT action_id, date_of_action FROM myTable) tmp;...

Why does this work in GHCi but not Scotty?

haskell,scotty,wai

fs <- liftIO $ filterM (doesFileExist . ((++) prefix)) entries Should that not be (++) path?...

How to share Azure Redis Cache between environments?

azure,redis

One approach is to use multiple Redis databases. I'm assuming this is available in your environment :) Some advantages over prefixing your keys might be: data is kept separate, you can flushdb in test and not touch the production data keys are smaller and consume less memory The main disadvantage...

Redirect domain and subdomain in SF2

symfony2,routing,subdomain

I dont know if this is the best way to do this but I have made it work. public function onKernelRequest(GetResponseEvent $getResponseEvent) { $request = $getResponseEvent->getRequest(); $host = $request->getHost(); $base_host = $this->baseHost; $sub_domain = str_replace('.'.$base_host,'',$host); $site = $this->em->getRepository('AppBundle:Client')->findOneBy(['subDomain' => $sub_domain]); if(!$site && $base_host != $sub_domain){ throw new NotFoundHttpException(sprintf( 'Cannot find...

SSRS Report Builder: Creating text color expression based on textbox value?

sql,sql-server,tsql,reporting-services,reportbuilder

The answer is yes, if you are using a very recent version of SSRS: =IIF(Me.Value < 0,"Red","Green") Link to original article here Hope that helps....

IE11 IFrame contents does not load

asp.net-mvc-4,internet-explorer,iframe,iis-express

I have found this issue and how to resolve it. The problem was that my web application is a Single Page Application using .NET MVC/Durandal/Breeze. Since it's a SPA, all the routing is done javascript and page URLs are setup after the hashtag prefix like this #/resources/info/1 This behavior causes...

ASP.NET MVC 5 relationship one to one with ApplicationUser

asp.net-mvc,entity-framework,asp.net-mvc-5,asp.net-identity,asp.net-identity-2

You could do it in the constructor: public ApplicationUser() { MapPosition = new MapPosition { PositionX = 0, PositionY = 0 }; } I prefer to construct view models in my Create action on the controller and handle it there. Then use AutoMapper to copy into the entity before updating....

How to setup cloud9-ide to reference other Javascript files?

javascript,cloud9-ide

There isn't a way for the Cloud9 linter (Cloud9 uses ESLint to lint Javascript) to know which files will be loaded before a certain file in which html file, but there is a way to let the linter know which objects are global so it will not warn you about...

JavaScript object literal. Why can't I refer to a method via “this”? [duplicate]

javascript

The logic looks good apart from 1 issue in your init function involving the this variable. In a statement like object.method(), within the method function, this refers to object. Keep this in mind. Now, Here's the problematic portion of your code: init: function() { if (!$('.mwdek').length) { var dek =...

Caffe: Extremely high loss while learning simple linear functions

python,neural-network,deep-learning,caffe,lmdb

The loss generated is a lot in this case because Caffe only accepts data (i.e. datum.data) in the uint8 format and labels (datum.label) in int32 format. However, for the labels, numpy.int64 format also seems to be working. I think datum.data is accepted only in uint8 format because Caffe was primarily...

SAS differences in outcome between sql and proc means

sas,sas-macro,proc-sql

proc sql noprint; select sum(zindi&aa. * wprm&aa.)/sum(wprm&aa.) into :Mean_zindi_aa from Panel(where=(annee&ap.<="&nais18" )); quit; Try this. Looks like you are trying to do a mean on (zindi&aa. * wprm&aa.). If you need the weighted average the above should work. because weighted average = sum(weight*variable)/sum(weights)...

Django Form context data lost on validation fail

python,django,django-forms

Finally solved it by amending the else clause as follows: user_object = self.request.user files = [user_object.logo] return render_to_response('directory/business_edit.html', {'form': form, 'uploaded_files': files}, context_instance=RequestContext(request)) As @Alasdair pointed out, it seems it is not a good idea to use class based views if you need any sort of custom behaviour. Probably best...

Rookie error while writing test with Chai, Mocha, Express, johnny-five and node

javascript,node.js,mocha,chai

After some playing around I found my error. johnny-five needs some time to connect to the board via the serial. As soon as the build in REPL is available I can use the functions on() and off(). So I made my test wait for 5 seconds before making the call...

Clang or GCC compiler for c++ 11 compatibility programming on Windows?

windows,c++11,gcc,clang,compatibility

Notice that compiler != IDE. VC++ is one of the most populars on Windows and depending on its version it has a good support for C++11 features. Check the list on the msdn blog to find out if there's everything you need. Gcc is also ported to Windows and you...

Whats the difference between 127.0.0.1 and ::1

osx,apache,localhost,hosts,apache-config

The first one is an IPv4 address and the other signifies and IPv6 local address. Loopback address for ipv4 127.0.0.1 imac.dev Loopback local address for ipv6 ::1 imac.dev In most current OSes IPv6 if enabled, takes precedence over ipv4 so that might be the reason you were having that issue....

Remove all Elements With a Custom Null Value Java

java,list,null,remove-if

In java 8 you could do dupeWordList.removeIf(e -> e.getValue() == null) ...

Exporting to CSV and Summing hours in Ruby on Rails

ruby,ruby-on-rails-3,csv

With some help from a friend and researching APIdocs I was able to refactor the method as so: def self.to_csv(records = [], options = {}) CSV.generate(options) do |csv| csv << ["Employee", "Clock-In", "Clock-Out", "Station", "Comment", "Total Shift Hours"] # records.group_by{ |r| r.user }.each do |user, records| records.each do |ce| csv...

selenium webdriver in python

python,selenium

If you have to use Selenium for navigation, such as on JavaScript-heavy sites, It would suggest acquiring the page source and using an HTML parser to extract the data you want. BeautifulSoup is a great choice of parser. For example: html = driver.page_source soup = BeautifulSoup(html) # Get *all* 'p'...

Get functions of a class

javascript,oop,ecmascript-6

This function will get all functions. Inherited or not, enumerable or not. All functions are included. function getAllFuncs(obj) { var props = []; do { props = props.concat(Object.getOwnPropertyNames(obj)); } while (obj = Object.getPrototypeOf(obj)); return props.sort().filter(function(e, i, arr) { if (e!=arr[i+1] && typeof obj[e] == 'function') return true; }); } Do...

Installing RVM with a specific bash command format using `-s`

linux,bash,rvm

-s is a bash argument not an rvm-installer argument. The other arguments are the rvm-installer arguments. So just pass those to rvm-installer yourself. ./rvm-installer stable --auto-dotfiles Using the, entirely pointless, explicit call to bash that would look like this /bin/bash -c './rvm-installer stable --auto-dotfiles 2>&1' though that could just as...

Drive Opera with selenium python

python,selenium,opera

Based on your question it looks like you are using an old driver for Opera version 12 and older. Assuming that you're trying to use the most recent version of Opera you'll want to use the driver available at the following site: OperaChromiumDriver The site lists sample python code which...

What is the minimum number of bits I need to express a n-bit, signed std_logic_vector in VHDL?

vhdl

Since you have specified that you're using a signed value, you may want to use the signed type (from the numeric_std library) instead of the more generic std_logic_vector. If your number is a compile time constant, you can write a function starting from the leftmost bit (in a for loop...

tellij.ide.SystemHealthMonitor - Low disk space on a IntelliJ IDEA system directory partition [closed]

java,intellij-idea,ide

Its resolved after adding this parameter - idea.no.system.path.space.monitoring=true in < intelliJ installed dir >/bin/idea.properties file. Source - https://youtrack.jetbrains.com/issue/IDEA-118718...

How to show a label after same second in a VB.NET

vb.net

Assuming WinForms? One way it could be done... Public Class Form1 Private LabelsEnumerator As IEnumerator Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim Labels() As Label = {Label1, Label2, Label3, Label4} For Each lbl As Label In Labels lbl.Hide() Next LabelsEnumerator = Labels.GetEnumerator Timer1.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds Timer1.Start()...

Passing attributes while using a partial inside another view

ruby-on-rails,ruby,devise

You can use hidden_field in the form for user_id and company_id f.input :user_id, :as => :hidden, :input_html => { :value => current_user.id } f.input :company_id, :as => :hidden, :input_html => { :value => @company.id } You need to define @company = Company.find(params[:id]) in companies_controller show method for this....

Pandas: Conditionally generate descriptions from column content

python,pandas

I spent some time writing this function: description_map = {"AXP":"American Express", "BIDU":"Baidu"} sign_map = {"LONG": "", "SHORT": "-"} stock_match = re.compile(r"\s(\S+)\s") leverage_match = re.compile("[0-9]x|x[0-9]|X[0-9]|[0-9]X") def f(value): f1 = lambda x: description_map[stock_match.findall(x)[0]] if stock_match.findall(x)[0] in description_map else '' f2 = lambda x: leverage_match.findall(x)[0] if len(leverage_match.findall(x)) > 0 else '' f3 =...

is it possible to stop php sessions carrying over from different folders

php,session

Dont use $_SESSION['userID'] to validate every session. once you set this it works across the site. So try this website 1 session $_SESSION['userID1'] website 2 session $_SESSION['userID2'] website 3 session $_SESSION['userID3'] website 4 session $_SESSION['userID4'] ...

Code Coverage for Strong Named Assemblies with Visual Studio Premium

.net,visual-studio,code-coverage

OK. I now have a working Test Code Coverage for my problem. At this point I've extracted the public key from my assembly using the following commands: sn -p input.pfx output.publickey sn -tp output.publickey This gives me the following public key text in the command line:...

How to get JSON array on client_JS from server_JS?

javascript,node.js

res.json already converts the data to JSON, so you don't have to do it manually: res.json(TasksJsonArray); I believe this will also set the appropriate headers, so on the client, you don't have to explicitly parse the JSON, jQuery will do it for you: $.get('/getArr').done(function(currencyData){ if (!currencyData.rates) { // possibly handle...

CSS: Scissor-Cut images layout

html,css,design,responsive-design

use pseudo element - :before or :after div{ width: 300px; height: 300px; background: #FF6100 url('http://www.hybworks.co.uk/wp-content/uploads/2015/05/los-angeles-auto-repair-300x300.jpg') no-repeat 0 0; position: relative; } div:after{ content: ''; position: absolute; bottom: 0px; left: 0; width: 0; height: 0; border-top: 150px solid transparent; border-right: 300px solid #fff; display: block; } span{ display: inline-block; width: 120px;...

Unity 5 custom shader broken after upgrade from Unity 4.x

ios,unity3d,shader

The error indicates to me that Shader.Find("Custom/LineRender") fails to return a valid shader. To ensure that your shader is available for you to load from your code, you can add it to the "Always included shaders". You can find these at Edit > Project Settings > Graphics in Unity's menu....

How to add and remove a class on an element when Bootstraps Affix is affixed or not

javascript,jquery,html,css,twitter-bootstrap

You'll want to tie into the events that bootstrap provides for affix. Try this: $(document).ready(function () { $('.sticky_cta').affix({ offset: {top: $('.abovebrandnav').height() + 70} }).on('affix.bs.affix', function () { $('.belowbrandnav').addClass("stickyoffset"); }).on('affix-top.bs.affix', function () { $('.belowbrandnav').removeClass("stickyoffset"); }); }); Take a look at this bootply demo. I made it change the color of the...

How can I configure a systemd service to restart periodically?

linux,service,systemd

Yes, you can make your service to restart it periodically by making your service of Type=notify. Add this option in [Service] section of your service file along with Restart=always and give WatchdogSec=xx, where xx is the time period in second you want to restart your service. Here your process will...

Check if method return type is based on generic parameter

c#,generics,reflection,methodinfo

I stand corrected... Given: public class GenericClass<T1> { public class InnerClass<T2> { public static Tuple<T1, T2, T3> A<T3>() { return null; } } } Type type = typeof(GenericClass<int>.InnerClass<long>); var methodInfo = type.GetMethod("A"); MethodInfo method = (MethodInfo)type.Module.ResolveMethod(methodInfo.MetadataToken); Here it was considered a problem... I use it as a feature :-)...

Invalid “ng-model” value with Bootstrap UI datepicker

javascript,angularjs,twitter-bootstrap,datepicker,angular-ui-bootstrap

The problem is with the format you are providing in the attribute 'datepicker-popup'. Use the value of the attribute as 'longDate' as follows : datepicker-popup="longDate" Use it as follows : <input type="text" class="form-control" datepicker-popup="fullDate" ng-model="dt" is-open="opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" /> I updated the plnkr....

N-Tier Application Authentication (RabbitMQ as Broker and C# as Business Tier) - WIF possible?

c#,authentication,rabbitmq,wif,amqp

As you are explicitly mentioning RabbitMq, I am suggesting ServiceStack for your service interface. One issue with MQs in general is that they are decoupled from any meta information, such as HTTP Headers, to inject authentication. You should in contrast provide a property Session (with pre authentication) or UserName and...

CSS border-radius Property Not Working [duplicate]

html,css,image,tumblr

try changing your padding for margin: #articleimage { float:left; margin-right: 10px; margin-bottom: 1px; width: 400px; border-radius:20px; } ...

Dynamic page transitions in jQuery Mobile

jquery,html,jquery-mobile,dynamic

I have made your original fiddle work by using event delegation to bind the dynamic button: var pageName = "default"; $(document).ready(function () { function changePage() { var newName = pageName == "alpha" ? "beta" : "alpha"; $("body").append("<div id=\"" + newName + "\" data-role=\"page\"><a id=\"dynamicButton\" data-role=\"button\">" + pageName + "</a></div>"); $(":mobile-pagecontainer").pagecontainer("change",...

Object Required Error after upgrading to Office 2013

vba,excel-vba,excel-2013

Apparently the Past method must be returning an array of ShapeRanges. I'm not sure if this is how it's always been and Office 2010 was a little more forgiving or not. So, to correct for this issue, when referencing sr I've had to do like sr(sr.Count). Working code below... Sub...

Mongoose: retrieve data in same order as schema

javascript,node.js,mongodb,mongoose

You will have to use an array. An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf...

Split two sentences into words and characters and show them individually

javascript,arrays,regex,split

What you're trying to do is splitting text into tokens. If you search, you'll find limitless solutions to this problem, as this is what most language parsers do in order to further analyze text. And I strongly suggest doing so, that's some useful stuff to be familiar with. You can...

Select a tab in Firefox from command line

firefox,command-line,tabs

Yes, there is: install MozRepl addon start it: Tools -> MozRepl -> Start use telnet to connect to the running MozRepl instance: $ telnet 127.0.0.1 4242 You can also use rlwrap to enable readline-like keybindings inside telnet session: $ rlwrap telnet 127.0.0.1 4242 define a function for searching a tab...

Jquery terminal text formatting syntax, what am I doing wrong?

jquery,css,syntax,text-formatting,jquery-terminal

Got the answer from Frédéric Hamidi, I needed to include COLOR and BACKGROUND, they were not optional.

Shell comm parameters issue

linux,shell,comm

Solutions: Since you have specified bash in the script's shebang, why do you call it with sh? Simply run ./test.sh /tmp/f1.txt /tmp/f2.txt /tmp/f3.txt Use bash explicitly: bash test.sh /tmp/f1.txt /tmp/f2.txt /tmp/f3.txt ...

Creating pandas dataframes within a loop

python,pandas

This is a python feature. See this simpler example: (comments show the outputs) values = [1,2,3] for v in values: print v, # 1 2 3 for v in values: v = 4 print v, # 4 4 4 print values # [1, 2, 3] # the values have not...

Play 2.3, Git and IDEA: universal path to embedded database

git,playframework,sbt

According to H2's FAQ it should be without anything, no . or ~. So to store your database into your project's folder like path_to_my_project/database/mydbfile you can use: jdbc:h2:database/mydbfile ...

dplyr on subset of columns while keeping the rest of the data.frame

r,dplyr

dg <- iris %>% mutate_each(funs(Replace15), matches("^Petal")) Alternatively (as posted by @aosmith) you could use starts_with. Have a look at ?select for the other special functions available within select, summarise_each and mutate_each. ...

How to Create a Printing Method in Python

python,class,object,printing

You need to add parentheses at the end of your function calls: peep.print_eatable() peep.print_species() So code should be: class chicken(): def __init__(self, name, eatable, species): self.name=name if eatable!="yes" and eatable!="no": self.eatable="no" else: self.eatable=eatable self.species=species #Print the species when called #Doesnt work for some reason def print_species(self): print"%s" %str(self.species) #Print whether...

Attempt to raise Null exception in disassembled code in Visual Studio

c#,visual-studio-2012,.net-3.5,nullreferenceexception,disassembly

It is possible only while debugging C/C++ code. Tested it on a mixed solution C# + C++, C#-side it was readonly, C++ side I could overwrite the text (note that the window "appearance" doesn't change... it is always something like the notepad) When debugging a C/C++ app, you can even...

What is the difference between on_data and on_status in the tweepy library?

python,twitter,tweepy

on_data() handles: replies to statuses deletes events direct messages friends limits, disconnects and warnings whereas, on_status() just handles statuses. source: https://github.com/tweepy/tweepy/blob/78d2883a922fa5232e8cdfab0c272c24b8ce37c4/tweepy/streaming.py...

Oracle sql: Using two listagg

sql,oracle

It doesn't matter how many tables in aggregation (unfortunately I can't check syntax without your data structure): select (select listagg(column_value,', ') within group (order by column_value) from table (del_text)) del_text ,(select listagg(column_value,', ') within group (order by column_value) from table (pal_text)) pal_text from (select collect (distinct tx1.text) del_text, collect (distinct...

How to send mail using Simple Java Mail framework?

java,email

You're using the wrong SMTP server. You need the GMail one. "smtp.aol.com" -> "smtp.gmail.com" ...

Is Quicksand a default font on Windows machines?

css,fonts

Through comments and a few other resources I found that it is not a default font on Windows machines - therefore I will have to include the font in my CSS files.

How to oblige a class' users to use it off the UI thread in Android?

java,android,multithreading

Use this construction to check if method is executed on the MainThread or not. if(Looper.myLooper() == Looper.getMainLooper()) { // Current Thread is Main Thread. throw new IllegalStateException("Please call this method asynchroniously!"); } Edit. Also add javadoc to notify a developer and also you can add throws signature to the method...

How to convert a csv file, that has array data, into a json file?

python,arrays,json,csv

It is because you are encoding it and then using json.dumps which is basically encoding it twice. Remove json.JSONEncoder().encode(...) and it should work correctly. import csv import json csvfile = open('userdata.csv', 'r') jsonfile = open('userdata.json', 'w') fieldnames = ("firstname", "lastname", "pet", "pet", "pet"); reader = csv.DictReader( csvfile, fieldnames) record =...

looking for (jQuery) painting plugin [closed]

jquery

Take a look at fabric.js It is a library for canvas drawing and there are many tutorials and demos out there. http://fabricjs.com...

How to Parse Nested / Multiple Json Objects using Retrofit

java,android,json,retrofit,pojo

I am officially a dumb scrub and completely looked over the easiest possible fix and should have my account and developer title revoked. This is all I should have done: public class ItemGroup { private String version; private Map<String,Item> data; //...Man i'm so dumb... } AS REFERENCE FOR THE FUTURE....

How to use JSON file using clientbundle in gwt

java,json,gwt

You need to use the com.google.gwt.json.client.JSONParser that is provided by GWT instead of the org.json.simple.parser.JSONParser. JSONValue value = JSONParser.parse(json); JSONObject productsObj = value.isObject(); JSONArray productsArray = productsObj.get("products").isArray(); ...

Slack integration for alarms or alerts

productivity,reminders,slack-api

I am not sure if you are looking for a generalizable alarm clock with static messages, or something custom. You can use Incoming Web Hooks to write your own custom integration. Create a simple script that you schedule as a cron job to run at 9am. If it's a weekend,...

JS/jQuery passing $_POST information to PHP script

javascript,php,jquery

There is no alert in PHP, it's a serverside language that has nowhere to alert. The solution is to return something to the ajax call instead <?php if (isset($_POST['action'])) { switch ($_POST['action']) { case 'enableSSH': echo "enableSSH has been selected"; break; case 'migrateDB': echo "migrateDB has been selected"; break; }...

Swift: using a for loop to insert items. At the end, when i query it shows only the value which was inserted last at each index

arrays,swift

class instances are reference types. You need to create a new card instance for each iteration. Move the line var playingCard = card() right after the for j in 0..<countRanks line and change var to let

Restlet 1.1 Access Control Header Issue

java,jquery,restlet

Thanks for your replies. After some analysis of the problem it turned out that I needed to configure Spring to allow option requests for my restlet in the web.xml file as shown below: <servlet> <servlet-name>ccrest</servlet-name> <servlet-class>com.noelios.restlet.ext.spring.RestletFrameworkServlet</servlet-class> <init-param> <param-name>dispatchOptionsRequest</param-name> <param-value>true</param-value> </init-param> <load-on-startup>2</load-on-startup>...

PHP Upload Script corrupting file, Size of file differs from source file

php

FTP_ASCII is intended to be used when handling text files, I believe you should use FTP_BINARY in order to properly handle your .zip file. Replace: ftp_get($ftp_conn, $local_file, $server_file, FTP_ASCII) with: ftp_get($ftp_conn, $local_file, $server_file, FTP_BINARY) And: ftp_put($ftp_conn, $server_file_u, $local_file_u, FTP_ASCII) With: ftp_put($ftp_conn, $server_file_u, $local_file_u, FTP_BINARY) ...

Empty Entity after data retrieving from MySQL DB

java,jpa,entity,querydsl

The debugger was showing me no data because of lazy data loading.

Doctrine Extensions REGEXP not working in Symfony2

php,regex,symfony2,doctrine2

I found the solution through the github page for the project Doctrine requires that all where clauses require a comparison operator even though a clause like REGEXP doesn't require it. $dql = "SELECT g FROM {$this->_entityName} g WHERE g.status = 1 AND REGEXP(g.name, '^[^[:alpha:]]') = 1"; Also my regex character...

jQuery append(): tag is closed before it should

javascript,jquery

You could simply change the second append to append to the class of the unordered list $('#eventos_stats').html('<h2>Events</h2>'); $('#eventos_stats').append('<ul class="list-group"><li class="list-group-item"><span class="badge">'+response.numero_eventos+'</span>Total events</li>'); $('.list-group').append('<li class="list-group-item"><span class="badge">'+response.asistencia_eventos+'</span>Total attendees</li></ul>'); ...

How could I make a good application architecture in Python with PyQt?

python,python-3.x,design,pyqt,pyqt5

1. In every parent class, import each child with : from childfilename import childclassname For example, in the optionwindow class, you will have : from mainwindowfilename import mainwindowclassname from toolbarfilename import toolbarsclassname from menubarfilename import menubarclassname Note 1 : For better lisibility, name your files with the same name as...

Load bitmap in recyclerView from internalStorage with Asynctask

android,bitmap,android-asynctask,adapter,recyclerview

Why not use Picasso or a library for that? It's as easy as: Uri uri = Uri.fromFile(yourFilePath); Picasso.with(activity).load(uri) .resize(100, 100).centerCrop().into(viewHolder.imageView); Or load the image in the onCreateViewHolder method @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Log.d(logTag, "view group " + parent); View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false); ImageView...

Is there an iOS override for when a view was popped back?

c#,ios,xamarin,monotouch

Try this: public partial class MasterViewController : UIViewController { public void ReloadTable() { TableView.ReloadData (); } } public partial class DetailViewController : UIViewController { public override void ViewWillDisappear (bool animated) { var masterViewController = NavigationController.ViewControllers.OfType<MasterViewController> ().FirstOrDefault(); if (masterViewController != null) { masterViewController.ReloadTable (); } base.ViewWillDisappear (animated); } } You need...

Is there any way to break Javascript function within an anonymous function?

javascript,firebase

If you add a few console.log statements, you'll be able to see how your code flows: console.log('1. starting call to Firebase'); CampaignsRef.once('value',function(snapshot){ console.log('3. for value from Firebase'); snapshot.forEach(function(childSnapshot){ console.log('4. inside childSnapshot'); if (campaign.Name==childSnapshot.val().Name){ console.log("campaign already exists on the DB"); return false; } console.log('5. done with snapshot.forEach'); }); }); console.log('2. we...

Mid line through a set of dicom images in matlab

image,matlab,image-processing,line,dicom

So it looks like ans.Img contains the 3D matrix consisting of your image stack. It looks like you've got something going, but allow me to do this a bit differently. Basically, you need to generate a set of coordinates where we can access the image stack and draw a vertical...

CSS3 animation won't stop on the last frame

css,css3,animation,css-animations

There are actually two problems here. First, you have an off-by-one error with the step function. The starting position shouldn't be included in number of steps passed to the step function. From MDN: steps(4, end) The second problem is that you seem to have an incorrect idea of what percentage...

Node Webkit - Options for encoding in writeFileSync not work?

node.js,encoding,node-webkit

The solution is to set the working node-webkit application page to have a utf-8 encoding. I have to add this to the page: <meta charset="utf-8"> It turns out to be something very simple yet I've missed....

Google Maps and java.net.SocketTimeoutException: Read timed out

java,google-maps,google-geocoder,google-geocoding-api,socket-timeout-exception

I've figured out what the issue was. I had to connect through a proxy (which our browsers automatically do and explains why I got a response when I used a web browser). I just had to modify my code in the following way: Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.url.com",...

CSS not changing after altering data attribute tag with AJAX post

javascript,jquery,css,ajax,html5

It is because of this line: equipment_span.data("available", new_avail); When jquery manages the data attributes it does so in memory and not "on the page", so if you inspect the page it will show data-available="whatever it was on page load" You need to do: equipment_span.attr("data-available", new_avail); ...

How to pull data moving backwards in a java ArrayList

java,arraylist

When you assign one primitive (such as an int) to another, this copies the value to the new variable. For objects, this works a bit differently in that these variables will point to the same object. int arraySize = list.size(); So the above line will just set arraySize to the...

PHP MYSQLi display error message in JAVASCRIPT alert

javascript,php,mysqli,alert

There is no such case where you would need it. In case its irrecoverable error In case it's production server, just say "Error". Giving out system error message is confusing and insecure. Log errors instead and read them from there. In case it's development server, you don't need no fancy...

Django: How to get exception instance in error handlers

python,django,error-handling,django-middleware,django-errors

This feature has been implemented as ticket 24733. In Django 1.9 and later, the exception will be passed to the error handlers....

Is it possible to change an assoicated value within an enum?

swift

Rob Napier's answer is fine but I have a different understanding of your question. I would have written something like this instead: enum MyEnum { case SomeCase(Int?) mutating func someFunc() { switch self { case .SomeCase(.Some(_)): self = .SomeCase(5) default: // or case .SomeCase(.None): if you prefer break } }...

Efficient bit checking in embedded C Program

embedded,avr

I suppose PIND is a peripheral register (what do you mean by "command"?). The first check will read it once or twice, depending on the first comparison. This might generate a glitch, if SW1 changes between the first and second read. Presuming SW? are switches: In general, it is better...

How to Build Software

Getting started tutorials how to be a good programmer, develop software with:

custompaging , coap , apc , patindex , django-modeltranslation , codenvy , musl , visualsvn-server , texas-instruments , feature-detection , libcurl , laravel-collection , gdal , minimum-spanning-tree , checkin , dvb , jd-gui , wamp , phpexcel , differential-equations , category , google-now , android-actionbar-tabs , text-analysis , nsjsonserialization , plsqldeveloper , capslock , boost-python , credible-interval , mod-python , function-attributes , jsonpath , membase , cppcheck , sql-function , openfire , r-lavaan , packaged-task , webcal , recorder , joomla-extensions , actionscript-3 , spring-android , finite-element-analysis , fsevents , system-variable , http-status-code-303 , qgraphicswidget , spring-3 , home-directory , finite-field , statusbar , timer-jobs , off-screen , materializecss , actionfilterattribute , nuget-spec , monaca , mop , pic , luajit , metal , thread-priority , klocwork , decoder , interactive , dhcp , fastly , language-lawyer , fread , nsmenuitem , trellis , compilationmode , pika , affinetransform , autorotate , dismax , portia , docpad , runge-kutta , dependencies , html.hiddenfor , street-address , gecko , affinity , moodle , highstock , stringbuffer , nservicebus5 , appcompat-v7-r22.2 , azure-webjobs , soundjs , fragmenttransaction , artifacts , tfsintegrationplatform , encodeuricomponent , limesurvey , jsobject , django-admin-tools , t4-template , wicked-pdf , autogrow , .slugignore , bookshelf.js , subdirectory , bamboo , tkinter , python-dragonfly , quadratic-curve , createuserwizard , yasnippet , manage.py , mks , android-jobscheduler , bjqs , smoothing , lxml.html , source-code , rcs , asp.net-mvc-5.1 , http-chunked , cannot-find-symbol , hsv , m2eclipse , categorical-data , jmstemplate , control-p5 , delphi-mocks , spin , actualheight , iis-8.5 , msdn , json-lib , bank , mingw , horizontal-scrolling , preferences , groovydoc , generate-series , inputstream , ivar , project-organization , pfquerytableviewcontrolle , mobilefirst-cli , tslint , sql-server-2014 , android-datepicker , msbuild-wpp , textrange , tabpage , gnu-screen , bloodhound , winpcap , kong , rad , django-mediagenerator , plural , vistadb , apache-commons-email , commandbar , inline-functions , as.date , sh , origodb , longest-substring , qtablewidget , tree-nodes , vmware-sdk , defineproperty , hiera , virtual-channel , user-input , angularjs-ng-href , transclusion , identity-management , required-field , pixel-shading , burn , enunciate , opl , tfs2015 , jquery-ias , libgosu , illegalargumentexception , relative-date , gnutls , function-fitting , biginteger , jstat , haskeline , imageview , cocos3d , document-management , appium , liclipse , slick-2.0 , nsundomanager , sql-server , slidingmenu , jsdoc3 , documentation , compare , multiple-select-query , django-filter , reportserver , spatial , dword , brew , return-type-deduction , value-type , cxf , evp-cipher , onunload , cumulative-sum , kanjivg , groc , reproducible-research , mirc , sar , nlopt , nanotime , extrinsic-parameters , openssh , virtual-hosts , proxy , resharper-9.1 , public-method , explicit-constructor , nest , cross-join , texreg , app-inventor , encryption-asymmetric , shapefile , metatable , wcs , android-gui , android-coordinatorlayout , python-2.6 , postfix-notation , mojolicious , mecab , worklight-appcenter , android-audiorecord , viewdata , subtyping , .war , pointer-events , facebook-checkins , dead-code , delete , rsync , paintevent , ovh , cursors , lr1 , beta , cancan , apache-spark , zshrc , sqlite3-ruby , rails-postgresql , xmlpullparser , jvisualvm , gitpython , viewdidload , kendo-menu , grunt-contrib-uglify , richedit , jes , schemaless , visualvm , xpathquery , qt5.2 , gcc , shinyapps , automated-tests , dash.js , self , cakeyframeanimation , hp-uft , ghostscript.net , jquery-triggerhandler , yolk , hashmap , centroid , rational-test-workbench , unified-service-desk , ppm , wiremock , locale , npp , nsthread , bad-request , window.opener , wimax , coldfusion-8 , html5-appcache , mxunit , kate , soundmanager2 , web-traffic , datagridviewcheckboxcell , reactive-extensions-js , char , dbal , multicol , gwtbootstrap3 , django-filebrowser , pose-estimation , xmlworker , owlim , renderer , xvfb , class-template , http-put , avisynth , userscripts , ta-lib , io-completion-ports , spark-streaming , allegro5 , default-programs , prefetch , android-4.4-kitkat , lockbits , javaexe , minmax , submitchanges , css-shapes , node-gyp , trunk , mongodb-query , nape , pass-by-name , photoshop , protect , warnings , neventstore , html2canvas , ng-repeat , primitive-types , shrink , binary-serialization , r.java-file , open-closed-principle , zlib , aspose-slides , jsnetworkx , nslayoutconstraint , mappedsuperclass , nslocalizedstring , shell32 , continuation-passing , filelock , spannable , directions , ssis-development , mft , server-sent-events , http-status-code-406 , e4x , toupper , ruby-test , beanshell , google-web-starter-kit , assertions , html-xml-utils , contentsize , liquid , dpi-aware , web-development-server , listener , method-overloading , google-compute-engine , page-tables , senchatouch-2.4 , angular-nglist , easy-install , assert , subdomains , iperf , tern , llvm-ir , placeholder , e10s , achartengine , material , walkthrough , ones-complement , maven-antrun-plugin , writing , filter-var , hierarchical , stl , runner , multi-tenancy , xla , storage-duration , sphinx4 , promoted-builds , ibm-db2 , ansi-c , tform , qr-code , oracle-adf , programming-pearls , multi-layer , pythonpath , ngmock , boost-lambda , chain , matlab-java , .net-micro-framework , polyml , file-association , webservicetemplate , annyang , suse , tokudb , sorcery , aggregate , maven-ant-tasks , audio-processing , jquery-jtable , ide , xml-visualizer , csrf-protection , jquery-queue , mps , gruntjs , jquery-focusout , document-imaging , codeigniter-routing , repast-simphony , itk , modelica , visual-studio-team-system , intersystems-cache , pyside , oxwall , nitrogen , telerik-radlistbox , leon , android-progaurd , system.web.optimization , my.cnf , pde , spectrum , brokeredmessage , orm , liferay-service-builder , bitwise-and , shakespeare-text , bluetooth-lowenergy , currentlocation , dopostback , lockbox-3 , jquery-mobile-collapsible , remote-control , closest-points , undertow , banana , notifyjs , lync-client-sdk , mathquill , posh-git , facebook-rest-api , sails.js , template-inheritance , khan-academy , lotus-wcm , opus , automatic-ref-counting , windows-10-iot-core , xpages-extlib , adonetappender , mapper , internet-explorer-9 , custom-activity , nanohttpd , svc , ftp-client , onpreferenceclicklistener , tableviewcell , drupal-field-collection , uiimagepngrepresentation , jquery-ajaxq , cursor-position , facebook-comments , pfsubclassing , https , tizen-emulator , charsequence , nsmetadataquery , delphi-5 , console.readkey , buttonfield , state-saving , snapchat , jython , processing-efficiency , dreamweaver , axapta , text-based , ef-migrations , chroot , css-filters , virtual-column , code-reuse , juno , kafka-consumer-api , bssid , pycharm , uri , android-time-square , bridge , web-analytics-tools , gitx , mtm , uitypeeditor , query-extender , passkit , activitynotfoundexception , extractor , twitter-bootstrap-tooltip , bootjack , goertzel-algorithm , false-positive , azimuth , opengl-es , unique-index , gnuradio , named-scope , skinny-war , simd , extern-c , web-deployment , packaging , fragment-backstack , datamember , metrics , cosmos , bitmask , tex-live , bioinformatics , screen-record , scala-macros , powershell-v3.0 , result , field-accessors , qdomdocument , jmc , interceptor , gridbaglayout , xml-drawable , openshift-enterprise , extaudiofile , codekit , windows-azure-diagnostics , mongorepository , iscsi , fullpage.js , axis , excel-udf , libgdx , mobicents , indexing , norm , monkeypatching , connection-timeout , table-splitting , amazon-mobile-analytics , sspi , pedestal , opencv-stitching , cryptojs , eigen , junit-theory , enterprise-integration , pixi.js , mark , android-fragments , strftime , lookup-tables , prolog-assert , gravatar , pairing-heap , scribble , mux , chmod , serp , permutation , skus , suppress-warnings , n-tier-architecture , creative-cloud , kademlia , mocha-phantomjs , vorbis , datetime-conversion , blockingcollection , models , drbd , cloudflare , appendchild , conv-neural-network , substrings , zend-router , perl5 , ensembles , trie , django-inheritance , croogo , portaudio , openstack-swift , supervised-learning , stdlist , document , salt-creation , rollingfileappender , slick-carousel , mlogit , date-formatting , mutual-authentication , visible , stata , youtube-dl , subparsers , fancytree , s4 , appointment , mxml , scrollable , collectioneditor , xml-namespaces , sse3 , kognitio-wx2 , colors , libdispatch , fromcharcode , haxepunk , fitnesse , multiple-databases , uianimation , test-runner , smtpclient , regions , market-basket-analysis , fragment-tab-host , history , gettime , multitasking , raymarching , qtreewidgetitem , ng-class , laravel-request , acoustics , logstash-drop , automatic-migration , scheme , twiml , code-complete , jvm-hotspot , antisamy , magento-1.3 , anonymity , content-length , angularjs-ng-touch , cookbook , containment , eclipse-gemini , servicestack-auth , emacsclient , windows-console , backbone-model , select , nullable , range-v3 , jointable , nslocale , rust , vram , software-quality , rails.vim , revisions , lz77 , liferay-6 , blackfire , cfclient , ir , pushpin , xmlschemaset , file-descriptor , simulink , netstream , getopt-long , associations , chromium-embedded , excel-charts , grunt-contrib-concat , pexpect , rest , array-unique , website-hosting , phpcas , q-learning , web-application-project , cclabelttf , best-fit , errorlevel , net.tcp , msxml , tess4j , url-parsing , query-cache , url-routing , re-engineering , motorola-emdk , concreteclass , spi , modal-window , angular-ui-bootstrap , visual-prolog , openni , django-cache-machine , xsd.exe , sendmailr , specs , cpuset , socks , uialertcontroller , compiler-constants , object-pascal , ptrace , websharper , dunn.test , puppetlabs-apache , intern , parallel-processing , intentservice , jaxp , amazon-cloudsearch , sequence , sapb1 , edx , google-directory-api , log4cpp , nightly-build , glsurfaceview , gridpanel , download , android-homebutton , pushdown-automaton , nullptr , wakeup , geben , carryflag , jmh , messaging , imread , gooddata , java-me , samtools , production , xattribute , knpmenu , .ico , paypal-ipn , flexslider , sqlsitemapprovider , compositecollection , selendroid , zoo , chefspec , wizard , irrlicht , fixeddocument , rx-android , taskstackbuilder , wsadmin , geoip , financial , windows-live , realloc , react-select , sortedlist , apache-poi , drawtext , angular-ng-if , u-boot , xmldocument , bootstrap-modal , application-lifecycle , qgraphicstextitem , yasm , django-orm , appengine-pipeline , five9 , ipython-parallel , vimeo-player , tun , inbox , scrollrect , webview , numberformatexception , hook-menu , template-classes , touchpad , appcompatactivity , glassfish-3 , banner , cdo.message , graphing , jspx , starling-framework , neodynamic , scala-swing , viewhelper , xc8 , tampermonkey , literals , wp-api , textinput , accessibilityservice , globalplatform , cron4j , bwu-datagrid , servemux , requestfiltering , dataflow , struts-action , description-logic , tfs , errorformat , gmt , packets , readlink , dbix-class , xmp , sigbus , construct , cub , selenium-chromedriver , continuous-deployment , gorm , string-split , splash-screen , stringification , openquery , dblink , wikipedia , exacttarget , buildpath , word-interop , eeglab , android-loadermanager , ontouchevent , timedelay , windows-update , uinavigationcontroller , angular-new-router , commerce , gd-graph , windowserror , activesupport , filter , exxeleron-q , binlog , gpl , draw , ios-frameworks , apache-commons-lang3 , on-screen-keyboard , ambient , yarn , lingpipe , decimal , cap , interop , unsigned-long-long-int , datadetectortypes , rasterize , datagridviewcomboboxcell , goodbarber , sgml , deletable , formcollection , windows-mobile-6.5 , left-recursion , messagepack , apportable , caroufredsel , wt , background-thread , preg-replace-callback , doevents , pocketpc , ruby-1.8.7 , genexus , flashlight , php-5.4 , protected-mode , karma-coverage , reversing , heroku-api , linq-to-nhibernate , web-administration , gtk3 , crontab , kettle , nano , restful-architecture , background-music , constraint-programming , android-linearlayout , dill , flask-cache , sitecore7.1 , ripple , bit.ly , blogger , y-combinator , fedex-api , character-class , multicore , durandal , geotiff , kentico-azure , contiguous , ria , jmapviewer , pascalscript , recursive-descent , wso2stratos , worklight-adapters , spacebars , joomla1.5 , paragraphs , servicecontract , spawn , eventaggregator , spool , c-standard-library , wavemaker , php-shorttags , dxf , notepad++ , touchesmoved , celery , eurekalog , sonarqube-4.5 , abstract , pgadmin , cgbitmapcontext , oledbdataadapter , tfs2012 , fact , approval , rebol2 , catamorphism , cumulative-line-chart , httpwebrequest , ecdsa , node-red , vista64 , default-constructor , trygetvalue , org.json , lto , sql-timestamp , shared-worker , qvector3d , uiprogressbar , fast-forward , phonertc , replacewith , cockroachdb , iif , xlsxwriter , zurb-foundation , sitemesh , jquery-cookie , factorization , value-class , zebra-puzzle , web-access , nth-element , mkpointannotation , decimal-point , ubuntu-14.10 , ecmascript-6 , windows-services , tortoisesvn , usb-otg , title , facebook-audience-network , addchild , mustache.php , getjson ,