text:
Q: text overflowing div with php echo I'm making my very first full stack project. I made this blog, on which you can post and comment, and all of the posts and comments are stored in a mysqli database.
to get all the data in the database when you load a page, I use php to store all of those datas in an array, and then echo those datas on the web page.
the part where it sets, get and shows the data on the page is fine. But when I echo the data from the array (which gets its data from the database table) the text overflows my div... I tried everything with CSS and bootstrap, it's not working.
I don't know why, I tried many things and I've been stuck on this for the last 2 days.
and forgive me for the bad practices of my code, I'm junior and mostly front-end. This is my first attempt for a full stack project, so I'm learning on my own while coding this.
 <?php foreach($datas as $value): ?>

<?php

$id = $value['id'];
echo $id;

$imgSrc = $value['image'];

echo
"

" . $value['title'] . "
".
"
".
"

" . $value['description'] . "

".
    "
" . $value['date'] . "
".

    "

    <form action='".setComments($conn, $id, $sessionComments)."' method='post' enctype='multipart/form-data' class='col-md-8 mx-auto'>

    <input name='comments' type='text' class='form-control' id='exampleFormControlInput1' >

Select image to upload:

<button type='submit' name='commentSubmit$id'  id='btnSend' class='w-25 mx-auto btn btn-primary'>Comment

</button>

    </form>
    ".

"

";

// afficher les commentaires
getComments($conn, $commentsArray, $id);

?>

<?php endforeach ?>

A: You can check this link, it explains how to make a div height depend by its content, the same thing can work with the width property (obviously it depends by the code you write).
Otherwise, if you don't like this solution, I have to ask you if you ever tried overflow-x: scroll; (width overflow) and/or overflow-y: scroll; (height overflow): these properties, with these values, allow you to adapt the divs with a specified size (like: width: 100px or also width: 100px), just to be able to scroll their content.
I hope I helped you to fix this issue.
By the way, I want to give you a tip about this community: to get faster and better questions you should give your CSS code, too.


text:
Q: ::slotted CSS selector for nested children in shadowDOM slot The CSS ::slotted selector selects children of the <slot> element.
However, when trying to select grandchildren like with ::slotted(*), ::slotted(*) *, or ::slotted(* *), the selector doesn't seem to take effect.

class MyElement extends HTMLElement {
  constructor() {
    super();
    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `

      <slot></slot>
    `;
  }
}
customElements.define('my-element', MyElement);
<my-element>

    Test

</my-element>

Note how the span doesn't get the border.
Is this expected behavior? I wasn't able to find concrete documentation for this.
If yes, is there a way to work around this?

A: styling ::slotted elements in shadowDOM

TL;DR

*

*::slotted Specs: https://drafts.csswg.org/css-scoping/#slotted-pseudo

*slotted content remains in light DOM, is reflected to a <slot> in shadow DOM

*::slotted(x) targets the lightDOM outer-Element (aka 'skin'), NOT the SLOT in shadowDOM

*::slotted(x) takes basic selectors

*Inheritable styles trickle into shadowDOM
https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/

*For the latest WHATWG discussion on SLOT and related topics, see

*

*https://github.com/whatwg/html/issues/6051#issuecomment-816971072
Participants: rniwa (Apple) , annvk (Mozilla), dominic (Google)

*https://github.com/WICG/webcomponents/issues/934#issuecomment-906063140
Interesting reads:

*

*A history of the HTML <slot> element by Jan Miksovsky

*Summary of positions on contentious bits of Shadow DOM — Web Components F2F on 2015-04-24

background
Yes, ::slotted() not styling nested elements is expected behavior.
The term slotted is counterintuitive,
it implies element lightDOM is moved to shadowDOM

slotted lightDOM is NOT moved, it remains.. hidden.. in lightDOM
the content (IF slotted) is reflected to a <slot></slot>

Or from Google Developer Documentation

,       .
 '   ;          .

I use the term reflected instead of render because render implies you can access it in shadowDOM.
You can not, because slotted content isn't in shadowDOM... only reflected from lightDOM.

Why :slotted has limited functionality
More advanced shadowDOM styling was tried.
WebComponents version 0 (v0) had <content> and ::content; but it was removed from the spec:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/content
The main takeway from the W3C standards discussions
(@hayatoito (Google team) here and here) is:

So in V1 we have :slotted: https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

Addition #1 : Performance if ::slotted allowed for complex selectors
From Mozilla developer Emilio:
source: https://github.com/w3c/webcomponents/issues/889

The performance issue is that it increments the amount of subtrees in
which every node needs to go look for rules that affect to them.
Right now the logic goes like: if you're slotted, traverse your slots
and collect rules in their shadow trees as needed. This is the code
This is nice because the complexity of styling the element
depends directly on the complexity of the shadow trees that you're
building, and it only affects slotted nodes.
If you want to allow combinators past slotted then every node would
need to look at its ancestor and prev-sibling chain and look at which
ones of them are slotted, then do that process for all their slots.
Then, on top, you also need to change the general selector-matching
code so that selectors that do not contain slotted selectors don't
match if you're not in the right shadow tree.
That's a cost that you pay for all elements, regardless of whether you
use Shadow DOM or ::slotted, and is probably just not going to fly.

So due to performance issues
:slotted( S ) got limited CSS selector functionality:

*

*► it only takes simple selectors for S. --> Basically anything with a space won't work

*► it only targets lightDOM 'skin'. --> In other words, only the first level
<my-element>

Hello World

    ....

    ....

</my-element>

*

*::slotted(h1) and ::slotted(p) works

*::slotted(.foo) works

*::slotted(span) (or anything deeper) will not work (not a 'skin' element)
Note: ::slotted([Simple Selector]) confirms to Specificity rules,
but (being simple) does not add weight to lightDOM skin selectors, so never gets higher Specificity.
You might need !important in some (rare) use cases.

  <slot></slot>
  <slot id=answer name=unanswered></slot>
</template>

<my-element>
  SLOTs are: <button>Cool</button> <button>Awesome</button> <button>Great</button>
  ?

  SUPER!

</my-element>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optimize MySQL Query - with a join within a sub select within a join Okay, so there is a slow query in SugarCRM that is causing significant issues when it runs back to back to back..., etc..  I've pasted the query below and I'm looking to see if there is any expert out there that might know of a better way to structure this query so that it runs in a fraction of a second as opposed to the 2+ seconds it takes now.
SELECT acl_actions.id,
   acl_actions.NAME,
   acl_actions.category,
   acl_actions.acltype,
   acl_actions.aclaccess,
   tt.access_override
FROM   acl_actions
   LEFT JOIN (SELECT acl_roles_users.user_id,
                     acl_roles_actions.action_id,
                     acl_roles_actions.access_override
              FROM   acl_roles_users
                     LEFT JOIN acl_roles_actions acl_roles_actions
                            ON acl_roles_actions.role_id =
                               acl_roles_users.role_id
                               AND acl_roles_actions.deleted = 0
              WHERE  ( acl_roles_users.user_id =
                       'XXXXXXXXX' )
                     AND ( acl_roles_users.deleted = 0 )) tt
          ON tt.action_id = acl_actions.id
WHERE  acl_actions.deleted = 0
ORDER  BY acl_actions.category ASC,
      acl_actions.NAME ASC;

Here's the results of EXPLAIN
+----+-------------+-------------------+------------+------+---------------------------------------------------------------+-----------------------+---------+------------------------------------------+------+----------+--------------------------+
| id | select_type | table             | partitions | type | possible_keys                                                 | key                   | key_len | ref                                      | rows | filtered | Extra                    |
+----+-------------+-------------------+------------+------+---------------------------------------------------------------+-----------------------+---------+------------------------------------------+------+----------+--------------------------+
|  1 | SIMPLE      | acl_actions       | NULL       | ref  | idx_del_category_name_acltype_aclaccess,idx_del_category_name | idx_del_category_name | 2       | const                                    | 3520 |   100.00 | Using index condition    |
|  1 | SIMPLE      | acl_roles_users   | NULL       | ref  | idx_acluser_id                                                | idx_acluser_id        | 145     | const                                    |    1 |   100.00 | Using where              |
|  1 | SIMPLE      | acl_roles_actions | NULL       | ref  | idx_acl_role_id,idx_del_override,idx_aclrole_action           | idx_del_override      | 147     | production.acl_roles_users.role_id,const |  312 |   100.00 | Using where; Using index |
+----+-------------+-------------------+------------+------+---------------------------------------------------------------+-----------------------+---------+------------------------------------------+------+----------+--------------------------+

CREATE TABLE
CREATE TABLE `acl_actions` (
  `id` char(36) NOT NULL,
  `date_entered` datetime DEFAULT NULL,
  `date_modified` datetime DEFAULT NULL,
  `modified_user_id` char(36) DEFAULT NULL,
  `created_by` char(36) DEFAULT NULL,
  `name` varchar(150) DEFAULT NULL,
  `category` varchar(100) DEFAULT NULL,
  `acltype` varchar(100) DEFAULT NULL,
  `aclaccess` int(3) DEFAULT NULL,
  `deleted` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_aclaction_id_del` (`id`,`deleted`),
  KEY `idx_category_name` (`category`,`name`),
  KEY `idx_del_category_name_acltype_aclaccess` (`deleted`,`category`,`name`,`acltype`,`aclaccess`),
  KEY `idx_del_category_name` (`deleted`,`category`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

CREATE TABLE `acl_roles_users` (
  `id` char(36) NOT NULL,
  `role_id` char(36) DEFAULT NULL,
  `user_id` char(36) DEFAULT NULL,
  `date_modified` datetime DEFAULT NULL,
  `deleted` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `idx_aclrole_id` (`role_id`),
  KEY `idx_acluser_id` (`user_id`),
  KEY `idx_aclrole_user` (`role_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

CREATE TABLE `acl_roles_actions` (
  `id` char(36) NOT NULL,
  `role_id` char(36) DEFAULT NULL,
  `action_id` char(36) DEFAULT NULL,
  `access_override` int(3) DEFAULT NULL,
  `date_modified` datetime DEFAULT NULL,
  `deleted` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `idx_acl_role_id` (`role_id`),
  KEY `idx_acl_action_id` (`action_id`),
  KEY `idx_del_override` (`role_id`,`deleted`,`action_id`,`access_override`),
  KEY `idx_aclrole_action` (`role_id`,`action_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4


text:
Q: Trying to make a loop which counts letters but not spaces I am trying to construct a simple programme which counts the number of letters in a user's input. My idea was to use a for loop which would loop for each letter in a string, increment a counter, and return the final counter total at the end. However, I do not want the programme to count spaces- I attempted to use the isalpha function to do this- but I seem to be formatting it incorrectly. Also, the way I tried to make the counter NOT increment for a space was with c = c, however, this also seems to be incorrect. Here is the code I have written so far:
int c = 0;

int main(void)
{
    string s = get_string("Input:  ");
    printf("Output: ");
    for (int i = 0; i < strlen(s); i++)
    {
    if( s[i] (isalpha))
        {
        c++;
        }
    else
        {
        c = c;
        }
    }
    printf("%i\n", c);
}

A: isalpha is effectively a function call. (It is a function call or a function-like macro.) A function call is written as name(), name(argument), or name(argument,…) according to whether it is passing zero, one, or more arguments. isalpha takes a single argument. That argument should be an unsigned char value. So you can call it as isalpha((unsigned char) s[i]). Your if statement should look like:
if (isalpha((unsigned char) s[i]))

Your program should also contain #include <ctype.h> to include the header that declares isalpha.

A: This record
s[i] (isalpha)

is incorrect and does not make a sense.
What you need is the following
size_t c = 0;

for ( size_t i = 0; s[i] != '\0'; i++ )
{
    if( isalpha( ( unsigned char )s[i] ) ) ++c;
}
printf("c = %zu\n", c );

Pay attention to that the function isalpha is declared in the header <ctype.h> that you have to include.


text:
Q: Cannot call member function, tried to do it properly still fails I implemented a new class (ProtoType) in my header file. Which looks like this:
class ProtoType : public Test
{
    public:
        uint32_t test();

};

class RealProtoType : public Real
{
    public:
        uint32_t real();

};

Then in C++ file I made this
uint32_t ProtoType::test()
{
    return 5;
}

uint32_t RealProtoType::real()
{

    uint32_t holder = ProtoType::test();

}

Then I get this error when compiling

error: cannot call member function 'uint32_t ProtoType::test()'
  without object    uint32_t ProtoType::test();

But I still fail, how can I resolve this?

A: Since ProtoType::test() is a non-static member function you need an object of type ProtoType to call the function upon:
uint32_t RealProtoType::real()
{
    ProtoType foo;
    uint32_t holder = foo.test();
    return 42;
}


text:
Q: Azure Data Factory: Dataset Dynamic DB Table name not resolving in Data Wrangling Flow I created a DataSet which points to a table in my database. The name of the table is set as dynamic content: @concat(dataset().db_prefix, '_Baseline_CIs'). This works when checking in the Dataset through 'Preview Data'. The table contents are shown.
BUT: When using the dataset in the Data Warngling Flow, the M-query fails with the following error:
Expression.Error: The key didn't match any rows in the table.
AdfDoc = Sql.Database("oedudigital.database.windows.net", "IntegratedEnvironments"),
  InputTable = AdfDoc{[Schema = "dbo", Item = "undefined"]}[Data]

As you can see, the table name concatenation has returned 'undefined'. Is this a bug?
BR, Denis

A: If I understand it right you have the DataSet which is parameter , at least that was the case on my side . Under the AdFResouce you will see the dataset name . You will have to pass the table name as
AdfDoc{[Schema = "dbo", Item = "TableName"]}[Data]
and then it will bring in the records .


text:
Q: Add order item image only if the product exist on Woocommerce order view On woocommerce My account view order pages I was able to add the product image using this answer code:
Add the product image to Woocommerce my account order view
But I have an issue related to imported orders where the product doesn't exist.
So this make an error with a blank page, when viewing those orders.
Any idea on how to avoid this problem?

A: So If I understand well, the products in the order might not exist in Woocommerce sometimes. This code version test if the product exist and if not it only return the order item name.
Try the following:
// Display the product thumbnail in order view pages
add_filter( 'woocommerce_order_item_name', 'display_product_image_in_order_item', 20, 3 );
function display_product_image_in_order_item( $item_name, $item, $is_visible ) {
    // Targeting view order pages only
    if( is_wc_endpoint_url( 'view-order' ) ) {
        // Get the WC_Product object (from order item)
        $product   = $item->get_product();

        // Testing if the product exist in Woocommerce <== UPDATE
        if( $product && is_object( $product ) ) {
            // Get the product thumbnail (from product object)
            $thumbnail = $product->get_image(array( 36, 36));
            // Avoiding empty thumbnail (updated)
            if( $product->get_image_id() > 0 )
                $item_name = '
' . $thumbnail . '
' . $item_name;
        } else {
            // When product doesn't exist, we get the name from the order item (with no thumbnail)
            $item_name = $item->get_name();
        }
    }
    return $item_name;
}

Code goes in function.php file of your active child theme (or active theme). I hope it will work.


text:
Q: R anesrake package producing NA in summary statistics table The r anesrake package is listing na in its summary statistics table instead of providing percentages. A reproducible example is pasted below. I cannot figure out what is causing this.
data<-NULL
library(anesrake)
#Dummy data generation
data$Q35Gender<-c(1,1,1,2,2,2,2,2,2,2,2,2)
data$ID<-c(1,2,3,4,5,6,7,8,9,10,11,12)
data<-as.data.frame(data)

#Set weight targets
gentarg<-c(0.5094,0.4906)
names(gentarg)<-c("Male","Female")
targets<-list(gentarg)

#Names
names(targets)<-c("Q35Gender")

#Calculate weights
outsave <- anesrake(targets, data, caseid=data$ID,verbose=FALSE,force1=TRUE,type="nolim",cap = 4)

#Summary to check
summary(outsave)

A: Anesrake seems to require that the variables are factors or logical, so I've set Q35Gender to factor.
data<-NULL
library(anesrake)
#Dummy data generation
data$Q35Gender<-c(1,1,1,2,2,2,2,2,2,2,2,2)
data$ID<-c(1,2,3,4,5,6,7,8,9,10,11,12)
data<-as.data.frame(data)

#Set as factor

data$Q35Gender<-as.factor(data$Q35Gender)
levels(data$Q35Gender)<-c("Male","Female")

#Set weight targets
gentarg<-c(0.7,0.3)
names(gentarg)<-c("Male","Female")
targets<-list(gentarg)

#Names
names(targets)<-c("Q35Gender")

#Calculate weights

outsave <- anesrake(targets, data, caseid=data$ID,verbose=FALSE,force1=TRUE,type="nolim",cap = 4)
#Summary - check that it shows the % distribution for unweighted and weighted (not NA)
summary(outsave)


text:
Q: Check Node in TreeView Control in C# How can I check that the selected Node is a File or directory in a TreeView Control in C#?
I am working on window form in C#.
I can check through the file extension but there are so many file extensions so it makes for a lengthy code. Can any body give me a small method for this?

A: You can use the node.GetType() property of the particular node to find out that it is directory or file. I.e.:
if (tree.SelectedNode.GetType() == typeof(FileNode))

Hope it helps.

A: You can use Tag property of the TreeNode to store information about node type - for example store there enum value, object or any other type that will be useful for you.


text:
Q: "Assign to Indexed" C++ Operator Overload Brainteaser I'm writing some funky audio code and trying to use operator overloading to create a very clean and simple API. It's become of a bit of a C++ brainteaser...
What I want would be solved immediately by an "assign to indexed" sort-of-compound operator which I'm pretty sure doesn't exist. Might anyone have any insights on whether the following is possible?
I have 2 object types....
Frames frames;  // audio data, contains 1 buffer (float *) for each channel
Sample s;       // a single sample, 1 float for each channel

So Sample is kind of an orthogonal slice of Frames, ie Frames is NOT an array of Sample's. If you know audio, Frames is "non-interleaved", and Sample is.
The Holy Grail...
s = frames[1];    // statement 1. gets a copy of values in frame 1
frames[1] = s;    // statement 2. replace values in frame 1 with those in Sample s

The first one is no problem:
// in class Frames...
Sample& operator[](size_t idx) const {
    Sample s;
    s.left = _leftCh[idx];
    s.right = _rightCh[idx];
    return s;
}

But the second assignment is tricky since the above function creates a copy of the data rather than a reference.
I've tried defining Sample with references...
class Sample {
public:
    float& L;
    float& R;
    Sample(float& lt, float& rt) : L(lt), R(rt) {};
}

But then you can't do something as simple as...
Sample s(0.0, 0.0);
s.left = 0.2;

Another potential solution would be to have the two statements call two different operator overloads. Then enforce that statement 2 calls this [] overload which returns a new Frames object pointing to the values rather than a Sample object:
Frames& operator[](size_t idx) {
    // Construct an new Frames object whose which
    // points to value idx in each channel
    Frames f(_size - idx);
    f._leftCh = &_leftCh[idx];
    f._rightCh = &_rightCh[idx];
    return f;
}

And then add an assignment operator to Frames which just replaces the first value...
Frames& operator=(const Sample& s) {
    _leftCh[0] = s.left;
    _rightCh[0] = s.right;
    return *this;
}

The compiler informs me that methods must differ by more than just the return type, but this is resolved by having const after the method name for one of the operator[] overloads.  Might there be a clue here?  Is there a way to have statement 1 call Sample& operator[]... and statment 2 call Frames& operator[]....  Or is there a much better way of accomplishing this??
Thanks for your patience if you've made it this far! Much appreciated...

A: How about this:
class SampleRef {
  float &left_, &right_;

public:
  SampleRef(float& left, float& right)
    : left_(left), right_(right)
  {}

  operator Sample () {
    return Sample(left_, right_);
  }

  SampleRef& operator= (const Sample &arg) {
    left_ = arg.left;
    right_ = arg.right;
    return *this
  }
};

SampleRef Frames::operator[] (size_t idx) {
  return SampleRef(_leftCh[idx], _rightCh[idx]);
}

You can of course also add a const overload of operator[] which will simply return a Sample:
Sample Frames::operator[] (size_t idx) const {
  return Sample(_leftCh[idx], _rightCh[idx]);
}

A: Have you tried without overloading just to work out the details? e.g. sample = frame.getSample(); frame.setSample(sample); Once the details are worked out to your satisfaction, then you can add the syntactic sugar and overload the [] and = operators.
It looks like you want to maintain a reference to the original Sample, so that for example:
sample.right = oldR;
sample.left = oldL;
f[x] = sample;

sample.right = newR;
sample.left = newL;
newSample = f[x];

assert(sample.right == newSample.right && sample.left == newSample.left);

Is this correct? If so, I don't think you can do that, because you "break" up your sample to insert it into the frame, so you lose the original connection.


text:
Q: How do you use a function as a parameter in a function? I am trying to use a function as a parameter in another function but I keep getting an error. Can you guys please take a look at my code.
#Program used to reverse the order of a string.

sentence = input("Write a sentence. After you click enter it will be returned in reverse order. ")
userInputList = [ ]
reverseInputList = [ ]

#remove any periods from the sentence.
def remove(sentence):
  stripped = sentence.replace(".", "")
  return stripped

#print string in reverse order
def convertList(stripped):
  userInputList = stripped.split()
  reverseInputList = userInputList[::-1]

  for i in range(len(reverseInputList)):
   print (reverseInputList[i], end=" ")

remove(sentence)

convertList(remove())

A: I don't know want error you get but I see mistake:
you have to assign result from remove(sentence) to variable and use this result in convertList()
result = remove(sentence)

convertList(result)

or you have to use function with argument remove(sentence) directly in convertList()
convertList(remove(sentence))


text:
Q: Listen to ArcGIS Pro project save event Is there a way to listen for the project save event in ArcGIS Pro? I need to check for something before allowing or denying the save event.

A: This sample subscribes to project open, saving and saved events.
Make sure to unsubscribe when no longer needed.
namespace N {
    public class X {
       private SubscriptionToken _eventToken = null;
       private SubscriptionToken _eventToken2 = null;
       private SubscriptionToken _eventToken3 = null;

       public X() {
           Project proj = Project.Current;
           if (proj == null)
           {
             // Wait for project to open.
             _eventToken = ProjectOpenedEvent.Subscribe(OnProjectInitialized);
           }
           else
           {
               ProjectEventArgs projEventAgs = new ProjectEventArgs(proj);
               OnProjectInitialized(projEventAgs);
           }
               _eventToken2 = ProjectSavingEvent.Subscribe(OnProjectSaving);
               _eventToken3 = ProjectSavedEvent.Subscribe(OnProjectSaved);
      }

      private void OnProjectInitialized(ProjectEventArgs project)
      {
          NotifyUser("Project has loaded", false);

          if (_eventToken != null)
          {
              ProjectOpenedEvent.Unsubscribe(_eventToken);
              _eventToken = null;
          }
      }

      private async Task<bool> OnProjectSaving(ProjectEventArgs project)
      {
          return await QueuedTask.Run(() =>
          {
              if (MessageBox.Show("Are you sure?", "Save Project?",
                            MessageBoxButton.OKCancel) == MessageBoxResult.OK)
              {
                  return true;
              }
              return false;
          });
      }

      private void OnProjectSaved(ProjectEventArgs project)
      {
          MessageBox.Show("Project was saved");
      }
   }
}

Please note that when I tested this, the project was saved regardless of whether OnProjectSaving() returned true or false. This could be a bug in the framework, but is much more likely to be a bug in my code or understanding.


text:
Q: Android dropbox sdk logout feature error I am using dropbox android sdk to integrate dropbox with my app and I want to logout from dropbox from my Application.  From official documentation and dropbox forums the  only way to logout is to call unlink() on the dropbox session and clear your access token and secret from SharedPreference.
mApi.getSession().unlink();
//clear dropbox accesstoken and secret keys from SharedPreference
clearKeys();

Well the above call is not doing anything. When I try to login later
AppKeyPair appKeyPair   =   new AppKeyPair(AppConstants.DROPBOX_API_KEY,AppConstants.DROPBOX_API_SECRET);
AndroidAuthSession session;
session             =   new AndroidAuthSession(appKeyPair, ACCESS_TYPE);

login screen is not getting shown, instead, the screen where api asks user permission to access a folder to dropbox (which normally shows after login screen) is shown instead.  Is there any way to logout from dropbox?

A: The problem here is when the application reaches onResume() function. Even if you are logged out, the dropbox api asks the browser to login, and it responds with keys. It seems the browser had cached the login. Try to clear web browser cache when calling logout function.

A: Because the unlink() call is purely client side work, it is not equal to unlink th e application with user account which you can do on Web under the "settings" page.
Here is the code snippet
@Override
public boolean isLinked() {
    return (oauth1AccessToken != null) || (oauth2AccessToken != null);
}

@Override
public void unlink() {
    oauth1AccessToken = null;
    oauth2AccessToken = null;
}


text:
Q: $\text{Determinant}=(\sum \text{Determinant})^2$ Denote by $\delta_{n-1}=(n-1,n-2,\dots,1,0,0,\dots)$ the staircase partition and the embedded partition
$\lambda=(\lambda_1,\lambda_2,\dots)\subset\delta_{n-1}$.

QUESTION 1. Is this true?
  $$\det\left[\binom{i+j-1}{2j-i-1}+\binom{i+j-2}{2j-i-2}\right]_{i,j=1}^n=
\left(\sum_{\lambda\,\subset\,\delta_{n-1}}
\det\left[\binom{n-i}{\lambda_j-j+i}\right]_{i,j=1}^n\right)^2.$$

A diagonal version of this (relative to the RHS) takes the form:

QUESTION 2. Is this true?
  $$\det\left[\binom{i+j-2}{2j-i-1}\right]_{i,j=1}^n=
\sum_{\lambda\,\subset\,\delta_{n-1}}
\left(\det\left[\binom{n-i}{\lambda_j-j+i}\right]_{i,j=1}^n\right)^2.$$


text:
Q: Uniqueness of the characteristic polynomial With a given linear transformation, does all the matrix representation of the transformation have the same characteristic polynomial?
Two similar matrices have the same  characteristic polynomial do two matrices representation of the same linear transformation are similar?

A: Yes they have the same characteristic polynomial since they are similar:
$$\det(PAP^{-1}-xI)=\det(PAP^{-1}-xPP^{-1})=\det(P(A-xI)P^{-1})\\=\det(P)\det(P^{-1})\det(A-xI)=\det(A-xI).$$

A: Yes, because if $A$ is the matrix of endomorphism $u$ in some basis, it is the determinant of endomorphism $u-\lambda \operatorname{id}$, and the determinant of an endomorphism is independant of the basis.


text:
Q: iText in android priducing Could not find class 10-02 05:36:39.589: E/dalvikvm(2570): Could not find class 'org.bouncycastle.cms.CMSEnvelopedData',
referenced from method com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj

The logcat shows this kind of error, I've been googling around and still can't find the solution.
here is the source code:

MainActivity.java

import java.io.FileOutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            GenerarPDF();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
        public void GenerarPDF()throws Exception{
            Document document = new Document();
            String file = Environment.getExternalStorageDirectory().getPath() + "/Hello.pdf";
            PdfWriter.getInstance(document,new FileOutputStream(file));
            document.open();
            Paragraph p = new Paragraph("Hello PDF");
            document.add(p);
            document.close();
        }
}

here is my manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.samplepdf"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

can anyone point out a solution to this problem?

A: Seems like you're not using the offical Android port of iText. The official port doesn't use BouncyCastle. It uses SpongyCastle to avoid clashes with the old BouncyCastle version that is shipped with Android. Use the official port and the problem will disappear.


text:
Q: django.db.utils.OperationalError: FATAL: database does not exist (postgres / deploy to digitalocean) I am trying to deploy a project with digital ocean. I followed the instructions found at https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
Some of the important ones:
I ran:
postgres=# CREATE DATABASE jobzumoDB;
CREATE DATABASE

then:
postgres=# CREATE USER admin WITH PASSWORD '123';
CREATE ROLE
postgres=# GRANT ALL PRIVILEGES ON DATABASE jobzumoDB  TO admin;
GRANT

set the following in settings.py:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'jobzumoDB',
        'USER':'admin',
        'PASSWORD':'123',
        'HOST':'localhost',
        'PORT':'',
    }

then tried to run:
 ~/jobzumo/manage.py makemigrations

and got:
 File "/home/justin/jobzumo/env/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect
        conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    django.db.utils.OperationalError: FATAL:  database "jobzumoDB" does not exist

Two things:
ALLOWED_HOSTS = ['jobzumo.com', '142.93.184.125']

I have not yet connect jobzumo.com to digital ocean, but the IP address was copied from my droplet.
Also, I ran: pip install django gunicorn psycopg2 (from digitial ocean)
but a tutorial on youtube said it was very important to now
install psycopg2-binary instead, however, I did not do this as the video was veering far from digital ocean's tutorial.
Thanks for any help, after starting to understand django I didn't think deploying would be this much of a headscratcher.

A: Formalizing what we worked out in the comments as an answer, when you give postgres an unquoted string as an identifier, it forces it to lower-case. see this similar answer from pgsql-general mailing list. So the actual name of the database created by the command CREATE DATABASE jobzumoDB; is jobzumodb. to create a database named jobzumoDB it's necessary to use quotes, as in CREATE DATABASE "jobzumoDB";

A: Use:
NAME': 'jobzumodb',
Instead of:
NAME': 'jobzumoDB',


text:
Q: Socket.io + Express + Testing not working, but why? My server code:
var express = require("express");
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);

function init() {
    server.listen(80, "0.0.0.0");
    app.get("/", function (req, res) {
        res.sendFile(__dirname + "/public/index.html");
    });
    app.use(express.static("public"));
}

Test file:
var expect = require('chai').expect;
var io     = require('socket.io-client');
var SocketTester = require('socket-tester');

var app = require('../server');

var socketUrl = 'http://127.0.0.1:3000';

var options = {
    transports: ['websocket'],
    'force new connection': true
};

var socketTester = new SocketTester(io, socketUrl, options);

describe('Sockets', function () {
    var client1, client2, client3;
    it('should send and receive a message', function (done) {
        client1 = io.connect(socketUrl, options);
    });
});

The test file gives me an error:
Error: listen EADDRINUSE 0.0.0.0:80
    at Object.exports._errnoException (util.js:856:11)
    at exports._exceptionWithHostPort (util.js:879:20)
    at Server._listen2 (net.js:1231:14)
    at listen (net.js:1267:10)
    at net.js:1376:9
    at node.js:933:3

How could I reach out to the server using the test file?
I'm not really sure what happens here:
var server = require("http").Server(app);
var io = require("socket.io")(server);

But if I'm not mistaken this way the HTTP server only sees the socket.io, I guess the problem should be around here somewhere.

A: Your port 80 is already in use by another application. Try to switch the node server to 3000 and then connect to it. Alternatively you can close the application listening on 80 - usually a webserver application.
In case it isn't clear, I'm referring to the following:
server.listen(3000); // There's no need to specify the host when you're running it on localhost.

A: I was able to get the following code working for my app
I borrowed the port configuration from chai-http
I believe this code finds a port which is not in use
//During the test the env variable is set to test
process.env.NODE_ENV = 'test';

var chai = require('chai');
var expect = chai.expect
var http = require('http');
var https = require('https');

var User = require.main.require('models/User');

// https://gist.github.com/branneman/8048520#7-the-wrapper
var app = require.main.require('app');

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

// From chai-http
function serverAddress (server, path) {
  if ('string' === typeof server) {
    return server + path;
  }
  var addr = server.address();
  if (!addr) {
    server.listen(0);
    addr = server.address();
  }
  var protocol = (server instanceof https.Server) ? 'https' : 'http';
  // If address is "unroutable" IPv4/6 address, then set to localhost
  if (addr.address === '0.0.0.0' || addr.address === '::') {
    addr.address = '127.0.0.1';
  }
  return protocol + '://' + addr.address + ':' + addr.port + path;
}

var socketURL = serverAddress(server,'/')

var options ={
  transports: ['websocket'],
  'force new connection': true
};

/**
 * Enable Socket.IO
 */
var io = require('socket.io')(server);

require('../../sockets')(io);

var ioClient = require('socket.io-client');

describe('Players Sockets', (done) => {

    var bonzo, magoo, fido;

    beforeEach((done) => { //Before each test we reset the database
      User.query().del().then(() => {
        var bonzoPromise = new User({name: 'bonzo', authtype: 'github', authid: '12345678'}).save();
        var magooPromise = new User({name: 'magoo', authtype: 'github', authid: '88345678'}).save();
        var fidoPromise = new User({name: 'fido', authtype: 'github', authid: '93231678'}).save();

        Promise.all([bonzoPromise,magooPromise,fidoPromise])
          .then((users)=>{
            bonzo = users[0];
            magoo = users[1];
            fido = users[2];
            done();
          })
      })
    });

  it('Should broadcast updated players when user disconnects', function(done){
    var clientFido = ioClient.connect(socketURL, options);

    clientFido.on('connect', function(data){
      clientFido.emit('whoami', { id: fido.id, name: fido.get('name') });

      var clientBonzo = ioClient.connect(socketURL, options);

      clientBonzo.on('connect', function(data){

        clientBonzo.emit('whoami', { id: bonzo.id, name: bonzo.get('name') });

        var clientMagoo = ioClient.connect(socketURL, options);

        clientMagoo.on('connect', function(data){
          clientMagoo.emit('whoami', { id: magoo.id, name: magoo.get('name') });

          clientMagoo.on('players', function(message){
            if(message.players.length < 3){ return; } // Ignore our own connect messages
            expect(message.players).to.be.a('array');
            expect(message.players.length).to.eq(3);
            expect(message.players.map((player)=>{ return player.name})).to.include.members([bonzo.get('name'), magoo.get('name'), fido.get('name')]);

            clientBonzo.on('players', function(message){
              expect(message.players).to.be.a('array');
              expect(message.players.length).to.eq(2);
              expect(message.players.map((player)=>{ return player.name})).to.include.members([bonzo.get('name'), fido.get('name')]);

              clientBonzo.disconnect();
              clientFido.disconnect();

              done();
            });

            clientMagoo.disconnect();
          });
        });
      });
    });
  });

  it('Should broadcast updated players when user connects', function(done){
    var clientFido = ioClient.connect(socketURL, options);

    clientFido.on('connect', function(data){
      clientFido.emit('whoami', { id: fido.id, name: fido.get('name') });

      clientFido.on('players', function(message){
        expect(message.players).to.be.a('array');
        if(message.players.length == 1){ return; } // Ignore our own connect message
        expect(message.players.length).to.eq(2);
        expect(message.players.map((player)=>{ return player.name})).to.include.members([bonzo.get('name'), fido.get('name')]);

        clientBonzo.disconnect();
        clientFido.disconnect();
        done();
      });

      var clientBonzo = ioClient.connect(socketURL, options);
      clientBonzo.on('connect', function(data){
        clientBonzo.emit('whoami', { id: bonzo.id, name: bonzo.get('name') });
      });
    });
  });

});


text:
Q: Making Methods All Static in Class I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in the class or make the class a singleton so that you don't have to use the keyword new for calling methods in this BL class.
I assume this is common and good practice?  Basic OOP?  I just want to see people's opinion on that.
I think basically he's saying since there's no state, no need for the methods to be instance methods.
I'm not sure about making it a singleton every time as an option in this case...is that some sort of pattern or good advice he's giving me?
Here's the class I'm talking about (please do not repost any of this code in this thread, this is private): http://www.elbalazo.net/post/class.txt

A: There's no absolute rule for when a class should be static. It may have no state, but you may need it for reference equality or locking. Classes should be static when their purpose fits it being implemented as a static class. You shouldn't follow hard-and-fast rules in these situations; use what you 'feel' is right.
Having no state makes it a candidate for static-ness, but look at what it's being used for before arbitarily refactoring it.

A: A lack of state alone is no reason to make methods static. There are plenty of cases where a stateless class should still have instance methods. For example, any time you need to pass specific implementations of some logic between routines, it's much easier to do it with classes that have instance methods, as it allows us to use interfaces:
interface IConnectionProvider
{
    object GetConnectedObject();
}

We could have a dozen implementations of the above, and pass them into routines that require an IConnectionProvider. In that case, static is a very clumsy alternative.
There's nothing wrong with having to use new to use a method in a stateless class.

A: As long as you don't need to create any abstraction from your class then static methods are fine.  If your class needs to be mocked or implement any sort of interface then you're better off making the class a singleton, since you cannot mock static methods on classes.  You can have a singleton implement an interface and can inherit instance methods from a singleton whereas you cannot inherit static methods.
We generally use singletons instead of static methods to allow our classes to be abstracted easily.  This has helped in unit testing many times since we've run into scenarios where we wanted to mock something and could easily do so since the behavior was implemented as instance methods on a singleton.

A: There is very little downside to calling new and constructing a class reference, especially if the class has no state.  Allocations are fast in .NET, so I wouldn't use this alone as a justification for a class to be static.
Typically, I feel a class should be made static if the class has no specific context - if you're using the class just as a placeholder for "utility" methods or non-context specific operations, then it makes sense to be a static class.
If that class has a specific need for context, and a meaning in a concrete sense, then it probably does not justify being static, even if it has no state (although this is rare).  There are times where the class purpose is defined by its reference itself, which provides "state" of a sort (the reference itself) without any local variables.
That being said, there is a big difference between a static class and a singleton.  A singleton is a different animal - you want to use it when you need an instance, but only one instance, of the class to be created.  There is state in a singleton, but you are using this pattern to enforce that there is only a single copy of the state.  This has a very different meaning, and I would highly recommend avoiding using a singleton just to prevent needing to "call new".

A: Utility classes are often composed of independant methods that don't need state. In that case it is good practice to make those method static. You can as well make the class static, so it can't be instantiated.
With C# 3, you can also take advantage of extension methods, that will extend other classes with those methods. Note that in that case, making the class static is required.
public static class MathUtil
{
    public static float Clamp(this float value, float min, float max)
    {
        return Math.Min(max, Math.Max(min, value));
    }
}

Usage:
float f = ...;
f.Clamp(0,1);

A: I can think of lots of reasons for a non-static class with no members.  For one, it may implement an interface and provide/augment behavior of another.  For two, it may have virtual or abstract methods that allow customization.  Basically using 'static' methods is procedural programming at it's worst and is contrary to object-oriented design.
Having said that, often small utilities routines are best done with a procedural implementation so don't shy away if it make sense.  Consider String.IsNullOrEmpty() a great example of a procedural static routine that provides benefit in not being a method.  (the benefit is that it can also check to see if the string is null)
Another example on the other side of the fence would be a serialization routine.  It doesn't need any members per-say.  Suppose it has two methods Write(Stream,Object) and object Read(Stream).  It's not required that this be an object and static methods could suffice; however, it make sense to be an object or interface.  As an object I could override it's behavior, or later change it's implementation so that it cached information about the object types it serialized.  By making it an object to begin with you do not limit yourself.

A: Most of the time it's OK to make the class static.  But a better question is why do you have a class without state?
There are very rare instances where a stateless class is good design.  But stateless classes break object oriented design.  They are usually a throwback to functional decomposition (all the rage before object oriented techniques became popular).  Before you make a class static, ask yourself whether the data that it is working on should be included int he class or whether all of the functionality in the utility class shouldn't be broken up between other classes that may or may not already exist.

A: Make sure that you have a good reason to make class static.
According to Framework Design Guidelines:

Static classes should be used only as
  supporting classes for the
  object-oriented core of the framework.
DO NOT treat static classes as a miscellaneous bucket.
There should be a clear charter for
  the class.

A: Static Class, Static Methods and Singleton class are three different concepts. Static classes and static methods are usually used to implement strictly utility classes or making them stateless and hence thread-safe and conncurrently usable.
Static classes need not be Singletons. Singleton means there is only one instance of a class, which is otherwise instantiable. It is most often used to encapsulate the physical world representation of a truly single instance of a resource, such as a single database pool or a single printer.
Coming back to your colleague's suggestion -- I tend to agree it is a sound advice. There is no need to instantiate a class if the methods are made static, when they can be static. It makes the caller code more readable and the called methods more easily usable.

A: It sounds like you're talking about a strictly Utility class, in which case there's really no reason to have seperate instances.
Make those utility methods static. You can keep the class as a regular object if you'd like (to allow for the future addition of instance methods/state information).


text:
Q: Semiconducting properties of diamond imperfect crystals Suppose we want to make a diamond crystal and during the process point defects(lattice gaps) are created.

Which is the energy of the electrons?(red circles)Can we deliberately create those point defects in order to create electron donor atoms or to give diamond semiconducting properties?


text:
Q: Flutter pressing back button pops up previous snackBar from Login page again I have a LoginPage in Flutter. After login, it shows a small snackbar with "success" or "failure.." if password is wrong, then it navigates to the todo list.
When I now press the "back" button on an Android device, it navigates back to the login screen. However, there is still the snackbar popping up and saying "Login successful, redirecting..", and also, my textfields are not emptied and still have the values from the first login, why? That should not happen, but I cannot figure out why that is... here is my code:
import 'package:flutter/material.dart';
import 'package:todoey_flutter/components/rounded_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todoey_flutter/util/file_handler.dart';
import 'package:provider/provider.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  String username;
  String password;
  String hashedPW;
  // Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  var _nameController = TextEditingController();
  var _pwController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    CryptOid cy = Provider.of<CryptOid>(context, listen: true);
    FileHandler fh = Provider.of<FileHandler>(context, listen: true);
    return Scaffold(
      backgroundColor: Colors.white,
      body: Builder(
        builder: (BuildContext scaffoldBuildContext) {
          return Container(
            //inAsyncCall: isSpinning,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 34.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  /*
                Flexible(
                  child: Hero(
                    tag: 'logo',
                    child: Container(
                      height: 200.0,
                      child: Image.asset('images/logo.png'),
                    ),
                  ),
                ),*/
                  SizedBox(
                    height: 48.0,
                  ),
                  TextField(
                    controller: _nameController,
                    style: TextStyle(color: Colors.black54),
                    onChanged: (value) {
                      //Do something with the user input.
                      username = value.toLowerCase();
                    },
                    decoration: InputDecoration(
                      hintText: 'Enter your username',
                    ),
                  ),
                  SizedBox(
                    height: 8.0,
                  ),
                  TextField(
                    controller: _pwController,
                    obscureText: true,
                    style: TextStyle(color: Colors.black54),
                    onChanged: (value) {
                      //Do something with the user input.
                      password = value;
                    },
                    decoration: InputDecoration(
                      hintText: 'Enter your password',
                    ),
                  ),
                  SizedBox(
                    height: 24.0,
                  ),
                  RoundedButton(
                    title: 'Login',
                    colour: Colors.lightBlueAccent,
                    onPressed: () async {
                      Scaffold.of(scaffoldBuildContext).removeCurrentSnackBar();

                      print("user: $username, pw: $password");
                      if ((username != '' && username != null) && (password != '' && password != null)) {
                        SharedPreferences prefs = await SharedPreferences.getInstance();
                        // cy.test();
                        if ((username != '' && username != null) && prefs.containsKey(username)) {
                          hashedPW = prefs.getString(username);
                          bool decryptPW = await cy.deHash(hashedPW, password);
                          if (decryptPW) {
                            cy.setUsername(username);
                            fh.setUser(username);
                            prefs.setString('activeUser', username);

                            Scaffold.of(scaffoldBuildContext).showSnackBar(
                              SnackBar(
                                content: Text("Login successful! redirecting.."),
                              ),
                            );

                            Navigator.pushNamed(context, 'taskScreen');
                          } else {
                            Scaffold.of(scaffoldBuildContext).showSnackBar(
                              SnackBar(
                                content: Text("Wrong password for user $username!"),
                              ),
                            );
                          }
                        } else {
                          String hashedPW = await cy.hashPW(password);
                          prefs.setString('activeUser', username);
                          prefs.setString(username, hashedPW);
                          cy.setUsername(username);
                          fh.setUser(username);

                          Scaffold.of(scaffoldBuildContext).showSnackBar(
                            SnackBar(
                              content: Text("User created successful! redirecting.."),
                            ),
                          );
                          Navigator.pushNamed(context, 'taskScreen');

                          //prefs.setString(username, hashedPW);
                        }
                        _nameController.clear();
                        _pwController.clear();
                      } else {
                        Scaffold.of(scaffoldBuildContext).showSnackBar(
                          SnackBar(
                            content: Text("User and password may not be empty.."),
                          ),
                        );
                        _nameController.clear();
                        _pwController.clear();
                        return;
                      }
                    },
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

A: You should create a ScaffoldState GlobalKey then assign the to the scaffold.
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: Container());
  }

The use the key to showSnackBar
void _showInSnackBar(String value) {
    _scaffoldKey.currentState
        .showSnackBar(new SnackBar(content: new Text(value)));
  }

So your full code would look like this:
import 'package:flutter/material.dart';
import 'package:todoey_flutter/components/rounded_button.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:todoey_flutter/util/file_handler.dart';
import 'package:provider/provider.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  String username;
  String password;
  String hashedPW;
  // Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  var _nameController = TextEditingController();
  var _pwController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    CryptOid cy = Provider.of<CryptOid>(context, listen: true);
    FileHandler fh = Provider.of<FileHandler>(context, listen: true);
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      body: Builder(
        builder: (BuildContext scaffoldBuildContext) {
          return Container(
            //inAsyncCall: isSpinning,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 34.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  /*
                Flexible(
                  child: Hero(
                    tag: 'logo',
                    child: Container(
                      height: 200.0,
                      child: Image.asset('images/logo.png'),
                    ),
                  ),
                ),*/
                  SizedBox(
                    height: 48.0,
                  ),
                  TextField(
                    controller: _nameController,
                    style: TextStyle(color: Colors.black54),
                    onChanged: (value) {
                      //Do something with the user input.
                      username = value.toLowerCase();
                    },
                    decoration: InputDecoration(
                      hintText: 'Enter your username',
                    ),
                  ),
                  SizedBox(
                    height: 8.0,
                  ),
                  TextField(
                    controller: _pwController,
                    obscureText: true,
                    style: TextStyle(color: Colors.black54),
                    onChanged: (value) {
                      //Do something with the user input.
                      password = value;
                    },
                    decoration: InputDecoration(
                      hintText: 'Enter your password',
                    ),
                  ),
                  SizedBox(
                    height: 24.0,
                  ),
                  RoundedButton(
                    title: 'Login',
                    colour: Colors.lightBlueAccent,
                    onPressed: () async {
                      _scaffoldKey.currentState.removeCurrentSnackBar();

                      print("user: $username, pw: $password");
                      if ((username != '' && username != null) &&
                          (password != '' && password != null)) {
                        SharedPreferences prefs =
                            await SharedPreferences.getInstance();
                        // cy.test();
                        if ((username != '' && username != null) &&
                            prefs.containsKey(username)) {
                          hashedPW = prefs.getString(username);
                          bool decryptPW = await cy.deHash(hashedPW, password);
                          if (decryptPW) {
                            cy.setUsername(username);
                            fh.setUser(username);
                            prefs.setString('activeUser', username);

                            _showInSnackBar("Login successful! redirecting..");

                            Navigator.pushNamed(context, 'taskScreen');
                          } else {
                            _showInSnackBar(
                                "Wrong password for user $username!");
                          }
                        } else {
                          String hashedPW = await cy.hashPW(password);
                          prefs.setString('activeUser', username);
                          prefs.setString(username, hashedPW);
                          cy.setUsername(username);
                          fh.setUser(username);

                          _showInSnackBar(
                              "User created successful! redirecting..");
                          Navigator.pushNamed(context, 'taskScreen');

                          //prefs.setString(username, hashedPW);
                        }
                        _nameController.clear();
                        _pwController.clear();
                      } else {
                        _showInSnackBar("User and password may not be empty..");
                        _nameController.clear();
                        _pwController.clear();
                        return;
                      }
                    },
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  void _showInSnackBar(String value) {
    _scaffoldKey.currentState
        .showSnackBar(new SnackBar(content: new Text(value)));
  }
}


text:
Q: Get load time of javascript and css files for a website in chrome extension I am a beginner with chrome extension development. I am trying to create and extension which will fetch the javascript and CSS file load time  for a particular website and display in the chrome extension popup.
However, I am unsure about the CHROME.API to achieve it
Please kindly suggest

A: You can fetch the HAR log using this
chrome.devtools.network.getHAR(function callback)

What are HAR logs?
A HAR file contains a JSON data structure that describes the network "waterfall", which also contains the loading time of every resource of that page.
So you will need to parse the HAR JSON, extract time for the js and css files.
More on HAR structure : http://www.softwareishard.com/blog/har-12-spec/


text:
Q: How to create GUI with text links and tabs I want to create a UI like http://www.ndtv.com/static/images/iphone/motorola_droid.jpg, where extra links are below the tabs. How can we achieve this?
I already made tabs but not understanding how to add this text view with this.

A: Try it like the XML below.
    <?xml version="1.0" encoding="utf-8"?>

    <TabHost
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/background_retinav2">

            <LinearLayout
                android:layout_gravity="center"
                android:foregroundGravity="bottom"
                android:background="@color/white"
                android:id="@+id/rl_1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <HorizontalScrollView
                    android:paddingTop="8dp"
                    android:id="@+id/gv"
                    android:layout_width="wrap_content"
                    android:layout_marginTop="0dp"
                    android:layout_height="wrap_content"
                    android:background="#ffffff"
                    android:scrollbars="none"
                    android:layout_weight="1"
                    android:foregroundGravity="bottom">

                    <TextView
                        android:text="Top Stories"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"></TextView>

                    <TextView
                        android:text="News"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>

                    <LinearLayout
                        android:id="@+id/san_tag"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                    </LinearLayout>
                </HorizontalScrollView>
            </LinearLayout>

            <FrameLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

                <WebView android:id="@+id/content_movies"
                    android:layout_weight="1"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"/>
            </FrameLayout>
        </LinearLayout>

        <TabWidget
            android:id="@android:id/tabs"
            android:gravity="top"
            android:layout_gravity="top"
            android:listSelector="@color/gray"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </TabHost>

Inside the scrollview, place the text view what you need, so it has your title menus.
For more about TabHost, refer to the URL http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/Tabs1.html.


text:
Q: How can I scale an image so that it is isotropic? I have a stack composed of 72 z planes, 700 px in x and 1000 px in y, let's say.
This is a label image, meaning that all the objects that have been segmented are defined by an integer value that works as a label that defines which pixels are occupied by the object in the image. The voxels are anisotropic (xy = 0.1 um, z = 0.25 um) and I would like to make them isotropic for downstream analysis. I am a bit confused on what could be the best way to do it in python using skimage and numpy.
Thank you! :D

A: I think that you can do this with an affine transformation. I am basing this mostly on similar work from https://github.com/VolkerH/Lattice_Lightsheet_Deskew_Deconv. I believe there is an example of this kind of scaling transform in one of their example notebooks. You will need to figure out the shape of the output volume but hopefully this gets you unstuck
import numpy as np
from scipy.ndimage import affine_transform

# create a transformation matrix
scale = np.eye(4)
scale[0, 0] = xy_voxelsize / z_voxelsize

# perform affine transformation
isotropic_vol = affine_transform(anisotropic_vol, np.linalg.inv(scale), output_shape=?, order=1)

I think that you can find some useful functions for determining the output shape from the same repository I mentioned above. This might be a little overkill for what you want but I have had good experience with much of the code there. You could probably figure out the output shape on your own pretty easily.
I'm not sure how many images you have, but these seem pretty big. If you have access to a GPU, the gputools version (https://github.com/maweigert/gputools) of affine transformation could also make your life easier.


text:
Q: list of item drops down to show a list I have a list ever item in that list will have an arrow-down and on clicking on that arrow in 1st item an sub list with check box will drop down. and on clicking 2nd item in the main list sublist of the 1st list should get closed and sublist of 2n item should get displayed.
<ion-grid>
    <ion-row>
        <ion-label>'Sex'</ion-label>
        <ion-icon name="ios-arrow-forward" (click)="arrowdown()" *ngIf="dropdown"></ion-icon>
        <ion-icon name="ios-arrow-down" (click)="arrowRight()" *ngIf="!dropdown"></ion-icon>
</ion-row>
 <ion-row >
      <ion-col *ngIf="!dropdown">
        <ion-item  *ngFor=" let item of GetTags; let i=index ">
           <ion-label>{{item.Sex}}</ion-label>
            <ion-checkbox color="dark"></ion-checkbox>
         </ion-item>
       </ion-col>
 </ion-row>

in this way i have 3 more grid with different value like color,size etc
dropdown: boolean = true;

 arrowdown(){
        this.dropdown = false;
    }
    arrowRight(){
        this.dropdown = true;
    }

dropdownModel = [
    {
        size: 1,
        label: 'Dresses',
        selected: false, // optional
        color: '#336699' // optional
    },
    {
        size: 2,
        label: 'Jeans',
        selected: false, // optional
        color: '#336699' // optional
    },
    {
        size: 3,
        label: 'Bags',
        selected: false, // optional
        color: '#336699' // optional
    },
    {
        size: 4,
        label: 'Blazzer',
        selected: false,
        color: '#336699'
    }

];


text:
Q: How to delete debug files in /sys/kernel/debug? sudo find / -size +5G -ls

listed debug files with more than 8GB size at /sys/kernel/debug/dri/n/amdgpu_vram
(n is the number of GPUs)
These might be useless debug files.
Cannot delete them (error "Operation not permited").
How to delete these files?

A: These are not files in the traditional sense.
The entire /sys filesystem is a virtual file system, which maps various system functions as files. They are not stored on disk; they're merely mechanisms to access various kernel functions. In this case, the file is the video RAM. The files can serve as a debugging interface, thus the naming.
Removing them does literally not make sense - as they're an representation of a physical feature of your computer system. That's why you're not allowed to remove them.
In short: Do not touch anything inside /sys or /proc unless you know what you are doing. You may crash your system. Reading them is generally safe - worst case will typically garble your terminal with random data.
There's lots of interesting stuff in /sys and /proc, that can tell you a whole lot about how your system operates, both the Linux kernel, and physical parts of your computer.

A: I have the same problem.
df -Th

command shows 100% Usage on / . Therefore, it is not imaginary problem. It is what did happen in my rig before, too. I solved it by using commands like
sudo apt autoremove
sudo apt autoclean
sudo apt clean
sudo apt autoremove --purge
sudo rm /var/log/kern.log
touch /forcefsck
sudo shutdown -rF now

If I find the full solution, I will post it here. ncdu is a better application for checking disk space usage in command line.
apt install ncdu

After several reboot and using commands like above and
sudo lsof +L1 | grep deleted
to detect processes which hold deleted files, the problem solved.


text:
Q: Assembly.GetTypes() returns strange type names e.g. "<>c" When using Assembly.GetTypes() I get types that have Type.Name that begin with <>c.....
I tried to google if this is anonymous types or something else. But cannot get a really good answer.
Is there a property on Type that indicate what these types are? I do not like having to do if(type.Name.StartsWith("<>"))

A: These are the CompilerGeneratedAttribute Class

Distinguishes a compiler-generated element from a user-generated
  element. This class cannot be inherited.

You can check it like
using System.Runtime.CompilerServices;

bool CompilerGen(Type t)
{
    var attr = Attribute.GetCustomAttribute(t, typeof(CompilerGeneratedAttribute));
    return attr != null;
}

A: These are compiler generated display classes. You can distinguish them by looking for the CompilerGeneratedAttribute:
var attr = Attribute.GetCustomAttribute(type, typeof(CompilerGeneratedAttribute));

A: They're compiler generated types, which would include anonymous types, but also the implementations of IEnumerable<T>, IEnumerator<T>, IEnumerable and IEnumerator that are produced by yield and the state-machine structures produced by await.
They will have the CompilerGeneratedAttribute.
You describe the names as "strange" and they are deliberately such. They are all names that are valid .NET names, but not valid in common .NET languages, particularly C# and VB.NET. This means you couldn't create such a class with C# coding directly, so there doesn't need to have any logic to check the programmer hasn't created a matching class.


text:
Q: ListView ограничение количества записей Как можно ограничить первоначальное количество элементов в списке ListView, чтобы вначале подгружалось тридцать первых записей, затем при достижении конца списка, подгружались следующие 30 и т.д.

A: *

*Повесьте слушатель скрола на ListView

*В нём определяйте, что достигли конца списка.

*Запускайте задачу добавления элементов.

Гуглить надо

endless scrolling listView

и лучше сделать это через RecyclerView - там это проще.

A: youListView.setOnScrollListener(new OnScrollListener() {

        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {

            if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
            {
                if(isLoading)
                {
                    isLoading = false;
                    additems();
                }
            }
        }
    });

В методе добавления доп итемов добавляйте следующие 30 элементов в ArrayList.
Необходимо так-же создать булеву(флаг) isLoading и после добавления присвоить ему значение true, и вызвать notifyDataSetChanged().


text:
Q: Complex SQL Query similar to a z order problem I have a complex SQL problem in MS SQL Server, and in drawing on a piece of paper I realized that I could think of it as a single bar filled with rectangles, each rectangle having segments with different Z orders.  In reality it has nothing to do with z order or graphics at all, but more to do with some complex business rules that would be difficult to explain.  Howoever, if anyone has ideas on how to solve the below that will give me my solution.
I have the following data:
ObjectID  |  PercentOfBar  |  ZOrder (where smaller is closer)
---------------------------------------------------------------
A         |  100           |  6
B         |  50            |  5
B         |  50            |  4
C         |  30            |  3
C         |  70            |  6

The result of my query that I want is this, in any order:
PercentOfBar  |  ZOrder
-------------------------
50            |  5
20            |  4
30            |  3

Think of it like this, if I drew rectangle A, it would fill 100% of the bar and have a z order of 6.
6666666666
AAAAAAAAAA

If I then layed out rectangle B, consisting of two segments, both segments would cover up rectangle A resulting in the following rendering:
4444455555
BBBBBBBBBB

As a rule of thumb, for a given rectangle, it's segments should be layed out such that the highest z order is to the right of the lower Z orders.
Finally rectangle C would cover up only portions of Rectangle B with it's 30% segment that is z order 3, which would be on the left.  You can hopefully see how the is represented in the output dataset I listed above:
3334455555
CCCBBBBBBB

Now to make things more complicated I actually have a 4th column such that this grouping occurs for each key:
Input:
SomeKey, ObjectID, PercentOfBar, ZOrder (where smaller is closer)
X, A, 100, 6
X, B, 50, 5
X, B, 50, 4
X, C, 30, 3
X, C, 70, 6
Y, A, 100, 6
Z, B, 50, 2
Z, B, 50, 6
Z, C, 100, 5

Output:
SomeKey, PercentOfBar, ZOrder
X, 50, 5
X, 20, 4
X, 30, 3
Y, 100, 6
Z, 50, 2
Z, 50, 5

Notice in the output, the PercentOfBar for each SomeKey would add up to 100%.
This is one I know I'm going to be thinking about when I go to bed tonight.
Just to be explicit and have a question:
What would be a query that would produce the results described above?

A: I'm making the following assumptions:

*

*You're using SQL Server 2005 or newer.

*SomeKey, ObjectID, ZOrder is unique.

Other notes:

*

*I have not optimized the query - I just tried to get the correct result.

*I've only tested it on your test data.

With that in mind you could try something like this:
WITH Bars AS (
    SELECT
        T1.SomeKey,
        T1.ObjectID,
        T1.ZOrder,
        SUM(T2.PercentOfBar) - T1.PercentOfBar AS PercentStart,
        SUM(T2.PercentOfBar) AS PercentEnd
    FROM Table1 T1
    JOIN Table1 T2
    ON T1.SomeKey = T2.SomeKey
        AND T1.ObjectID = T2.ObjectID
        AND T1.ZOrder >= T2.ZOrder
    GROUP BY T1.SomeKey, T1.ObjectID, T1.PercentOfBar, T1.ZOrder),
Boundaries AS (
    SELECT P, ROW_NUMBER() OVER (ORDER BY P) AS rn
    FROM (
        SELECT DISTINCT PercentStart AS P FROM Bars
        UNION
        SELECT DISTINCT PercentEnd FROM Bars
    ) T1),
Intervals AS (
    SELECT B1.P AS PercentStart, B2.P AS PercentEnd
    FROM Boundaries B1
    JOIN Boundaries B2
        ON B1.rn + 1 = B2.rn),
Bits AS (
    SELECT
        SomeKey,
        ObjectId,
        ZOrder,
        Intervals.PercentStart,
        Intervals.PercentEnd
    FROM Intervals
    JOIN Bars
        ON Bars.PercentStart <= Intervals.PercentStart
        AND Bars.PercentEnd >= Intervals.PercentEnd),
LowestZOrder AS (
    SELECT SomeKey, PercentStart, MIN(ZOrder) AS ZOrder
    FROM Bits
    GROUP BY SomeKey, PercentStart),
LowestBits AS (
    SELECT Bits.*
    FROM Bits
    JOIN LowestZOrder
        ON Bits.SomeKey = LowestZOrder.SomeKey
        AND Bits.PercentStart = LowestZOrder.PercentStart
        AND Bits.ZOrder = LowestZOrder.ZOrder)
SELECT
    SomeKey,
    MAX(PercentEnd) - MIN(PercentStart) AS PercentOfBar,
    ZOrder
FROM LowestBits
GROUP BY SomeKey, ObjectID, ZOrder
ORDER BY SomeKey, ObjectID, MIN(PercentStart) DESC

Result:
SomeKey PercentOfBar ZOrder
X       50           5
X       20           4
X       30           3
Y       100          6
Z       50           2
Z       50           5

Test data:
CREATE TABLE Table1 (SomeKey NVARCHAR(100) NOT NULL, ObjectID NVARCHAR(100) NOT NULL, PercentOfBar INT NOT NULL, ZOrder INT NOT NULL);
INSERT INTO Table1 (SomeKey, ObjectID, PercentOfBar, ZOrder) VALUES
('X', 'A', 100, 6),
('X', 'B', 50, 5),
('X', 'B', 50, 4),
('X', 'C', 30, 3),
('X', 'C', 70, 6),
('Y', 'A', 100, 6),
('Z', 'B', 50, 2),
('Z', 'B', 50, 6),
('Z', 'C', 100, 5);


text:
Q: SQL populating added field rows with default value =0 I have table with three fields:
ID|DESCRIPTION |PRICE
01|Item 1      |2.95
02|Item 2      |5.95

Now, more fields can be added to the end as supplier selling price.
What's the SQL query to default every existing item's selling price to 0 for this newly added field?

*

*List item

A: For sql Server:
ALTER TABLE YOURTBL
        ADD sellingprice numeric(20,4) NULL
        DEFAULT (0)

My SQL
ALTER TABLE YOURTBL ADD COLUMN sellingprice decimal(20,4) NULL DEFAULT 0;

Oracle
ALTER TABLE YOURTBL
ADD sellingprice  NUMBER(20,4) DEFAULT 0 NULL

MSAccess
ALTER TABLE YOURTBL ADD COLUMN sellingprice NUMBER DEFAULT 0

A: is the current field Price the one you want to default to 0 for each new record? is so, then run this
ALTER TABLE t1 ADD CONSTRAINT df_Name DEFAULT 0 FOR Price

For a new field, this will create the field, and add 0 as the default
ALTER TABLE TableName ADD NewFieldName DECIMAL(10,4) DEFAULT(0)

A: ALTER TABLE Table_Name
ADD supplier_selling_price INT NULL DEFAULT (0)

From DEFAULT Key word you can assign a default value to existing lines of newly added column. Please change the data type as per your need. (int, numeric, decimal)


text: Q: Pause upgrade halfway through? With my current Internet connection, it will take about 18 hours to download all the files needed to upgrade from 12.04 to 12.10. Is there a way that I can first download the files in the background and then do the upgrade? Alternatively, if I use the graphical Distribution Upgrade tool via Update Manager, can I Cancel halfway through the downloads and start again where I left off, or will it delete the files it's downloaded so far?


text:
Q: Vim closing bracket (using no plugin) to act different when I press enter or when I don't press enter immediately after first bracket How can I achieve the following auto-close bracket behavior in Vim 8 using no external plugins?
If I use
inoremap { {};<Left><Left>

then if I enter
int array[2] = {

it will automatically perform correctly by placing }; as well as placing the cursor inside the brackets.
But what I want is that when I am working with structs I want the following to happen after I press enter immediately after inserting the first bracket,
struct test {
    | <- cursor is here
};

What do I have to change in order to achieve both behaviors shown above in Vim 8?

A: The part of "using no external plugins" is the tricky one.
To get the behavior you want, you have to inoremap the <CR> key, probably using an <expr> mapping, that will look at the character under the cursor, see if it's a } and, in that case, move it two lines down, unindent that line (only if the first one was indented), go back up one, re-indent it...
And if it's not a }, then just behave like a normal <CR> (this part is easy with an <expr> mapping.)
The problem is, when you get that far, you're halfway through to writing a plug-in, so you might as well just get one that was thoroughly debugged for all the corner cases that can happen here.
If you want something really simple though:
inoremap <expr> <CR>
    \ getline('.')[col('.')-1]=='}'
    \ ? "\<CR>\<C-d>\<C-o>O" : "\<CR>"

It uses a <CR> followed by a CTRL-D to unindent the }, then CTRL-O to use the O normal mode command, which inserts a new line above this one. (Using O here to get the indentation right.)
But, as mentioned, this will not always work as expected. It's very simple.
And next you'll want to fix backspace, or fix it that when you type } if you're on a } already you'll skip it... You'll want the plug-in, trust me!

A: How about adding this in your ftplugin file:
function! CloseBracket()
        if getline('.') =~ '^struct\s\w\+\s'
                return "{}\<left>\<cr>\<c-o>O\<tab>"
        endif
        return "{};\<left>\<left>"
endfunction

inoremap { <C-R>=CloseBracket()<CR>

So when { is pressed in insert mode we insert the contents of a register , the following = then states we want to use the expression register which in this case is the CloseBracket function.
The function it self gets the current line, and runs some regex to see if the line is a struct definition, if so it does some fancy foot work as requested, otherwise it just closes the brackets and moves the cursor left.


text:
Q: Entity Framework generating error for entity that does not exist in bottom error details neither Encoding and other mentioned entities are part of my project. Still i got this error. This error is generated suddenly when i started project after few hours without changes.
This error is occurring when first entity framework based call is made.
 One or more validation errors were detected during model generation:

Website1.Models.Encoding: : EntityType 'Encoding' has no key defined. Define the key for this EntityType.
ActionResults: : The referenced EntitySet 'ActionResults' for End 'ContentResult_ContentEncoding_Source' could not be found in the containing EntityContainer.
ActionResults: : The referenced EntitySet 'ActionResults' for End 'JsonResult_ContentEncoding_Source' could not be found in the containing EntityContainer.
Encodings: EntityType: EntitySet 'Encodings' is based on type 'Encoding' that has no keys defined.
ActionResults: EntityType: EntitySet 'ActionResults' is based on type 'ActionResult' that has no keys defined.
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.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

Website1.Models.Encoding: : EntityType 'Encoding' has no key defined. Define the key for this EntityType.
ActionResults: : The referenced EntitySet 'ActionResults' for End 'ContentResult_ContentEncoding_Source' could not be found in the containing EntityContainer.
ActionResults: : The referenced EntitySet 'ActionResults' for End 'JsonResult_ContentEncoding_Source' could not be found in the containing EntityContainer.
Encodings: EntityType: EntitySet 'Encodings' is based on type 'Encoding' that has no keys defined.
ActionResults: EntityType: EntitySet 'ActionResults' is based on type 'ActionResult' that has no keys defined.

Here is complete : database class : > HERE

A: Problem was with the Datatype of one of the table's column that was not supported. A column was itself representing as entity, and i don't know how.
by mistake i defined the following datatype:
public ActionResult effectcolumn {get; set;}


text:
Q: Angular Component with Generic Type I have a component (table) that takes an array of any data. This component then calls a function in a service that requires a generic to determine what the data is (the function maps data).
However, I don't know of a way to using a generic with an Input / Component.
Anyone know how to do this?
When the component is used (in the template) on the parent level I would like to provide the actual Type of T. Any ideas?
@Component({
  selector: 'inm-mapped-table',
  template: `
  <pre>{{ $rows | async }} </pre>
  `,
})
export class InmMappedTableComponent<T extends Record<string, any>> implements OnInit {
  @Input() $data: Observable<T[]>;
  @Input() config: MappingConfig<T>[] = [];

  $rows: Observable<Row[]>;

  constructor(private readonly mappingService: InmTableMappingService) {}

  ngOnInit(): void {
    this.$rows = this.$data.pipe(
        switchMap( data => this.mappingService.getRows<T>(data, this.config) )
    )
  }
}

A: Please check this code below I think you have to make your component generic first:
pass a generic input property


text:
Q: Change Slick Slider Arrow Position I want to change slick slider arrow position as same in the picture but i am unable to acheive the same in jquery .

$('.your-class').slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 1,
    centerMode: true,
    variableWidth: true,
    prevArrow:'',
    nextArrow:''

});

A: Add Class on your Slick function like
prevArrow: $(".pp2"),
nextArrow: $(".nn2"),

& Below button add with style :
<button class="pp2">back</button>
<button class="nn2">forward</button>

A: You can change the position of arrows using CSS.  Try like below
.clr-gry.slick-arrow {
    top: 0;
    position: absolute;
}
.fa-angle-left.clr-gry {
    right: 10px;
}

.fa-angle-right.clr-gry {
    right: 0;
}

If this not work, please share the HTML page.

A: .slick-next and .slick-prev are pre-defined classes in slick slider. For customizing the CSS of arrow you can use these classes to get your desired result.
Works whether you are using jQuery or React.


text:
Q: One of my Android activities work badly Hello dear StackOverflow community!!!
While developing my recent application project i found some problems while debugging the app. In my project i want to pass one data element through 2 activities. Everything looks good (no errors or other stuff) until i choose WatchingActivity in my app. It displays no webview but only white blank space while there should be video choosen in PartActivity. Please help!!!!
public class MainActivity extends AppCompatActivity {
    String clipname;
    ImageView ka;
    ImageView jb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ka = (ImageView) findViewById(R.id.imageView1);
        jb = (ImageView) findViewById(R.id.imageView2);
    }

    public void imageView1Clicked(View view) {
        // method that is signed in layout file to be called by clicking on imageView1
        clipname="Kendra's Adventure";
        Intent mainintent = new Intent(this, ChooseAPartActivity.class);
        mainintent.putExtra("CLIP", clipname);
        startActivity(mainintent);
    }

    public void imageView2Clicked(View view) {
        clipname="Johhny Big";
        Intent mainintent = new Intent(this, ChooseAPartActivity.class);
        mainintent.putExtra("CLIP", clipname);
        startActivity(mainintent);

    }
}

public class ChooseAPartActivity extends AppCompatActivity {
    TextView title;
    TextView part1;
    TextView part2;
    TextView part3;
    TextView part4;
    TextView part5;
    TextView part6;
    String videoname;
    String partnumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_a_part);
        title.findViewById(R.id.textView);

        title.findViewById(R.id.textView);

        Intent mainintent = getIntent();

        String clipname = mainintent.getStringExtra("CLIP");

        title.setText(clipname);
        videoname = clipname;
    }

    public void partone (View view) {
    //method assigned to textview in layout file
        partnumber = "one";
        Intent partintent = new Intent(this, WatchingActivity.class);
        partintent.putExtra("PART", videoname);
        partintent.putExtra("NUMBER", partnumber);
        startActivity(partintent);
    }
    public void parttwo (View view) {
        partnumber = "two";
        Intent partintent = new Intent(this, WatchingActivity.class);
        partintent.putExtra("PART", videoname);
        partintent.putExtra("NUMBER", partnumber);
        startActivity(partintent);
    }
    public void partthree (View view) {
        partnumber = "three";
        Intent partintent = new Intent(this, WatchingActivity.class);
        partintent.putExtra("PART", videoname);
        partintent.putExtra("NUMBER", partnumber);
        startActivity(partintent);
    }
    public void partfour (View view) {
        partnumber = "four";
        Intent partintent = new Intent(this, WatchingActivity.class);
        partintent.putExtra("PART", videoname);
        partintent.putExtra("NUMBER", partnumber);
        startActivity(partintent);
    }
    public void partfive (View view) {
        partnumber = "five";
        Intent partintent = new Intent(this, WatchingActivity.class);
        partintent.putExtra("PART", videoname);
        partintent.putExtra("NUMBER", partnumber);
        startActivity(partintent);
    }
    public void partsix (View view) {
        partnumber = "six";
        Intent partintent = new Intent(this, WatchingActivity.class);
        partintent.putExtra("PART", videoname);
        partintent.putExtra("NUMBER", partnumber);
        startActivity(partintent);
    }
}
public class WatchingActivity extends AppCompatActivity {

    String clipkey;
    WebView screen;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_watching);
Intent sceneintent = getIntent();

        String videoname = partintent.getStringExtra("PART");
        String partnumber = sceneintent.getStringExtra("NUMBER");

        if(videoname == "Kendra's Adventure"){
            if(partnumber == "one"){
         clipkey = "";
            }
        }
        else if(videoname == "Johnny Big"){
            if(partnumber == "one") {
                clipkey = "";
            }
            else if(partnumber == "two"){
                clipkey = "";

            }
        }
        screen=(WebView)findViewById(R.id.webView);
        screen.getSettings().setJavaScriptEnabled(true);
        String myvideokey = clipkey;
        screen.loadData(myvideokey, "text/html", "utf-8");
        screen.setWebChromeClient(new WebChromeClient(){
        });
}
}

A: String videoname = partintent.getStringExtra("PART");

Is that line ok in WatchingActivity? There is no partintent field or something.
Defining all activities in the same class-file is not really good idea.


text:
Q: Show Google Maps using Latitude and Longitude in ASP.Net I am trying to mark the location of requesters of my website on google map.I successfully store longitude and latitude of Requester in DB but now I want to mark the location on google map, I used this code(Found it from a website) asp controls got red underlined:
<script type="text/javascript">
    var markers = [
    <asp:Repeater ID="rptMarkers" runat="server">
    <ItemTemplate>
                {
                    "title": '<%# Eval("Name") %>',
                "lat": '<%# Eval("Latitude") %>',
                "lng": '<%# Eval("Longitude") %>',
                "description": '<%# Eval("Description") %>'
            }
</ItemTemplate>
<SeparatorTemplate>
    ,
</SeparatorTemplate>
</asp:Repeater>
];
</script>

Thanks in advance


text:
Q: Save Excel Spreadsheet As Jpeg In C++? I have an Excel spreadsheet which is one sheet with a table and chart in it. What I need to do is add this to a PDF. The PDF API I am using does not support importing Excel documents so I wondered if there is any way from C++ to save/convert an Excel document to a Jpeg (or BMP)?
Just to add, obviously this has to be done in C++ as part of an existing application which creates PDFs every time it is run. I wouldn't be asking the question if it was a one off that could just be done manually.

A: Well I have, after much effort and hair pulling, managed to answer my own question. Contrary to what was said in other answers, it is possible to save an Excel spreadsheet as Jpeg (although I have stuck to bitmap format as that's good enough for me. It would be easy enough to convert to jpeg though). What I did via the Excel API was select the used range. From there, I copy this to the clipboard as a picture, then get the clipboard data and convert it to a picture object with an IPicture interface. From there, create a stream and copy this to the stream before saving this stream to file. The result is a bmp file with exactly the image I was after. Code sample below.
    CRange range = sheet.get_UsedRange();

    range.CopyPicture(Excel::xlScreen, Excel::xlBitmap);

    if (IsClipboardFormatAvailable(CF_BITMAP)) // just to be sure it copied
    {
        if (OpenClipboard(NULL) > 0)
        {
            // save clipboard as bmp
            HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);

            SaveBitmap(ps_filename, hBitmap, NULL);

            CloseClipboard();
        }
    }
}

bool CExcelDocument::SaveBitmap(LPCSTR filename, HBITMAP bmp, HPALETTE pal)
{
    bool bReturn = false;
    PICTDESC pictdesc;
    LPPICTURE pPicture;

    ::ZeroMemory( &pictdesc, sizeof(pictdesc) );
    pictdesc.picType        = PICTYPE_BITMAP;
    pictdesc.bmp.hbitmap    = bmp;
    pictdesc.bmp.hpal       = pal;
    pictdesc.cbSizeofstruct = sizeof(PICTDESC);

    HRESULT hr = OleCreatePictureIndirect(&pictdesc, IID_IPicture, false, reinterpret_cast<void**>(&pPicture));

    if (!SUCCEEDED(hr))
        return false;

    LPSTREAM pStream;
    hr = CreateStreamOnHGlobal(0, true, &pStream);

    if (!SUCCEEDED(hr))
    {
        pPicture->Release();
        return false;
    }

    LONG lBytesRead = 0;
    DWORD lBytesWritten = 0;
    hr = pPicture->SaveAsFile(pStream, true, &lBytesRead);

    if (!SUCCEEDED(hr))
    {
        pStream->Release();
        pPicture->Release();
        return false;
    }

    HANDLE hFile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

    if (!hFile)
    {
        return false;
    }

    HGLOBAL hMemory = 0;
    GetHGlobalFromStream(pStream, &hMemory);
    LPVOID pData = GlobalLock(hMemory);

    bReturn = !!WriteFile(hFile, pData, lBytesRead, &lBytesWritten, 0);
    bReturn &= (lBytesWritten == static_cast<DWORD>(lBytesRead));

    GlobalUnlock(hMemory);
    CloseHandle(hFile);

    pStream->Release();
    pPicture->Release();

    return bReturn;
}

A: What you can do is, load the spreadsheet into C++ using the Execl API (Office Interop). Now you have access to the values within the rows and columns. You should also be able to extract how large they are (width and height). This is your starting point.
Now the simplest approach is to use GDI (or whatever) to create a new picture and walk through every cell within your excel sheet and draw the content of it into your picture. After this you can draw lines resembling the cells itself.
Anyway this results in a lot of work and won't be easy, especially if you have to consider things like text alignment within the cell and border sizes and so on.