Change color of Gridview row if it in the same date be white color and then gray

Question: i need to have three color on dynamic Gridview one white and the another is gray  but if it in the same date
and if the previous date not found be red
what i mean is :
Name        Checkin           Checkout              Branch
450 10/6/2014 9:13:38 AM    10/6/2014 6:01:50 PM    branch0  white
450 10/7/2014 9:16:34 AM    10/7/2014 6:44:21 PM    branch0 gray
450 10/8/2014 9:11:53 AM                            branch0 white
450 10/8/2014 6:03:25 PM                            branch0 white
450 10/11/2014 9:17:33 AM   10/11/2014 6:29:16 PM   branch0 red
450 10/11/2014 4:50:42 PM                           branch0 red
450 10/12/2014 9:09:38 AM                           branch0 white

and that is my gridview
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
            AutoGenerateColumns="False" DataSourceID="SqlDataSource2"
            BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
            CellPadding="3" CellSpacing="2" HorizontalAlign="Center" Width="602px">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name"
                    SortExpression="Name" />
                <asp:BoundField DataField="Checkin" HeaderText="Checkin"
                    SortExpression="Checkin" ReadOnly="True" />
                <asp:BoundField DataField="Checkout" HeaderText="Checkout"
                    SortExpression="Checkout" ReadOnly="True" />
                <asp:BoundField DataField="MachineAlias" HeaderText="Branch"
                    SortExpression="MachineAlias" />
            </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>

and this is the code
Public Class WebForm2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

End Class

after i search i have this code
Dim found As Boolean
    Dim dt As DateTime
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As
    System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If Not IsDBNull(DataBinder.Eval(e.Row.DataItem, "Checkout")) Then
                dt = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "Checkout")).Date

            End If

            If e.Row.RowIndex > 0 And found = False Then
                e.Row.BackColor = Drawing.Color.Red
            End If
            found = Not IsDBNull(DataBinder.Eval(e.Row.DataItem, "Checkout"))
        End If
    End Sub

but it give my error

when i try the code from MR @Zack i have this error
Comment: Pretty sure you can use the RowDataBound event to compare the two columns against each other and highlight them when there is a match in the date. You would need to format the data coming from the cell to mm/dd/yyyy and drop the time though in order for it to be an exact match. I'd give you an example but I'm not sitting at a computer with a compiler and don't want to give you ugly code. If you google it though you should be able to find something on it.
Comment: The error line is because it needs to be e.Row.RowType and you just have an 'R' in the middle of it. It's also handling GridView1.DataBinding and needs to be GridView1.RowDataBound
Answer: Try using this...
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles        GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim arg1 As Date = Date.Parse(e.Row.Cells(1).Text)
        Dim arg2 As Date = Date.Parse(iif(isDate(e.Row.Cells(2).Text),e.Row.Cells(2).Text,"1/1/1900"))

        If arg1 = arg2 Then
            e.Row.BackColor = Drawing.Color.Red
        End If

    End If
End Sub

Comment: first let me thank you and i edit my post for you i have an error and are make sure if i try this code i will have the three color W and G and R
Comment: Try changing to my suggestion above, sorry if the syntax is jacked up I'm doing this from memory at the moment...


background coursel comes on bootstrap modal

Question: I encountered a problem working on my web app. bootstrap modal works very bad and background pace Coursera icon comes on top of modal.
this is error image
Comment: could you replicate the same on jsfiddle,http://jsfiddle.net
Comment: try to add this class into your css at bottom `.modal{z-index:9999999}`
Comment: Learner: thank you, Your solution was perfect
Answer: The z-index Solution:
The CSS z-index property specifies which element will stay at the top if they overlap each other. The Bootstrap modal probably has a lower (or set to default) z-index than your carousel. So the carousel navigation button is overlapping the modal.
To fix this, try adding the following CSS at the bottom of your stylesheet:
.modal {
  z-index: 9999999;
}

This basically sets the z-index of the modal to a much higher value than the carousel.
References:

http://www.w3schools.com/cssref/pr_pos_z-index.asp
https://developer.mozilla.org/en-US/docs/Web/CSS/z-index
https://css-tricks.com/almanac/properties/z/z-index/


Could not find a command named "version" - Flutter

Question: I am trying to get all versions of Flutter using command line directly -as always- but it is not working anymore.
Command:
flutter version

Result:
Could not find a command named "version".

Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options.

Is there any alternative for it rather than opening the website?
Comment: @someuser it was working like a week ago.
Comment: @someuser thanks but I want to get the version history not my current version
Answer: As the flutter version on my Flutter 1.22.4 installation says:
[!] The "version" command is deprecated and will be removed in a future version of
Flutter. See https://flutter.dev/docs/development/tools/sdk/releases for previous
releases of Flutter.

Here is the Pull Request that removed this deprecated command.
Here is the corresponding issue.
Comment: Can you please suggest to me how to change the flutter version? I have used "flutter version v1.20.2" and getting the "Could not find a command named "version" " error .
Comment: You cannot do this that easily. I'd personally recommend using the [fvm](https://github.com/leoafarias/fvm) tool for quick and easy switching between Flutter versions and channels.


Alternate inner products on Euclidean space?

Question: After reading about inner products as a generalization of the dot product, I was hoping to be able to prove that the dot product is in some sense the unique inner product in Euclidean space (e.g., up to constant scaling).
But it seems that there are a whole bunch of alternative inner products in $\mathbb{R}^2$ with nonzero cross-terms between basis vectors, for example, $\langle (a, b)^\intercal, (x, y)^\intercal \rangle = ax + by + 0.5(ay + bx)$. Unless I've made a mistake, this satisfies symmetry, linearity, and positive-definiteness.
Is there a sense in which the dot product is the canonical inner product on Euclidean space? Or do we just pick it because the implied norm matches our notion of distance?
Comment: Not quite what you're asking - but we *do* know that any two inner products on a finite-dimensional vector space are equivalent, which means there are positive constants $c, C$ such that $c \langle x, y \rangle_1 \le \langle x, y \rangle_2 \le C \langle x, y \rangle_2$ for all $x,y$.  So although the inner product is not unique, at least any two are within a constant scaling factor of each other.  (This fact is most useful when studying a topology induced by the inner product - it means the corresponding topology doesn't depend on the choice of inner product.)
Answer: Any inner product is dot product in some basis. For example, your inner product is standard dot product written in basis $\left(e_1, \frac{1}{2}e_1 + \frac{\sqrt{3}}{2}e_2\right)$.
Comment: No it's not. $e_2 = (-1,2)/\sqrt{3}$ in that basis, which has euclidean norm 5/3. But $\left = 1$.
Comment: Using author's inner product we have $\langle (-1, 2) / \sqrt{3}, (-1, 2) / \sqrt{3}\rangle = 1$. And in general - if we write two vectors in this basis and take inner product as defined in question, we get their standard dot product.
Answer: There is nothing special about the dot product. Yes, it corresponds to the Euclidean norm if you are using an orthonormal basis. But if your basis is not orthonormal then the Euclidean norm will be represented by some other symmetric matrix.
Answer: For an arbitrary inner product $\left<\right>$ on $\mathbb R^n$, there is a positive definite real symmetric matrix $A_{ij} = \left<e_i|e_j\right>$ that defines the transform. Since it is real and symmetric, it is orthogonally diagonalizable. That is, for any inner product on $\mathbb R^n$, there is a set of real numbers $\lambda_j$ and an orthonormal basis $\left|\xi_j\right>$ such that
$$
\left<a|b\right> = \sum_j\lambda_j\left<a|\xi_j\right>\left<\xi_j|b\right>
$$
Roughly speaking, the inner product resolves $a$ and $b$ into their $\xi_j$ components, then weights the resulting dot product by $\lambda_j$.
In general, this choice of $\left|\xi_j\right>$ will be unique. However, for some inner products, there will be multiple possible choices of $\left|\xi_j\right>$. The Euclidean norm is unique (up to a constant scaling) in that every choice of $\left|\xi_j\right>$ allows the inner product to be written in that form--it is independent of the chosen basis.


How do I get the public url of a file from the uri or filename

Question: I'm using php from with a view (Views PHP) I'm trying to extract the real url of a file from a file reference. I am able to get the the uri of the file and or the filename. What drupal function can I use to get thee actual public URL of the file?.
$videouri = db_query('SELECT filename FROM `file_managed` WHERE fid = ' . $nidvideo)->fetchColumn();
//drupal_set_message('
'. print_r($videourl, TRUE) .'
');
$realpath = drupal_realpath($videouri);
$videourl = file_create_url($realpath);
return($videourl);

Answer: What do you mean by "public URL" exactly ?
file_create_url() can give the absolute URL to the image out of the box.
$videouri = db_query('SELECT uri FROM {file_managed} WHERE fid = :nidvideo', array(':nidvideo' => $nidvideo))->fetchColumn();
//drupal_set_message('
'. print_r($videourl, TRUE) .'
');
$videourl = file_create_url($videouri);

file_create_url() expects a valid uri. drupal_realpath() gives the server path which does not work.
I also changed your database query to avoid any SQL injection vulnerable.
Answer: Don't use drupal_realpath() as it has been deprecated now.
Either of the following can be used:
1. (file_stream_wrapper_get_instance_by_uri($uri)):
$uri = $field[0]['uri'];  // file path as uri: 'public://';
if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  $path = $wrapper->realpath();
}

2. (file_create_url($uri)):
$uri = $node->field_video['und'][0]['uri'];  // file path as uri: 'public://';
$video_path = file_create_url($uri);

Comment: @user379468 Has the above solution worked for you, or if you found some better solution than please share. Thanks!!
Comment: This is a common misconception that is incorrect. `drupal_realpath()` is not deprecated -- it's just discouraged in cases where a path could be remote, since it only works for local paths. The first code snippet posted above is exactly what `drupal_realpath()` does under the hood.
Comment: To clarify: my comment is specific to Drupal 7. Either way, I still stand by my assertion that using the same code as what's inside a deprecated function is no better than just calling the deprecated function.
Answer: Check the following example:
$url = file_stream_wrapper_get_instance_by_uri($filepath)->getExternalUrl()

See: API for DrupalPublicStreamWrapper.
Related:

Why drupal_realpath('public://') returns sites/all/modules/current_module/sites/default/files path?
How can I convert a file uri to relative path?
Answer: In Drupal 8 you can use the file_url_generator service
Drupal::service('file_url_generator')->generateAbsoluteString($uri)

Because the file_create_url($uri) function is deprecated since 9.3:
https://www.drupal.org/node/2940031


How does one go about creating custom IntelliJ project templates?

Question: I wish to have a custom project template in IntelliJ IDEA (Community edition 12.0)
What I need, is for the project, when created, to copy in some standard files and then insert some values into those files.
I can probably do this myself using a bit of bash magic, but it would be very nice and tidy to just pick the template when creating a new project and get it all done in one go..
MSVS has very good support for custom projects, and I was kind of hoping IntelliJ had some of the same, though I have not been able to find it.
The only thing I found was the plugin facility, but I couldn't get started with that - IntelliJ just tells me the package com.intellij.openapi.components doesn't exist when I add an application component to the plugin project.
Cheers!
Answer: I figured out that you can create project templates quite easily, all you do is go into the meny, tools, save project as template.
Unfortunately, this did not provide me with features I needed, so I have made a bash script to do what I need.
Comment: If it helps anybody, [here's a link to the documentation](https://www.jetbrains.com/idea/help/saving-projects-as-templates.html) on how to save a project as a template, but the procedure is as Morten describes.


Why is my form not validating when submit is clicked

Question:


Administrative page still accessible by anonymous users?

Question: It's almost 2 years I don't program modules in D7.
I'm creating a module that shows 2 forms.
One is public (and to's working) and one is a setup form under /admin space.
The issue is that the one in the admin still accessible to anonymous, even when I check the checkbox into the "permission" page.
Could you help me please to find out what I miss?
Please here part of the code
function MyModule_permission() {
  return array(
    'administer MyModule' => array(
      'title' => t('Administer MyModulemodule'),
      'description' => t('Perform administration tasks for MyModule module.')
    ),
  );
}

here below the address of the 2 forms
/**
 * Implements hook_menu().
 *
 * Displays module information.
 */
function MyModule_menu() {
  $items = array();

  // It should be accessible by everybody
  $items['fillin'] = array(
    'title' => 'Participation Data',
    'description' => 'Please fill here below the fields in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_form'),
    'access callback' => TRUE
  );

  // it should be accessible only by admin
  $items['admin/config/setup_collection'] = array(
    'title' => 'Participation Text',
    'description' => 'Text for the presentation',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_setup_form'),
    'access arguments' => array('administer'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE
  );

  return $items;
}

Here below the setup form with the default content, that should be accessible only by the administrator
/**
 * Implement hook_form()
 *
 * Creates the form for the setup page
 *
 */
function MyModule_setup_form($form, &$form_state) {
  $form['MyModule_message'] = array(
    '#type' => 'textarea',
    '#title' => t('TEXT '),
    '#wysiwyg' => TRUE,
    '#default_value' => variable_get('MyModule_message', 'Subscribe fill in the form below'),
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('SUBMIT'),
  );
  return $form;
}

Here below just a part of the form accessible by the anonymous user
/**
 * Implements hook_form().
 *
 * Creates the form for the user.
 */
function MyModule_form($form, &$form_state) {

  global $conf;

  $form['MyModule_main_message']['hello'] = array(
    '#markup' => variable_get('MyModule_message'),
  );

  $form['first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Put your first name'),
    '#size' => 50,
    '#maxlength' => 50,
    '#required' => TRUE,
  );

            ...
            ...
            ...

Answer:
The problem is you are setting
'access callback' => TRUE
this gives access to all.
I also to sure that administer is a valid permission in 'access arguments' => array('administer'), instead try 'access arguments' => array('administer site configuration'),.
Comment: Ohh remember to flush the cache after the change
Comment: yes, I did flush it and indeed it works fine now :)
Comment: Sorry if I disturb you again. When I reinstalled the module, the admin got forbidden to access to the admin page :-/ In order to avoid this, I had to comment this line `'access callback' => FALSE`
Answer: In the "admin/config/setup_collection" array you use:
'access callback' => TRUE

In this way all users can access to this url and it overrides the "access arguments" array.
Remove line with "access callback" and clear cache.
Answer: As the other answers are telling you, setting the access callback to TRUE is making Drupal allow the access to that page to every user, without checking which permissions they have. Instead of TRUE, you should set the access callback to 'user_access' (yes, a string), or not set it at all, and Drupal will use the default value, which in most cases is 'user_access'.
If you don't want any issue, especially if it's possible you are going to change the route your module defines, and make admin/config/setup_collection a MENU_DEFAULT_LOCAL_TASK route, set the access callback explicitly, even if you are going to use the default value Drupal uses.
What the other answers aren't telling you is that setting the access arguments to array('administer'), you aren't telling Drupal to check the currently logged-in user who is trying to access admin/config/setup_collection has the permission you defined in MyModule_permission(). For that, you would need to use code similar to the following one.
function MyModule_menu() {
  $items = array();

  // It should be accessible by everybody
  $items['fillin'] = array(
    'title' => 'Participation Data',
    'description' => 'Please fill here below the fields in',
    'access callback' => TRUE,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_form'),
  );

  // it should be accessible only by admin
  $items['admin/config/setup_collection'] = array(
    'title' => 'Participation Text',
    'description' => 'Text for the presentation',
    'access callback' => 'user_access',
    'access arguments' => array('administer MyModule'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyModule_setup_form'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

As side note, never use capital letters in the module machine name. While PHP is not case sensitive, you are going to have issues when you will implement hook_update_N() for your module (and usually modules are going to implement that hook) because the Drupal code that gets the list of update hooks implemented from a module is case sensitive, as you can see from the following code used from drupal_get_schema_versions().
// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\\d+)$/';
$functions = get_defined_functions();

// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\\d+$/', $functions['user']) as $function) {

  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

Since the content of $regexp isn't '/^(?P<module>.+)_update_(?P<version>\\d+)$/i', the regular expression used from Drupal is case-sensitive.
This means that if the machine name of your module is MyModule and, by accident, you define an update hook as mymodule_update_7100(), it will not be recognized as update hook for your module.
It would also be true if the update hook would be named MyModule_UPDATE_7100().


What is the limit inferior and limit superior of sequence,$x_n=\left(1-\dfrac{1}{n}\right)\sin \left(\dfrac{n\pi}{3}\right),n\geq1$?

Question: Let,$x_n=(1-\frac{1}{n}) \sin(\frac{n\pi}{3}),n\geq1$.Then what is the limit inferior and limit superior if this sequence?
I know that the limit inferior of $x_n$ and limit superior of $x_n$ are respectively the smallest and the largest accumulation point.
Writing the sequence in the explicit form,
{$x_1$,$x_2$,,$x_3$,$x_4$,$x_5$,$x_6$,$x_7$,...,...}
={$(1-\frac{1}{1}) \sin(\frac{1\pi}{3})$,$(1-\frac{1}{2}) \sin(\frac{2\pi}{3})$,$(1-\frac{1}{3}) \sin(\frac{3\pi}{3})$,$(1-\frac{1}{4}) \sin(\frac{4\pi}{3})$,$(1-\frac{1}{5}) \sin(\frac{5\pi}{3})$,$(1-\frac{1}{6}) \sin(\frac{6\pi}{3})$,$(1-\frac{1}{7}) \sin(\frac{7\pi}{3})$}={$0,\frac{1}{4}$,$(1-\frac{1}{n}) \sin(\frac{n\pi}{3}),...,...$}
={$0,\frac{1}{4}$,$\frac{-2}{3}$,$\frac{-3\sqrt3}{8}$,$\frac{-2\sqrt3}{5}$,$0$,$\frac{3\sqrt3}{7}$,$\frac{-7\sqrt3}{16}$,...,...}
Now i collected the subsequences;{$x_1$,$x_6$,$x_{11}$,$x_{16}$,$x_{17},,,$}={$0,0,0,0,...,...,...$}.
I got struck here.I'm unable to select other suitable subsequences of ($x_n$) by which we can choose the smallest and the largest accumulation point of the
Comment: Try the three subsequences given by $n=3k$, $n=3k+1$, and $n=3k-1$.
Comment: Please write sine function as `\sin x` instead of `Sinx`.
Comment: @HagenvonEitzen:What  do you mean by $k$,here?
Comment: @JaideepKhare Please refrain from adding commands that force display style such as `\dfrac` to the title. Display mode is simply not designed for use on the same line as normal text. Using it in titles results breaks visual continuity on the front page due to misaligned line heights and excess white spaces.
Answer: Check that
$$\sin\frac{n\pi}3=\begin{cases}&0,&n=0,\,3\pmod 6\\{}\\&\cfrac{\sqrt3}2,&n=1,\,2\pmod3\\{}\\&-\cfrac{\sqrt3}2,&n=4,\,5\pmod 6\end{cases}$$
IT may also be worthwhile to take into account that $\;\left\{\left(1-\frac1n\right)\right\}\;$ is a descending sequence...
Comment: @PKStyles Yes, because $\;1-\frac1n\xrightarrow[n\to\infty]{}1\;$ , so taking $\;n\,$'s with different values modulo $\;6\;$ will give us the different values we want. For example: $$\left(1-\frac1{6n+5}\right)\sin\frac{(6n+5)\pi}3\xrightarrow[n\to\infty]{}-\frac{\sqrt3}2$$
Comment: :It means $limsup(x_n)=\frac{\sqrt3}{2}$ &$liminf(x_n)=\frac{-\sqrt3}{2}$?By the way excellent way of representation.
Comment: :Why had you chosen $(mod 6)$ particularly??
Comment: @PKStyles Because that's the way to obtain **all** the possible values...Remember that $\;\sin x\;$ is periodic $\;2\pi\;$ .


Is this a valid recursive formula for the geometric sequence?

Question:
Your friend lends you \$100. He adds a \$0.25 fee every single day, and then charges you 1% interest. Create a formula that represents this relationship.

The first day:
$T_1=(100+0.25)*1.01=\$101.2525$
And the geometric formula I came up with:
$T_d=(a_{d-1}+0.25)*1.01$ for $d>1$
But now the question is asking me to come up with a formula in terms of $P$ principle and $d$ days. And check the amount after 365 days.
I used Excel, but there is no common ratio (probably because it increases by \$0.25 a day). At first, the ratio is 1.012493766, then 1.012462994, etc. It seems the limit is tending towards 1.01 (after extending it in Excel for over 350 days).
So then I came up with the recursive formula:
$T_d=P(1.0125^{d})$
But it doesn't seem to be close to any of the values I have. The first day is \$101.2525, the 2nd day is \$102.517525. Even rounding the dollar values and using the limit ratio of 1.01 doesn't match. I just can't seem to take into account the $0.25 in the recursive formula.
Comment: $1$% per day ? Change friend !
Answer: Your geometric formula is correct. Let us further simplify it as: $$ T_d = (T_{d-1}+0.25)*1.01$$ $$=((T_{d-2}+0.25)*1.01+0.25)*1.01=(1.01T_{d-2}+0.25*1.01+0.25)*1.01$$ $$=(1.01)^2T_{d-2}+(0.25)*(1.01)^2+(0.25)*(1.01)$$ $$=(1.01)^2[(T_{d-3}+0.25)*1.01]+0.25[1.01+1.01^2]$$ $$=(1.01)^3T_{d-3}+0.25[1.01+1.01^2+1.01^3]$$ $$=…$$ $$=(1.01)^{d-1}T_1+0.25[1.01+1.01^2+…1.01^{d-1}]$$
Can you take it from here?
Comment: @JozemiteApps Just use the formula for the sum of a geometric progression.
Comment: As I commented, this is pure fraud ! I suppose that you computed the result for $d=365$ !
Comment: I spent a while but I can't figure it out. What is the closed form for the section in the square brackets?
Comment: Remembered it earlier; thanks!


windows timer vba change speed

Question: I'm using the windows timer API within VBA to proc a sub every 0.5s. I want to be able to change the timerproc speed while the timer is running. Unfortunately the StartTimer sub is only called once at the beginning. Any ideas on how I can modify my code to change speeds (say to 0.25s)?
Public Declare Function SetTimer Lib "user32" ( _
    ByVal HWnd As Long, _
    ByVal nIDEvent As Long, _
    ByVal uElapse As Long, _
    ByVal lpTimerFunc As Long) As Long

Public Declare Function KillTimer Lib "user32" ( _
    ByVal HWnd As Long, _
    ByVal nIDEvent As Long) As Long

Public TimerID As Long
Public TimerSeconds As Single

Sub stopTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
End Sub
Sub StartTimer()
    RerunSpeed = 0.5
    TimerSeconds = RerunSpeed
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
        ByVal nIDEvent As Long, ByVal dwTimer As Long)

    Call RecalculateData

End Sub

Answer: Make the following modifications to your code.
Public TimerID As Long
Public TimerSeconds As Single
Public TimerRunning As Boolean

Sub stopTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
    TimerRunning = False
End Sub

Sub StartTimer(Optional RerunSpeed As Double = 0.5)
    If TimerRunning Then stopTimer
    TimerSeconds = RerunSpeed
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
    TimerRunning = True
End Sub

You can make subsequent calls to the StartTimer sub procedure with alternate time intervals. If the timer is currently active, it will be halted and reinstated with a new interval; e.g. StartTimer 0.25
Answer: The timer interval is specified once and for all when you create the timer by calling SetTimer. If you need to modify the interval, you need to re-create the timer by calling KillTimer first, and then SetTimer with the new interval.

windows timer vba change speed


How and where do I programmatically add a menu to the Navigation menu?

Question: I want to add menu items to the Navigation menu dynamically, depending on certain states (example: user is logged in, etc). I assume I do this in theme_preprocess, but I can't seem to find the var to tweak.
Am I looking in the wrong place? Where is the best place to do this, and what is the best method?
Comment: I am having the same needs now. Did you figure out how this can be done?
Answer: I'd suggest checking out hook_menu(). For example, the following implementation of hook_menu() placed in either a module or template.php should insert a menu item into the navigation menu for anonymous users. Take a look at the User module for some good examples of how to implement hook_menu() for different user roles.
function MODULE_menu() {
   $items = array();
   $items['the/menu/path'] = array(
   'access callback' => 'user_is_anonymous',  //or 'user_is_logged_in' to check if logged in
   'type' => MENU_NORMAL_ITEM,
   'menu_name' => 'navigation',
   'title' => t('Title of Menu Item'),
  );
  return $items;
}

Comment: The find the menu item and run the hook_menu_alter on it and add the access callback.
Comment: Themes cannot implement hooks, except specific alter hooks in Drupal 7.
Comment: If I understand correctly, that is how to create menus in the menu system. I'm wanting to refine a menu that is defined in the GUI, a built-in nav called Navigation.
Comment: hook_menu_alter() only runs when the menu system is being rebuilt. I'm looking to refine the menu on the page load.
Comment: Golden oldie! The answer above would be fine. For non-code options, check out https://www.drupal.org/project/menu_item_visibility, https://www.drupal.org/project/menu_per_role, or https://www.drupal.org/project/custom_menu_perms.
Answer: I think you can create it by using menu_link_save().
$item = array(
  'link_path' => 'my_path',
  'link_title' => 'title',
  'menu_name' => 'header-top-menu', // Menu machine name, for example: main-menu
  'weight' => 0,
  'language' => $node->language,
  'plid' => 0, // Parent menu item, 0 if menu item is on top level
  'module' => 'menu',
);
menu_link_save($item);

You could use the code I am showing in a hook_update_N() implementation.
See also Drupal 7 Menu Link update through update.php.
Comment: FYI - you missed a end quote at the end of 'title


Display main menu vertically (Drupal. 7.9)

Question: I am not sure how this has happened. but wherever I render the block of my main menu, it displays it's links horizontally rather vertically. Essentially I want to create a main menu that displays its links vertically.
Anybody have a lead on how this can be done ? I am tempted to go into the CSS and alter the theme myself but given that Drupal probably has a switch that allows me to alter the way a main-menu is listed, I want to caution myself.
Thanks!
Answer: You need to use Firebug and find the style rule that is being applied to the
elements that will be displaying them inline. Firebug will tell you where the CSS is being loaded and this will lead you to the culprit. One tip is to make sure you're not aggregating CSS so you can find the correct stylesheet. If it isn't theme specific it may be CSS being loaded by a module, but I am confident that there is some CSS there that is creating the result you're seeing.
Answer: Sounds a lot like a css issue my friend. Have you changed anything recently in your css that may be cascading into your menu? It is likely that your block elements have been set to inline or floating.
Comment: probably, because I do think I tampered with the CSS at times, alternately, do you advocate creating your own menus or using a menu module ?
Comment: But here's the thing, use any theme I want, it still displays the menu horizontally, so I am assuming that it is not a theme-specific problem, any leads on this ?


An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Question: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Cannot open database "SIS.mdf" requested by the login. The login failed.
<code>SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=SIS.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT TOP 5     [book_name]      ,[book_link]      ,[user_id] FROM library", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
</code>
Comment: your connectionstring is also invalid. Initial Catalog is the name of the database - not the filename.
Answer: The database probably requires a username and password.  The error message tells it all.


Any way to see the password for attempted RDP intrusions?

Question: I have a silly person in china (According to IP-Reversal websites) who is trying to login to my machine using RDP. I first noticed this when I found a stream of messages similar to this one:
<code>[LAN access from remote] from 184.108.40.206:65086 to 192.168.1.20:3389 Thursday, November 16,2017 10:20:17
[LAN access from remote] from 188.8.131.52:56522 to 192.168.1.20:3389 Thursday, November 16,2017 10:19:00
</code>
Anyway I am not concerned as he is trying every minute or so to log into Administrator account. I have left it disabled and locked as it was.
<code>The computer attempted to validate the credentials for an account.

Authentication Package: MICROSOFT_AUTHENTICATION_PACKAGE_V1_0
Logon Account:  ADMINISTRATOR
Source Workstation:
Error Code: 0xC000006A
</code>
I know I could change the Port for RDP to something other than 3389 but I need to stick to this port as my office only allows RDPs to the default one.
I also know that I could setup a VPN but then again this might be an overkill for my case.
I changed windows firewall to allow only RDP connections from a range of IPs but had to revert that as my office uses different ISPs and the IP at any moment could be different than after the next network restart.
I was hoping to see the passwords he is trying to use to brute force his way in.
Also is there anyway for me (using default windows policies) to throttle/ban IPs that send invalid credentials for some time?
Also,
As I have a dynamic IP, first thing I did was restart my router and got a new IP, but apparently the habit is too strong as it didn't take longer than a day for another silly guy to start trying his luck with a new range of IPs and get mine within them.
Answer: It wouldn't be a good practice to do what you are requesting for as it would also log any legitimate attempts i.e. actual passwords. Even logging just the failures would log any mistyped passwords, too.
Instead, you could automatically block an IP address after certain amount of failed attempts. See this question: Does fail2ban do Windows?


Overriding behaviour of sibling components

Question: I've been struggling with the concept of overriding the behaviour of components between sibling components (components that do not have a parent-child relationship).
I have an App component that renders a header and a content component. The header contains a button that will let a user navigate back (not for real in this example). Now I want the content component to override the back button's behaviour, for example if a user is editing a form and I want to pop up a modal.
The reason I want to do this is because I want to (optionally) control navigation from within the content component itself.
I have found this (see snippet) solution, but I feel like it's not the right way to handle this. I would like to have some advice on how to handle this situation.
A few side-notes:

I'm actually building a react-native app, but in the hope of reaching more people I've simplified it down to a react example. I'm using NavigatorExperimental for navigation.
I am using redux/redux-form

Any help is appreciated.

class NavigationHeader extends React.Component {
  render() {
    return (
       Go back!
    );
  }
}

class Content extends React.Component {
  componentDidMount() {
    this.props.setBackButtonBehaviour(() => console.log("BackButton overridden from Content"));
  }

  componentWillUnmount() {
     this.props.resetBackButtonBehaviour();
  }

  render() {
    return (
Content
);
  }

}

class Navigator extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      overrideHeaderBackButtonBehaviour: null
    }
  }

  setBackButtonBehaviour(func) {
      this.setState({overrideHeaderBackButtonBehaviour: func});
  }

  resetBackButtonBehaviour() {
       this.setState({overrideHeaderBackButtonBehaviour: null});
  }

  defaultBackButtonBehaviour() {
    console.log("Default back-button behaviour");
  }

  render() {
    return (

        <NavigationHeader goBack={this.state.overrideHeaderBackButtonBehaviour || this.defaultBackButtonBehaviour} />
        <Content
          setBackButtonBehaviour={this.setBackButtonBehaviour.bind(this)}
          resetBackButtonBehaviour={this.resetBackButtonBehaviour.bind(this)}
    />

    );
  }
}

ReactDOM.render(<Navigator />, document.getElementById("app"));

Comment: What's exactly your question? Have you got any problem with that code? I think It's correctly written and It´ll work fine.
You should add a constructor to Header class like you did in App class in order to receive props.
But i think it is good
Comment: I want to know whether this is a bad practice or not, since it's not really the "react-way" of doing things. I know it's working fine. I just wonder what the best way is to handle this use-case.
Answer: You can try something like this:
Header.js
import actions from './actions';

@connect(
  // map state to props
  (state, props) => ({
    canNavigate: state.navigation.canNavigate,
  }),
  // map dispatch to props
  {
    goBack: actions.goBack,
    showNavigationAlert: actions.showNavigationAlert,
  }
)
class Header extends React.Component {
  render() {
    return (
      {/* if 'canNavigate' flag is false and user tries to navigate, then show alert */}

          Go back!

    );
  }
}

Content.js
import actions from './actions';

@connect(
  // map state to props
  (state, props) => ({
    navigationAlert: state.navigation.navigationAlert,
  }),
  // map dispatch to props
  {
    toggleNavigation: actions.toggleNavigation,
  }
)
class Content extends React.Component {
  render() {
    return (

        {/*
            Show modal if 'navigationAlert' flag is true;
            From the modal, if user choose to leave page then call toggleNavigation.
            You may call the corresponding navigation function after this (eg: goBack)
        */}
        {this.props.navigationAlert && <Modal toggleNavigation={this.props.toggleNavigation} />}

        {/* eg: disable navigation when clicked inside the div */}
        <form onClick={this.props.toggleNavigation}>
          Content click!
        </form>

    );
  }
}

App.js
class App extends React.Component {
  render() {
    return (

        <Content />

    );
  }
}

navigationReducer.js
const initialState = {
  canNavigate: true,
  navigationAlert: false,
};

export function navigationReducer(state = initialState, action = {}) {
  let newState = {};

  switch (action.type) {
    case TOGGLE_NAVIGATION:
      return { ...state, canNavigate: !state.canNavigate };

    case TOGGLE_NAVIGATION_ALERT:
      return { ...state, navigationAlert: !state.navigationAlert };

    default:
      return state;
  }
}

actions.js
export function toggleNavigation(gdsSession) {
  return { type: TOGGLE_NAVIGATION };
}

export function toggleNavigationAlert(gdsSession) {
  return { type: TOGGLE_NAVIGATION_ALERT };
}

// ... other actions

and render into DOM.
ReactDOM.render(<App />, document.getElementById("app"));

Comment: Yes this is a workaround, but it still doesn't give me the amount of control I want over the header-buttons from my context component. Ideally I would like to optionally override the header's buttons if desired by the content component.
Comment: This is how we usually implement communication between components via global store. But I am still unclear about the statement "optionally control navigation". Can you give a better use case? What I attempted here is to solve the use case that you gave in the question.


Login programmatically + remember me

Question: When a user confirm its registration (a link sent in an email), I can log him manually like this (I don't like this code, but didn't found a better way to achieve this):
<code>$user = $em->find(...);
$securityToken = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($securityToken);
</code>
My question : I also need to set the remember-me cookie, but I have no idea how to achieve this. I'm trying to figure out how authentication classes work in Symfony, but it's jungle out there :/
I know that Symfony generate a key (stored in a MySQL table), and then set a cookie, what should I use to reproduce the same behavior?
I'm not using any kind of external bundle, just Symfony.
Thx for any help!
Comment: What was your *exact* question?
Comment: Why don't you just redirect to your login page with the request parameters already filled in, including the _remember_me (or whatever name you gave it in the config)? This would avoid any hacks.
Comment: My question : how can I set the remember-me cookie after login.
Comment: Are you using a user bundle?
Comment: @NoChecksum I'm not using any bundles, just the symfony basics.
Answer: After reading again and again the Security component code, I found a way to log a user and set him the remember-me cookie. I don't like that kind of hack, if someone find a cleaner way I'll be happy to test it. I hope it can help someone, and I wish we will see one day a manual login helper in symfony.
<code>// Replace "main" by the firewall name
$user = $em->find(...);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());

// Find UsernamePasswordFormAuthenticationListener and call the onSuccess method
$authenticationListener = null;
foreach ($this->get('security.firewall.map.context.main')->getContext()[0] as $listener) {
    if ($listener instanceof UsernamePasswordFormAuthenticationListener) {
        $authenticationListener = $listener;
        break;
    }
}

if ($authenticationListener) {
    // The onSuccess method is private
    $onSuccessMethod = (new \ReflectionClass($authenticationListener))->getMethod('onSuccess');
    $onSuccessMethod->setAccessible(true);
    $response = $onSuccessMethod->invoke($authenticationListener, $request, $securityToken);

    // Do what you want with the response
}
</code>

Login programmatically + remember me


What class of software should I use to intercept HTTP requests and perform an action

Question: We have inherited an old Web application that needs to be extended with some logging capacities for compliance purposes. Unfortunately, we can't change the application. The application receives XML POST requests. We need to capture several specific XML values and log them in a separate file. So this involves XML parsing and some custom code. We are thinking about putting a kind of a proxy in front of the server. Are there proxies that allow custom request body processing without low level programming? Or an IDS is better for this purposes?
Comment: Snort can watch and pump to a DB, I would suggest a custom app to do "the action"
Comment: consider using `mod_security` - Information about its [audit log](https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#wiki-SecAuditEngine).
Comment: @Jacob: I understand that Snort can match some values in requests and raise alerts. Is it able to capture data fields and log them? Does it takes a custom plugin?
Comment: @fuero: Unfortunatelly mod_security logs the whole request body, which greatly increases the log size.
Comment: @test1839 Lemme check my Snort reference book, but yes you can match like that. Is the location of the data static, or will it be different in 2 packets?
Comment: @Jacob: The XML structure is stable but value lengths may vary.
Answer: You have not specified what action you have to preform after logging, so for now I will skip that.
First, I would suggest setting Snort to log to a database(most likely MYSQL). In Fact, I would suggest sending binary logs to Barnyard to export to the DB depending on your load to this application.
Anyhow more of what your interested in is how to actually log the data. Luckily, Snort has all kinds of ways to match against packets. What I would suggest is writing a rule to use the HTTP preprocessor. You can use a content match to find the service identifier.
For reasons I will explain in a second, we want to use a specific piece of information that always appears in the same general area in every packet. This is because we can optimize the rule by telling Snort where too look inside the packet for the match. You can use uricontent to to match against the URI, but we can go better and specificity exactly where in the packet the data will be with the depth and offset modifier.
The depth mod on its own will set the search length from the start of the packet, but when you use the offset mod it will set the starting point for depth. EX. If I say offset 10 depth 50 then Snort will check from bytes 10-50 of the payload only. The content match is only done within the payload, and you have to use other processors to check the header.
This should be enough to get the data you need, but you also have to remember the security of the Snort and DB instance if you ae logging sensitive data.
A good resource on this is Snort IDS toolkit published by Syngress.
Comment: 1. I forgot to mention that this is an SSL encrypted connection. Would Snort be able to deal with the encrypted traffic?
Comment: 2. As for the action to perform, after each logging event we eventually need to send an update to another server (syslog or database update). Basically, I would need a possibility to run a custom script.


Adobe Air integrar Flex Componets

Question: Eu estou a desenvolver um projecto através do Adobe AIR e Action-Script 3, deparei que as UI Components não tem suporte para mobile, ou seja em Android ou iOS eles não fazem scroll-bar para baixo e para cima com o dedo.
Pelo que percebo, que tem essa funcionalidade é a Framework Flex. é possivel integrar os componentes Flex para o projecto actual que está em AIR? Se sim, como?
Tecnologias:
Adobe Flash Profissional CC 2015
Adobe Flash Builder 4.7
Adobe AIR 18
Answer: Você não conseguirá utilizar as bibliotecas do Flex no AIR AS3 por possuírem SDKs e compiladores diferentes. O Flex SDK é quase uma extensão do AIR SDK, mas não totalmente compatível pois existem estruturas de pastas e arquivos de projetos distintos.
O que você pode fazer é converter sua aplicação. Esse processo envolve a migração de bibliotecas, objetos visuais e estrutura de pastas, o que torna muito trabalhoso de fazer.
Você pode utilizar algumas bibliotecas de componentes de terceiros ou criar os seus próprios componentes. O código a seguir tem um exemplo bem básico de scrolling:
<code>import flash.display.MovieClip;
import flash.display.GradientType;
import flash.ui.MultitouchInputMode;
import flash.ui.Multitouch;
import flash.events.TouchEvent;
import flash.geom.Rectangle;

var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF0000);
mc.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight * 2);
mc.graphics.endFill();
mc.graphics.beginFill(0x0000FF);
mc.graphics.drawCircle(stage.stageWidth/2, stage.stageHeight, 50);
mc.graphics.endFill();

this.addChild(mc);

Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

mc.addEventListener(TouchEvent.TOUCH_BEGIN, touchBegin);
mc.addEventListener(TouchEvent.TOUCH_END, touchEnd);

function touchBegin(e:TouchEvent):void {
    mc.startTouchDrag(e.touchPointID, false, new Rectangle(0, - stage.stageHeight, 0, stage.stageHeight * 2));
}

function touchEnd(e:TouchEvent):void {
    mc.stopTouchDrag(e.touchPointID);
}
</code>
Há outros tutoriais na internet para você realizar o scroll de objetos. Uma boa biblioteca para você incrementar com efeitos de smoothing é o Greensock.

Adobe Air integrar Flex Componets


Displaying multiple referenced nodes' fields through Views, using Views Slideshow

Question: I'm trying to build some image carousel functionality. To accomplish this, I've created two content types: Slideshow, and Slide. The Slide content type is what you would expect--a few fields that hold the content of the slide. The Slideshow content type's only purpose is to hold an ordered collection of slides in an Entity Reference field.
The advantage to this approach is that the use of an Entity Reference field means that the content administrator gets a drag'n'droppable UI for the ordering of slides, which is much nicer than some clunky integer weight fields.
So, having got that part set up, I scoot off to Views to work some magic with Views Slideshow. I create a view which calls up my Slideshow node and uses a relationship based on that Entity Reference field to get to the Slide nodes. With that, I can set up the fields of the slides how I like.
The last step would've been switching to the Slideshow view format and configuring the thing, but it was here that I ran into a problem. After I got things set up the way I thought they should be, I found that only the first slide's node was being displayed.
I did my Googling, and I found another question here on Drupal Answers that was similar to mine, which you'll need to read to understand the rest of my question. Reading through it, I tried out the solution that one kind soul provided, and it worked. But it required that I switch from the Slideshow view format to the Unformatted List view format.
So now it appears that I have a choice: I show all the slides as an unformatted list, which is not a slideshow. Or, I can show one of slides as a slideshow, which is not a slideshow.
This bums me out, because I thought I found an almost perfect setup. A content-manageable slideshow with an easy-to-use UI that didn't require the client to understand weight numbers and struggle through the tedium of setting them up. Can anyone help me jump over this roadblock?
Answer: I don't know if it's possible to do this with views_slideshow but I just created a patch for the field_slideshow module. It will be committed once I have tested it a little more or there is some feedback.
The Field Slideshow module page.
The issue with the patch.
And the documentation page: drupal.org/node/1495622
So once you have installed the dependancies and libraries here is how to download and apply the patch:
<code>git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/field_slideshow.git
cd field_slideshow
wget http://drupal.org/files/entity_reference_support-1634412-3.patch
git apply entity_reference_support-1634412-3.patch
</code>
Then enable the module and go to your content type display setting page ( something like admin/structure/types/manage/article/display ). Here you should be able to define the format of the reference field to be a slideshow.


TabBarview com card gerando erro ao carregar dados no flutter

Question: Bom dia, estou começando agora no mundo flutter e estou montando uma TabBarView com card com dados vindos de um banco.
Estou colocando dentro de ListView para poder separar nas tabs e carregando os dados dentro de um ListView.builder. Ao debuggar, vi que os dados estão sendo pegos, porém gera um erro e não carrega na tela.
O erro é:
════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderViewport#0e7dd NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1702 pos 12: 'hasSize'

════════ Exception caught by rendering library ═════════════════════════════════
The getter 'scrollOffsetCorrection' was called on null.
Receiver: null
Tried calling: scrollOffsetCorrection

A classe de montagem de tela:
class _LacamentosWidgetState extends State<LacamentosWidget> {

  @override
  Widget build(BuildContext context) {
    Lancamentos _lancamentos = Provider.of(context);

    return TabBarView(
      children: <Widget>[
        //aba despesas
        ListView(
          children: <Widget>[
            Card(
              margin: EdgeInsets.all(10),
              child: Column(
                children: <Widget>[
                  ListTile(
                    title: Text('Descrição'),
                  ),
                ],
              ),
            )
          ],
        ),
        //aba receitas
        ListView(
          children: <Widget>[
            ListView.builder(
                itemCount: _lancamentos.itemsCount,
                itemBuilder: (_, int position) {
                  final item = position;
                  return Card(
                    child: ListTile(
                      title: Text('sdfd'),
                    ),
                  );
                }),
          ],
        ),
      ],
    );
  }
}

e a classe de pega os dados:
class Lancamento {
  final int id;
  final String descLancamento;
  final DateTime diaLancamento;
  final double valorLancamento;
  final bool isReceita;
  final String tipoLancamento; //FIXO VARIAVEL para enum

  Lancamento({
    this.id,
    this.descLancamento,
    this.diaLancamento,
    this.valorLancamento,
    this.isReceita = true,
    this.tipoLancamento,
  });
}

class Lancamentos with ChangeNotifier {

  List<Lancamento> _items = DUMMY_LANCAMENTOS;

  List<Lancamento> get items {
    return [..._items];
  }

  int get itemsCount {
    return _items.length;
  }
}

Answer: Você precisa adicionar um TabController a sua classe para trabalhar com a TabBarView.
No seu caso seria
controller: TabController(length: 2, vsync: this)

Uma outra coisa errada é que você esta criando uma lista dentro de outra lista, sem definir o tamanho das listas internas, causando assim um erro ao desenhá-las, pois as ListView quando não possuem um height especificado, tomam todo o tamanho do Widget pai, e como elas podem ter tamanhos infinitos, nunca terminam de desenhar...
Ao invés de fazer:
ListView(
    children: <Widget>[
        ListView.builder(
        itemCount: _lancamentos.itemsCount,
        itemBuilder: (_, int position) {
            final item = position;
            return Card(
                child: ListTile(
                  title: Text('sdfd'),
            ),
            );
        }),
    ],
),

Faça apenas assim:
ListView.builder(
    itemCount: _lancamentos.itemsCount,
    itemBuilder: (_, int position) {
        final item = position;
        return Card(
            child: ListTile(
                    title: Text('sdfd'),
        ),
        );
    }
),

Obs.: Se precisar ser como está, defina um height para as listas internas.
Classe completa corrigida
class _LacamentosWidgetState extends State<LacamentosWidget> with SingleTickerProviderStateMixin {

  @override
  Widget build(BuildContext context) {

    TabController _controller = TabController(length: 2, vsync: this);

    return TabBarView(
      controller: _controller,
      children: <Widget>[
        //aba despesas
        ListView(
          children: <Widget>[
            Card(
              margin: EdgeInsets.all(10),
              child: Column(
                children: <Widget>[
                  ListTile(
                    title: Text('Descrição'),
                  ),
                ],
              ),
            )
          ],
        ),
        //aba receitas
        ListView.builder(
            itemCount: _lancamentos.itemsCount,
            itemBuilder: (_, int position) {
              final item = position;
              return Card(
                child: ListTile(
                  title: Text('sdfd'),
                ),
              );
            }
         ),
      ],
    );
  }
}


Number field type for specific format

Question: I have to store number data into database in format xx-xxxxxx-xx for example I have xml data in format:
ISBN="10-000000-701"
ISBN="11-000000-002"
ISBN="11-000000-004"
and I need to store that number in db field but I don't know what field type to use. Any help?
Comment: There is an ISBN field module.
Answer: You can create a 'simple text' field. Then you can add a constraint to that field to ensure that it is in the correct format.
Comment: Sure. But in this specific case of OP: https://www.drupal.org/project/isbn

Number field type for specific format


Key error when selecting a column in pandas dataframe after read_csv

Question: I am trying to read a CSV file and running into error when trying to print any column. Printing the whole dataset works but not a particular column. I see that there are no spaces in the column names.
df_all = pd.read_csv('feb_25.csv')
print(df_cpu.columns.tolist())
df_cpu.head(5)

['datetimestamp', 'cpu_usage_p', 'mth_ave_cpu_usage_p', 'mth_max_cpu_usage_p']
Out[298]:
   datetimestamp    cpu_usage_p mth_ave_cpu_usage_p mth_max_cpu_usage_p
0   2016-10-03 05:08:00 59.1    51.68   99.87
1   2017-01-14 02:01:00 69.31   59.36   100
2   2016-12-02 14:00:00 73.78   84.51   100
3   2017-01-16 10:01:00 36.19   56.79   100
4   2017-01-06 00:00:00 69.2    42.00   100

>>>df_cpu[df_cpu.cpu_usage_p]<<<

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-299-4b0ea47da1c6> in <module>()
----> 1 df_cpu[df_cpu.cpu_usage_p]

C:\Program Files\Anaconda3\envs\ML\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2051         if isinstance(key, (Series, np.ndarray, Index, list)):
   2052             # either boolean or fancy integer index
-> 2053             return self._getitem_array(key)
   2054         elif isinstance(key, DataFrame):
   2055             return self._getitem_frame(key)

C:\Program Files\Anaconda3\envs\ML\lib\site-packages\pandas\core\frame.py in _getitem_array(self, key)
   2095             return self.take(indexer, axis=0, convert=False)
   2096         else:
-> 2097             indexer = self.ix._convert_to_indexer(key, axis=1)
   2098             return self.take(indexer, axis=1, convert=True)
   2099

C:\Program Files\Anaconda3\envs\ML\lib\site-packages\pandas\core\indexing.py in _convert_to_indexer(self, obj, axis, is_setter)
   1228                 mask = check == -1
   1229                 if mask.any():
-> 1230                     raise KeyError('%s not in index' % objarr[mask])
   1231
   1232                 return _values_from_object(indexer)

KeyError: "['59.1' '69.31' '73.78' ..., '75.86' '81.7' '72.07'] not in index"

Comment: You should take a look at the Indexing section of the docs, what you attempted looks rather confused.
Answer: Try df_cpu['cpu_usage_p']
df_cpu.cpu_usage_p refers to a specific column and when passed to df_cpu data frame as a Key, of course it is not found.


Is it possible that the AIC and BIC give totally different model selections?

Question: I'm performing a Poisson Regression model with 1 response variable and 6 covariates. Model selection using AIC results in a model with all covariates as well as 6 interaction terms. The BIC however, results in a model with only 2 covariates and no interaction terms. Is it possible that the two criteria, that look very similar, yield totally different model selections?
Comment: If it wasn't possible to get different model recommendations from the two metrics, then there wouldn't be two metrics, we'd just always use one.
Comment: The word "totally different" is hard to interpret when models are the result of choosing from a set of discrete parameters.
Answer: It is possible indeed. As explained at https://methodology.psu.edu/AIC-vs-BIC, "BIC penalizes model complexity more heavily. The only way they should disagree is when AIC chooses a larger model than BIC."
If your goal is to identify a good predictive model, you should use the AIC. If your goal is to identify a good explanatory model, you should use the BIC. Rob Hyndman nicely summarizes this recommendation at
https://robjhyndman.com/hyndsight/to-explain-or-predict/:
"The AIC is better suited to model selection for prediction as it is asymptotically equivalent to leave-one-out cross-validation in regression, or one-step-cross-validation in time series. On the other hand, it might be argued that the BIC is better suited to model selection for explanation, as it is consistent."
The recommendation comes from Galit Shmueli's paper "To explain or to predict?", Statistical Science, 25(3), 289-310 (https://projecteuclid.org/euclid.ss/1294167961).
Addendum:
There is a third type of modeling - descriptive modeling - but I don't know of any references on which of AIC or BIC is best suited for identifying an optimal descriptive model. I hope others here can chime in with their insights.
Comment: "_The only way they should disagree is when AIC chooses a larger model than BIC._" Technically BIC could choose a larger model if $\ln n < 2$, i.e. $n \le 7$. Hopefully samples of size 7 aren't too much of an issue, though. :p
Comment: If we understand the meaning of "descriptive" & take it seriously, I'm not sure it makes sense to talk about identifying the optimal descriptive model.
Comment: Good point! With a sample size of 7 or less, I would imagine model selection is off the table.
Comment: There is a third type of modeling - descriptive modeling - but I don't know of any references on which of AIC or BIC is best suited for identifying an optimal descriptive model. I hope others here can chime in with their insights. Is it an answer or a question ?
Comment: @subhashc.davar: No answer yet - I'm tempted to email Galit Shmueli and ask her for her thoughts on that.
Answer: Short answer: yes, it is very possible. The two apply different penalties based on the number of estimated parameters (2k for AIC vs ln(n) x k for BIC, where k is the number of estimated parameters and n is the sample size). Thus, if the likelihood gain from adding a parameter is small, BIC may select different models to AIC. This effect is dependent on sample size, however.
Comment: would be nice to make explicit that n is the sample size in the above equation


Image of morphism of sheaves

Question: Suppose I have a morphism of sheaves $f : E^{\oplus4} \to I_p$ on $X$ a degree $3$ Fano threefold, where $E$ is a rank $2$ vector bundle on $X$ and $I_p$ is an ideal sheaf of a point $p \in X$. I'm interested in knowing the image of $f$.
For each of the direct summands, I have a morphism $f_i : E \to I_p$ and I know that the image of such a morphism is $I_{D_i}$ where $D_i$ is a degree $5$ curve containing $p$. Is there a way in which I can use this information to find the image of $f$? I'm hoping that this  makes $\mathrm{im}(f) = I_p$, but I'm not sure if this is true, and if so, how to proceed.
Thanks.
Answer: To compute the image you can replace $I_p$ by $\mathcal{O}_X$ and the copies of $E$ by $I_{D_i}$. Then your question becomes: what is the image of
$$
I_{D_1} \oplus I_{D_2} \oplus I_{D_3} \oplus I_{D_4} \to \mathcal{O}_X.
$$
The image of the direct sum of ideal sheaves is, of course, the sum of the corresponding ideals, i.e., the ideal of the corresponding intersection of schemes. So, it proves that the image you are interested in is $I_Z$, where
$$
Z = D_1 \cap D_2 \cap D_3 \cap D_4.
$$
In particular, if you want to prove it is $I_p$, you need to check that the scheme-theoretic intersection of your quintic curves is the point $p$.
Comment: Thanks for your answer!

Image of morphism of sheaves


When copying VM filesystem over netcat, dd copies double the disk size

Question: I'm attempting to copy the disk of a working headless virtualbox VM (VM1) on one server to a new VM (VM2) on a vCloud server.  I don't have access to the host of VM2.
The OS is Windows Server 2003 (32-bit)

I start both VMs with a live Knoppix image.
I run 'nc -l  | dd of=/dev/sda bs=512' on VM2
I run 'dd if=/dev/sda bs=512 | nc  ' on VM1

I previously did this with another windows VM and it worked fine.
VM1 has a disk of size ~70GB (verified with fdisk); however, the amount of data dd reports read/written is ~139GB.
Of course the target machine doesn't work properly.  I get a Windows splash screen, then blue error screen with general 'system not working' information.
I'm at a loss what could cause this.  Any ideas?
Comment: can you show us fdisk -l from within source VM? parted -l would also be nice
Answer: My guess is that the source files are sparsely allocated (i.e. physical size < visible size) with "holes" in the data space.  If you use dd, it will return zeros for the currently unallocated blocks in the file, thus the resulting output will be FAR larger than what your source file is.
Comment: Doesn't make sense, because 1) he is reading data from within VM, 2) data is doubled: 70->140, how could zeros do that?
Comment: A sparce situation takes up less space because blocks that never were in use are not allocated.  when you do logical access via dd, ZEROs are added where unallocated space was present.  The result is NOT sparce but a fully allocated file with the ZERO blocks where the unallocated space was.
Comment: Reading the disk size from inside the VM shows 70GB of space.  This doesn't change based on how sparsely files are allocated or how much of the disk is used.


Linear Algebra - Finding point Q using distance

Question: Let $P$ be the point $(-3, 2, 1)$. Suppose that the point $P_0(1, -3, 6)$ is  $1/8$  of the way from $P$ to $Q$.
Find the point $Q$.

I was thinking of using the midpoint formula for this but that would take a lot more work. I also thought the distance formula would be more appropriate but I don't exactly know how to implement it. Can anyone help me with this?
Answer: hint
$$\vec{PP_0}=\frac 18\vec{PQ}$$
$$\implies$$
$$x_0-x_P=\frac 18(x_Q-x_P)$$
$$\implies$$
$$x_Q=8x_0-7x_P=29$$