Will my Cookie Clicker save last beyond a reboot? – gaming.stackexchange.com
I have been loathe to reboot my machine for risk my Cookie Clicker game
would lose all its hard-won progress. Am I being silly, here?
Monday, 30 September 2013
Prove that $ P \cup Q = Q$ and $P \cap Q = P$ if $P$ is a subset of $Q$
Prove that $ P \cup Q = Q$ and $P \cap Q = P$ if $P$ is a subset of $Q$
pWhen $P$ is a subset of $Q$, use logical connectives to/p blockquote ol
lipProve $P \cup Q = Q$./p/li lipProve $P \cap Q = P$./p/li /ol
/blockquote pI know that they are true, but I don't know how to use the
definitions of union and intersection in terms of logical connectives to
prove them./p pThanks in advance!/p
pWhen $P$ is a subset of $Q$, use logical connectives to/p blockquote ol
lipProve $P \cup Q = Q$./p/li lipProve $P \cap Q = P$./p/li /ol
/blockquote pI know that they are true, but I don't know how to use the
definitions of union and intersection in terms of logical connectives to
prove them./p pThanks in advance!/p
Android and expandable results preview
Android and expandable results preview
what I want to do is realizing an awsome layout for my app. For this
reason I've thought to Display result of searches in a particular way: -
when I have less then or 4 results I display them in a simple listview; -
when I have more then 4 results I display the first four resoults and an
element that, when is clicked, expands my listview and shows all results.
I've seen ExpandableListView but it does not give me the possibility of
results preview. Any ideas?
what I want to do is realizing an awsome layout for my app. For this
reason I've thought to Display result of searches in a particular way: -
when I have less then or 4 results I display them in a simple listview; -
when I have more then 4 results I display the first four resoults and an
element that, when is clicked, expands my listview and shows all results.
I've seen ExpandableListView but it does not give me the possibility of
results preview. Any ideas?
VisualStateManager: how the page is aware of initial VisualState
VisualStateManager: how the page is aware of initial VisualState
I have one doubt regarding the working of VisualStateManager in Windows
Store apps...
Assume this sample page:
<common:LayoutAwarePage x:Name="pageRoot">
<Grid Style="{StaticResource LayoutRootStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListView Grid.Column="0"
x:Name="testElement" />
<Grid Grid.Column="1" />
</Grid>
<common:LayoutAwarePage/>
I declare the next VisualStateManager behavior, with a sample VisualState:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ApplicationViewStates">
<VisualState x:Name="Snapped">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="testElement"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0"
Value="Collapsed" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
And now my questions:
How can the application determine that the "state" (I mean, the values of
the properties) is the one I used in the XAML declaration of the page?
Do I need to explicitly set the "initial" values of the page in - for
example - a FullScreenLandscapeOrWide VisualState?
Is it possible that the page will start (maybe with other screen
resolutions or particular devices) in a different VisualState "state" (not
FullScreenLandscapeOrWide), giving me problems if I do not declare the
FullScreenLandscapeOrWide VisualState (the initial status) ?
Thank you in advance for clarifications...
I have one doubt regarding the working of VisualStateManager in Windows
Store apps...
Assume this sample page:
<common:LayoutAwarePage x:Name="pageRoot">
<Grid Style="{StaticResource LayoutRootStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListView Grid.Column="0"
x:Name="testElement" />
<Grid Grid.Column="1" />
</Grid>
<common:LayoutAwarePage/>
I declare the next VisualStateManager behavior, with a sample VisualState:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ApplicationViewStates">
<VisualState x:Name="Snapped">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="testElement"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0"
Value="Collapsed" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
And now my questions:
How can the application determine that the "state" (I mean, the values of
the properties) is the one I used in the XAML declaration of the page?
Do I need to explicitly set the "initial" values of the page in - for
example - a FullScreenLandscapeOrWide VisualState?
Is it possible that the page will start (maybe with other screen
resolutions or particular devices) in a different VisualState "state" (not
FullScreenLandscapeOrWide), giving me problems if I do not declare the
FullScreenLandscapeOrWide VisualState (the initial status) ?
Thank you in advance for clarifications...
Sunday, 29 September 2013
C++ return negative string
C++ return negative string
Hi i have the following code to convert string integer into integer, these
are the code:
#include <stdio.h>
int str_to_int(char* str) {
int output = 0;
char* p = str;
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
return output;
}
int main(){
printf("%d\n", str_to_int("456xy"));
printf("%d\n", str_to_int("32"));
printf("%d\n", str_to_int("-5"));
return 0;
}
But some how printf("%d\n", str_to_int("-5")); some how returning 5
instead -5, where am i wrong here? Thanks
Hi i have the following code to convert string integer into integer, these
are the code:
#include <stdio.h>
int str_to_int(char* str) {
int output = 0;
char* p = str;
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
return output;
}
int main(){
printf("%d\n", str_to_int("456xy"));
printf("%d\n", str_to_int("32"));
printf("%d\n", str_to_int("-5"));
return 0;
}
But some how printf("%d\n", str_to_int("-5")); some how returning 5
instead -5, where am i wrong here? Thanks
Umbraco 6.1.3 - Specified cast is not valid
Umbraco 6.1.3 - Specified cast is not valid
I am getting error that is "Specified cast is not valid." in umbraco 6.1.3
version. (Razor - MVC)
Page has macro that is rendering company list to the page. I am creating
company list data with ucomponents data grid component.
Also I added all error below. Why can i get this error? And how can i fix
this? I searched it but i didnt get any idea to fix.
Thanks
Server Error in '/' Application.
Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not valid.
Source Error:
Line 7:
Line 8: <div class="interior-page-content">
Line 9: @Umbraco.RenderMacro("All-FirmaListesi", new {anaSayfa="1055"})
Line 10: </div>
Source File:
c:\inetpub\vhosts\cbmeturkey.com\httpdocs\Views\KatilimListesi.cshtml
Line: 9
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Byte() +52
System.Data.SqlClient.SqlDataReader.GetByte(Int32 i) +62
umbraco.DataLayer.RecordsReaderAdapter`1.GetByte(String fieldName) +168
umbraco.cms.businesslogic.macro.MacroProperty.setup() +215
umbraco.cms.businesslogic.macro.MacroProperty.GetProperties(Int32
MacroId) +189
umbraco.cms.businesslogic.macro.MacroModel..ctor(Macro m) +186
umbraco.macro..ctor(String alias) +117
Umbraco.Web.UmbracoHelper.RenderMacro(String alias, IDictionary`2
parameters) +59
Umbraco.Web.UmbracoHelper.RenderMacro(String alias, Object parameters) +47
ASP._Page_Views_KatilimListesi_cshtml.Execute() in
c:\inetpub\vhosts\cbmeturkey.com\httpdocs\Views\KatilimListesi.cshtml:9
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +199
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter
writer, Object instance) +257
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext,
TextWriter writer) +107
StackExchange.Profiling.MVCHelpers.WrappedView.Render(ViewContext
viewContext, TextWriter writer) +159
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
+23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionResult actionResult) +176
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) +311
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__19() +23
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult
_) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult
ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult
asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult
ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET
Version:4.0.30319.17929
I am getting error that is "Specified cast is not valid." in umbraco 6.1.3
version. (Razor - MVC)
Page has macro that is rendering company list to the page. I am creating
company list data with ucomponents data grid component.
Also I added all error below. Why can i get this error? And how can i fix
this? I searched it but i didnt get any idea to fix.
Thanks
Server Error in '/' Application.
Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not valid.
Source Error:
Line 7:
Line 8: <div class="interior-page-content">
Line 9: @Umbraco.RenderMacro("All-FirmaListesi", new {anaSayfa="1055"})
Line 10: </div>
Source File:
c:\inetpub\vhosts\cbmeturkey.com\httpdocs\Views\KatilimListesi.cshtml
Line: 9
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Byte() +52
System.Data.SqlClient.SqlDataReader.GetByte(Int32 i) +62
umbraco.DataLayer.RecordsReaderAdapter`1.GetByte(String fieldName) +168
umbraco.cms.businesslogic.macro.MacroProperty.setup() +215
umbraco.cms.businesslogic.macro.MacroProperty.GetProperties(Int32
MacroId) +189
umbraco.cms.businesslogic.macro.MacroModel..ctor(Macro m) +186
umbraco.macro..ctor(String alias) +117
Umbraco.Web.UmbracoHelper.RenderMacro(String alias, IDictionary`2
parameters) +59
Umbraco.Web.UmbracoHelper.RenderMacro(String alias, Object parameters) +47
ASP._Page_Views_KatilimListesi_cshtml.Execute() in
c:\inetpub\vhosts\cbmeturkey.com\httpdocs\Views\KatilimListesi.cshtml:9
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +199
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter
writer, Object instance) +257
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext,
TextWriter writer) +107
StackExchange.Profiling.MVCHelpers.WrappedView.Render(ViewContext
viewContext, TextWriter writer) +159
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
+23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func`1 continuation) +245
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionResult actionResult) +176
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) +311
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__19() +23
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult
_) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult
ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult
asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult
ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET
Version:4.0.30319.17929
Making stored procedure after insert update other table trigger
Making stored procedure after insert update other table trigger
I've got these tables:
Reservations
Reseration_ID
User_ID
Total_Amount
Tourist_Reservation
Tourist_ID- foreign key
Reservation_ID - foreign key to Reservation
Extra_Charges table
Extra_Charge_ID
Amount
Description
Tourist_Extra_Charges
Tourist_ID - foreign key
Extra_Charge_ID - foreign key
But when a user makes a reservation at first – for example, the basic
packet costs 500 euro – it is inserted into the TotalAmount column in the
Reservation table.
But in the next form the user can select extra_charges which will (but
also he may not select any extra_charges) which are immediately inserted
in the Tourist_Extra_charges table.
The problem is that as the user has selected extra_charges I should update
the column TotalAMount.
So after insert in the tourist_extra_charges table I want to make a
trigger that will update the column TotalAmount in the Reservation table.
And this is what I came up with. Please advice me if I can optimize it and
as a whole if the procedure is good.
CREATE TRIGGER [dbo].[tralAmount] on [dbo].[TOURIST_EXTRA_CHARGES] After
Insert
AS
BEGIN
Declare @Res_ID int
Declare @Sum_toAdd money
select @Res_ID = Reservation_ID from inserted
Inner join TOURIST_RESERVATION on
inserted.Tourist_ID=TOURIST_RESERVATION.Tourist_ID
select @Sum_toAdd = Amout from inserted
Inner Join EXTRA_CHARGES on inserted.Extra_Charge_ID=
EXTRA_CHARGES.Extra_Charge_ID
Update RESERVATIONS
Set Reservation_TotalAmount = (Reservation_TotalAmount + @Sum_toAdd)
where Reservation_ID=@Res_ID
END
I've got these tables:
Reservations
Reseration_ID
User_ID
Total_Amount
Tourist_Reservation
Tourist_ID- foreign key
Reservation_ID - foreign key to Reservation
Extra_Charges table
Extra_Charge_ID
Amount
Description
Tourist_Extra_Charges
Tourist_ID - foreign key
Extra_Charge_ID - foreign key
But when a user makes a reservation at first – for example, the basic
packet costs 500 euro – it is inserted into the TotalAmount column in the
Reservation table.
But in the next form the user can select extra_charges which will (but
also he may not select any extra_charges) which are immediately inserted
in the Tourist_Extra_charges table.
The problem is that as the user has selected extra_charges I should update
the column TotalAMount.
So after insert in the tourist_extra_charges table I want to make a
trigger that will update the column TotalAmount in the Reservation table.
And this is what I came up with. Please advice me if I can optimize it and
as a whole if the procedure is good.
CREATE TRIGGER [dbo].[tralAmount] on [dbo].[TOURIST_EXTRA_CHARGES] After
Insert
AS
BEGIN
Declare @Res_ID int
Declare @Sum_toAdd money
select @Res_ID = Reservation_ID from inserted
Inner join TOURIST_RESERVATION on
inserted.Tourist_ID=TOURIST_RESERVATION.Tourist_ID
select @Sum_toAdd = Amout from inserted
Inner Join EXTRA_CHARGES on inserted.Extra_Charge_ID=
EXTRA_CHARGES.Extra_Charge_ID
Update RESERVATIONS
Set Reservation_TotalAmount = (Reservation_TotalAmount + @Sum_toAdd)
where Reservation_ID=@Res_ID
END
How do I pass a variable's value to html->link() $title?
How do I pass a variable's value to html->link() $title?
My code looks like this:
<li>
<?php echo $html-> link($post['Post']['title'],
array('action'=>'post', $post['Post']['id'])); ?>
</li>
I'm trying to get a link in the form of /cake/posts/view/<id>, where id is
1, 2, 3 etc.
The error Cake gives is
Error: Call to a member function link() on a non-object
Full code here: http://pastebin.com/hexVvkfk
My code looks like this:
<li>
<?php echo $html-> link($post['Post']['title'],
array('action'=>'post', $post['Post']['id'])); ?>
</li>
I'm trying to get a link in the form of /cake/posts/view/<id>, where id is
1, 2, 3 etc.
The error Cake gives is
Error: Call to a member function link() on a non-object
Full code here: http://pastebin.com/hexVvkfk
Saturday, 28 September 2013
Multithreading a password checker in C
Multithreading a password checker in C
pCurrently attempting to get this program to use multithreading using
codepthread_create/code, codepthread_join/code, codepthread_exit/code, and
codepthread_self/code. I then intend to use codecrypt_r/code in place of
codecrypt/code in my code./p pIt will only be able to go up to 8 threads,
but I don't even know how to get started with two. I just have one line
that declares codepthread_t t1,t2,t3,t4,t5,t6,t7,t8/code./p pThe plan with
these is to put them in to codepthread_create/code but besides
initializing these values, I don't know where to go from here./p pI know
that pthread_create's input would be something like codepthread_create(t1,
NULL, ... , ...)/code but I do not know how to go about making the 3rd
input or what the 4th input even is. I then have to make sure to split up
the range of letters that each thread is checking based on the number of
threads specified by a command line arg. I've designed this so far to work
on one thread only, planning on moving it to codecrypt_r/code with
multithreading.../p pReally confused as to how I could get to make this
work.. If possible./p pI know some sort of void function is the third
entry in to codepthread_create/code.. but does that function have to be
what my passwordChecker is? Or what?/p precode/* crack.exe */ /* g++ -o
crack crack.c -lcrypt -lpthread */ //#define _GNU_SOURCE #include
lt;crypt.hgt; #include lt;unistd.hgt; #include lt;stdio.hgt; #include
lt;stdlib.hgt; #include lt;errno.hgt; #include lt;pthread.hgt; #include
lt;string.hgt; #include lt;math.hgt; void *passwordLooper(int ks, char
target[9], char s[10]); void *threadFunction(void *threads); int main(int
argc, char *argv[]){ /* usage = crack threads keysize target */ int i = 0;
/* arg[0] = crack, arg[1] = #of threads arg[2] = size of password, arg[3]
= hashed password being cracked */ if (argc != 4) { fprintf(stderr, Too
few/many arguements give.\n); fprintf(stderr, Proper usage: ./crack
threads keysize target\n); exit(0); } int threads = *argv[1]-'0'; //
threads is now equal to the second command line argument number int
keysize = *argv[2]-'0'; // keysize is now equal to the third command line
argument number char target[9]; strcpy(target, argv[3]); char salt[10];
while ( i lt; 2 ){ //Takes first two characters of the hashed password and
assigns them to the salt variable salt[i] = target[i]; i++; }
printf(threads = %d\n, threads); /*used for testing */ printf(keysize =
%d\n, keysize); printf(target = %s\n, target); printf(salt = %s\n, salt);
if (threads lt; 1 || threads gt; 8){ fprintf(stderr, 0 lt; threads lt;=
8\n); exit(0); } /*Checks to be sure that threads and keysize are*/ if
(keysize lt; 1 || keysize gt; 8){ /*of the correct size */ fprintf(stderr,
0 lt; keysize lt;= 8\n); exit(0); } pthread_t t1,t2,t3,t4,t5,t6,t7,t8; if
( threads = 1 ){ pthread_create(amp;t1, NULL, *threadFunction, threads); }
char unSalted[30]; int j = 0; for (i = 2; target[i] != '\0'; i++){
/*generates variable from target that does not include salt*/ unSalted[j]
= target[i]; j++; } printf(unSalted = %s\n, unSalted); //unSalted is the
variable target without the first two characters (the salt) char
password[9] = {0}; passwordLooper(keysize, target, salt); }
/*_____________________________________________________________________________________________________________*/
/*_____________________________________________________________________________________________________________*/
void *passwordLooper(int ks, char target[9], char s[10]){ char password[9]
= {0}; struct crypt_data cd; cd.initialized = 0; int result; for (;;){ int
level = 0; while (level lt; ks amp;amp; strcmp( crypt(password, s), target
) != 0) { if (password[level] == 0){ password[level] = 'a'; break; } if
(password[level] gt;= 'a' amp;amp; password[level] lt; 'z'){
password[level]++; break; } if (password[level] == 'z'){ password[level] =
'a'; level++; } } char *cryptPW = crypt(password, s); result =
strcmp(cryptPW, target); if (result == 0){ //if result is zero, cryptPW
and target are the same printf(result = %d\n, result); printf (Password
found: %s\n, password); printf(Hashed version of password is %s\n,
cryptPW); break; } if (level gt;= ks){ //if level ends up bigger than the
keysize, break, no longer checking for passwords printf(Password not
found\n); break; } } return 0; } /code/pre
pCurrently attempting to get this program to use multithreading using
codepthread_create/code, codepthread_join/code, codepthread_exit/code, and
codepthread_self/code. I then intend to use codecrypt_r/code in place of
codecrypt/code in my code./p pIt will only be able to go up to 8 threads,
but I don't even know how to get started with two. I just have one line
that declares codepthread_t t1,t2,t3,t4,t5,t6,t7,t8/code./p pThe plan with
these is to put them in to codepthread_create/code but besides
initializing these values, I don't know where to go from here./p pI know
that pthread_create's input would be something like codepthread_create(t1,
NULL, ... , ...)/code but I do not know how to go about making the 3rd
input or what the 4th input even is. I then have to make sure to split up
the range of letters that each thread is checking based on the number of
threads specified by a command line arg. I've designed this so far to work
on one thread only, planning on moving it to codecrypt_r/code with
multithreading.../p pReally confused as to how I could get to make this
work.. If possible./p pI know some sort of void function is the third
entry in to codepthread_create/code.. but does that function have to be
what my passwordChecker is? Or what?/p precode/* crack.exe */ /* g++ -o
crack crack.c -lcrypt -lpthread */ //#define _GNU_SOURCE #include
lt;crypt.hgt; #include lt;unistd.hgt; #include lt;stdio.hgt; #include
lt;stdlib.hgt; #include lt;errno.hgt; #include lt;pthread.hgt; #include
lt;string.hgt; #include lt;math.hgt; void *passwordLooper(int ks, char
target[9], char s[10]); void *threadFunction(void *threads); int main(int
argc, char *argv[]){ /* usage = crack threads keysize target */ int i = 0;
/* arg[0] = crack, arg[1] = #of threads arg[2] = size of password, arg[3]
= hashed password being cracked */ if (argc != 4) { fprintf(stderr, Too
few/many arguements give.\n); fprintf(stderr, Proper usage: ./crack
threads keysize target\n); exit(0); } int threads = *argv[1]-'0'; //
threads is now equal to the second command line argument number int
keysize = *argv[2]-'0'; // keysize is now equal to the third command line
argument number char target[9]; strcpy(target, argv[3]); char salt[10];
while ( i lt; 2 ){ //Takes first two characters of the hashed password and
assigns them to the salt variable salt[i] = target[i]; i++; }
printf(threads = %d\n, threads); /*used for testing */ printf(keysize =
%d\n, keysize); printf(target = %s\n, target); printf(salt = %s\n, salt);
if (threads lt; 1 || threads gt; 8){ fprintf(stderr, 0 lt; threads lt;=
8\n); exit(0); } /*Checks to be sure that threads and keysize are*/ if
(keysize lt; 1 || keysize gt; 8){ /*of the correct size */ fprintf(stderr,
0 lt; keysize lt;= 8\n); exit(0); } pthread_t t1,t2,t3,t4,t5,t6,t7,t8; if
( threads = 1 ){ pthread_create(amp;t1, NULL, *threadFunction, threads); }
char unSalted[30]; int j = 0; for (i = 2; target[i] != '\0'; i++){
/*generates variable from target that does not include salt*/ unSalted[j]
= target[i]; j++; } printf(unSalted = %s\n, unSalted); //unSalted is the
variable target without the first two characters (the salt) char
password[9] = {0}; passwordLooper(keysize, target, salt); }
/*_____________________________________________________________________________________________________________*/
/*_____________________________________________________________________________________________________________*/
void *passwordLooper(int ks, char target[9], char s[10]){ char password[9]
= {0}; struct crypt_data cd; cd.initialized = 0; int result; for (;;){ int
level = 0; while (level lt; ks amp;amp; strcmp( crypt(password, s), target
) != 0) { if (password[level] == 0){ password[level] = 'a'; break; } if
(password[level] gt;= 'a' amp;amp; password[level] lt; 'z'){
password[level]++; break; } if (password[level] == 'z'){ password[level] =
'a'; level++; } } char *cryptPW = crypt(password, s); result =
strcmp(cryptPW, target); if (result == 0){ //if result is zero, cryptPW
and target are the same printf(result = %d\n, result); printf (Password
found: %s\n, password); printf(Hashed version of password is %s\n,
cryptPW); break; } if (level gt;= ks){ //if level ends up bigger than the
keysize, break, no longer checking for passwords printf(Password not
found\n); break; } } return 0; } /code/pre
What is the PHP equivalent of MySQL's UNHEX()?
What is the PHP equivalent of MySQL's UNHEX()?
What is the PHP equivalent of MySQL's UNHEX()?
For instance, the following query and PHP function should provide the same
value.
SELECT UNHEX(c1) AS unhexed_c1 FROM table;
$unhexed_c1=PHPs_UNHEX_Equivalent($c1);
What is the PHP equivalent of MySQL's UNHEX()?
For instance, the following query and PHP function should provide the same
value.
SELECT UNHEX(c1) AS unhexed_c1 FROM table;
$unhexed_c1=PHPs_UNHEX_Equivalent($c1);
AngularJS - Help creating a YouTube frameapi directive
AngularJS - Help creating a YouTube frameapi directive
I am trying to build a yotube directive with the Youtube Player FrameAPI
example code
Here is the code
HTML
<div you-tube id="player"></div>
Directive
angular.module('mainApp.player').directive('youTube',
function(/*slides_ui*/) {
return {
restrict: 'A', // only activate on element attribute
scope: true, // New scope to use but rest inherit from parent
controller: function($scope, $element, $attrs) {
}, //open for now
link: function(scope, elm, attrs, ctrl) {
// Load the js api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
});
Now the problem I am facing is where to put the rest of the frameapi js.
FrameAPI js
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
If I leave the above code in the HTML it works.
If I move it in the Controller/link function of the directive it doesn't
work.
What am I missing?
I am trying to build a yotube directive with the Youtube Player FrameAPI
example code
Here is the code
HTML
<div you-tube id="player"></div>
Directive
angular.module('mainApp.player').directive('youTube',
function(/*slides_ui*/) {
return {
restrict: 'A', // only activate on element attribute
scope: true, // New scope to use but rest inherit from parent
controller: function($scope, $element, $attrs) {
}, //open for now
link: function(scope, elm, attrs, ctrl) {
// Load the js api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
}
});
Now the problem I am facing is where to put the rest of the frameapi js.
FrameAPI js
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
If I leave the above code in the HTML it works.
If I move it in the Controller/link function of the directive it doesn't
work.
What am I missing?
Dynamic ContextMenuStrip
Dynamic ContextMenuStrip
In my application I have 3 RichTextboxes, I created only one
ContextMenuStrip because I don't like the idea of duplicate the same code
of the same contextmenu and all the context menu options 3 times to use it
with the other 2 Richs, the problem is I don't know how to use the same
ContextMenu for the three RichTextBoxes.
For example one option of the ContextMenuStrip is "Clear text", then
inside the procedure I need to specify the RichTextbox object name to
clear the text:
Private Sub MenuItem_Clear_Text_Click(sender As Object, e As EventArgs) _
Handles MenuItem_Clear_Text.Click
RichTextBox_Affix.Clear()
End Sub
How I can handle in a dynamic way the clear method in that sub for the
other richtextboxes?
I've tried to find the necessary information about which RichTextBox
called the contextmenu to handle the contextmenu procedure only for that
RichTextBox, but I've found anything in the sender or "e" variables.
In my application I have 3 RichTextboxes, I created only one
ContextMenuStrip because I don't like the idea of duplicate the same code
of the same contextmenu and all the context menu options 3 times to use it
with the other 2 Richs, the problem is I don't know how to use the same
ContextMenu for the three RichTextBoxes.
For example one option of the ContextMenuStrip is "Clear text", then
inside the procedure I need to specify the RichTextbox object name to
clear the text:
Private Sub MenuItem_Clear_Text_Click(sender As Object, e As EventArgs) _
Handles MenuItem_Clear_Text.Click
RichTextBox_Affix.Clear()
End Sub
How I can handle in a dynamic way the clear method in that sub for the
other richtextboxes?
I've tried to find the necessary information about which RichTextBox
called the contextmenu to handle the contextmenu procedure only for that
RichTextBox, but I've found anything in the sender or "e" variables.
Friday, 27 September 2013
RGTK2 block user input while processing
RGTK2 block user input while processing
I have written a GUI in R with RGTK2 and Tcltk that does a lot of fairly
heavy calculations and aggregations on big data sets.
I would like to find a way to stop the user interface from accepting user
inputs while it is processing a large data set, and ideally, change the
interface color, popup a dialogue, or change the mouse pointer to an
hourglass/spinner to indicate to users that the application is active.
The implementation that I want would look something like:
gSignalConnect(bigRedButton,"clicked",
f=function(widget)
{
something$start() # object with method that blocks further user input
# and pops up loading bar or "Processing" dialogue
# (or possibly spins the mouse)
# Code that does a very big set of calculations
something$stop() # unblocks user inputs and removes visual impedance
}
)
I have tried using gtkDialogue to solve the problem, but this seems to
stop execution of the whole program until one closes the dialogue, which
rather defeats the purpose.
Any help would be greatly appreciated.
I have written a GUI in R with RGTK2 and Tcltk that does a lot of fairly
heavy calculations and aggregations on big data sets.
I would like to find a way to stop the user interface from accepting user
inputs while it is processing a large data set, and ideally, change the
interface color, popup a dialogue, or change the mouse pointer to an
hourglass/spinner to indicate to users that the application is active.
The implementation that I want would look something like:
gSignalConnect(bigRedButton,"clicked",
f=function(widget)
{
something$start() # object with method that blocks further user input
# and pops up loading bar or "Processing" dialogue
# (or possibly spins the mouse)
# Code that does a very big set of calculations
something$stop() # unblocks user inputs and removes visual impedance
}
)
I have tried using gtkDialogue to solve the problem, but this seems to
stop execution of the whole program until one closes the dialogue, which
rather defeats the purpose.
Any help would be greatly appreciated.
jQuery Mobile popups/notifications
jQuery Mobile popups/notifications
I want to create a small popup/notification that will occur when values
change in my database. the logic is being passed correctly. However, I'm
not sure how to make the popups occur properly and at all as well.
I have two buttons:
<a href="#" data-icon="GhCsStatus-Red" data-rel="popup"
data-inline="true" data-mini="true" data-role="button" id="GhCsStatus_CS"
style="pointer-events: none;">CS</a>
<a href="#" data-icon="GhCsStatus-Red" data-rel="popup"
data-inline="true" data-mini="true" data-role="button" id="GhCsStatus_GH"
style="pointer-events: none;">GH</a>
I would like to have the notifications pop up a little bit above these
buttons. This is what I have created but I just haven't positioned them
yet:
<div id="GH_popup" data-role="popup">
<p> GH is OFF! </p>
</div>
<div id="CS_popup" data-role="popup">
<p> CS is OFF! </p>
</div>
I also have some Javascript that determines when these notifications will
pop up:
<script type="text/javascript" >
$(document).ready(function () { GrabGhCsStatus(); });
function GrabGhCsStatus() {
var url = '@Html.Raw(Url.Action("index","GhCsStatus"))';
$.get(url, function (data) {
if (data.CheckIfCsIsRunning == 1 && data.CheckIfGhIsRunning == 0) {
$("#GH_popup").popup();
$("#GhCsStatus_GH").remove();
if (data.CsStatus == 0) {
$('#GhCsStatus_CS').buttonMarkup({ icon: 'GhCsStatus-Red' });
} else {
$('#GhCsStatus_CS').buttonMarkup({ icon:
'GhCsStatus-Green' });
}
}
}
...
...
...
</script>
I feel as though I am putting the jQuery popup attributes in the wrong
areas and that I am not using them properly =/
I want to create a small popup/notification that will occur when values
change in my database. the logic is being passed correctly. However, I'm
not sure how to make the popups occur properly and at all as well.
I have two buttons:
<a href="#" data-icon="GhCsStatus-Red" data-rel="popup"
data-inline="true" data-mini="true" data-role="button" id="GhCsStatus_CS"
style="pointer-events: none;">CS</a>
<a href="#" data-icon="GhCsStatus-Red" data-rel="popup"
data-inline="true" data-mini="true" data-role="button" id="GhCsStatus_GH"
style="pointer-events: none;">GH</a>
I would like to have the notifications pop up a little bit above these
buttons. This is what I have created but I just haven't positioned them
yet:
<div id="GH_popup" data-role="popup">
<p> GH is OFF! </p>
</div>
<div id="CS_popup" data-role="popup">
<p> CS is OFF! </p>
</div>
I also have some Javascript that determines when these notifications will
pop up:
<script type="text/javascript" >
$(document).ready(function () { GrabGhCsStatus(); });
function GrabGhCsStatus() {
var url = '@Html.Raw(Url.Action("index","GhCsStatus"))';
$.get(url, function (data) {
if (data.CheckIfCsIsRunning == 1 && data.CheckIfGhIsRunning == 0) {
$("#GH_popup").popup();
$("#GhCsStatus_GH").remove();
if (data.CsStatus == 0) {
$('#GhCsStatus_CS').buttonMarkup({ icon: 'GhCsStatus-Red' });
} else {
$('#GhCsStatus_CS').buttonMarkup({ icon:
'GhCsStatus-Green' });
}
}
}
...
...
...
</script>
I feel as though I am putting the jQuery popup attributes in the wrong
areas and that I am not using them properly =/
I screw up the database and schema of my rails app, what should I do to rebuild database from my migration files?
I screw up the database and schema of my rails app, what should I do to
rebuild database from my migration files?
My code is all OK, and it has all and only the migrations from which I
want my database to be create, as I re-run them one bye one..
How should I do this.
my schema file is also screwed up.
thanks
rebuild database from my migration files?
My code is all OK, and it has all and only the migrations from which I
want my database to be create, as I re-run them one bye one..
How should I do this.
my schema file is also screwed up.
thanks
Automated web testing using selenium help needed
Automated web testing using selenium help needed
I'm using selenium to test a web application but need some help. One of
the nodes that needs to be clicked has a constant changing value on
startup.
Example:
click css=#f0012 > ins.jstree-icon
On startup the letter before 0012 is randomly assigned (a letter from
a-z). This means each time my selemnium script is run, I need to somehow
obtain this character or just reference the 0012 so that the program knows
which button to click.
I'm really stuck on this so would appreciate any help
I'm using selenium to test a web application but need some help. One of
the nodes that needs to be clicked has a constant changing value on
startup.
Example:
click css=#f0012 > ins.jstree-icon
On startup the letter before 0012 is randomly assigned (a letter from
a-z). This means each time my selemnium script is run, I need to somehow
obtain this character or just reference the 0012 so that the program knows
which button to click.
I'm really stuck on this so would appreciate any help
Gridview not showing in web site but showing in localhost
Gridview not showing in web site but showing in localhost
I have a web site that uses .net framework and I have a table that pulls
data from a db to display on the site. I have the connection to the db,
the data is being pulled and when I use the localhost browser it shows
perfect but when I use the site on the server it gives me an error or
shows nothing. When I get an error it is the web.config custom errors
needs to me turned off. What would stop the table from showing on the
server but showing on the localhost?
I have a web site that uses .net framework and I have a table that pulls
data from a db to display on the site. I have the connection to the db,
the data is being pulled and when I use the localhost browser it shows
perfect but when I use the site on the server it gives me an error or
shows nothing. When I get an error it is the web.config custom errors
needs to me turned off. What would stop the table from showing on the
server but showing on the localhost?
streams cuda how can offeres concurent execution
streams cuda how can offeres concurent execution
in cuda documentation, it is mentionned that if we use 2 streams (stream0
and stream1) like this way: we copy data in stream0 then we launch the
first kernel in stream0 , then we recuperate data from the device in
stream0, and then the same operations are made in stream1, this way , like
mentioned in the book "CUDA by example 2010", doesn't offer the conccurent
execution, but in the "concurrent kernels sample" this method is used and
offeres the conccurent execution. So can you help me please to understand
the difference beteween the two examples? thanks a lot for your help.
in cuda documentation, it is mentionned that if we use 2 streams (stream0
and stream1) like this way: we copy data in stream0 then we launch the
first kernel in stream0 , then we recuperate data from the device in
stream0, and then the same operations are made in stream1, this way , like
mentioned in the book "CUDA by example 2010", doesn't offer the conccurent
execution, but in the "concurrent kernels sample" this method is used and
offeres the conccurent execution. So can you help me please to understand
the difference beteween the two examples? thanks a lot for your help.
Thursday, 26 September 2013
What component to derive my 'TCard' from? (game)
What component to derive my 'TCard' from? (game)
I am trying to make a TCard component for a game. What class should I
derive it from?
This is for a card game like MTG or yu gi oh. The card should have a blank
image, and when created it will load either a front or back view.
If it loads the front view, it will then have to have a few labels (for
properties like power/cost/def/text). Cards must be clickable.
type
TCard = class(zzzzzzzzz)
private
Now once that is done, do I have to add anything to the
constructor/destructor? Currently I have:
constructor TCard.Create(AOwner: Tcomponent);
begin
inherited Create(AOwner);
end;
{******************************************************************************}
{ Free any resources allocated to component
}
destructor TCard.Destroy;
begin
inherited Destroy;
end;
Also I think I added the onclick parts right but not sure. In the
published area I have
{Inherited properties}
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnClick;
property OnDblClick;
etc...
I am trying to make a TCard component for a game. What class should I
derive it from?
This is for a card game like MTG or yu gi oh. The card should have a blank
image, and when created it will load either a front or back view.
If it loads the front view, it will then have to have a few labels (for
properties like power/cost/def/text). Cards must be clickable.
type
TCard = class(zzzzzzzzz)
private
Now once that is done, do I have to add anything to the
constructor/destructor? Currently I have:
constructor TCard.Create(AOwner: Tcomponent);
begin
inherited Create(AOwner);
end;
{******************************************************************************}
{ Free any resources allocated to component
}
destructor TCard.Destroy;
begin
inherited Destroy;
end;
Also I think I added the onclick parts right but not sure. In the
published area I have
{Inherited properties}
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnClick;
property OnDblClick;
etc...
Thursday, 19 September 2013
c++ read in csv file and manipulate data then print error
c++ read in csv file and manipulate data then print error
This is a continuation for my problem here: c++ reading in text file into
vector<vector> then writing to vector or array depending on first word in
internal vector .Im reading in a file and the using the values of node
coordinates to calc cell centres and want to pring the cell centres file
with Headers: ID,X,Y,Z, with Z all 0s.
Code so far:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
std::vector<double> GetValues(const std::vector<std::string>& src, int
start, int end)
{
std::vector<double> ret;
for(int i = start; i <= end; ++i)
{
ret.push_back(std::strtod(src[i].c_str(), nullptr));
}
return ret;
}
std::vector<double> polycentre(const std::vector<double>& x,const
std::vector<double>& y,int ID)
{
std::vector<double> C(3, 0);
std::vector<double> x1(x.size(),0);
std::vector<double> y1(y.size(),0);
int sizx = x.size();
int sizy = y.size();
if(sizy != sizx)
{
std::cerr << "polycentre inputs not equal length";
}
double x0 = x[0];
double y0 = y[0];
for(int aa = 1; aa < sizx; ++aa)
{
if(x[aa] < x0){x0 = x[aa];}
if(y[aa] < y0){y0 = y[aa];}
}
double A = 0.0;
double B = 0.0;
for(int aa = 0; aa < sizx; ++aa)
{
x1[aa] = x[aa] - x0;
y1[aa] = y[aa] - x0;
if(aa != sizx-1)
{
A = A + (x1[aa]*y1[aa+1] - x1[aa+1]*y1[aa]);
B = B + ((x1[aa]+x1[aa+1])*(x1[aa]*y1[aa-1]-x1[aa-1]*y1[aa]));
}
else if(aa == sizx-1)
{
A = A + (x1[aa] - y1[aa]);
B = B + ((x1[aa]+1)*(x1[aa]*1-1*y1[aa]));
}
}
A = A*0.5;
C[0] = ID;
C[1] = ((1/6/A)*B)+x0;
C[2] = ((1/6/A)*B)+y0;
return C;
}
void PrintValues(const std::string& title,
std::vector<std::vector<double>>& v)
{
std::cout << title << std::endl;
for(size_t line = 0; line < v.size(); ++line)
{
for(size_t val = 0; val < v[line].size(); ++val)
{
std::cout << v[line][val] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main()
{
std::vector<std::vector<std::string>> values;
std::ifstream fin("example.2dm");
for (std::string line; std::getline(fin, line); )
{
std::istringstream in(line);
values.push_back(
std::vector<std::string>(std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>()));
}
std::vector<std::vector<double>> cells;
std::vector<std::vector<double>> nodes;
for (size_t i = 0; i < values.size(); ++i)
{
if(values[i][0] == "E3T")
{
cells.push_back(GetValues(values[i], 1, 5));
}
else if(values[i][0] == "E4Q")
{
cells.push_back(GetValues(values[i], 1, 6));
}
else if(values[i][0] == "ND")
{
nodes.push_back(GetValues(values[i], 1, 4));
}
}
std::vector<std::vector<double>> cell_centres;
for (size_t aa = 0; aa < cells.size(); ++aa)
{
if(cells[aa].size() == 4)
{
std::vector<double> xs = {&nodes[cells[aa][1]][1],
&nodes[cells[aa][2]][1], &nodes[cells[aa][3]][1]};
std::vector<double> ys = {&nodes[cells[aa][1]][2],
&nodes[cells[aa][2]][2], &nodes[cells[aa][3]][2]};
cell_centres.push_back(polycentre(xs,ys,aa));
}
}
PrintValues("Cell Centres", cell_centres);
PrintValues("Cells", cells);
PrintValues("Nodes", nodes);
return 0;
}
Im getting the following compilation error:
$ g++ cell_centres.cpp -std=c++11
cell_centres.cpp: In function 'int main()':
cell_centres.cpp:110:105: error: could not convert '{(&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(1u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(1u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(2u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(1u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(3u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(1u))}' from
'<brace-enclosed initializer list>' to 'std::vector<double>'
cell_centres.cpp:111:105: error: could not convert '{(&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(1u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(2u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(2u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(2u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(3u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(2u))}' from
'<brace-enclosed initializer list>' to 'std::vector<double>'
could someone tell me where I went wrong??
BTW the MATLAB code is:
function cell_centres(infil,outfil)
% read 2DM file
MESH = RD2DM(infil);
% get cell centres
if (isfield(MESH,'E3T'))
ne3 = length(MESH.E3T);
else
ne3 = 0;
end
if (isfield(MESH,'E4Q'))
ne4 = length(MESH.E4Q);
else
ne4 = 0;
end
ne = ne3 + ne4;
ctrd = zeros(ne,2);
id = zeros(ne,1);
z = zeros(ne,1);
k = 1;
if (isfield(MESH,'E3T'))
for i = 1:length(MESH.E3T)
pts = MESH.E3T(i,2:4);
x = MESH.ND(pts,2);
y = MESH.ND(pts,3);
z(k) = mean(MESH.ND(pts,4));
ctrd(k,:) = polycentre(x,y);
id(k) = MESH.E3T(i,1);
k = k+1;
end
end
if (isfield(MESH,'E4Q'))
for i = 1:length(MESH.E4Q)
pts = MESH.E4Q(i,2:5);
x = MESH.ND(pts,2);
y = MESH.ND(pts,3);
z(k) = mean(MESH.ND(pts,4));
ctrd(k,:) = polycentre(x,y);
id(k) = MESH.E4Q(i,1);
k = k+1;
end
end
% order cell ids
[id i] = sort(id,'ascend');
ctrd = ctrd(i,:);
z = z(i);
% write .csv file
fid = fopen(outfil,'w');
fprintf(fid,'%s\n','ID,X,Y,Z');
for aa = 1:ne
fprintf(fid,'%i,%.7f,%.7f,%.7f\n',id(aa),ctrd(aa,1),ctrd(aa,2),z(aa));
end
fclose(fid);
display('done & done :-)')
Cheers
This is a continuation for my problem here: c++ reading in text file into
vector<vector> then writing to vector or array depending on first word in
internal vector .Im reading in a file and the using the values of node
coordinates to calc cell centres and want to pring the cell centres file
with Headers: ID,X,Y,Z, with Z all 0s.
Code so far:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
std::vector<double> GetValues(const std::vector<std::string>& src, int
start, int end)
{
std::vector<double> ret;
for(int i = start; i <= end; ++i)
{
ret.push_back(std::strtod(src[i].c_str(), nullptr));
}
return ret;
}
std::vector<double> polycentre(const std::vector<double>& x,const
std::vector<double>& y,int ID)
{
std::vector<double> C(3, 0);
std::vector<double> x1(x.size(),0);
std::vector<double> y1(y.size(),0);
int sizx = x.size();
int sizy = y.size();
if(sizy != sizx)
{
std::cerr << "polycentre inputs not equal length";
}
double x0 = x[0];
double y0 = y[0];
for(int aa = 1; aa < sizx; ++aa)
{
if(x[aa] < x0){x0 = x[aa];}
if(y[aa] < y0){y0 = y[aa];}
}
double A = 0.0;
double B = 0.0;
for(int aa = 0; aa < sizx; ++aa)
{
x1[aa] = x[aa] - x0;
y1[aa] = y[aa] - x0;
if(aa != sizx-1)
{
A = A + (x1[aa]*y1[aa+1] - x1[aa+1]*y1[aa]);
B = B + ((x1[aa]+x1[aa+1])*(x1[aa]*y1[aa-1]-x1[aa-1]*y1[aa]));
}
else if(aa == sizx-1)
{
A = A + (x1[aa] - y1[aa]);
B = B + ((x1[aa]+1)*(x1[aa]*1-1*y1[aa]));
}
}
A = A*0.5;
C[0] = ID;
C[1] = ((1/6/A)*B)+x0;
C[2] = ((1/6/A)*B)+y0;
return C;
}
void PrintValues(const std::string& title,
std::vector<std::vector<double>>& v)
{
std::cout << title << std::endl;
for(size_t line = 0; line < v.size(); ++line)
{
for(size_t val = 0; val < v[line].size(); ++val)
{
std::cout << v[line][val] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main()
{
std::vector<std::vector<std::string>> values;
std::ifstream fin("example.2dm");
for (std::string line; std::getline(fin, line); )
{
std::istringstream in(line);
values.push_back(
std::vector<std::string>(std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>()));
}
std::vector<std::vector<double>> cells;
std::vector<std::vector<double>> nodes;
for (size_t i = 0; i < values.size(); ++i)
{
if(values[i][0] == "E3T")
{
cells.push_back(GetValues(values[i], 1, 5));
}
else if(values[i][0] == "E4Q")
{
cells.push_back(GetValues(values[i], 1, 6));
}
else if(values[i][0] == "ND")
{
nodes.push_back(GetValues(values[i], 1, 4));
}
}
std::vector<std::vector<double>> cell_centres;
for (size_t aa = 0; aa < cells.size(); ++aa)
{
if(cells[aa].size() == 4)
{
std::vector<double> xs = {&nodes[cells[aa][1]][1],
&nodes[cells[aa][2]][1], &nodes[cells[aa][3]][1]};
std::vector<double> ys = {&nodes[cells[aa][1]][2],
&nodes[cells[aa][2]][2], &nodes[cells[aa][3]][2]};
cell_centres.push_back(polycentre(xs,ys,aa));
}
}
PrintValues("Cell Centres", cell_centres);
PrintValues("Cells", cells);
PrintValues("Nodes", nodes);
return 0;
}
Im getting the following compilation error:
$ g++ cell_centres.cpp -std=c++11
cell_centres.cpp: In function 'int main()':
cell_centres.cpp:110:105: error: could not convert '{(&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(1u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(1u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(2u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(1u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(3u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(1u))}' from
'<brace-enclosed initializer list>' to 'std::vector<double>'
cell_centres.cpp:111:105: error: could not convert '{(&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(1u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(2u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(2u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(2u)), (&(&
nodes.std::vector<_Tp, _Alloc>::operator[]<std::vector<double>,
std::allocator<std::vector<double> > >((std::vector<std::vector<double,
std::allocator<double> >, std::allocator<std::vector<double,
std::allocator<double> > > >::size_type)*((std::value_type<double,
std::allocator<double> >*)cells.operator[]()(aa))->std::vector<double,
std::allocator<double> >::operator[]()(3u)))->std::vector<_Tp,
_Alloc>::operator[]<double, std::allocator<double> >(2u))}' from
'<brace-enclosed initializer list>' to 'std::vector<double>'
could someone tell me where I went wrong??
BTW the MATLAB code is:
function cell_centres(infil,outfil)
% read 2DM file
MESH = RD2DM(infil);
% get cell centres
if (isfield(MESH,'E3T'))
ne3 = length(MESH.E3T);
else
ne3 = 0;
end
if (isfield(MESH,'E4Q'))
ne4 = length(MESH.E4Q);
else
ne4 = 0;
end
ne = ne3 + ne4;
ctrd = zeros(ne,2);
id = zeros(ne,1);
z = zeros(ne,1);
k = 1;
if (isfield(MESH,'E3T'))
for i = 1:length(MESH.E3T)
pts = MESH.E3T(i,2:4);
x = MESH.ND(pts,2);
y = MESH.ND(pts,3);
z(k) = mean(MESH.ND(pts,4));
ctrd(k,:) = polycentre(x,y);
id(k) = MESH.E3T(i,1);
k = k+1;
end
end
if (isfield(MESH,'E4Q'))
for i = 1:length(MESH.E4Q)
pts = MESH.E4Q(i,2:5);
x = MESH.ND(pts,2);
y = MESH.ND(pts,3);
z(k) = mean(MESH.ND(pts,4));
ctrd(k,:) = polycentre(x,y);
id(k) = MESH.E4Q(i,1);
k = k+1;
end
end
% order cell ids
[id i] = sort(id,'ascend');
ctrd = ctrd(i,:);
z = z(i);
% write .csv file
fid = fopen(outfil,'w');
fprintf(fid,'%s\n','ID,X,Y,Z');
for aa = 1:ne
fprintf(fid,'%i,%.7f,%.7f,%.7f\n',id(aa),ctrd(aa,1),ctrd(aa,2),z(aa));
end
fclose(fid);
display('done & done :-)')
Cheers
Multiple images being loaded with onload to call function and only last one loaded calls the function
Multiple images being loaded with onload to call function and only last
one loaded calls the function
I have multiple images being loaded from my database with an
onload="imgLoaded($(this));" that when is called gives the ability to the
image to be draggable, resizable and deletable.
Images:
<img src='data:image/".$ext.";base64,".base64_encode(XXXXX)."'
style=\"width:inherit; height:inherit;\" class='img_set'
onload=\"imgLoaded($(this));\">
Function imgLoaded:
function imgLoaded(imgElemt)
{
$('.db_result').html('<img src="images/loader.gif" />');
var full_url = document.URL;
if(full_url.indexOf('idedit') <= 0 || imgAreaMap > 0){
if(imgElemt.closest(".child").width() < imgElemt.width() ||
imgElemt.closest(".child").height() < imgElemt.height()){
if(imgElemt.closest(".child").width() >
imgElemt.closest(".child").height()){
imgElemt.parent(".imgh").height("100%");
imgElemt.parent(".imgh").width(imgElemt.width());
}else{
imgElemt.parent(".imgh").width("100%");
imgElemt.parent(".imgh").height(imgElemt.height());
}
}
else{
imgElemt.parent(".imgh").width(imgElemt.width());
}
}
$('.db_result').delay(500).queue(function(n) { $(this).html(''); });
$('#liveDimensions').text('Largura: '+imgElemt.width()+' px\nAltura:
'+imgElemt.height()+' px');
$('.imgh').on( 'resize', function( event, ui ) {
$('#liveDimensions').text('Largura: '+$(this).width()+'
px\nAltura: '+$(this).height()+' px');
});
imgElemt.parent('.imgh').append('<div class=\"close\"><img
src=\"images/delete.png\"/></div>');
imgElemt.closest('.child').children('.fileinput-holder').remove();
imgElemt.closest('.imgh').draggable({ containment:
imgElemt.closest('.child'), scroll: true, snap: true, snapTolerance: 5
});
imgElemt.closest('.imgh').resizable({ containment:
imgElemt.closest('.child') });
}
My problem is that only the last image loaded calls the function imgLoaded.
How can I force all the onload to happen for each single loaded image?
one loaded calls the function
I have multiple images being loaded from my database with an
onload="imgLoaded($(this));" that when is called gives the ability to the
image to be draggable, resizable and deletable.
Images:
<img src='data:image/".$ext.";base64,".base64_encode(XXXXX)."'
style=\"width:inherit; height:inherit;\" class='img_set'
onload=\"imgLoaded($(this));\">
Function imgLoaded:
function imgLoaded(imgElemt)
{
$('.db_result').html('<img src="images/loader.gif" />');
var full_url = document.URL;
if(full_url.indexOf('idedit') <= 0 || imgAreaMap > 0){
if(imgElemt.closest(".child").width() < imgElemt.width() ||
imgElemt.closest(".child").height() < imgElemt.height()){
if(imgElemt.closest(".child").width() >
imgElemt.closest(".child").height()){
imgElemt.parent(".imgh").height("100%");
imgElemt.parent(".imgh").width(imgElemt.width());
}else{
imgElemt.parent(".imgh").width("100%");
imgElemt.parent(".imgh").height(imgElemt.height());
}
}
else{
imgElemt.parent(".imgh").width(imgElemt.width());
}
}
$('.db_result').delay(500).queue(function(n) { $(this).html(''); });
$('#liveDimensions').text('Largura: '+imgElemt.width()+' px\nAltura:
'+imgElemt.height()+' px');
$('.imgh').on( 'resize', function( event, ui ) {
$('#liveDimensions').text('Largura: '+$(this).width()+'
px\nAltura: '+$(this).height()+' px');
});
imgElemt.parent('.imgh').append('<div class=\"close\"><img
src=\"images/delete.png\"/></div>');
imgElemt.closest('.child').children('.fileinput-holder').remove();
imgElemt.closest('.imgh').draggable({ containment:
imgElemt.closest('.child'), scroll: true, snap: true, snapTolerance: 5
});
imgElemt.closest('.imgh').resizable({ containment:
imgElemt.closest('.child') });
}
My problem is that only the last image loaded calls the function imgLoaded.
How can I force all the onload to happen for each single loaded image?
Dynamically resizing table with jquery
Dynamically resizing table with jquery
I am creating a table where someone can enter a width and height, and it
will be rezied to x units ov 16x16 td's
I have gotten it to work mostly properly, problems only arise when I am
increasing the size on the x axis.
(function() {
var src = $('#grid-source');
var wrap = $('<div id="grid-overlay"></div>');
var gsize = 16;
var cols = 32;
var rows = 32;
// create overlay
var tbl = $('<table></table>');
for (var y = 1; y <= rows; y++) {
var tr = $('<tr></tr>');
for (var x = 1; x <= cols; x++) {
var td = $('<td></td>');
td.css('width', gsize+'px').css('height', gsize+'px');
td.addClass('eraser');
tr.append(td);
}
tbl.append(tr);
}
src.css('width', cols * gsize+'px').css('height', rows * gsize+'px')
// attach overlay
wrap.append(tbl);
src.after(wrap);
function setSize(newx, newy) {
var xchange = newx - cols;
var ychange = newy - rows;
if (xchange < 0) {
console.log('reducing x: ' + xchange);
for (var x = xchange; x < 0; x++) {
console.log(x);
$('#grid-overlay table tbody tr').find('th:last,
td:last').remove();
}
}
if (ychange < 0) {
console.log('reducing y: ' + ychange);
for (var y = ychange; y < 0; y++) {
$('#grid-overlay table tbody').find('tr:last').remove();
}
}
if (xchange > 0) {
console.log('increasing x: ' + xchange);
$('#grid-overlay').find('tr').each(function(){
$(this).find('td').eq(-1).after(Array(xchange).join("<td
class='eraser' style='width:16px; height:16px;'></td>"));
});
}
if (ychange > 0) {
console.log('increasing y: ' + ychange);
for (var y = 1; y <= ychange; y++) {
var tr = $('<tr></tr>');
for (var x = 1; x <= newx; x++) {
var td = $('<td></td>');
td.css('width', gsize+'px').css('height', gsize+'px');
td.addClass('eraser');
tr.append(td);
}
tbl.append(tr);
}
}
cols = newx;
rows = newy;
src.css('width', cols * gsize+'px').css('height', rows * gsize+'px');
}
$('#resizeChart').click(function() {
x = $('#inputWidth').val();
y = $('#inputHeight').val();
setSize(x,y);
});
})();
You can find a fully functional example here http://jsfiddle.net/6Ru72/
the questionable block of code is
if (xchange > 0) {
console.log('increasing x: ' + xchange);
$('#grid-overlay').find('tr').each(function(){
$(this).find('td').eq(-1).after(Array(xchange).join("<td
class='eraser' style='width:16px; height:16px;'></td>"));
});
}
if you tinker with the demo, you will see it only increases the width of
the table after a certain point along the y axis. Does anyone have an idea
why this behavior is happening? http://jsfiddle.net/6Ru72/
I am creating a table where someone can enter a width and height, and it
will be rezied to x units ov 16x16 td's
I have gotten it to work mostly properly, problems only arise when I am
increasing the size on the x axis.
(function() {
var src = $('#grid-source');
var wrap = $('<div id="grid-overlay"></div>');
var gsize = 16;
var cols = 32;
var rows = 32;
// create overlay
var tbl = $('<table></table>');
for (var y = 1; y <= rows; y++) {
var tr = $('<tr></tr>');
for (var x = 1; x <= cols; x++) {
var td = $('<td></td>');
td.css('width', gsize+'px').css('height', gsize+'px');
td.addClass('eraser');
tr.append(td);
}
tbl.append(tr);
}
src.css('width', cols * gsize+'px').css('height', rows * gsize+'px')
// attach overlay
wrap.append(tbl);
src.after(wrap);
function setSize(newx, newy) {
var xchange = newx - cols;
var ychange = newy - rows;
if (xchange < 0) {
console.log('reducing x: ' + xchange);
for (var x = xchange; x < 0; x++) {
console.log(x);
$('#grid-overlay table tbody tr').find('th:last,
td:last').remove();
}
}
if (ychange < 0) {
console.log('reducing y: ' + ychange);
for (var y = ychange; y < 0; y++) {
$('#grid-overlay table tbody').find('tr:last').remove();
}
}
if (xchange > 0) {
console.log('increasing x: ' + xchange);
$('#grid-overlay').find('tr').each(function(){
$(this).find('td').eq(-1).after(Array(xchange).join("<td
class='eraser' style='width:16px; height:16px;'></td>"));
});
}
if (ychange > 0) {
console.log('increasing y: ' + ychange);
for (var y = 1; y <= ychange; y++) {
var tr = $('<tr></tr>');
for (var x = 1; x <= newx; x++) {
var td = $('<td></td>');
td.css('width', gsize+'px').css('height', gsize+'px');
td.addClass('eraser');
tr.append(td);
}
tbl.append(tr);
}
}
cols = newx;
rows = newy;
src.css('width', cols * gsize+'px').css('height', rows * gsize+'px');
}
$('#resizeChart').click(function() {
x = $('#inputWidth').val();
y = $('#inputHeight').val();
setSize(x,y);
});
})();
You can find a fully functional example here http://jsfiddle.net/6Ru72/
the questionable block of code is
if (xchange > 0) {
console.log('increasing x: ' + xchange);
$('#grid-overlay').find('tr').each(function(){
$(this).find('td').eq(-1).after(Array(xchange).join("<td
class='eraser' style='width:16px; height:16px;'></td>"));
});
}
if you tinker with the demo, you will see it only increases the width of
the table after a certain point along the y axis. Does anyone have an idea
why this behavior is happening? http://jsfiddle.net/6Ru72/
method_missing visibility in Ruby
method_missing visibility in Ruby
method_missing shows up in Object.private_methods, not in
Object.public_methods.
However, when I call Object.method_missing :stupidmethod, I get
NoMethodError: undefined method `stupidmethod' for Object:Class
I would expect to get
NoMethodError: private method `method_missing' called for Object:Class
because that's what I get when I try to invoke Object's other private
methods, e.g. Object.chop.
As more evidence, if I call Object.method_missing without an argument, I get
ArgumentError: no id given
So it seems like I really am invoking that "private" method_missing
function from outside of its object. Can you explain this?
method_missing shows up in Object.private_methods, not in
Object.public_methods.
However, when I call Object.method_missing :stupidmethod, I get
NoMethodError: undefined method `stupidmethod' for Object:Class
I would expect to get
NoMethodError: private method `method_missing' called for Object:Class
because that's what I get when I try to invoke Object's other private
methods, e.g. Object.chop.
As more evidence, if I call Object.method_missing without an argument, I get
ArgumentError: no id given
So it seems like I really am invoking that "private" method_missing
function from outside of its object. Can you explain this?
Task Parallel Library and SQL Connections
Task Parallel Library and SQL Connections
I'm hoping someone can confirm what is actually happening here with TPL
and SQL connections.
Basically, I have a large application which, in essence, reads a table
from SQL Server, and then processes each row - serially. The processing of
each row can take quite some time. So, I thought to change this to use the
Task Parallel Library, with a "Parallel.ForEach" across the rows in the
datatable. This seems to work for a little while (minutes), then it all
goes pear-shaped with...
"The timeout period elapsed prior to obtaining a connection from the pool.
This may have occurred because all pooled connections were in use and max
pool size was reached."
Now, I surmised the following (which may of course be entirely wrong).
The "ForEach" creates tasks for each row, up to some limit based on the
number of cores (or whatever). Lets say 4 for want of a better idea. Each
of the four tasks gets a row, and goes off to process it. TPL waits until
the machine is not too busy, and fires up some more. I'm expecting a max
of four.
But that's not what I observe - and not what I think is happening.
So... I wrote a quick test (see below):
Sub Main()
Dim tbl As New DataTable()
FillTable(tbl)
Parallel.ForEach(tbl.AsEnumerable(), AddressOf ProcessRow)
End Sub
Private n As Integer = 0
Sub ProcessRow(row As DataRow, state As ParallelLoopState)
n += 1
Console.WriteLine("Starting thread {0}({1})", n,
Thread.CurrentThread.ManagedThreadId)
Using cnx As SqlConnection = New
SqlConnection(My.Settings.ConnectionString)
cnx.Open()
Thread.Sleep(TimeSpan.FromMinutes(5))
cnx.Close()
End Using
Console.WriteLine("Closing thread {0}({1})", n,
Thread.CurrentThread.ManagedThreadId)
n -= 1
End Sub
This creates way more than my guess at the number of tasks. So, I surmise
that TPL fires up tasks to the limit it thinks will keep my machine busy,
but hey, what's this, we're not very busy here, so lets start some more.
Still not very busy, so... etc. (seems like one new task a second -
roughly).
This is reasonable-ish, but I expect it to go pop 30 seconds (SQL
connection timeout) after when and if it gets 100 open SQL connections -
the default connection pool size - which it doesn't.
So, to scale it back a bit, I change my connection string to limit the max
pool size.
Sub Main()
Dim tbl As New DataTable()
Dim csb As New SqlConnectionStringBuilder(My.Settings.ConnectionString)
csb.MaxPoolSize = 10
csb.ApplicationName = "Test 1"
My.Settings("ConnectionString") = csb.ToString()
FillTable(tbl)
Parallel.ForEach(tbl.AsEnumerable(), AddressOf ProcessRow)
End Sub
I count the real number of connections to the SQL server, and as expected,
its 10. But my application has fired up 26 tasks - and then hangs. So,
setting the max pool size for SQL somehow limited the number of tasks to
26, but why no 27, and especially, why doesn't it fall over at 11 because
the pool is full ?
Obviously, somewhere along the line I'm asking for more work than my
machine can do, and I can add "MaxDegreesOfParallelism" to the ForEach,
but I'm interested in what's actually going on here.
PS.
Actually, after sitting with 26 tasks for (I'm guessing) 5 minutes, it
does fall over with the original (max pool size reached) error. Huh ?
Thanks.
I'm hoping someone can confirm what is actually happening here with TPL
and SQL connections.
Basically, I have a large application which, in essence, reads a table
from SQL Server, and then processes each row - serially. The processing of
each row can take quite some time. So, I thought to change this to use the
Task Parallel Library, with a "Parallel.ForEach" across the rows in the
datatable. This seems to work for a little while (minutes), then it all
goes pear-shaped with...
"The timeout period elapsed prior to obtaining a connection from the pool.
This may have occurred because all pooled connections were in use and max
pool size was reached."
Now, I surmised the following (which may of course be entirely wrong).
The "ForEach" creates tasks for each row, up to some limit based on the
number of cores (or whatever). Lets say 4 for want of a better idea. Each
of the four tasks gets a row, and goes off to process it. TPL waits until
the machine is not too busy, and fires up some more. I'm expecting a max
of four.
But that's not what I observe - and not what I think is happening.
So... I wrote a quick test (see below):
Sub Main()
Dim tbl As New DataTable()
FillTable(tbl)
Parallel.ForEach(tbl.AsEnumerable(), AddressOf ProcessRow)
End Sub
Private n As Integer = 0
Sub ProcessRow(row As DataRow, state As ParallelLoopState)
n += 1
Console.WriteLine("Starting thread {0}({1})", n,
Thread.CurrentThread.ManagedThreadId)
Using cnx As SqlConnection = New
SqlConnection(My.Settings.ConnectionString)
cnx.Open()
Thread.Sleep(TimeSpan.FromMinutes(5))
cnx.Close()
End Using
Console.WriteLine("Closing thread {0}({1})", n,
Thread.CurrentThread.ManagedThreadId)
n -= 1
End Sub
This creates way more than my guess at the number of tasks. So, I surmise
that TPL fires up tasks to the limit it thinks will keep my machine busy,
but hey, what's this, we're not very busy here, so lets start some more.
Still not very busy, so... etc. (seems like one new task a second -
roughly).
This is reasonable-ish, but I expect it to go pop 30 seconds (SQL
connection timeout) after when and if it gets 100 open SQL connections -
the default connection pool size - which it doesn't.
So, to scale it back a bit, I change my connection string to limit the max
pool size.
Sub Main()
Dim tbl As New DataTable()
Dim csb As New SqlConnectionStringBuilder(My.Settings.ConnectionString)
csb.MaxPoolSize = 10
csb.ApplicationName = "Test 1"
My.Settings("ConnectionString") = csb.ToString()
FillTable(tbl)
Parallel.ForEach(tbl.AsEnumerable(), AddressOf ProcessRow)
End Sub
I count the real number of connections to the SQL server, and as expected,
its 10. But my application has fired up 26 tasks - and then hangs. So,
setting the max pool size for SQL somehow limited the number of tasks to
26, but why no 27, and especially, why doesn't it fall over at 11 because
the pool is full ?
Obviously, somewhere along the line I'm asking for more work than my
machine can do, and I can add "MaxDegreesOfParallelism" to the ForEach,
but I'm interested in what's actually going on here.
PS.
Actually, after sitting with 26 tasks for (I'm guessing) 5 minutes, it
does fall over with the original (max pool size reached) error. Huh ?
Thanks.
file not found exception while deploying versioned application in Tomcat with ant
file not found exception while deploying versioned application in Tomcat
with ant
I try to build a Target "deploy" in my build.xml Ant build file. the
deploy line is the well known :
<deploy url="${url}" username="${username}" password="${password}"
path="${warfile}" war="file:${filePath}"/>
Everithngs works fine if the {filePath} Property contais for example
E:\workspace\testweb\testweb.war
now the problem: Tomcat allows to set a version in the name by adding
##versionNumber to the name of the war.
this "versioned filename" looks like to:
E:\workspace\testweb\testweb##1.9.1.war
So I try to use a "versioned" name for the war file as follows:
<target name="deploywar">
<property name = "url" value = "http://testweb:8080/" />
<property name = "username" value = "tomcats"/>
<property name = "password" value = "tomcats"/>
<property name = "warfile" value ="testweb"/>
<property name = "version" value ="1.9.1"/>
<property name = "filePath" value
="E:\workspace\testweb\${warfile}##${version}.war"/>
<echo>filePath= ${filePath}</echo>
<echo>warfile = ${warfile}</echo>
<deploy url="${url}" username="${username}" password="${password}"
path="${warfile}" war="file:${filePath}"/>
</target>
In this case, the ant build, fails the deploy task giving the following
result:
Buildfile: E:\workspace\testweb\build.xml
deploywar:
[echo] filePath= E:\workspace\testweb\testweb##1.9.1.war
[echo] warfile = testweb
BUILD FAILED
E:\workspace\testweb\build.xml:341: java.io.FileNotFoundException:
E:\workspace\testweb\testweb (The system cannot find the file specified)
Total time: 328 milliseconds
It seems that Deploy task cannot read the name after the ## !!
If I remove only the "##1.9.1" part the deploy end with success. It's a
bug or an error by me? Is there a workaround? Thank you.
with ant
I try to build a Target "deploy" in my build.xml Ant build file. the
deploy line is the well known :
<deploy url="${url}" username="${username}" password="${password}"
path="${warfile}" war="file:${filePath}"/>
Everithngs works fine if the {filePath} Property contais for example
E:\workspace\testweb\testweb.war
now the problem: Tomcat allows to set a version in the name by adding
##versionNumber to the name of the war.
this "versioned filename" looks like to:
E:\workspace\testweb\testweb##1.9.1.war
So I try to use a "versioned" name for the war file as follows:
<target name="deploywar">
<property name = "url" value = "http://testweb:8080/" />
<property name = "username" value = "tomcats"/>
<property name = "password" value = "tomcats"/>
<property name = "warfile" value ="testweb"/>
<property name = "version" value ="1.9.1"/>
<property name = "filePath" value
="E:\workspace\testweb\${warfile}##${version}.war"/>
<echo>filePath= ${filePath}</echo>
<echo>warfile = ${warfile}</echo>
<deploy url="${url}" username="${username}" password="${password}"
path="${warfile}" war="file:${filePath}"/>
</target>
In this case, the ant build, fails the deploy task giving the following
result:
Buildfile: E:\workspace\testweb\build.xml
deploywar:
[echo] filePath= E:\workspace\testweb\testweb##1.9.1.war
[echo] warfile = testweb
BUILD FAILED
E:\workspace\testweb\build.xml:341: java.io.FileNotFoundException:
E:\workspace\testweb\testweb (The system cannot find the file specified)
Total time: 328 milliseconds
It seems that Deploy task cannot read the name after the ## !!
If I remove only the "##1.9.1" part the deploy end with success. It's a
bug or an error by me? Is there a workaround? Thank you.
jQuery Wrap table colum text
jQuery Wrap table colum text
Hi i am generating a dynamic list which contains table, the problem is
that content in the table in not wrapping when it exceeds width of device.
I am using Jquery mobile 1.3.0.
I am using this code :
list += '<li id="list_"><a href="#abcd" ><table data-role="table"
id="movie-table" class="ui-responsive table-stroke">'
+ '<thead>'
+ '<tr> '
+ '<th data-priority="1">Temp Id</th> '
+ '<th data-priority="persist">Product</th> '
+ '<th data-priority="2">Scheme</th> '
+ '<th data-priority="3"> Name</th> '
+ '</tr> '
+ '</thead>'
+ '<tbody>'
+ '<tr> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '</tr> '
+ '<tr> ' + '</tbody>' + '</table> </a></li>';
here xxxxxxxxxxxxxxxx is a javascript variable.
Hi i am generating a dynamic list which contains table, the problem is
that content in the table in not wrapping when it exceeds width of device.
I am using Jquery mobile 1.3.0.
I am using this code :
list += '<li id="list_"><a href="#abcd" ><table data-role="table"
id="movie-table" class="ui-responsive table-stroke">'
+ '<thead>'
+ '<tr> '
+ '<th data-priority="1">Temp Id</th> '
+ '<th data-priority="persist">Product</th> '
+ '<th data-priority="2">Scheme</th> '
+ '<th data-priority="3"> Name</th> '
+ '</tr> '
+ '</thead>'
+ '<tbody>'
+ '<tr> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '<td>'
+ XXXXXXXXXXXXXXXXXXXXXX
+ '</td> '
+ '</tr> '
+ '<tr> ' + '</tbody>' + '</table> </a></li>';
here xxxxxxxxxxxxxxxx is a javascript variable.
Page loading partially
Page loading partially
I have deployed my project to local server. There are 12-15 pages in my
project. Which running fine in lan environment. Now i assign a dedicated
ip to my server. All pages rendered correctly, but only one page load
partially and some time it show "The connection was reset".
I have deployed my project to local server. There are 12-15 pages in my
project. Which running fine in lan environment. Now i assign a dedicated
ip to my server. All pages rendered correctly, but only one page load
partially and some time it show "The connection was reset".
Wednesday, 18 September 2013
How can I use DateTime to get the time to this format?
How can I use DateTime to get the time to this format?
'Wed, 18 Sep 2013 22:22:44 -0700'
I tried datetime.datetime.now().strftime, but I can't get it perfectly in
that format.
'Wed, 18 Sep 2013 22:22:44 -0700'
I tried datetime.datetime.now().strftime, but I can't get it perfectly in
that format.
Merging a git repo from the origin to the upstream repository
Merging a git repo from the origin to the upstream repository
Let's say I have an upstream repository, which I have forked to a new origin.
If I want to merge changes from the upstream repo into my forked origin, I
would do something like this from within the fork:
$ git merge upstream/master
How would I go the other direction, from origin to upstream? Say I change
something in the fork that I want to push to the parent — how would I go
about that?
Is it just a matter of setting a new remote/upstream for the parent, using
the fork as the parent's upstream?
Let's say I have an upstream repository, which I have forked to a new origin.
If I want to merge changes from the upstream repo into my forked origin, I
would do something like this from within the fork:
$ git merge upstream/master
How would I go the other direction, from origin to upstream? Say I change
something in the fork that I want to push to the parent — how would I go
about that?
Is it just a matter of setting a new remote/upstream for the parent, using
the fork as the parent's upstream?
which of ANN (nnetar) and ARIMA are better forecasting methods?
which of ANN (nnetar) and ARIMA are better forecasting methods?
**I conducted a forecasting study on water influent characteristics to
water treatment plant with to well-known ANN (nnetar) and arima from
forecast package. i write below code in r for doing cross validation on
the fotecasted values by medels. i modefied the example code for
crass-validation by Prof. Hyndman, i am not sure this modified code be
free of mistakes. but it provide interesting results. in many literature i
found that ANN models have better performances in forecasting because
these models can find non linearity behavior of the natural processes. but
after running my code MAE for cross-validation analysis and
Diebold-Mariano test says that ARIMA model have more accuracy than
nnetar!! please let me know am i in mistakes regard my code or this result
can be approved.
Var<-Alk " Alkalinity of water
library(forecast)
tsVar<- ts(Alk, start=1,end=length(Var),frequency=1)
library(Hmisc)
label(tsVar) <- "mgCaCO3/li"
label(Label)<-"Alk"
length(Var)
h= 10 # the horizon for forecasting
#End point of modeling
End=(length(Var)-h)
library(AID)
library(forecast)
L<-boxcoxnc(na.omit(Var), method = "sw", lam = seq(-5,5,0.01), plotit =
TRUE, rep = 30, p.method = "BY")
Lambda<- L$result[1,]
k <- End
n <- length(tsVar)
m<- n-k
For1<- matrix(NA,n-k,h)
For2<- matrix(NA,n-k,h)
Obs<- matrix(NA,n-k,h)
mae1<- matrix(NA,n-k,h)
mae2 <- matrix(NA,n-k,h)
error1<- matrix(NA,n-k,h)
error2 <- matrix(NA,n-k,h)
for(i in 1:(n-k))
{
yshort <- window(tsVar, end =(End-1)+i)
ynext <- window(tsVar, start= End+i, end=length(tsVar) )
fit1 <- nnetar(yshort,8, , repeats=20 ,lambda=Lambda)
fcast1 <- forecast(fit1, h=(h+1)-i)
fit2 <- Arima(yshort, order=c(1,1,1), seasonal=list(order=c(0,0,0)),
lambda= Lambda)
fcast2 <- forecast(fit2, h=(h+1)-i)
Obs[i, (m-length(ynext))+1:length(ynext)] <- ynext
For1[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast1[['mean']])
For2[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast2[['mean']])
mae1[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast1[['mean']]-ynext)
mae2[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast2[['mean']]-ynext)
error1[i, (m-length(ynext))+1:length(ynext)] <- (ynext-fcast1[['mean']])
error2[i, (m-length(ynext))+1:length(ynext)] <- (ynext-fcast2[['mean']])
}
# The Diebold-Mariano test compares the forecast accuracy of two forecast
# methods.
dm.test(colMeans(error1, na.rm=TRUE), colMeans(error2,na.rm=TRUE),
alternative=c("greater"),h=10, power=2)
# H0= two methods have the same forecast accuracy
#if "greater" selected H1= method 2 (ARIMA) is more accurate than method 1
mean(mae1, na.rm=TRUE)#MAE for NNAR
mean(mae2, na.rm=TRUE)#MAE for ARIMA
dev.new()
par(mfrow = c(2,2))
plot(1:h, colMeans(mae1,na.rm=TRUE), type="l", col=2, xlab="horizon",
ylab="MAE",ylim=c(min (colMeans(mae1,na.rm=TRUE)), max
(colMeans(mae1,na.rm=TRUE))))
lines(1:h, colMeans(mae2,na.rm=TRUE), type="l",col=3)
legend("topleft",legend=c("NNAR","ARIMA"),col=2:4,lty=1)
plot(1:h, colMeans(For1,na.rm=TRUE), type="l", col=2, xlab="horizon",
ylab="Forecasted",ylim=c(min (colMeans(Obs,na.rm=TRUE)), max
(colMeans(Obs,na.rm=TRUE))))
lines(1:h, colMeans(For2,na.rm=TRUE), type="l",col=3)
lines(1:h, colMeans(Obs,na.rm=TRUE), type="l",col=4)
legend("topleft",legend=c("NNAR","ARIMA","Obs"),col=2:4,lty=1)
**I conducted a forecasting study on water influent characteristics to
water treatment plant with to well-known ANN (nnetar) and arima from
forecast package. i write below code in r for doing cross validation on
the fotecasted values by medels. i modefied the example code for
crass-validation by Prof. Hyndman, i am not sure this modified code be
free of mistakes. but it provide interesting results. in many literature i
found that ANN models have better performances in forecasting because
these models can find non linearity behavior of the natural processes. but
after running my code MAE for cross-validation analysis and
Diebold-Mariano test says that ARIMA model have more accuracy than
nnetar!! please let me know am i in mistakes regard my code or this result
can be approved.
Var<-Alk " Alkalinity of water
library(forecast)
tsVar<- ts(Alk, start=1,end=length(Var),frequency=1)
library(Hmisc)
label(tsVar) <- "mgCaCO3/li"
label(Label)<-"Alk"
length(Var)
h= 10 # the horizon for forecasting
#End point of modeling
End=(length(Var)-h)
library(AID)
library(forecast)
L<-boxcoxnc(na.omit(Var), method = "sw", lam = seq(-5,5,0.01), plotit =
TRUE, rep = 30, p.method = "BY")
Lambda<- L$result[1,]
k <- End
n <- length(tsVar)
m<- n-k
For1<- matrix(NA,n-k,h)
For2<- matrix(NA,n-k,h)
Obs<- matrix(NA,n-k,h)
mae1<- matrix(NA,n-k,h)
mae2 <- matrix(NA,n-k,h)
error1<- matrix(NA,n-k,h)
error2 <- matrix(NA,n-k,h)
for(i in 1:(n-k))
{
yshort <- window(tsVar, end =(End-1)+i)
ynext <- window(tsVar, start= End+i, end=length(tsVar) )
fit1 <- nnetar(yshort,8, , repeats=20 ,lambda=Lambda)
fcast1 <- forecast(fit1, h=(h+1)-i)
fit2 <- Arima(yshort, order=c(1,1,1), seasonal=list(order=c(0,0,0)),
lambda= Lambda)
fcast2 <- forecast(fit2, h=(h+1)-i)
Obs[i, (m-length(ynext))+1:length(ynext)] <- ynext
For1[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast1[['mean']])
For2[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast2[['mean']])
mae1[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast1[['mean']]-ynext)
mae2[i, (m-length(ynext))+1:length(ynext)] <- abs(fcast2[['mean']]-ynext)
error1[i, (m-length(ynext))+1:length(ynext)] <- (ynext-fcast1[['mean']])
error2[i, (m-length(ynext))+1:length(ynext)] <- (ynext-fcast2[['mean']])
}
# The Diebold-Mariano test compares the forecast accuracy of two forecast
# methods.
dm.test(colMeans(error1, na.rm=TRUE), colMeans(error2,na.rm=TRUE),
alternative=c("greater"),h=10, power=2)
# H0= two methods have the same forecast accuracy
#if "greater" selected H1= method 2 (ARIMA) is more accurate than method 1
mean(mae1, na.rm=TRUE)#MAE for NNAR
mean(mae2, na.rm=TRUE)#MAE for ARIMA
dev.new()
par(mfrow = c(2,2))
plot(1:h, colMeans(mae1,na.rm=TRUE), type="l", col=2, xlab="horizon",
ylab="MAE",ylim=c(min (colMeans(mae1,na.rm=TRUE)), max
(colMeans(mae1,na.rm=TRUE))))
lines(1:h, colMeans(mae2,na.rm=TRUE), type="l",col=3)
legend("topleft",legend=c("NNAR","ARIMA"),col=2:4,lty=1)
plot(1:h, colMeans(For1,na.rm=TRUE), type="l", col=2, xlab="horizon",
ylab="Forecasted",ylim=c(min (colMeans(Obs,na.rm=TRUE)), max
(colMeans(Obs,na.rm=TRUE))))
lines(1:h, colMeans(For2,na.rm=TRUE), type="l",col=3)
lines(1:h, colMeans(Obs,na.rm=TRUE), type="l",col=4)
legend("topleft",legend=c("NNAR","ARIMA","Obs"),col=2:4,lty=1)
Run a jQuery function after browse 3 pages
Run a jQuery function after browse 3 pages
I would like to run a javascript function with Jquery on the user, but
only when he browse 3 pages on the site. Does anyone know if it is
possible to do this? And how?
I would like to run a javascript function with Jquery on the user, but
only when he browse 3 pages on the site. Does anyone know if it is
possible to do this? And how?
D3.js and dragdealer JS
D3.js and dragdealer JS
I am using dragdealer JS with D3.js. What i am doing is that when You drag
the slider made by dragdealer JS the elements made by D3.js will move like
a picture slider.
Here is the code which which i wrote : code.
Now there are two problems with this code:
1) This code is working in FireFox but not in Chrome?
2) How to configure the slider so that on one slide, only one tile will
move into the view and only one will move out?
The number of tiles or rectangles are not fixed. There can be any number
of tiles depending on the user.
Code:
var width = 4000,
height = 200,
margin = 2,
nRect = 20,
rectWidth = (width - (nRect - 1) * margin) / nRect,
svg = d3.select('#chart').append('svg')
.attr('width', width);
var data = d3.range(nRect),
posScale = d3.scale.linear()
.domain(d3.extent(data))
.range([0, width - rectWidth]);
console.log(rectWidth)
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', posScale)
.attr('width', rectWidth)
.attr('height', height);
function redraw(x)
{
svg.transition()
.ease("linear")
.attr("transform", "translate(" + -(x*rectWidth) + ")" );
console.log(-(x*rectWidth));
}
var step = nRect/2;
new Dragdealer('magnifier',
{
steps: step,
snap: true,
animationCallback: function(x, y)
{ console.log(x*10)
redraw(x*step);
}
});
i am trying to devise a way so that the value of steps will change
according to the number of tiles.
Please help me.
I am using dragdealer JS with D3.js. What i am doing is that when You drag
the slider made by dragdealer JS the elements made by D3.js will move like
a picture slider.
Here is the code which which i wrote : code.
Now there are two problems with this code:
1) This code is working in FireFox but not in Chrome?
2) How to configure the slider so that on one slide, only one tile will
move into the view and only one will move out?
The number of tiles or rectangles are not fixed. There can be any number
of tiles depending on the user.
Code:
var width = 4000,
height = 200,
margin = 2,
nRect = 20,
rectWidth = (width - (nRect - 1) * margin) / nRect,
svg = d3.select('#chart').append('svg')
.attr('width', width);
var data = d3.range(nRect),
posScale = d3.scale.linear()
.domain(d3.extent(data))
.range([0, width - rectWidth]);
console.log(rectWidth)
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', posScale)
.attr('width', rectWidth)
.attr('height', height);
function redraw(x)
{
svg.transition()
.ease("linear")
.attr("transform", "translate(" + -(x*rectWidth) + ")" );
console.log(-(x*rectWidth));
}
var step = nRect/2;
new Dragdealer('magnifier',
{
steps: step,
snap: true,
animationCallback: function(x, y)
{ console.log(x*10)
redraw(x*step);
}
});
i am trying to devise a way so that the value of steps will change
according to the number of tiles.
Please help me.
Comparing two numpy arrays of different length
Comparing two numpy arrays of different length
I need to find the indices of the first less than or equal occurrence of
elements of one array in another array. One way that works is this:
import numpy
a = numpy.array([10,7,2,0])
b = numpy.array([10,9,8,7,6,5,4,3,2,1])
indices = [numpy.where(a<=x)[0][0] for x in b]
indices has the value [0, 1, 1, 1, 2, 2, 2, 2, 2, 3], which is what I
need. The problem of course, is that python "for" loop is slow and my
arrays might have millions of elements. Is there any numpy trick for this?
This doesn't work because they arrays are not of the same length:
indices = numpy.where(a<=b) #XXX: raises an exception
Thanks!
I need to find the indices of the first less than or equal occurrence of
elements of one array in another array. One way that works is this:
import numpy
a = numpy.array([10,7,2,0])
b = numpy.array([10,9,8,7,6,5,4,3,2,1])
indices = [numpy.where(a<=x)[0][0] for x in b]
indices has the value [0, 1, 1, 1, 2, 2, 2, 2, 2, 3], which is what I
need. The problem of course, is that python "for" loop is slow and my
arrays might have millions of elements. Is there any numpy trick for this?
This doesn't work because they arrays are not of the same length:
indices = numpy.where(a<=b) #XXX: raises an exception
Thanks!
unittest.mock.patch a class instance, and set method return values
unittest.mock.patch a class instance, and set method return values
I've got an Alarm object that uses a Sensor object. In my test I'd like to
patch Sensor with a Stub. The code below works, but I have to explicitly
pass in the stub to the Alarm constructor:
#tire_pressure_monitoring.py
from sensor import Sensor
class Alarm:
def __init__(self, sensor=None):
self._low_pressure_threshold = 17
self._high_pressure_threshold = 21
self._sensor = sensor or Sensor()
self._is_alarm_on = False
def check(self):
psi_pressure_value = self._sensor.sample_pressure()
if psi_pressure_value < self._low_pressure_threshold or
self._high_pressure_threshold < psi_pressure_value:
self._is_alarm_on = True
@property
def is_alarm_on(self):
return self._is_alarm_on
#test_tire_pressure_monitoring.py
import unittest
from unittest.mock import patch, MagicMock, Mock
from tire_pressure_monitoring import Alarm
from sensor import Sensor
class AlarmTest(unittest.TestCase):
def test_check_with_too_high_pressure(self):
with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
test_sensor_class.instance.sample_pressure.return_value=22
alarm = Alarm(sensor=test_sensor_class.instance)
alarm.check()
self.assertTrue(alarm.is_alarm_on)
What I'd like to do, but can't seem to find a way to achieve, is to
replace the Sensor instance with a stub, without passing anthing to the
Alarm constructor. This code looks to me like it should work, but doesn't:
def test_check_with_too_high_pressure(self):
with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
test_sensor_class.instance.sample_pressure.return_value=22
alarm = Alarm()
alarm.check()
self.assertTrue(alarm.is_alarm_on)
The Alarm instance gets an instance of MagicMock, but the
'sample_pressure' method doesn't return 22. Basically I want to know if
there is a way to use unittest.mock to test the Alarm class without
needing a constructor that takes a Sensor instance as argument.
I've got an Alarm object that uses a Sensor object. In my test I'd like to
patch Sensor with a Stub. The code below works, but I have to explicitly
pass in the stub to the Alarm constructor:
#tire_pressure_monitoring.py
from sensor import Sensor
class Alarm:
def __init__(self, sensor=None):
self._low_pressure_threshold = 17
self._high_pressure_threshold = 21
self._sensor = sensor or Sensor()
self._is_alarm_on = False
def check(self):
psi_pressure_value = self._sensor.sample_pressure()
if psi_pressure_value < self._low_pressure_threshold or
self._high_pressure_threshold < psi_pressure_value:
self._is_alarm_on = True
@property
def is_alarm_on(self):
return self._is_alarm_on
#test_tire_pressure_monitoring.py
import unittest
from unittest.mock import patch, MagicMock, Mock
from tire_pressure_monitoring import Alarm
from sensor import Sensor
class AlarmTest(unittest.TestCase):
def test_check_with_too_high_pressure(self):
with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
test_sensor_class.instance.sample_pressure.return_value=22
alarm = Alarm(sensor=test_sensor_class.instance)
alarm.check()
self.assertTrue(alarm.is_alarm_on)
What I'd like to do, but can't seem to find a way to achieve, is to
replace the Sensor instance with a stub, without passing anthing to the
Alarm constructor. This code looks to me like it should work, but doesn't:
def test_check_with_too_high_pressure(self):
with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
test_sensor_class.instance.sample_pressure.return_value=22
alarm = Alarm()
alarm.check()
self.assertTrue(alarm.is_alarm_on)
The Alarm instance gets an instance of MagicMock, but the
'sample_pressure' method doesn't return 22. Basically I want to know if
there is a way to use unittest.mock to test the Alarm class without
needing a constructor that takes a Sensor instance as argument.
Is TakeWhile(...) and etc. extension methods thread safe in Rx 1.0?
Is TakeWhile(...) and etc. extension methods thread safe in Rx 1.0?
I have an event source which fired by a Network I/O very frequently, based
on underlying design, of course the event was always on different thread
each time, now I wrapped this event via Rx with:
Observable.FromEventPattern(...), now I'm using the TakeWhile(predict) to
filter some special event data. At now, I have some concerns on its thread
safety, the TakeWhile(predict) works as a hit and mute, but in concurrent
situation, can it still be guaranteed? because I guess the underlying
implementation could be(I can't read the source code since it's too
complicated...):
public static IObservable<TSource> TakeWhile<TSource>(this
IObservable<TSource> source, Func<TSource, bool> predict)
{
ISubject<TSource> takeUntilObservable = new
TempObservable<TSource>();
IDisposable dps = null;
// 0 for takeUntilObservable still active, 1 for predict failed,
diposed and OnCompleted already send.
int state = 0;
dps = source.Subscribe(
(s) =>
{
/* NOTE here the 'hit and mute' still not thread safe,
one thread may enter 'else' and under CompareExchange,
but meantime another thread may passed the predict(...)
and calling OnNext(...)
* so the CompareExchange here mainly for avoid multiple
time call OnCompleted() and Dispose();
*/
if (predict(s) && state == 0)
{
takeUntilObservable.OnNext(s);
}
else
{
// !=0 means already disposed and OnCompleted send,
avoid multiple times called via parallel threads.
if (0 == Interlocked.CompareExchange(ref state, 1, 0))
{
try
{
takeUntilObservable.OnCompleted();
}
finally
{
dps.Dispose();
}
}
}
},
() =>
{
try
{
takeUntilObservable.OnCompleted();
}
finally { dps.Dispose(); }
},
(ex) => { takeUntilObservable.OnError(ex); });
return takeUntilObservable;
}
That TempObservable is just a simple implementation of ISubject.
If my guess reasonable, then seems the thread safety can't be guaranteed,
means some unexpected event data may still incoming to OnNext(...) because
that 'mute' is still on going. Then I write a simple testing to verify,
but out of expectation, the results are all positive:
public class MultipleTheadEventSource
{
public event EventHandler OnSthNew;
int cocurrentCount = 1000;
public void Start()
{
for (int i = 0; i < this.cocurrentCount; i++)
{
int j = i;
ThreadPool.QueueUserWorkItem((state) =>
{
var safe = this.OnSthNew;
if (safe != null)
safe(j, null);
});
}
}
}
[TestMethod()]
public void MultipleTheadEventSourceTest()
{
int loopTimes = 10;
int onCompletedCalledTimes = 0;
for (int i = 0; i < loopTimes; i++)
{
MultipleTheadEventSource eventSim = new
MultipleTheadEventSource();
var host = Observable.FromEventPattern(eventSim, "OnSthNew");
host.TakeWhile(p => { return int.Parse(p.Sender.ToString()) <
110; }).Subscribe((nxt) =>
{
//try print the unexpected values, BUT I Never saw it
happened!!!
if (int.Parse(nxt.Sender.ToString()) >= 110)
{
this.testContextInstance.WriteLine(nxt.Sender.ToString());
}
}, () => { Interlocked.Increment(ref onCompletedCalledTimes); });
eventSim.Start();
}
// simply wait everything done.
Thread.Sleep(60000);
this.testContextInstance.WriteLine("onCompletedCalledTimes: " +
onCompletedCalledTimes);
}
before I do the testing, some friends here suggest me try to use
Synchronize<TSource> or ObserveOn to make it thread safe, so any idea on
my proceeding thoughts and why the issue not reproduced?
I have an event source which fired by a Network I/O very frequently, based
on underlying design, of course the event was always on different thread
each time, now I wrapped this event via Rx with:
Observable.FromEventPattern(...), now I'm using the TakeWhile(predict) to
filter some special event data. At now, I have some concerns on its thread
safety, the TakeWhile(predict) works as a hit and mute, but in concurrent
situation, can it still be guaranteed? because I guess the underlying
implementation could be(I can't read the source code since it's too
complicated...):
public static IObservable<TSource> TakeWhile<TSource>(this
IObservable<TSource> source, Func<TSource, bool> predict)
{
ISubject<TSource> takeUntilObservable = new
TempObservable<TSource>();
IDisposable dps = null;
// 0 for takeUntilObservable still active, 1 for predict failed,
diposed and OnCompleted already send.
int state = 0;
dps = source.Subscribe(
(s) =>
{
/* NOTE here the 'hit and mute' still not thread safe,
one thread may enter 'else' and under CompareExchange,
but meantime another thread may passed the predict(...)
and calling OnNext(...)
* so the CompareExchange here mainly for avoid multiple
time call OnCompleted() and Dispose();
*/
if (predict(s) && state == 0)
{
takeUntilObservable.OnNext(s);
}
else
{
// !=0 means already disposed and OnCompleted send,
avoid multiple times called via parallel threads.
if (0 == Interlocked.CompareExchange(ref state, 1, 0))
{
try
{
takeUntilObservable.OnCompleted();
}
finally
{
dps.Dispose();
}
}
}
},
() =>
{
try
{
takeUntilObservable.OnCompleted();
}
finally { dps.Dispose(); }
},
(ex) => { takeUntilObservable.OnError(ex); });
return takeUntilObservable;
}
That TempObservable is just a simple implementation of ISubject.
If my guess reasonable, then seems the thread safety can't be guaranteed,
means some unexpected event data may still incoming to OnNext(...) because
that 'mute' is still on going. Then I write a simple testing to verify,
but out of expectation, the results are all positive:
public class MultipleTheadEventSource
{
public event EventHandler OnSthNew;
int cocurrentCount = 1000;
public void Start()
{
for (int i = 0; i < this.cocurrentCount; i++)
{
int j = i;
ThreadPool.QueueUserWorkItem((state) =>
{
var safe = this.OnSthNew;
if (safe != null)
safe(j, null);
});
}
}
}
[TestMethod()]
public void MultipleTheadEventSourceTest()
{
int loopTimes = 10;
int onCompletedCalledTimes = 0;
for (int i = 0; i < loopTimes; i++)
{
MultipleTheadEventSource eventSim = new
MultipleTheadEventSource();
var host = Observable.FromEventPattern(eventSim, "OnSthNew");
host.TakeWhile(p => { return int.Parse(p.Sender.ToString()) <
110; }).Subscribe((nxt) =>
{
//try print the unexpected values, BUT I Never saw it
happened!!!
if (int.Parse(nxt.Sender.ToString()) >= 110)
{
this.testContextInstance.WriteLine(nxt.Sender.ToString());
}
}, () => { Interlocked.Increment(ref onCompletedCalledTimes); });
eventSim.Start();
}
// simply wait everything done.
Thread.Sleep(60000);
this.testContextInstance.WriteLine("onCompletedCalledTimes: " +
onCompletedCalledTimes);
}
before I do the testing, some friends here suggest me try to use
Synchronize<TSource> or ObserveOn to make it thread safe, so any idea on
my proceeding thoughts and why the issue not reproduced?
Custom button in joomla for exporting data to excel [backend]
Custom button in joomla for exporting data to excel [backend]
First of all, I'm really new to joomla 2.5 development. All I have done so
far is just making a custom button for 'export to excel' task in
'administrator/includes/toolbar.php' and putting some codes to show it on
view.html.php. Button's caption appears but it doesn't happen on the image
itself. Also I don't have idea how to link the button to a function in
controller so the download box is ready to have me exporting the data to
excel.
Any advice for this? Thanks in advance.
First of all, I'm really new to joomla 2.5 development. All I have done so
far is just making a custom button for 'export to excel' task in
'administrator/includes/toolbar.php' and putting some codes to show it on
view.html.php. Button's caption appears but it doesn't happen on the image
itself. Also I don't have idea how to link the button to a function in
controller so the download box is ready to have me exporting the data to
excel.
Any advice for this? Thanks in advance.
Tuesday, 17 September 2013
Switch case statement
Switch case statement
I am trying to create an application in C# that converts numbers in a text
box to roman numerals in a label control and need to use a case statement.
However one of my variable Roman gets the error message: Use of unassigned
local variable 'Roman'.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Roman_Numeral_Converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
int Number=int.Parse(txtNum.Text); // To hold Number
string Roman; // To hold Roman Numeral
if (Number>=1 && Number <=10)
{
switch (Roman)
{
case "Number==1":
lblRoman.Text = "I";
break;
case "Number==2":
lblRoman.Text = "II";
break;
case "Number==3":
lblRoman.Text = "III";
break;
case "Number==4":
lblRoman.Text = "IV";
break;
case "Number==5":
lblRoman.Text = "V";
break;
case "Number==6":
lblRoman.Text = "VI";
break;
case "Number==7":
lblRoman.Text = "VII";
break;
case "Number==8":
lblRoman.Text = "VIII";
break;
case "Number==9":
lblRoman.Text = "IX";
break;
case "Number==10":
lblRoman.Text = "X";
break;
}
}
else
{
MessageBox.Show("Error: Invalid Input");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtNum.Text = "";
lblRoman.Text = "";
}
}
}
I am trying to create an application in C# that converts numbers in a text
box to roman numerals in a label control and need to use a case statement.
However one of my variable Roman gets the error message: Use of unassigned
local variable 'Roman'.
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Roman_Numeral_Converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
int Number=int.Parse(txtNum.Text); // To hold Number
string Roman; // To hold Roman Numeral
if (Number>=1 && Number <=10)
{
switch (Roman)
{
case "Number==1":
lblRoman.Text = "I";
break;
case "Number==2":
lblRoman.Text = "II";
break;
case "Number==3":
lblRoman.Text = "III";
break;
case "Number==4":
lblRoman.Text = "IV";
break;
case "Number==5":
lblRoman.Text = "V";
break;
case "Number==6":
lblRoman.Text = "VI";
break;
case "Number==7":
lblRoman.Text = "VII";
break;
case "Number==8":
lblRoman.Text = "VIII";
break;
case "Number==9":
lblRoman.Text = "IX";
break;
case "Number==10":
lblRoman.Text = "X";
break;
}
}
else
{
MessageBox.Show("Error: Invalid Input");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtNum.Text = "";
lblRoman.Text = "";
}
}
}
how to build a 64 bit project in visual studio
how to build a 64 bit project in visual studio
In my visual studio 2010 ultimate, codes in #if _WIN64 region is always
dark. I selected X64 platform in my configuration manager. What do I do to
compile a 64 bit project?
In my visual studio 2010 ultimate, codes in #if _WIN64 region is always
dark. I selected X64 platform in my configuration manager. What do I do to
compile a 64 bit project?
How to define a value on "Creating default object from empty value" error
How to define a value on "Creating default object from empty value" error
I knew many question about this, I try to read but still got this error
message on my Wordpress :
"Creating default object from empty value in
/home/forthemde/public_html/wp-content/themes/mayadeep/admin/admin.php on
line 225"
Here the code on admin.php and:
function upfw_setup_theme_options(){
$up_options_db = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
global $up_options;
//Check if options are stored properly
if( isset($up_options_db) && is_array($up_options_db) ):
//Check array to an object
foreach ($up_options_db as $k => $v) {
$up_options -> {$k} = $v;
}
else:
do_action('upfw_theme_activation');
endif;
}
add_action('upfw_theme_init','upfw_setup_theme_options',10);
add_action('upfw_admin_init','upfw_setup_theme_options',100);
Line 225 is here:
$up_options -> {$k} = $v;
I try to fix by myself, but no result. Please help me, really appreciate
for any help.
Regards.
I knew many question about this, I try to read but still got this error
message on my Wordpress :
"Creating default object from empty value in
/home/forthemde/public_html/wp-content/themes/mayadeep/admin/admin.php on
line 225"
Here the code on admin.php and:
function upfw_setup_theme_options(){
$up_options_db = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
global $up_options;
//Check if options are stored properly
if( isset($up_options_db) && is_array($up_options_db) ):
//Check array to an object
foreach ($up_options_db as $k => $v) {
$up_options -> {$k} = $v;
}
else:
do_action('upfw_theme_activation');
endif;
}
add_action('upfw_theme_init','upfw_setup_theme_options',10);
add_action('upfw_admin_init','upfw_setup_theme_options',100);
Line 225 is here:
$up_options -> {$k} = $v;
I try to fix by myself, but no result. Please help me, really appreciate
for any help.
Regards.
Design patterns behind UI application (any book?)
Design patterns behind UI application (any book?)
I am wondering what design patterns people use to construct complex UI or
UI like application?
Let's consider a UI made up of thousands of small widgets, once one widget
changes its state, it broadcasts an event to partners(maybe one hundred)
to update their state correspondingly. When widget state changing, its
view changes as well. However, there must be some place putting business
logic, from GoF design patterns it should be Mediator. however I have no
idea how people do it in real world.
I understand GoF patterns, MVC patterns, event/message system, two way
data binding. I am not writing any UI application, but the problem UI(for
example, Java intellij IDE) applications solve is very interesting. It
manages lots of small piece(widgets) and change its behavior in line with
widgets' states change. How to code such a system in a maintainable way is
what I am searching. To me imperative way in such system is not working,
there must be some declarative patterns for this.
Much appreciates if some one can point out some good reads. Thanks.
I am wondering what design patterns people use to construct complex UI or
UI like application?
Let's consider a UI made up of thousands of small widgets, once one widget
changes its state, it broadcasts an event to partners(maybe one hundred)
to update their state correspondingly. When widget state changing, its
view changes as well. However, there must be some place putting business
logic, from GoF design patterns it should be Mediator. however I have no
idea how people do it in real world.
I understand GoF patterns, MVC patterns, event/message system, two way
data binding. I am not writing any UI application, but the problem UI(for
example, Java intellij IDE) applications solve is very interesting. It
manages lots of small piece(widgets) and change its behavior in line with
widgets' states change. How to code such a system in a maintainable way is
what I am searching. To me imperative way in such system is not working,
there must be some declarative patterns for this.
Much appreciates if some one can point out some good reads. Thanks.
Using jquery on a .php file
Using jquery on a .php file
How do I add jquery to this page as the HTML head element of the page is
in the include() file. Do I have to add it to the HTML form found at the
bottom of the page? Or do I add the Jquery to the ./includes/header.html
page ?
Add A film"; if(isset($_POST['submitted'])){ $errors = array(); //
Initialize erroy array. // Check for title. if
(empty($_POST['movie_title'])){ $errors[] = "You forgot to enter a
title."; } else { $mn = (trim($_POST['movie_title'])); } // Check for
leading actor if (empty($_POST['leading_actor'])){ $errors[] = "You forgot
to enter the leading actor."; } else { $la =
(trim($_POST['leading_actor'])); } // Check for a rating if
(empty($_POST['rating'])){ $errors[] = "Please select a rating."; } else {
$rating = ($_POST['rating']); } // Check for a review if
(empty($_POST['review'])){ $errors[] = "Please write a review"; } else {
$review = (trim($_POST['review'])); } if (empty($errors)) { // If no
errors were found. require_once('./includes/Mysql_connect.php'); // Make
the insert query. $query = "INSERT INTO films (movie_title, actor, rating)
Values ('$mn', '$la', '$rating' )"; $result = mysql_query($query); $id =
mysql_insert_id(); $query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')"; $result = mysql_query($query); //Report
errors. } else { foreach ($errors as $msg){ echo " - $msg
"; } } } ?>
<form action="add_film.php" method="post" id="add_film">
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating[]" name="rating" />
<option selected="selected" disabled="disabled">Select a
Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="textarea" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
How do I add jquery to this page as the HTML head element of the page is
in the include() file. Do I have to add it to the HTML form found at the
bottom of the page? Or do I add the Jquery to the ./includes/header.html
page ?
Add A film"; if(isset($_POST['submitted'])){ $errors = array(); //
Initialize erroy array. // Check for title. if
(empty($_POST['movie_title'])){ $errors[] = "You forgot to enter a
title."; } else { $mn = (trim($_POST['movie_title'])); } // Check for
leading actor if (empty($_POST['leading_actor'])){ $errors[] = "You forgot
to enter the leading actor."; } else { $la =
(trim($_POST['leading_actor'])); } // Check for a rating if
(empty($_POST['rating'])){ $errors[] = "Please select a rating."; } else {
$rating = ($_POST['rating']); } // Check for a review if
(empty($_POST['review'])){ $errors[] = "Please write a review"; } else {
$review = (trim($_POST['review'])); } if (empty($errors)) { // If no
errors were found. require_once('./includes/Mysql_connect.php'); // Make
the insert query. $query = "INSERT INTO films (movie_title, actor, rating)
Values ('$mn', '$la', '$rating' )"; $result = mysql_query($query); $id =
mysql_insert_id(); $query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')"; $result = mysql_query($query); //Report
errors. } else { foreach ($errors as $msg){ echo " - $msg
"; } } } ?>
<form action="add_film.php" method="post" id="add_film">
<label for="title">Movie Title</label>
<input type="text" name="movie_title" id="movie_title" />
<br/>
<br/>
<label for="actor">Leading Actor</label>
<input type="text" name="leading_actor" id="leading_name" />
<br/>
<br/>
<label for="rating">Rating</label>
<select id="rating[]" name="rating" />
<option selected="selected" disabled="disabled">Select a
Rating</option>
<option value="Terrible">Terrible</option>
<option value="Fair">Fair</option>
<option value="Ok">Ok</option>
<option value="Good">Good</option>
<option value="Excellent">Excellent</option>
</select>
<br/>
<br/>
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="textarea" rows="15" cols="60"></textarea>
<br/>
<br/>
<input type="submit" name="submit" id="submit" value="submit" />
<input type="hidden" name="submitted" value="TRUE" />
Excel formula to change the value of another cell?
Excel formula to change the value of another cell?
is it possible to force an [UDF] user-defined-function to be executed on a
cell we specify ? in another words : if I execute an UDF in the cell A1 it
will return result in A2 cell , but what if I want to change A2 by another
cell ?
is it possible to force an [UDF] user-defined-function to be executed on a
cell we specify ? in another words : if I execute an UDF in the cell A1 it
will return result in A2 cell , but what if I want to change A2 by another
cell ?
Sunday, 15 September 2013
WPF Memory leak on window closing
WPF Memory leak on window closing
I have "MainWindow", in which i create new windows, named "Maket", after
closing they are not released from memory. So i post a picture of tree,
from ANTS memory profiler, if code needed i can post it. What is the
problem, why they are not released?
I have "MainWindow", in which i create new windows, named "Maket", after
closing they are not released from memory. So i post a picture of tree,
from ANTS memory profiler, if code needed i can post it. What is the
problem, why they are not released?
Reading in Multiple Coordinates on one line (Java)
Reading in Multiple Coordinates on one line (Java)
I'm having an issue reading in a multiple set of of values that will be
saved as x,y coordinates and then stored as nodes. I am writing this
program in Java. Some input lines from a text file looks like this:
(220 616) (220 666) (251 670) (272 647) # Poly 1
(341 655) (359 667) (374 651) (366 577) # Poly 2
(311 530) (311 559) (339 578) (361 560) (361 528) (336 516) # Poly 3
I need to read in each of these coordinates and store them as a node in
the format node(x,y). What is the best way to accomplish this? So far I am
using a scanner that reads the input file while there is a next line. I
save the line in a string s and am trying to parse it like so
while (scanner.hasNextLine()) {
String s = nextLine();
//parse code goes here
}
I've read several posts above delimiters but I'm still a bit lost.
Essentially I need to be able to loop through and save each x,y coordinate
as a node that I will then be storing in an array.
Any help helps! Thanks!
I'm having an issue reading in a multiple set of of values that will be
saved as x,y coordinates and then stored as nodes. I am writing this
program in Java. Some input lines from a text file looks like this:
(220 616) (220 666) (251 670) (272 647) # Poly 1
(341 655) (359 667) (374 651) (366 577) # Poly 2
(311 530) (311 559) (339 578) (361 560) (361 528) (336 516) # Poly 3
I need to read in each of these coordinates and store them as a node in
the format node(x,y). What is the best way to accomplish this? So far I am
using a scanner that reads the input file while there is a next line. I
save the line in a string s and am trying to parse it like so
while (scanner.hasNextLine()) {
String s = nextLine();
//parse code goes here
}
I've read several posts above delimiters but I'm still a bit lost.
Essentially I need to be able to loop through and save each x,y coordinate
as a node that I will then be storing in an array.
Any help helps! Thanks!
find text by grep and replace path of that with sed
find text by grep and replace path of that with sed
I have *.dot file, for example:
...
0 -> 1 [color=black];
1 -> 2 [color=blue];
1 -> 3 [color=blue];
2 -> 4 [color=gold3];
..
I need to change "color" of lines whose started with $a number. I can easy
get =blue using
a="1"
cat experimental.dot | grep "^$a\ ->" | grep -o =[a-Z0-9]*
But i can't change =blue to =red in file using sed.
I have *.dot file, for example:
...
0 -> 1 [color=black];
1 -> 2 [color=blue];
1 -> 3 [color=blue];
2 -> 4 [color=gold3];
..
I need to change "color" of lines whose started with $a number. I can easy
get =blue using
a="1"
cat experimental.dot | grep "^$a\ ->" | grep -o =[a-Z0-9]*
But i can't change =blue to =red in file using sed.
Adding all the numbers from a list together(not summing). Python 3.3.2
Adding all the numbers from a list together(not summing). Python 3.3.2
say that I have this list:
alist = [2, 0, 1]
How would I make a string named "hahaha" for example equal to 201 ? Not 5
(sum). Would I need to something like "
for number in alist .....
thanks !
say that I have this list:
alist = [2, 0, 1]
How would I make a string named "hahaha" for example equal to 201 ? Not 5
(sum). Would I need to something like "
for number in alist .....
thanks !
css center div inside container?
css center div inside container?
This HTML code works:
<div class="MyContainer" align="center">
<div>THIS DIV IS CENTERED</div>
</div>
But I would like to do it at the css of the container, something like:
.MyContainer{
align: center;
}
So all my containers will center the divs inside.
This HTML code works:
<div class="MyContainer" align="center">
<div>THIS DIV IS CENTERED</div>
</div>
But I would like to do it at the css of the container, something like:
.MyContainer{
align: center;
}
So all my containers will center the divs inside.
Exported jar file freezes after executing
Exported jar file freezes after executing
Hi I've been having problems trying to export my java code into a runnable
jar file.
When I double click the .jar file it starts up but for some reason the
only image that I use doesn't show up (since this was a basic test all the
objects are draw using shapes from what I think is java.awt). So the only
thing that doesn't show up is a bullet sprite in which I put in a data
folder next to the src folder.
The main problem is that it seems to crash or freeze after a few seconds
of running the game. (I'm was using eclipse to run it and it worked fine).
Now I'm not that experienced with making this without the compiler so I'm
not sure if I had missed anything when making this program
Here is what I have to get the image (which I believe is the main problem):
private BufferedImage pShot;
//then in the public World method
try {
pShot = ImageIO.read(new File("data/bulletShot2.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hi I've been having problems trying to export my java code into a runnable
jar file.
When I double click the .jar file it starts up but for some reason the
only image that I use doesn't show up (since this was a basic test all the
objects are draw using shapes from what I think is java.awt). So the only
thing that doesn't show up is a bullet sprite in which I put in a data
folder next to the src folder.
The main problem is that it seems to crash or freeze after a few seconds
of running the game. (I'm was using eclipse to run it and it worked fine).
Now I'm not that experienced with making this without the compiler so I'm
not sure if I had missed anything when making this program
Here is what I have to get the image (which I believe is the main problem):
private BufferedImage pShot;
//then in the public World method
try {
pShot = ImageIO.read(new File("data/bulletShot2.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Embedding a java applet within my window (as a browser does)
Embedding a java applet within my window (as a browser does)
How can I accomplish this? I was not able to find any information on this
from searching.
I know I would use JNI, and call JNI_CreateJavaVM, but where do I go from
here?
How can I accomplish this? I was not able to find any information on this
from searching.
I know I would use JNI, and call JNI_CreateJavaVM, but where do I go from
here?
Saturday, 14 September 2013
Setting objects in an ArrayList to null
Setting objects in an ArrayList to null
If I was to have an ArrayList of objects, and I set a few of them to null,
are they susceptible to gc? Or will they stay since they are still being
referenced by the ArrayList
ex:
for(NPC n : NPCs){
n.act();
n.draw(frame);
if(n == outOfMap){
n = null;
}
}
If that loop is "always" being iterated over, will the outOfMap objects be
collected? or simply stay there will a null value?
If I was to have an ArrayList of objects, and I set a few of them to null,
are they susceptible to gc? Or will they stay since they are still being
referenced by the ArrayList
ex:
for(NPC n : NPCs){
n.act();
n.draw(frame);
if(n == outOfMap){
n = null;
}
}
If that loop is "always" being iterated over, will the outOfMap objects be
collected? or simply stay there will a null value?
scale coordinates to project on floor
scale coordinates to project on floor
I want to take locations of stock markets in the world using their
longitude/latitude coordinates and 'project' this in a room with a size of
10x8 metres. Thus there would be a world map on the floor with each
location marked. Can somebody tell me how I should convert the lon/lat
values to x/y values? Not in a programming language but just the formula
would be great.
I want to take locations of stock markets in the world using their
longitude/latitude coordinates and 'project' this in a room with a size of
10x8 metres. Thus there would be a world map on the floor with each
location marked. Can somebody tell me how I should convert the lon/lat
values to x/y values? Not in a programming language but just the formula
would be great.
Perl: Using regular expressions with hashes
Perl: Using regular expressions with hashes
I cannot pinpoint a bug in this submodule I'm writing for analyzing a
yeast genome. Help anyone?
The sub should use the hash key as a regular expression to check for a
certain pair of capital letters. If we have a match, return the associated
value. However, it seems to only match "TT" and return the value 5. I have
no idea why it would jump to the TT hash element; everything else seems to
be the same between the different elements. I would think it would return
each of the values, or none, but it only returns TT.
The full code is here on github: https://github.com/bsima/yeast-TRX
Here is the relevant code (line 159 of script.pl):
sub trxScore {
my ( $dinucleotide ) = @_;
my %trxScores = (
qr/(CG)/ => 43,
qr/(CA)/ => 42,
qr/(TG)/ => 42,
qr/(GG)/ => 42,
qr/(CC)/ => 42,
qr/(GC)/ => 25,
qr/(GA)/ => 22,
qr/(TC)/ => 22,
qr/(TA)/ => 14,
qr/(AG)/ => 9,
qr/(CT)/ => 9,
qr/(AA)/ => 5,
qr/(TT)/ => 5,
qr/(AC)/ => 4,
qr/(GT)/ => 4,
qr/(AT)/ => 0
);
foreach my $re (keys %trxScores) {
if ( match($re,$dinucleotide) ) {
return $trxScores{$re};
} else {
return "null";
}
}
}
The output is in bayanus-TRXscore.csv:
Saccharomyces bayanus
gene,gene pair,position,trx score
...
eYAL001C,TA,23,null
eYAL001C,AT,24,null
eYAL001C,TT,25,5
eYAL001C,TT,26,5
eYAL001C,TT,27,5
eYAL001C,TA,28,null
I cannot pinpoint a bug in this submodule I'm writing for analyzing a
yeast genome. Help anyone?
The sub should use the hash key as a regular expression to check for a
certain pair of capital letters. If we have a match, return the associated
value. However, it seems to only match "TT" and return the value 5. I have
no idea why it would jump to the TT hash element; everything else seems to
be the same between the different elements. I would think it would return
each of the values, or none, but it only returns TT.
The full code is here on github: https://github.com/bsima/yeast-TRX
Here is the relevant code (line 159 of script.pl):
sub trxScore {
my ( $dinucleotide ) = @_;
my %trxScores = (
qr/(CG)/ => 43,
qr/(CA)/ => 42,
qr/(TG)/ => 42,
qr/(GG)/ => 42,
qr/(CC)/ => 42,
qr/(GC)/ => 25,
qr/(GA)/ => 22,
qr/(TC)/ => 22,
qr/(TA)/ => 14,
qr/(AG)/ => 9,
qr/(CT)/ => 9,
qr/(AA)/ => 5,
qr/(TT)/ => 5,
qr/(AC)/ => 4,
qr/(GT)/ => 4,
qr/(AT)/ => 0
);
foreach my $re (keys %trxScores) {
if ( match($re,$dinucleotide) ) {
return $trxScores{$re};
} else {
return "null";
}
}
}
The output is in bayanus-TRXscore.csv:
Saccharomyces bayanus
gene,gene pair,position,trx score
...
eYAL001C,TA,23,null
eYAL001C,AT,24,null
eYAL001C,TT,25,5
eYAL001C,TT,26,5
eYAL001C,TT,27,5
eYAL001C,TA,28,null
iOS 7 - Resize tab bar on rotation
iOS 7 - Resize tab bar on rotation
When I rotate the device to portrait to landscape, the width of the tab
bar is not extended and a gap is shown on the right hand side (where you
see the text 'location').
This problem has popped up after installing iOS 7 and wasn't present under
iOS 6. It occurs on both the simulator and actual device.
When I rotate the device to portrait to landscape, the width of the tab
bar is not extended and a gap is shown on the right hand side (where you
see the text 'location').
This problem has popped up after installing iOS 7 and wasn't present under
iOS 6. It occurs on both the simulator and actual device.
Load kendo ui treeview children when selected node?
Load kendo ui treeview children when selected node?
hi, i want use mvc kendo ui treeview and load children node when selected
node but i don't Know implement it, please help me?
public JsonResult Employees(string id)
{
var dataContext = new Data.ISMSEntities();
var employees = from e in dataContext.Assets
where (string.IsNullOrEmpty(id)?e.LocationID_FK==null:
e.LocationID_FK == id)
select new
{
id = e.LocationID_FK,
Name = e.asName
,
//hasChildren = e.asName.Any()
hasChildren=true
};
int i=employees.Count();
return Json(employees, JsonRequestBehavior.AllowGet);
}
hi, i want use mvc kendo ui treeview and load children node when selected
node but i don't Know implement it, please help me?
public JsonResult Employees(string id)
{
var dataContext = new Data.ISMSEntities();
var employees = from e in dataContext.Assets
where (string.IsNullOrEmpty(id)?e.LocationID_FK==null:
e.LocationID_FK == id)
select new
{
id = e.LocationID_FK,
Name = e.asName
,
//hasChildren = e.asName.Any()
hasChildren=true
};
int i=employees.Count();
return Json(employees, JsonRequestBehavior.AllowGet);
}
Adding object with several sub-objects at once
Adding object with several sub-objects at once
Let's say I have following database:
Company (name, sector) has many Products (name, price)
I would like users of my Rails website to be able to add new companies
along with their products. So the form would look like:
Add new company
--------------------
Name: [ ]
Sector: [ ]
Product 1:
Name [ ]
Price [ ]
Product 2:
Name [ ]
Price [ ]
Product 3:
Name [ ]
Price [ ]
Ideally users would be able to add as many products at once as required
(auto expanding list?). How can I program that in Rails?
Let's say I have following database:
Company (name, sector) has many Products (name, price)
I would like users of my Rails website to be able to add new companies
along with their products. So the form would look like:
Add new company
--------------------
Name: [ ]
Sector: [ ]
Product 1:
Name [ ]
Price [ ]
Product 2:
Name [ ]
Price [ ]
Product 3:
Name [ ]
Price [ ]
Ideally users would be able to add as many products at once as required
(auto expanding list?). How can I program that in Rails?
Friday, 13 September 2013
Porting WPF app to class library -> How to handle themes, resources and paths?
Porting WPF app to class library -> How to handle themes, resources and
paths?
I am working on making class libraries for use in another application. My
class library is in a separate folder than the application itself and is
loaded and run by the application. I am running into many problems porting
the code. Anywhere a resource, theme or code that resolves references is
used exceptions are thrown like crazy.
For example, in the application there will be code like this:
var directoryCatalog = new DirectoryCatalog(@"./");
Needs to be modified to the following in order to correctly discover
assemblies that are in the class libraries folder:
var directoryCatalog = new
DirectoryCatalog(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
My question is how to handle custom controls and themes. I have a
theme.xaml file and it is loaded with the following code:
CurrentTheme = new ResourceDictionary
{
Source = new
Uri("/Gemini;component/Themes/VS2010/Theme.xaml",
UriKind.Relative)
};
However this is never found, and never loaded since it is relative and the
running applications directory does not contain this resource. How would
you modify the Uri code so it will find the resource in the current
executing assemblies directory?
If I manually create a Uri hard coded to the class libraries folder then
it will load the first few lines, but then when it hits a style for a
custom control it states:
'Failed to create a 'Type' from the text 'toolbars:ToolBarEx'
My theme file:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mainmenu="clr-namespace:Gemini.Modules.MainMenu.Controls"
xmlns:toolbars="clr-namespace:Gemini.Modules.ToolBars.Controls"
xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Brushes.xaml" />
<ResourceDictionary Source="StatusBar.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type ContextMenu}">
<!-- BasedOn="{StaticResource {x:Type ContextMenu}} -->
<Setter Property="Background" Value="{StaticResource
ContextMenuBackground}" />
<Setter Property="BorderBrush" Value="{StaticResource
ContextMenuBorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
</Style>
<Style TargetType="{x:Type ToolBar}">
<!-- BasedOn="{StaticResource {x:Type ToolBar}}" -->
<Setter Property="Background" Value="{StaticResource
ToolBarBackground}" />
</Style>
<Style TargetType="{x:Type toolbars:ToolBarEx}">
<!-- BasedOn="{StaticResource {x:Type ToolBar}}" -->
<Setter Property="Background" Value="{StaticResource
ToolBarBackground}" />
</Style>
So it is working up until it gets to the extended ToolBarEx. I read that
this was resolved by others by adding a reference to the class library and
add using statements so these namespaces could be found.
The main application my class library is working with exposes a standard
add-in interface and since it is a commercial project I can't add a
reference or using statements to their code.
How would you get this to work? How do I tell .NET to stop looking in the
application directory and only pay attention to what is going on in the
class library directory?
paths?
I am working on making class libraries for use in another application. My
class library is in a separate folder than the application itself and is
loaded and run by the application. I am running into many problems porting
the code. Anywhere a resource, theme or code that resolves references is
used exceptions are thrown like crazy.
For example, in the application there will be code like this:
var directoryCatalog = new DirectoryCatalog(@"./");
Needs to be modified to the following in order to correctly discover
assemblies that are in the class libraries folder:
var directoryCatalog = new
DirectoryCatalog(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
My question is how to handle custom controls and themes. I have a
theme.xaml file and it is loaded with the following code:
CurrentTheme = new ResourceDictionary
{
Source = new
Uri("/Gemini;component/Themes/VS2010/Theme.xaml",
UriKind.Relative)
};
However this is never found, and never loaded since it is relative and the
running applications directory does not contain this resource. How would
you modify the Uri code so it will find the resource in the current
executing assemblies directory?
If I manually create a Uri hard coded to the class libraries folder then
it will load the first few lines, but then when it hits a style for a
custom control it states:
'Failed to create a 'Type' from the text 'toolbars:ToolBarEx'
My theme file:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mainmenu="clr-namespace:Gemini.Modules.MainMenu.Controls"
xmlns:toolbars="clr-namespace:Gemini.Modules.ToolBars.Controls"
xmlns:xcad="http://schemas.xceed.com/wpf/xaml/avalondock">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Brushes.xaml" />
<ResourceDictionary Source="StatusBar.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type ContextMenu}">
<!-- BasedOn="{StaticResource {x:Type ContextMenu}} -->
<Setter Property="Background" Value="{StaticResource
ContextMenuBackground}" />
<Setter Property="BorderBrush" Value="{StaticResource
ContextMenuBorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
</Style>
<Style TargetType="{x:Type ToolBar}">
<!-- BasedOn="{StaticResource {x:Type ToolBar}}" -->
<Setter Property="Background" Value="{StaticResource
ToolBarBackground}" />
</Style>
<Style TargetType="{x:Type toolbars:ToolBarEx}">
<!-- BasedOn="{StaticResource {x:Type ToolBar}}" -->
<Setter Property="Background" Value="{StaticResource
ToolBarBackground}" />
</Style>
So it is working up until it gets to the extended ToolBarEx. I read that
this was resolved by others by adding a reference to the class library and
add using statements so these namespaces could be found.
The main application my class library is working with exposes a standard
add-in interface and since it is a commercial project I can't add a
reference or using statements to their code.
How would you get this to work? How do I tell .NET to stop looking in the
application directory and only pay attention to what is going on in the
class library directory?
Writing a method
Writing a method
void move(Dot sideOrUp); method
I need tips on what is the best way to do this. The move method changes
the position of the entire segment by moving the lower point to the new
position. In other words, the entire segment moves, without changing its
length or angle, so that the lower point is in the new position. For
horizontal segments (where both endpoints have the same y coordinate), it
moves the left point to the new position.
would it be better to use an if statement?
void move(Dot sideOrUp); method
I need tips on what is the best way to do this. The move method changes
the position of the entire segment by moving the lower point to the new
position. In other words, the entire segment moves, without changing its
length or angle, so that the lower point is in the new position. For
horizontal segments (where both endpoints have the same y coordinate), it
moves the left point to the new position.
would it be better to use an if statement?
asp.net call textbox[i] from textbox array created by hand before
asp.net call textbox[i] from textbox array created by hand before
My problem is: There is a button on web-form. It creates 5 textBoxes.
Then, there is another button on the same web-form. It gets values from
created textBoxes and make something:
protected void Page_Load(object sender, EventArgs e) { }
TextBox[] textbox;
protected void Button1_Click(object sender, EventArgs e)
{
textbox = new TextBox[5];
for (int i = 0; i < 5; i++)
{
textbox[i] = new TextBox();
textbox[i].ID = "textbox[" + i + "]";
PlaceHolder1.Controls.Add(textbox[i]);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string str = "";
for (int i = 0; i < 5; i++)
{
str += textbox[i].Text;
}
Label1.Text = str;
}
The error is in Button2_Click at textbox[i] is null. I understand why it
is happened, but I don't understand how can I solve this problem.
My problem is: There is a button on web-form. It creates 5 textBoxes.
Then, there is another button on the same web-form. It gets values from
created textBoxes and make something:
protected void Page_Load(object sender, EventArgs e) { }
TextBox[] textbox;
protected void Button1_Click(object sender, EventArgs e)
{
textbox = new TextBox[5];
for (int i = 0; i < 5; i++)
{
textbox[i] = new TextBox();
textbox[i].ID = "textbox[" + i + "]";
PlaceHolder1.Controls.Add(textbox[i]);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string str = "";
for (int i = 0; i < 5; i++)
{
str += textbox[i].Text;
}
Label1.Text = str;
}
The error is in Button2_Click at textbox[i] is null. I understand why it
is happened, but I don't understand how can I solve this problem.
How to configure the root directory correct on this host provider?
How to configure the root directory correct on this host provider?
I have a domain name on godaddy.com and I host my site on another host
company, they give me FTP and MySQL account only there is no panel of any
type and I want to know:
for uploading my files when I connected to the host with FTP I have empty
directory as the image below with this permission = ( xxx ) to the root "/
" folder :
image for the root directory
what configuration i must do (e.g: where to upload my files, permission to
them or to the root ) to correctly upload my files without any problem or
lack of security.
thanks
I have a domain name on godaddy.com and I host my site on another host
company, they give me FTP and MySQL account only there is no panel of any
type and I want to know:
for uploading my files when I connected to the host with FTP I have empty
directory as the image below with this permission = ( xxx ) to the root "/
" folder :
image for the root directory
what configuration i must do (e.g: where to upload my files, permission to
them or to the root ) to correctly upload my files without any problem or
lack of security.
thanks
Save json or multidimentional array to DB in C#
Save json or multidimentional array to DB in C#
Example of returned output:
[{"id":1,"children":[{"id":2,"children":[{"id":4},{"id":7},{"id":8}]},{"id":3}]},{"id":5},{"id":6}]
i need output like
Array ( [0] => Array ( [id] => 1 [children] => Array ( [0] => Array ( [id]
=> 2 [children] => Array ( [0] => Array ( [id] => 4 )
[1] => Array
(
[id] => 7
)
[2] => Array
(
[id] => 8
)
)
)
[1] => Array
(
[id] => 3
)
)
)
[1] => Array
(
[id] => 5
)
[2] => Array
(
[id] => 6
)
)
Example of returned output:
[{"id":1,"children":[{"id":2,"children":[{"id":4},{"id":7},{"id":8}]},{"id":3}]},{"id":5},{"id":6}]
i need output like
Array ( [0] => Array ( [id] => 1 [children] => Array ( [0] => Array ( [id]
=> 2 [children] => Array ( [0] => Array ( [id] => 4 )
[1] => Array
(
[id] => 7
)
[2] => Array
(
[id] => 8
)
)
)
[1] => Array
(
[id] => 3
)
)
)
[1] => Array
(
[id] => 5
)
[2] => Array
(
[id] => 6
)
)
EasyMock incompatible return value type for return type Collection
EasyMock incompatible return value type for return type Collection
i am getting the following exception for a method where the return type of
the method is collection...
java.lang.IllegalStateException: incompatible return value type at
org.easymock.internal.MocksControl.andReturn(MocksControl.java:218)
expect(training.getTrainingMaterials()).andReturn(new HashSet());
where the training.getTrainingMaterials() --> return type is Collection..
Can you please help me what needs to be done?
Thanks.
i am getting the following exception for a method where the return type of
the method is collection...
java.lang.IllegalStateException: incompatible return value type at
org.easymock.internal.MocksControl.andReturn(MocksControl.java:218)
expect(training.getTrainingMaterials()).andReturn(new HashSet());
where the training.getTrainingMaterials() --> return type is Collection..
Can you please help me what needs to be done?
Thanks.
Thursday, 12 September 2013
Label not defined Error
Label not defined Error
i have this code i'm using a goto option i'm always getting that the label
nextrecord is not defined .. what shall i do ? am i missing something? can
you please tell me when shall i do :) thank you in advance ! that's the
code i'm writing ..
Private Sub Timer_Tick(sender As System.Object, e As System.EventArgs)
Handles Timer.Tick
Try
Timer.Interval = 5000
sendSched()
If send = True Then
GoTo NEXTRECORD
End If
Catch
End Try
End Sub
Private Sub sendSched()
subTable.Rows.Clear()
subTable = selectSubscriber(content.mt, content.clID)
subCount = subTable.Rows.Count()
If content.timeSend = DateTime.Now.ToString("hh:mm") Then
Timer.Enabled = False
UpdateListBoxRec2("Sending content: " & content.contentSend & " to
:")
For Each subRow As DataRow In subTable.Rows
content.moSend = subRow("sim_mo")
UpdateListBoxRec2(content.moSend)
MsgBox(content.contentSend)
Next
send = True
Else
Timer.Enabled = True
Timer.Interval = 5000
End If
End Sub
Private Sub start_check_CheckedChanged(sender As System.Object, e As
System.EventArgs) Handles start_check.CheckedChanged
For Each contentRow As DataRow In contentTable.Rows
content.mt = contentRow("cnt_mt")
content.clID = contentRow("cnt_cl_id")
content.contentSend = contentRow("cnt_content")
content.id = contentRow("cnt_id")
content.timeSend = contentRow("cnt_time_to_send")
UpdateListBoxRec("Content to send at: " & content.timeSend)
Timer.Enabled = True
Timer.Interval = 0
NEXTRECORD:
Next
End Sub
i have this code i'm using a goto option i'm always getting that the label
nextrecord is not defined .. what shall i do ? am i missing something? can
you please tell me when shall i do :) thank you in advance ! that's the
code i'm writing ..
Private Sub Timer_Tick(sender As System.Object, e As System.EventArgs)
Handles Timer.Tick
Try
Timer.Interval = 5000
sendSched()
If send = True Then
GoTo NEXTRECORD
End If
Catch
End Try
End Sub
Private Sub sendSched()
subTable.Rows.Clear()
subTable = selectSubscriber(content.mt, content.clID)
subCount = subTable.Rows.Count()
If content.timeSend = DateTime.Now.ToString("hh:mm") Then
Timer.Enabled = False
UpdateListBoxRec2("Sending content: " & content.contentSend & " to
:")
For Each subRow As DataRow In subTable.Rows
content.moSend = subRow("sim_mo")
UpdateListBoxRec2(content.moSend)
MsgBox(content.contentSend)
Next
send = True
Else
Timer.Enabled = True
Timer.Interval = 5000
End If
End Sub
Private Sub start_check_CheckedChanged(sender As System.Object, e As
System.EventArgs) Handles start_check.CheckedChanged
For Each contentRow As DataRow In contentTable.Rows
content.mt = contentRow("cnt_mt")
content.clID = contentRow("cnt_cl_id")
content.contentSend = contentRow("cnt_content")
content.id = contentRow("cnt_id")
content.timeSend = contentRow("cnt_time_to_send")
UpdateListBoxRec("Content to send at: " & content.timeSend)
Timer.Enabled = True
Timer.Interval = 0
NEXTRECORD:
Next
End Sub
dot dot dot JS plugin dont work
dot dot dot JS plugin dont work
I want to use dotdotdot JS plugin on my Django site, but it doesnt work
for me. why? I just want to element to have dotdotdot on the end This is
HTML head:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" language="javascript"
src="/static/mainpage/dotdotdot-1.6.5/jquery.dotdotdot.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#prispevek").dotdotdot({
/* The HTML to add as ellipsis. */
ellipsis : '... ',
/* How to cut off the text/html: 'word'/'letter'/'children' */
wrap : 'word',
/* Wrap-option fallback to 'letter' for long words */
fallbackToLetter: true,
/* jQuery-selector for the element to keep and put after the
ellipsis. */
after : null,
/* Whether to update the ellipsis: true/'window' */
watch : false,
/* Optionally set a max-height, if null, the height will be
measured. */
height : null,
/* Deviation for the height-option. */
tolerance : 10,
/* Callback function that is fired after the ellipsis is added,
receives two parameters: isTruncated(boolean),
orgContent(string). */
callback : function( isTruncated, orgContent ) {},
lastCharacter : {
/* Remove these characters from the end of the truncated
text. */
remove : [ ' ', ',', ';', '.', '!', '?' ],
/* Don't add an ellipsis if this array contains
the last character of the truncated text. */
noEllipsis : []
}
});
});
</script>
This is css:
#prispevek
{
height:80px;
/*text-overflow:ellipsis;
overflow:hidden;*/
text-align: justify;
}
this is my body: Content is through Django
{% for object in prispevky %}
<article>
<h1><a href="novinky/{{ object.id }}/">{{ object.nadpis }}</a></h1>
<p id="prispevek">{{ object.text|linebreaksbr }}</p>
</article>
{% endfor %}
I want to use dotdotdot JS plugin on my Django site, but it doesnt work
for me. why? I just want to element to have dotdotdot on the end This is
HTML head:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" language="javascript"
src="/static/mainpage/dotdotdot-1.6.5/jquery.dotdotdot.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#prispevek").dotdotdot({
/* The HTML to add as ellipsis. */
ellipsis : '... ',
/* How to cut off the text/html: 'word'/'letter'/'children' */
wrap : 'word',
/* Wrap-option fallback to 'letter' for long words */
fallbackToLetter: true,
/* jQuery-selector for the element to keep and put after the
ellipsis. */
after : null,
/* Whether to update the ellipsis: true/'window' */
watch : false,
/* Optionally set a max-height, if null, the height will be
measured. */
height : null,
/* Deviation for the height-option. */
tolerance : 10,
/* Callback function that is fired after the ellipsis is added,
receives two parameters: isTruncated(boolean),
orgContent(string). */
callback : function( isTruncated, orgContent ) {},
lastCharacter : {
/* Remove these characters from the end of the truncated
text. */
remove : [ ' ', ',', ';', '.', '!', '?' ],
/* Don't add an ellipsis if this array contains
the last character of the truncated text. */
noEllipsis : []
}
});
});
</script>
This is css:
#prispevek
{
height:80px;
/*text-overflow:ellipsis;
overflow:hidden;*/
text-align: justify;
}
this is my body: Content is through Django
{% for object in prispevky %}
<article>
<h1><a href="novinky/{{ object.id }}/">{{ object.nadpis }}</a></h1>
<p id="prispevek">{{ object.text|linebreaksbr }}</p>
</article>
{% endfor %}
Subscribe to:
Comments (Atom)