text:
Q: How can I extract a specific element from HTML code using python I'm not so confident with HTML language and I'm having trouble in parsing this portion of HTML code (result of print soup.prettify() ) with Python.

$("#global-flash").html("");

$('#reviews-tab-navigation').trigger('repaint');
$('#edit-review-tab').html('

 \n

  \n

   \n

    Rezensionsdaten<\/span>\n

    \n\n

     \n

      \n

       \n

        \n

         5<\/span>\n\n                Rezensionen gefunden\n            <\/th>\n          <\/tr>\n        <\/thead>\n\n

          \n

           \n

            \n

             \n                  5\n

             \n\n

              Bel colore come in foto, morbidissima, piacevole sulla pelle, non stringe anzi aderisce bene senza segnare i difettucci e i rotolini.<\/span>\n                <\/span>\n              <\/td>\n            <\/tr>\n

               \n

                \n

                 \n                  5\n

                 \n\n

                  bella<\/span>\n                <\/span>\n              <\/td>\n            <\/tr>\n

                   \n

                    \n

                     \n                  4\n

                     \n\n

                      Buon rapporto qualità-prezzo, buona vestibilità, tessuto morbido.<\/span>\n                <\/span>\n              <\/td>\n            <\/tr>\n

                       \n

                        \n

                         \n                  5\n

                         \n\n

                          Davvero un buon capo! Ottima qualità, giusto peso<\/span>\n                <\/span>\n              <\/td>\n            <\/tr>\n

                           \n

                            \n

                             \n                  5\n

                             \n\n

                              Preso anche in altri colori .... bello e funzionale. Taglia regolare.<\/span>\n                <\/span>\n              <\/td>\n            <\/tr>\n        <\/tbody>\n      <\/table>\n    <\/div>\n  <\/div>\n\n

                               \n

                                \n

                                 \n

                                  \n

                                   Informazioni articolo<\/span>\n

                                   \n

                                    <\/a>\n

                                     N. art.<\/label>\n

                                      95341195<\/a>\n

                                       Masterstyle-ID<\/label>\n52826321\n

                                        Digistyle-ID<\/label>\n12709620\n

                                         Ø Media dei voti<\/label>\n4.45

                                          \n

                                           Lunghezza<\/label>\nGiusto\n

                                            Larghezza<\/label>\nGiusto\n

                                             Disponibilità<\/label>\n\n(37)\n\n        <\/div>\n      <\/div>\n\n

                                              \n

                                               \n

                                                Dati cliente<\/span>\n

                                                \n

                                                 \n

                                                  \n

                                                   \n

                                                    Nome<\/label>\n      nome\n    <\/td>\n

                                                     \n

                                                      Cognome<\/label>\n      cognome\n    <\/td>\n  <\/tr>\n

                                                       \n

                                                        \n

                                                         Codice cliente<\/label>\n      N/A\n    <\/td>\n

                                                          \n

                                                           Indirizzo e-mail<\/label>\n      ********@gmail.com\n    <\/td>\n  <\/tr>\n<\/table>\n\n

                                                            Commento articolo<\/span>\n

                                                            \n

                                                             <\/i>

                                                             \n\n
                                                             <textarea id='\"review-text\"' name='\"text\"' readonly='\"readonly\"' rows='\"12\"'>\nBel colore come in foto, morbidissima, piacevole sulla pelle, non stringe anzi aderisce bene senza segnare i difettucci e i rotolini.<\/textarea>\n\nCommenti sulla vestibilità<\/span>\n
\n
\n
\n    \n      Lunghezza<\/label>\n      Giusto\n    <\/td>\n    \n      Larghezza<\/label>\n      Giusto\n    <\/td>\n    \n      Taglia<\/label>\n      62/64\n    <\/td>\n    \n      Varianti<\/label>\n       \n    <\/td>\n    \n      Statura<\/label>\n      165-169\n    <\/td>\n  <\/tr>\n<\/table>\n
\n
\n
\n      \n        Rezensions-ID:<\/b>\n        10613555<\/span>\n      <\/td>\n      \n        Creata:<\/b>\n        \n          01.10.2017 11:06:26\n        <\/span>\n      <\/td>\n    <\/tr>\n
\n      \n        Letzte Änderung<\/b>\n        \n          01.10.2017 11:06:26\n        <\/span>\n      <\/td>\n      \n        di<\/b>\n        Kunde\n      <\/td>\n    <\/tr>\n
\n      \n        Data pubblicazione:<\/b>\n        \n          01.10.2017 11:06:26\n        <\/span>\n      <\/td>\n    <\/tr>\n  <\/table>\n<\/p>\n\n        <\/div>\n      <\/div>\n\n
\n
\n            Modifica<\/span>\n
\n
\n  Scegli un destinatario<\/label>\n  Cancella la lista destinatari<\/a>\n  <select id='\"email-recipients-select\"' name='\"email-recipients-select\"'><option value='\"\"'><\/option>\n<option value='\"*****@*****.it\"'>servizio@******.it<\/option><\/select>\n  <textarea id='\"email-recipients-textarea\"' name='\"email-recipients-textarea\"'>\n<\/textarea>\n  Invia recensione<\/a>\n  Traduci<\/label>\n  <textarea id='\"review-uebersetzung\"' name='\"text\"'>\n<\/textarea>\n  Feedback al cliente<\/label>\n  <textarea id='\"review-feedbackToCustomer\"' name='\"text\"'>\n<\/textarea>\n<\/div>\n
\n  Tipo di recensione<\/label>\n  <select id='\"review-meinungstyp\"' name='\"meinungstyp\"'><option selected='\"selected\"' value='\"R\"'>Recensione<\/option>\n<option value='\"G\"'>Risposte<\/option>\n<option value='\"A\"'>Archivio<\/option><\/select>\n<\/div>\n
\n
\n    Pubblicata<\/label>\n    <input id='\"review_aktiv\"' name='\"review_aktiv\"' type='\"hidden\"' value='\"T\"'/>\n
\n
\n        Sì<\/a>\n        No<\/a>\n      <\/div>\n    <\/div>\n  <\/div>\n<\/div>\n\n
\n  Salva recensione<\/a>\n  <\/i> Cancella recensioni<\/a>\n<\/div>\n\n        <\/div>\n      <\/div>\n    <\/div>\n  <\/div>\n<\/div>\n').trigger('repaint');
reviews.initEditReviewTab();
$('#reviews-tab-navigation').tabs('option', 'active', 0);
$('.search-tab-buttons').html('
\n
\n
\n        Cerca<\/a><\/td>\n      Ricerca standard<\/a><\/td>\n      Statistiche<\/a><\/td>\n    <\/tr>\n  <\/table>\n<\/div>');
$('.mini-statistics').replaceWith('
\n
\n      Da controllare: 100 / Pubblicata: 304316 / Non pubblicata: 9207 / Prenotate: [0], mie: [0]\n    <\/p>\n  <\/div>\n');

</option></option></option></select>
</textarea></textarea></textarea></option></option></select>

</textarea>

Basically I would like to extract the number after each "data-review-id" (in this portion of html there are 5: 10613555, 10610141, 10575319, 10554514, 9469234) but I don't understand which tags I should select to get the result I want.
I've tried several combinations of soup.find_all but without any result.
Any help or suggestion would be really appreciated.
Thanks in advance!

A: The HTML you have is inside some Javascript and appears to have been escaped. Copy/pasting the exact HTML you have given and assigning it to html, the following could be used:
from bs4 import BeautifulSoup

html = """ ---- add HTML here ---"""

html = html.replace('"', ''). replace(r'\/', '/')
soup = BeautifulSoup(html, "html.parser")

for td in soup.find_all('td', {'data-review-id':True}):
    print td['data-review-id']

This then displays:
10613555
10610141
10575319
10554514
9469234


text:
Q: Exposing internal modules to tests in Cabal I'm contributing to an open source project which defines its project setup in a cabal file that looks like this (omitting lots of properties that are not relevant for this problem):
library
  hs-source-dirs:    src
  build-depends:
                     base >= 4.9 && < 5,
                     some-other-deps
  exposed-modules:
                     Data.Foo.Bar,
                     Data.Foo.Baz
  other-modules:
                     Data.Foo.Bar.Internal

test-suite test
  hs-source-dirs:
                     tests
  build-depends:
                     foo-library
  other-modules:
                     Foo.Bar.Tests,
                     Foo.Baz.Tests

Now, in order to test the feature I'm adding, I want the tests to have access to the Data.Foo.Bar.Internal module, but since it's hidden in the library, I can't access it from the tests.
I looked at the cabal docs which suggested adding a third component - an internal library (unfortunately not linkable, but search for "internal libraries"). If I understand the documentation correctly, I should be able to do something like this:
library foo-internal
  hs-source-dirs:    src
  build-depends:
                     base,
                     some-other-deps
  exposed-modules:
                     Data.Foo.Bar.Internal

library
  hs-source-dirs:    src
  build-depends:
                     base >= 4.9 && < 5,
                     foo-internal,
                     some-other-deps
  exposed-modules:
                     Data.Foo.Bar,
                     Data.Foo.Baz

test-suite test
  hs-source-dirs:
                     tests
  build-depends:
                     foo-library,
                     foo-internal
  other-modules:
                     Foo.Bar.Tests,
                     Foo.Baz.Tests

but running stack build here gives me warnings that Data.Foo.Bar.Internal "should be added to exposed-modules or other-modules in ./foo.cabal", and then a build error in the test that seems to be caused by failed unification (it points to a function argument for a function defined in the library, says that its type must be Data.Foo.Bar.Internal.Qux defined in package foo, and that the type foo:Data.Foo.Bar.Internal.Qux don't match).
How can I expose internal modules to the test suite, without exposing them also to consumers of the library?

A: As mentioned in the comments, different components (internal libraries, executables) should have modules under different roots.

*

*This is a recurrent point of confusion. For another example: https://stackoverflow.com/a/6711739/6863749

*There is an open ticket on Cabal's issue tracker  about clarifying this with a suitable warning; it's apparently non-trivial to detect this situation reliably because it overlaps with legitimate use cases: https://github.com/haskell/cabal/issues/5335

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where should I put my custom applications? I have downloaded some third party software, should I just put under /Applications or should I put under my home folder, e.g. ~/MyApps/?

A: It depends on what applications you want to keep to yourself and which ones you want to make accessible to all users:

*

*Applications stored in /Applications are installed for all users.

*The ~ stands for your home folder.
Applications stored in ~username/Applications are only for access by the user username.

A: I tried separating "personal" apps to ~/Applications/ and eventually gave it up after awhile because I found it to be annoying.
It turned out to be a lot hassle in little ways, and finally I just moved them all. I kept finding apps which only looked in /Applications/ so I had to keep tweaking settings.
More and more apps include checks to see if they are in /Applications/ and offer to move themselves, which meant even more annoyances.
If you install apps, such as Microsoft Office, which come with installers, you probably won't even have the choice.
But your experience won't necessarily be mine.
I'd put them into ~/Applications/ and then if you decide that you want to change it later, drag them all to /Applications/. It's easier to do that than try to separate them later because some apps do install themselves to /Applications/ and won't handle being moved somewhere else.

A: I just put everything in the application folder.  I used to try to sort things but had issues with applications that do not like being an any folder other than applications (MS Office, Adobe programs, etc).  Since I couldn't easily move these around, my organization scheme was incomplete and I just gave up.
This is probably sacrilege but you might want to try using Launchpad.  The folders you create there aren't actual folders in the file system and therefore won't break picky applications that absolutely must live in applications.  Mountain Lion also added a few new features to Launchpad that make it more useable, such as searching.


text:
Q: PHP Description Excerpt I have the following code and need it to only echo out 100 words or less in the description rather than the entire description. Is there anyway to do that by editing this code?
public static function getExcerpt($profile) {
    $out='';
    if(!empty($profile['description'])) {
        $out.=$profile['description'].' '.__('', 'lovestory');
    }

    return $out;
}

Thanks!

A: // for 100 characters...
if (strlen($profile['description']) > 100)
    $description = substr($profile['description'], 0, 100) . "...";
else
    $description = $profile['description'];

$out.= $description . ' ' . __('', 'lovestory');

// for 100 words
$out.= implode(" ", array_slice(explode(" ", $profile['description']), 0, 100)) .' '.__('', 'lovestory');

A: You can simply use PHP's wordwrap function as shown below.
$text = "The quick brown fox jumped over the lazy dog.";
$newText = wordwrap(substr($text, 0, 20), 19, '...');
echo $newText;

will print The quick brown fox...

A: You can use explode with an empty space to create an array of words, and if there are more than 100 words, use array_slice to select the first 100, then implode that array back into a string
$words = explode(' ', $out);
if(count($words) > 100){
    return implode(' ', array_slice($words, 0, 100));
else{
    return $out;
}

A: That depends on how exact you want to be or how complicated your word boundaries are, but in general something like this would work for you:
$excerpt = explode(' ', $profile['description']);
$excerpt = array_slice($excerpt, 0, 100);
$out .= implode(' ', $excerpt).' '.__('', 'lovestory');


text:
Q: Animation with multiple steps with smooth speed I want to make an animation in jQuery to move a div to another div smoothly but recalculating the coordinates of the final destination in case a user scrollsdown with his mouse for example.
The red square is absolute positioned and the blue square has a fixed position.
I had an idea of calling several times the stop() function and then animate again to the new position of the blue square but the transition isn't smooth at all.
Is there a way to set new destination from time to time but keeping it smooth?
http://codepen.io/anon/pen/gkLzh


text:
Q: what' the simplest way to bind my grid view on one record(distinct different data) What's the simplest way to bind my grid view to a single data row :
I have the following data for example :
dep_code = 3;
dep_name = "computer science";
boss_num = 356;
boss_name ="Ahmed";

i want to bind those data on my gridview.

A: I think List of list should be simplest
List<List<string>> list = {{dep_code,dep_name,boss_num,boss_name}};
GridView1.DataSource = list;
GridView1.DataBind();


text:
Q: Prove if $z=a+bi$ is a root of the polynomial P(z), $\overline{z} =a-bi$ will be a root too. I have a polynomial $P( z) =a_{n} z^{n} +...+a_{1} z+a_{0}$ with real coefficients and I know that $z=a+bi$ is a root of it, but I don't know how to prove that $\overline{z}$ is a root too. Thanks!

A: To prove the statement we will use the following facts:
\begin{align*}
\overline{x+y} &= \overline{x} + \overline{y} \\
\overline{x\cdot y} &= \overline{x}\cdot\overline{y}
\end{align*}
Also recall that for $r \in \mathbb{C}$
\begin{gather*}
r\in\mathbb{R} \iff r = \overline{r}
\end{gather*}
Then
\begin{gather*}
P(\overline{z}) = \sum_{i=0}^n a_i \overline{z}^i = \sum_{i=0}^n \overline{a_i} \overline{z^i} = \overline{\sum_{i=0}^n a_i z^i} = \overline{P(z)}
\end{gather*}
Recall that $\lambda$ is a root of $P(z) \iff P(\lambda)=0$. But then $P(\overline{\lambda}) = \overline{P(\lambda)}=0$, so $\overline{\lambda}$ is also a root of $P(z)$


text:
Q: Moving local SQL Server 2008 databases over to a single Internet based server Has anyone any experience moving a number of identical SQL Server databases (with unique data) from individual local servers to a single internet based server?
We currently have 10 companies using our Windows app which uses SQL Server 2008 for data storage, but we are finding that maintaining the databases and ensuring they are backed up etc is a major headache as they are all on individual local LANS.
We are now looking into the prospect of increasing the client base to 40-50 organisations and also needed to report on the data across all the organisations.
If we simply created 50 identical databases on our own internet based server, we could achieve this without too much of a redesign, but is this the best approach?
Or should we merge all the databases into one and create an extra column to identify the organisation so they only see their own data?
Each organisation has between 2-10 staff members and input about 5000-10000 records per year consisting of 20 fields of mainly chars and ints so it's not too enormous.
Any guidance would be appreciated.

A: You'll probably find that re-architecting the whole app to only allow access to data identified by the organization column a lot more development work with the possibility of leaking data from one organization to another if it all isn't thoroughly tested.
Also you'll probably find that having lots of databases on a single server might help with scaling things up at a later date, as you can move some databases off to another server.
For backups, a single maintenance plan can backup all databases on the SQL server.
In the longer term I think this is probably the best solution without knowing much more about how the database and app execution details and planned growth over time.

A: You are most likely better served to keep the databases separate. We had a similar issue and the need to assure customers that their data would not be mixed with others (in case of a security problem) was the primary concern, although the ability to move some customers to another server is a good one as well. Also, with separate databases you can have minor modifications to one customer without affecting them all (either for customized solutions or different versions if one doesn't want to upgrade, etc).
We created a single "global" database to track information about each customer (including the database name and server their data was located on). Then you can do most high level queries against that and rarely have to go through each individual customer database.
We also created some scripts/batch programs that would run SQL queries against all (or given) databases so that updates or reporting queries could be run against 50+ databases very quickly without any extra work. Those scripts are definitely worth the effort to develop, and there might be third party applications that do the same thing.

A: If all databases contains some common tables with same data, the best solution is to merge all the databases into one with partitioning of tables with different data for each organization by new organization column, though.


text:
Q: How can get both text and value of lookup column on React material-table? How can I get both text and value of lookup column from editable material-table? Lookup gets only value of selected item. For example;
{ "0":"Istanbul", "2":"Ankara", "3":"Izmir" }

If I select "Istanbul" on lookup then I get 0 value. But I need both 0 and Istanbul.
This is my row value when adding a new row.
[{
    "txtIsinAdi":"İş 1",
    "lstIsinSinifi":"0"
},
{
    "txtIsinAdi":"İş 2",
    "lstIsinSinifi":"1"
}]

And this is my row added code :
               onRowAdd: newData =>
                new Promise((resolve, reject) => {
                    if(this.props.datafield.IsReadOnly === false)
                    {
                        setTimeout(() => {
                        {
                            const data = this.state.data;
                            data.push(newData);
                            this.setState({ data }, () => resolve());
                        }
                        resolve()
                        }, 1000)
                    }
                    else
                    {
                        this.messageHelper.showWarningMessage("Bu tabloya kayıt ekleme yetkiniz yok.");
                        reject();
                    }
                  })
            }}

A: You can simply make the lookup object global like this:
const lookup = { "0":"Istanbul", "2":"Ankara", "3":"Izmir" }
class Table { ....}

and use that in the columns
columns={columns={[
      { title: 'Name', field: 'name' },
      { title: 'Surname', field: 'surname' },
      { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
      {
        title: 'Birth Place',
        field: 'birthCity',
        lookup: lookup,
      },
    ]}}

and reference that in your callback:
 onRowAdd: newData =>
            new Promise((resolve, reject) => {
                // The value (0)
                const value = newData.birthCity;
                // The city (Istanbul)
                const city = lookup[value];
                if(this.props.datafield.IsReadOnly === false)
                {
                    setTimeout(() => {
                    {
                        // You are mutating your data here because its the same object
                        const data = this.state.data;
                        data.push(newData);
                        this.setState({ data }, () => resolve());
                    }
                    resolve()
                    }, 1000)
                }
                else
                {
                    this.messageHelper.showWarningMessage("Bu tabloya kayıt ekleme yetkiniz yok.");
                    reject();
                }
              })
        }}

Additionally, you are mutating your data object in the onRowAdd callback. The state data could also be different on the setState call since they get batched up. Set the data like this:
this.setState(prevState => ({ data: [...prevState.data, newData] }), () => resolve());

This will ensure that data is already up to date and it does not get mutated.


text:
Q: Undo TFS Unshelve I am using Visual Studio 2015. Version of TFS is 2012 (Version 11.0.51106.1). Is there a way to undo unshelve, other's user shelveset, to have situation as before unshelve command?

A: No, there is no this command.Unshelving is how you restore the shelveset to your machine so you can keep working on it. It doesn't change the shelveset or anything else  on the server. It's just a get operation.
Seems you just want to bring the code back to how it was before you loaded up someone's shelveset onto the workspace.
If you hadn't made changes in pending changes before loading the shelveset, Undo Pending Changes can solve your problem. Otherwise, you may have to manually excluded the changes you made then undo the changes in shelveset.

Moreover, if you encounter such a situation again, a good suggestion might be to save your workspace to your own shelveset before unshelving anyone else's code.

A: When there is no pending changes ... choose Get Specific Version > Latest Version ... this will restore the files to the last check-in.


text:
Q: Lost data after store and reload of UIImage in iPhone App I have developed an iOS7 app. I use the UIImagePickerController to get a UIImage. During the usage of the app an image
is stored to the local app directory and loaded. The file will be overwritten several times. I use UIImagePNGRepresentation and NSData storeToFile to store
the picture. In order to load the image I use UIImage initWithContentsOfFile.
It works fine for some store and load processes. With the Debugger I can confirm that the picture is stored and loaded appropriately.
But after some time the stored picture does not contain a picture anymore. When I look at the load procedure with the debugger I can see that
a picture is loaded but it seems to be completely transparent with no other information.
This phenomenon only occurs on a device and not during a simulation with the simulator. Furthermore, the effect seems to occur only when the app is kicked out of the memory (double tap of the home button)
I debugged the app for hours but I cannot imagine the reasons for this behaviour. Additionally it is difficult to debug due to the complete termination of the app. Does anybody know a solution or has been faced with the same problem? Could anybody give me a hint what to debug to track down the problem?
Thanks in advance. Any help is appreciated. :)
Thanks for your answers. Here is a code excerpt:
Code to store image:
Generate file path in documents directory
NSString *name = [NSString stringWithFormat:@"ImageforButton%i.png",i];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [[path objectAtIndex:0] stringByAppendingPathComponent:name];

Create NSData from UIImage (image is a UIImage that always has the correct image data)
NSData *picData = UIImagePNGRepresentation(image);

Write NSData to file
[picData writeToFile:file atomically:true];

Code to load image:
Generate file path
NSString *name = [NSString stringWithFormat:@"ImageforButton%i.png",i];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [[path objectAtIndex:0] stringByAppendingPathComponent:name];

Load picture
UIImage *img;
if ([[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:false] == true)
{
img = [UIImage imageWithContentsOfFile:[self saveFilePath:name]];
}

img does not always contain the right data. Before the app is completely terminated img
contains the expected picture. After the app was completely terminated a valid
UIImage can be loaded to img but it seems only to contain a transparent picture.
All in all it does not contain the right picture anymore.


text:
Q: SharePoint: Farm backup stuck Ours is a SharePoint 2010 Server (Single server Farm). We started the Farm backup specifying a local drive folder. After this Backup process screen appeared. However, since then (Last 2) hours there is no update. Refresh of page shows same message. Also there are no errors in ULS or Event Viewer. SharePoint Timer and Administration Services are running.
What could be wrong. What are we missing.

A: Go to backup and Restore > Check backup and restore job status pages, check if there is any record about the process.
Whether there is backup file in the backup location?
You can run the commend below in SharePoint 2010 Management Shell and run as administrator to check the backup log:
gc -Path \\path\spbr0000\spbackup.log -Wait


text:
Q: Is it available if Kafka Sink consume multiple sink into multiple table with standalone configuration? I have read that an Kafka connect source can receive a multiple topics from a database (a topic represent one table). I have PostgreSQL database with many table, and one Kafka source are satisfied enough for this time. But is it available if I declare only single JDBC Kafka sink to consume all the topics into topic-based destination table, for example all tables from PostgreSQL into single MS SQL Server Database? It is time-cost, for example if I have 200 Tables from one database and must make 200 sinks connection for each tables, although I only need to declare the source once.

A: You can use Debezium to snapshot one database and all tables to send them over Kafka and dump to any other sink connector (including MSSQL), yes
How many connectors you need to run or how many tables on the destination you'll create are ultimately up to your own configurations
And standalone doesn't matter, but distributed mode is preferred anyway, even if you are only using one machine


text:
Q: auth_middleware..middleware() got an unexpected keyword argument 'user_id' I am trying to apply my custom auth middleware in the url path that has id .
But getting this error.
from .views import Profile

app_name = 'account'

from employer.middlewares.auth import auth_middleware

urlpatterns =[
    path('dashboard/pages-profile/<int:user_id>', auth_middleware(Profile.as_view()), name='profile'),
    ]

And my auth middleware is this:
from django.http import HttpResponseRedirect
def auth_middleware(get_response):
    def middleware(request):
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        response = get_response(request)
        return response
    return middleware

A: You need to hook your custom middleware into the chain of middleware defined in MIDDLEWARE in your settings.py. The path statement where you currently just place it expects a function or Class based view. So you try to activate your middleware by just kind of wrapping the view in the path statement which is not correct. Se also the explanations when you look for "custom middleware tutorial" in the django docs.


text:
Q: CSS- and HTML-only tabs not responding properly This one really has me confused. It's probably something simple that I've missed, but I sure can't find it...
I've created a fiddle to show you what I'm talking about.
You see originally this had 4 sections, these scrolled through fine with all of the links working correctly. The client has since added 1 more section, now for some reason when I add a further radio link, the whole control of the slide show goes to pot. See what I mean here.
All I've added is an extra link and content area. Does anyone know what I'm doing wrong? If you erase the below from the jsfiddle you'll see that it works correctly, but with the label for tab 5, it gives up. I'm at a loss... Any help greatly appreciated!
<input id="tab-5" type="radio" name="radio-set" class="tab-selector-5" /> POS

Fullfilment

Whatever your project involves Expressive Print are experienced in delivering it for you. From daily pick and pack requirements to contract packing and bulk despatches we have the ideal space to work in - clean, modern and secure premises with packing teams who are all fully CRB checked, robust stock control systems, comprehensive insurance cover and expertise. This ensures the right things are packed in the right order and sent the right people – simple but critical. Selecting a fulfilment partner who has strong systems with full accountability and customer service resource is vital to ensure your product's success.

A: Demo your Jsfiddle
Now you just add one line css in your css file
.tabs input.tab-selector-1:checked ~ .content .content-1,
.tabs input.tab-selector-2:checked ~ .content .content-2,
.tabs input.tab-selector-3:checked ~ .content .content-3,
.tabs input.tab-selector-4:checked ~ .content .content-4,
.tabs input.tab-selector-5:checked ~ .content .content-5  // add this line in your css file
{
    -webkit-transform: translateY(0px);
    -moz-transform: translateY(0px);
    -o-transform: translateY(0px);
    -ms-transform: translateY(0px);
    transform: translateY(0px);
    z-index: 100;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    opacity: 1;
    -webkit-transition: all ease-out 0.3s 0.3s;
    -moz-transition: all ease-out 0.3s 0.3s;
    -o-transition: all ease-out 0.3s 0.3s;
    -ms-transition: all ease-out 0.3s 0.3s;
    transition: all ease-out 0.3s 0.3s;
}

Demo


text:
Q: Accessing User defined service in spring boot I am working on spring boot application which uses REST webservices. Till now , all the database paaswords i used to store in my application.properties class and am using HICKARI CP also to manage the connection pooling.
But now , i have created the user services in Cloud foundry and have included the script of CF in my build.gradle file too.
But i do not have any idea as to how shall i access these services within my code and how can i autowire thise datasources. Please advice any solution.

A: Use Spring cloud service connector. This is sub project of Springs cloud.
http://cloud.spring.io/spring-cloud-connectors/spring-cloud-spring-service-connector.html#_relational_database_db2_mysql_oracle_postgresql_sql_server

you can create a mysql service inside your cloud foundry space. And the bind the same to your app. This can be done as defining services inside your manifest.yml or using bind-service command in cf cli.
You can add spring cloud service connector dependencies in your gradle build and add datasource configuration bean.
@Bean
public DataSource dataSource() {
    return connectionFactory().dataSource("your-mysql-service-name");
}

This creates a datasource of the mysql service in your application, and registers as a bean in spring context. That can be autowired where ever needed.
Alternatively, cloud foundry exposes the details about every service that application is binded to, in VCAP_SERVICES env variable. Once your application is binded to service, you can find your mysql service username, password, connection url, db name etc in this variable. You can read this variable and parse the values and build a datasource of your own.
Using service connectors are preferred approach as the infrastructure code is handled by springs.


text:
Q: Automatically update user_id and date fields at django into database I'm new to Python and Django and there are some things I would like to achieve in models.py:
After a user submits a form I would like to safe both the current date and the current user_id of the user into the database.
I know django offers to use @property decorators for those, but the problem with that is that I would like to make SQL queries using user_id and that doesn't work with decorators.
Another related question is how to establish calc fields like an automatic calculation of two values in the form before submitting.

A: Try making a model for the submission of the form. And give the model a foreign key which is connected to the user. Then add a DateField and prove the default value as datetime.now() from the datetime module which is probably already installed on your device.

A: In settings.py I added this line: 'crum.CurrentRequestUserMiddleware',
In models.py:
from django.contrib.auth.models import User
import crum

class PlantSpecies(models.Model):

    def save(self, *args, **kwargs):
        userid = crum.get_current_user()
        self.userid = userid.id
        super(PlantSpecies, self).save(*args, **kwargs)

    userid = models.CharField(max_length=45, blank=True, default=crum.get_current_user())
    date = models.DateTimeField(auto_now_add=True)
    species = models.CharField(max_length=45, blank=True)
    common_name = models.CharField(max_length=30, null=True, blank=True)

    def __str__(self):
        return self.species


text:
Q: Bindings.isNotNull causes null pointer exception I have a simple field (well a property, really):
    private final SimpleObjectProperty<ObjectWithColor> colored;

The ObjectWithColor class has a property SimpleObjectProperty<Color>, hence the name.
Okay,now this property sometimes points nowhere; What I'd like to do is to have a ObjectExpression<Color> that returns colored's color when not null, or  BLACK otherwise.
I wrote this code in the constructor:
colored = new SimpleObjectProperty<>();
ObjectExpression<Color> color= Bindings.when(colored.isNotNull()).then(colored.get().colorProperty()). otherwise(Color.BLACK);

What I don't understand is why I get a NullPointerException running that line of code. I understand that gets called, but I don't understand why. Shouldn't that be called only when colored is non null?

A: > Shouldn't that be called only when colored is non null?
No. Lets do some analogy with your code:
SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty<>();
colored.get().colorProperty();

Since the Property and its derivative classes are all wrapper ones, it can be thought as a Person class having (wrapping) fullName field as String. So the analogy for the above:
Person person = new Person();
person.getFullName().toString();

We get NullPointerException at getFullName().toString(), since getFullName() returns null.
For both comparisons the assumption was; the wrapped field does not has a default value or does not initialized in the default constructor.
Lets continue with this assumption. In this case we can avoid NullPointerException by,
initializing value through constructor:
Person person = new Person("initial full name");
person.getFullName().toString();

or calling setter:
Person person = new Person();
person.setFullName("Foo Bar");
person.getFullName().toString();

The same is true for your code:
SimpleObjectProperty<ObjectWithColor> colored =
                     new SimpleObjectProperty<>(new ObjectWithColor(Color.RED));
colored.get().colorProperty();

or
SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty<>();
colored.set(new ObjectWithColor(Color.RED));
colored.get().colorProperty();

I hope I have understood your question correctly. Nevertheless, on other hand, in a "Shouldn't that be called only when colored is non null?" prompt, you are talking about colored is non null while you actually checking for lastSupplier.isNotNull(). I presume it as not a typo and answered based on current code piece.

EDIT: Ohh! It was a typo then!
Was able to generate the problem. As  a documentation of javafx.beans.binding.When#then() mentions, this method returns:

the intermediate result which still requires the otherwise-branch

Thereby the statement colored.get().colorProperty() must be reachable. Normally the bindable if-then-else block was designed for the usages like:
SimpleObjectProperty<Double> doubleProperty = new SimpleObjectProperty();
ObjectExpression<Double> expression = Bindings.when(doubleProperty.isNotNull()).then(doubleProperty).otherwise(-1.0);
System.out.println(doubleProperty.getValue() + "  " + doubleProperty.isNotNull().getValue() + "  " + expression.getValue());
doubleProperty.setValue(1.0);
System.out.println(doubleProperty.getValue() + "  " + doubleProperty.isNotNull().getValue() + "  " + expression.getValue());

Output:
null  false  -1.0
1.0  true  1.0

As a result, you may define an initial default value:
SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty(new ObjectWithColor(Color.BLACK));

or may use ObjectWithColor.colorProperty in bindings directly.


text:
Q: Setting CRS automatically on Raster using QGIS? I'm currently working with the Semi-Automatic Classification Plugin to help ID agricultural plots. However, when I attempt to set up the training I am given the error message.

Error [61]: Projection error. Try to assign projection to raster
  /Users/User/Documents/University/Thesis/Map
  Layers/Rasters/orthophoto2015_1m.tif

The Raster is projected for EPSG 2039 ITM. Despite this, every time I load the Raster or save my work I am either asked to select a CRS, if one is not assigned as a default. I don't run into issues with training on rasters that have their own projection already.
In short, how do I set up a raster file so that it is automatically assigned a CRS without having to select one manually or have it set to that of the project?


text:
Q: how to avoid reloading Rad Tree List I am using Telerik Rad Tree List. when expanding the tree , it is postback and get child data from server. it is ok. but when collapse the tree, the page is again reload.
i am not sure, it is default action in telerik tree list.
i am using vs2010 and sql server 2008 for my web application.
How to avoid the reloading while collapse the tree.
Thanks,
Pooja

A: The TreeList will still have to do a postback when you expand because the parent node's children get created on expand. I believe this is how it loads -- I am facing the same problem actually. But if you want to decrease time it takes to reload the page, you can "ajaxify" it. Refer to this link: http://www.telerik.com/help/aspnet-ajax/treeview-onclientnodeclicking.html
If you really want to get rid of the postback, refer to this link: http://www.telerik.com/help/aspnet-ajax/treeview-onclientnodeclicking.html
But that's for TreeView, might work on TreeList. I still think it'll go back to the server when you try to structure on the client-side.

A: write the client side onclientnodeclicking event and check if node is expand then write code for collapse.


text:
Q: What is lsh_ used for and/or what is it doing? I am new to programming in Linux and I am quite confused. I notice the lsh_ prefix is used for function names here. I'm not sure why.
The only thing I can find on the internet is that lsh could possibly mean "limited shell". However, it is not clear. If that is what it means, what is a "limited shell" and how or why are we using it?
example: lsh_loop()

A: The article points to https://github.com/brenns10/lsh and in
https://github.com/brenns10/lsh/blob/master/src/main.c#L9 it says:
@brief        LSH (Libstephen SHell)

So lsh stands for Libstephen SHell.
libstephen is also a name of another repository of the same user
https://github.com/brenns10/libstephen.


text:
Q: Setting Lightswitch Email Address Editor width I have a Lightswitch 2011 application with an Email address inpput.
For some reason, I cannot set the width on it - it ignores it unless I set it to Stretch (but then the control is centered which is not what I want).
When the user types in the text box it then expands. The same behaviour happens with the Currency Editor control.
How do I set the width on this control? I have included a video to demonstrate the problem.
Video of width setting issues

A: You need to select anything other than Stretch (in your case, shown in the video, I'd suggest Left), then select the Pixels option, entering the width that you want.
You may have tried this combination, but unless you do it in the correct sequence, it sometimes ignores your selections. This is a known bug in LS 2011. I hope it's fixed in V2, but I haven't started using V2 yet, so I can't confirm that it has been fixed.
The order that I use to get around this is as follows:

*

*Select Left

*Select Pixels

*Type in the width

*Click on another textbox before you save

Edit: removed "or move on to the next control" from step 4

A: As Yann pointed out - it is a known bug in LS 2011 and works fine after I upgraded to LS 12 in Visual Studio 2012 (i.e. as expected)


text:
Q: Python: how to loop through folders and files and index them in array I have a bunch of folders, each containing a set and equal number of files. I want to use python to loop through each folder and do some analysis to each file. I want to store the results of the analysis within a numpy array.
For example, suppose we have 3 folders, each containing 5 files. I want the analysis results to be stored within an array results=np.zeros((3,5))
Here's a code snippet close to what I want, but not correct.
results=np.zeros((3,5))
dircount=0
filecount=0
for root, dirs, files in os.walk(ROOTFOLDER):
  for dir in root:
    for file in dirs:
      result[dircount,filecount]=#do some analysis with file
      filecount=filecount+1
    dircount=dircount+1
    filecount=0
print result

I must confess, I do not fully understand how os.walk works, but it seems good for jobs involving a loop through files and folders.

A: os.walk() does the most part of what you're trying to do manually:
results=np.zeros((3,5))
dircount=0
for root, dirs, files in os.walk(ROOTFOLDER):
    filecount = 0
    for f in files:
        #  absolute filename is os.path.join(root, f)
        result[dircount,filecount] = #do some analysis with file
        filecount += 1
    dircount += 1
print result

The main loop will walk down all folders in dirs recursively, and thus you get all files in that folder tree.

A: You can use os.walk here
results=np.zeros((3,5))
dircount=0
for root, dirs, files in os.walk(ROOTFOLDER):
    filecount = 0
    for f in files:
        #  absolute path is os.path.join(root,f)
        result[dircount,filecount]
        filecount += 1
    dircount += 1

print result
If you need complete files_list in the folder reccursively
files_list = [os.path.join(folder,i) for folder, subdirs, files in os.walk(ROOTFOLDER) for i in files]


text:
Q: setAdapter not recognize in android studio I have a tutorial video, in Video teacher can use setAdapter as you see below Image, but in my code, android studio not Recognize it
image of teacher learning:

and below is my code screenshot:

A: Replace
ViewPager.setAdapter(...

with
viewPager.setAdapter(...

ViewPager (with a capital letter) is a class name and by using it here, you are trying to access the static method of that class. There is no static method setAdapter and hence the error.
For readability, replace viewPager with pager. It will make it easier for you to avoid such mistakes and the code will be more readable :-)

A: Write viewpager.setAdapter instead of ViewPager.setAdapter
By writing ViewPager.setAdapter you try to execute class method, not object method. But ViewPager.class has no such method, only instance of it.


text:
Q: zcat filename expansion in for loop I got these files:
bonds.txt.gz
bonds_201307.txt.gz
bonds_201308.txt.gz
bonds_201309.txt.gz
bonds_201310.txt.gz
bonds_201311.txt.gz
bonds_201312.txt.gz

I have a for loop to go through the files, uncompress them, and find a string with grep:
for f in `ls *.txt.gz`; do echo $f; zcat $f | grep MYBOND; done

If I run this I get the following:
bonds.txt.gz
zcat: bonds.txt.gz.gz: No such file or directory
bonds_201307.txt.gz
zcat: bonds_201307.txt.gz.gz: No such file or directory
bonds_201308.txt.gz
zcat: bonds_201308.txt.gz.gz: No such file or directory
bonds_201309.txt.gz
zcat: bonds_201309.txt.gz.gz: No such file or directory
bonds_201310.txt.gz
zcat: bonds_201310.txt.gz.gz: No such file or directory
bonds_201311.txt.gz
zcat: bonds_201311.txt.gz.gz: No such file or directory
bonds_201312.txt.gz
zcat: bonds_201312.txt.gz.gz: No such file or directory

Seems like zcat is expanding the filename with an extra .gz
However its not doing it when I try to zcat a file from the command line just picks up the filename which is provided and doing its job. Why is it happening when called in a loop?
I know I can achieve the same by using zgrep or find, but still interested in understanding this behaviour of zcat.
Thanks!

A: I tried your script, there is no issue, but if I set alias ls='ls --color=always', I will have the same issue
maybe your ls returns some hidden characters like color code
can you try
for f in `\ls *.txt.gz`

but you could have used
for f in *.txt.gz instead of
for f in `ls *.txt.gz`

and if your system has zgrep, you could use zgrep MYBOND $f instead of zcat $f | grep MYBOND
The code will be like this:
for f in *.txt.gz; do echo "$f"; zgrep MYBOND "$f"; done


text:
Q: How to separate application from data in a good manner? During development of my php-app I've stored all data that the app produces within the app-folder and hence the data being part of my git-repo. The root of the repo is also the webroot. This has worked well for me during the beginning of development and it sort of made sense at the time to commit the app together with the data.
But I feel this needs to be redone now for several reasons. One being that the data-size is getting too big for me to comfortable store it in the git-repo.
Another is that I simply do not need to have a snapshot of the data for a given commit.
The main-reason, I guess is that I've deployed my app to my NAS(synology) for real use, and I push commits to it via webdav. And to my knowledge of git, it's not possible or at least not practical to do pushes while leaving certain data in the remote-repo untouched.
Also, it would be nice though not necessary if both the app on the nas and the app on my computer, while testing has access to the same data-directory. This made me think of moving the data out from the app-directory and access it via ftp. But I'm not sure that would be a good idea, especially since all the "real" access to the files would be from the very same device, the nas.
What would be a good structure and file access methods etc for this?

A: I always keep my data in a separate directory which I take out of git with a .gitignore file.  This means that when I push changes I am not overwriting the live data.
If I need fresh data to test on I use ftp to download a new version of the data directory from the live server to my development server.
This works for me because most of the data is uploaded by users so it quickly gets out of sync with my development copy and I don't want to overwrite it.  It also means that I can't accidentally corrupt their data with a mistake in development.


text:
Q: OpenShift with Tomcat and PHP I have successfully set up a OpenShift application using Tomcat 7.
I have successfully set up a OpenShift application using PHP5.4.
But my objective is a web application that uses Tomcat (Java) but also serves a few PHP pages.
Is it possible to do this?
That is, an OpenShift application that uses both Tomcat 7 and PHP 5.4?

A: I'm pretty sure that is not possible unless you do a custom install and have an apache/nginx proxy in front of your java server, and have it take care of the php pages, and then forward java requests on to the other server.


text:
Q: Why isn't the Sorgenfrey line sigma-compact? Maybe my misunderstanding of topology and compact sets is seriously flawed, but as far as I can tell I can't see why the "Sorgenfrey Line" is not $\sigma$-compact.
A topological space is $\sigma$-compact if it is the countable union of compact subsets. The Sorgenfrey Line is simply the real line endowed with the topology of half-open intervals. As stated on Wikipedia, the sets $(-\infty, a)$ and $[b, \infty)$ are both open, implying $[a, b)$ is clopen, and hence compact for finite $a, b$ (closed and bounded, unless Heine-Borel doesn't hold in this space for some reason).
Then we can write $\mathbb{R} = \bigcup_{n\in\mathbb{Z}}[n-\epsilon,n+1)$ for some $\epsilon>0$, so the Sorgenfrey line is clearly $\sigma$-compact.
What's the flaw in the logic? Is it the assumption that Heine-Borel holds in this space, and so the subsets with finite open subcovers aren't exactly the closed, bounded sets?

A: Heine-Borel is specific to the Euclidean topology, and need not hold in a general space (where "bounded" makes no sense, necessarily), and it does not hold for the Sorgenfrey line: $[0,1]$ can be covered by the open sets $[0,1-\frac{1}{n})$, $n \in \mathbb{N}$ and $[1,2)$ and this cover has no finite subcover. So $[0,1]$ is not compact.
In fact, I showed here that a compact subset of the Sorgenfrey line is at most countable. So a $\sigma$-compact subset is also at most countable.
As a bonus an indirect proof: suppose $S$ were $\sigma$-compact.
Then $S \times S$ would be $\sigma$-compact (hence Lindelöf) as well, and $T_3$, and a $T_3$ Lindelöf space is normal while $S \times S$ is not normal.
Or, $D':= \{(x,-x) : x \in S\} \subset S \times S$ is closed, uncountable and discrete and so $S \times S$ cannot be $\sigma$-compact, as otherwise $D'$ would be too, which it is not: the only $\sigma$-compact discrete spaces are the countable ones.


text:
Q: Query .evtx converted to .xml Having used evtx_dump.py to convert .evtx files to .xml i seek to learn how to query it using XQuery or whatever helps me datamine the document using BaseX.
At this point whatever i try i can only query the whole document using //Events
When i define a path such as //Events/Event/System/[EventID = '4688'] i get 0 results.
This first query is to simply track all specific EventID matching a specific value.
Being new to BaseX and XQuery i found the documentation hard to apply to this use case.
I looked for tools to help me build an XQuery to no avail.
BaseX has all index features enabled  i could find.
Br,
Joris

A: When XQuery fails to return data you are expecting it is often caused by the presence XML namespaces.
The Microsoft XML event log uses a XML namespace on Event nodes and it is inherited by their children. This is the xmlns='http://schemas.microsoft.com/win/2004/08/events/event' you can see in the files. E.g
    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <Events><Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'>
   <System><Provider Name='SideBySide'/><EventID Qualifiers='49409'>59</EventID><Version>0</Version>
    ...

Your XQuery must adjust for that. Either by saying any namespace is ok (using *:)
//*:System/[*:EventID = '4688']

or by explicitly specifing the expected namespaces.
declare namespace ns="http://schemas.microsoft.com/win/2004/08/events/event";
/Events/ns:Event/ns:System[ns:EventID= '4688' ]

See this similar issue xquery-not-working-with-namespaces


text:
Q: How do I know what I need to show when using induction? (Peano axioms) As an exercise I wanted to prove that addition was commutative using the Peano axioms.
To quickly restate the definition of addition (where $S(n)$ is the successor function of $n$, which we can show is the same as $S(n) = n+1$):
$$\begin{align}
a + 0 &= a \tag{additive identity} \\
a + S(b) &= S(a + b) \tag{addition of naturals}
\end{align}$$
The axiom of induction then is the statement that:
$$\forall P(P(0) \land (P(k) \implies P(k+1)) \implies \forall n(P(n)))$$
Which means for all predicates, some base case being true and the $k$th case implying the $k+1$th case means that the predicate is true for all $n$.
For the purposes of this question, assume we have just proven that $a + 0 = 0 + a$, that $a + 1 = 1 + a$, and that $(a+b)+c = a+(b+c)$.
Then my question is how we're actually using this induction for proving the general commutative case $a+b=b+a$. Here is what I originally did:
Base case: We have $a + 0 = 0 + a$ as true.
Inductive step: Suppose $a+b = b+a$. Then $a+S(b) = S(a + b) = S(b + a) = b + S(a) = b + (a + 1) = b + (1 + a) = (b + 1) + a = S(b) + a$. We also have $(b+1)+a = (1+b)+a = 1+(b+a) = 1+(a+b) = (1+a)+b = S(a) + b$.
I figure that $P(0)$ here is when $k=0$ and we say $a+k = k+a$ is our base case, same as how we say $a + 0 = 0 + a$ is our base case.
But then what exactly is the $k+1$th case here? I mean I tried to show that $a+b=b+a$ implied all sorts of identities (I basically tried to sledgehammer it with every permutation I could think of) but I don't know exactly what is minimal and sufficient to prove the inductive step.
If the inductive hypothesis is $a+b=b+a$ and this is our $k$th step, i.e. $P(k)$ is true, what is $k$ here? $k=a$? $k=b$? Is it enough to show that $S(a) + b = b + S(a)$? If not, how do I know what all I must prove here?
I'm trying to stay strict within the definitions here so that I don't run the risk of letting intuition and "common sense" cheat myself of the understanding here.
How do I correctly interpret the $P$ statements here? What is $P(0)$? What is $P(k)$? What is $P(k+1)$ and what must I do to show it? Or is my induction axiom not correct? What should I be doing here?

A: We want to prove commutativity of sum, i.e.: $m+n=n+m$.
The proof has a first step by induction on $n$, and thus the $P(n)$ to be used with induction axioms is:

$a+n=n+a$.

(i) Basis: $a+0=0+a$ ($P(0)$), and
(ii) Induction step: assuming that $a+n=n+a$ holds (induction hypotheses) we have to prove that $a+s(n) = s(n)+a$.
Having done the two steps of induction, the Induction axioms allows to conclude with:

$\forall n \ (a+n=n+a)$.

The above result has been derived for a "generic" $a$ (for $a$ whatever): thus, we may geenralize it using Universal generalization to conclude with:

$\forall m \ \forall n \ (m+n=n+m)$.

A:
In the vein of my previous answer, here's some Agda:
data _≡_ {A : Set} (a : A) : A → Set where
    Refl : a ≡ a

data ℕ : Set where
    Z : ℕ
    S : ℕ → ℕ

_+_ : ℕ → ℕ → ℕ
m + Z = m
m + S n = S (m + n)

cong : {A B : Set} → (f : A → B) → {x y : A} → x ≡ y → f x ≡ f y
cong f Refl = Refl

_trans_ : {A : Set} → {x y z : A} → x ≡ y → y ≡ z → x ≡ z
Refl trans q = q

left-additive-identity : {n : ℕ} → (Z + n) ≡ n
left-additive-identity {Z} = Refl
left-additive-identity {S n} = cong S (left-additive-identity {n})

left-increment : {m n : ℕ} → (S m + n) ≡ S (m + n)
left-increment {m} {Z} = Refl
left-increment {m} {S n} = cong S (left-increment {m} {n})

commutative : {m n : ℕ} → (m + n) ≡ (n + m)
commutative {Z} {n} = left-additive-identity {n}
commutative {S m} {n} = left-increment {m} {n} trans cong S (commutative {m} {n})

This uses the equivalent of three uses of the induction axiom. One each for left-additive-identity which proves that $0+n=n$ ($n+0=n$ comes automatically from the definition of _+_); left-increment which proves $(m+1)+n=(m+n)+1$; and commutativity itself. Refl represents reflexivity of equality. cong represents the congruence property of equality, i.e. that functions take equal inputs to equal outputs. This is only used in the form: if $m=n$, then $m+1=n+1$. trans is the transitivity of equality.


text:
Q: How do I get value instead of reference from icollection when pullling in cshtml I am trying to display the values of an icollection in cshtml nut instead of the value I get the system reference.
System.Data.Entity.DynamicProxies.ReferralICD10Code_F7D1453817B346998A38AA8F0A6458AB31F1C8E815585BE8E92F6BBA57298BC8
The icollection is defined as
[Display(Name = "Referral ICD10Codes")]
public virtual ICollection<ReferralICD10Code> ReferralICD10Codes { get; set; }

And when I try to build up the variable to display in the cshtml I am using
    @{
        var reficd10codes = "";
        foreach (var item in Model.Visit.ReferralICD10Codes)
        {
            reficd10codes = reficd10codes + " " + Model.Visit.ReferralICD10Codes.FirstOrDefault().ToString();
        }
    }

If I leave out the firstordefault() I get
System.Collections.Generic.HashSet`1[Clinton.Core.Domain.ReferralICD10Code]

So now I am trying to figure out how to get the actual values instead of the reference.
Thanks


text:
Q: Release Management for Visual Studio 2013 - Deployment Agent "Unknown username or bad password" We're using Release Management for Visual Studio 2013 and deployments are working smoothly in DEV, QA and Staging servers, which are all in the same domain as the RM/Build server.
Trying to setup Production deployment agent on a server that is outside the RM server domain and having issues.
A local "shadow" account was created on the RM server and Production server, both with same username/password. Deployment agent was installed on the Production server and setup was successful using "./shadow_user" format for the username.
Release Management client isn't showing the Production server, and Event Viewer on the RM server shows numerous security audit failures from the deployment agent. Failure detail shows the Production server name for the domain instead of the RM server name (impersonation is failing). Specific message is:
An account failed to log on.

Subject:
    Security ID:        NULL SID
    Account Name:       -
    Account Domain:     -
    Logon ID:       0x0

Logon Type:         3

Account For Which Logon Failed:
    Security ID:        NULL SID
    Account Name:       shadow_User
    Account Domain:     PROD-SVR

Failure Information:
    Failure Reason:     Unknown user name or bad password.
    Status:         0xC000006D
    Sub Status:     0xC0000064

Process Information:
    Caller Process ID:  0x0
    Caller Process Name:    -

Network Information:
    Workstation Name:   PROD-SVR
    Source Network Address: -
    Source Port:        -

Detailed Authentication Information:
    Logon Process:      NtLmSsp
    Authentication Package: NTLM
    Transited Services: -
    Package Name (NTLM only):   -
    Key Length:     0

This event is generated when a logon request fails. It is generated on the computer where access was attempted.

The Subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service, or a local process such as Winlogon.exe or Services.exe.

The Logon Type field indicates the kind of logon that was requested. The most common types are 2 (interactive) and 3 (network).

The Process Information fields indicate which account and process on the system requested the logon.

The Network Information fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.

The authentication information fields provide detailed information about this specific logon request.
    - Transited services indicate which intermediate services have participated in this logon request.
    - Package name indicates which sub-protocol was used among the NTLM protocols.
    - Key length indicates the length of the generated session key. This will be 0 if no session key was requested

Any suggestions to solve this issue?
We've tried Windows Credential manager, using the RM server shadow account credentials, but no difference.

A: Instead of using shadow account approach .Use VNext release which supports standard deployment (agent less) which will communicate using WINRM port only requirement is to have machines in same network.
for more information:
http://blogs.msdn.com/b/visualstudioalm/archive/2014/07/07/how-to-setup-environments-for-agent-less-deployments-in-release-management-release-management-2013-with-update-3-rc.aspx

A: The solution was to login with the shadow account on the Production server and add credentials to Credential Manager. Was previously logged in with a different account, and the Deployment Agent didn't see entries in the other Credential Manager instance.


text:
Q: How does opengl project a 3d point to screenspace? I am trying to emulate a subset of opengl with my own software rasterizer.
I'm taking a wild guess that the process looks like this:
Multiply the 3d point by the modelview matrix -> multiply that result by the projection matrix
Is this correct?
Also what size is the projection matrix and how does it work?

A: The point is multiplied by the modelview matrix and then with projection matrix. The resultant is normalized and then multiplied with viewport matrix to get the screen coordinates. All matrices are 4X4 matrix. You can view this link for further details.
http://www.songho.ca/opengl/gl_transform.html#example2

A: (shameless self-promotion, sorry) I wrote a tutorial on the subject :
http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/
There is a slight caveat that I don't explain, though. At the end of the tutorial, you're in Normalized Device Coordinates, i.e. -1 to +1. A simple linear mapping transorms this to [0-screensize].

A: You might also benefit from looking at the gluProject() code.  This takes an x, y, z point in object coordinates as well as pointers to modelView, projection, and viewport matrices and tells you what the x, y, (z) coordinates are in screenspace (the z is a value between 0 and 1 that can be used in the depth buffer).  All three matrix multiplications are shown there in the code, along with the divisions necessary for perspective.


text:
Q: Why are there two listed time complexities for breadth-first search? The Wikipedia article on breadth-first search lists two time complexities for breadth-first search over a graph: O(|E|) and O(bd). Later on the page, though, it only lists O(|E|).
Why are there two different runtimes? Which one is correct?

A: Both time complexities are correct, but are used in different circumstances to measure the time complexity relative to two different quantities. This has to do with the fact that the breadth-first search algorithm typically refers to two different related algorithms used in different contexts.
In one context, BFS is an algorithm that, given a graph and a start node in the graph, visits every node reachable from the start node by first visiting all nodes at distance 0, then distance 1, then distance 2, etc. until all nodes are visited. This will visit every node in the graph and in the process of doing so explore each node one and edge edge at most once (in the directed case) or twice (in the undirected case). By using queues to keep track of which nodes to explore next and using appropriate bookkeeping, the runtime will be O(|E| + |V|) (and with further optimizations, it will be O(|E|)).
In a different context, BFS is a search algorithm used to find the shortest path from some start node in a graph to a destination node in the graph. In this case, the algorithm stops running as soon as it discovers the destination node. This means that the runtime depends on how far away the destination node is from the source node. That distance in turn depends on the structure of the graph. If the graph is densely connected, the node can't be that far away, and if the graph is sparse, the node might be extremely distant. In this context, it's common to add in a parameter called the "branching factor" b, which describes the average or maximum number of edges adjacent to any node. This means that

*

*There is one node at distance 0 from the start node.

*There are at most b nodes at distance 1 from the start node.

*There are at most b2 nodes at distance 2 from the start node.

*...

*There are at most bk nodes at distance k from the start node.

If we assume that the destination node is at distance d from the start node, then BFS will visit at most b0 + b1 + ... + bd = O(bd) nodes during its search, spending O(b) time on each of them. Accordingly, the total runtime will be O(bd).
In summary:

*

*The runtime of O(|E|) is typically used when discussing the algorithm when being used to explore the entire graph.

*The runtime of O(bd) is typically used when discussing the algorithm when being used to find a specific node in the graph.

Hope this helps!


text:
Q: Using the TaskBarItemInfo in WPF for the progress bar in Win 7 taskbar Does anybody have a WPF example of updating the ProgressState through the available enum states when progressing through ProgressValue?
I have the following code which binds my progress value to run from 0 to 1:
<Window.TaskbarItemInfo>
    <TaskbarItemInfo Description="An app with a taskbar info description"
                     ProgressValue="{Binding Count}" ProgressState="Normal"/>
</Window.TaskbarItemInfo>

But, what is a good way to go from None to Normal to None or other flows: None-Normal-Paused-Normal-None.
The code above shows the progress bar on the left at 0% and then finishes at 100% (1).
I imagine I could bind this with a converter to another property hanging of my ViewModel, but wanted to see if anyone had any slicker solutions.
Thanks!

A: ProgressValue is double
use value from 0 to 1

A: In the same way that you are binding the ProgressValue, you can also bind the ProgressState. The type of the ProgressState is an enum called TaskbarItemProgressState, which includes the states you already mentioned.
public enum TaskbarItemProgressState
{
    // Summary:
    //     No progress indicator is displayed in the taskbar button.
    None = 0,
    //
    // Summary:
    //     A pulsing green indicator is displayed in the taskbar button.
    Indeterminate = 1,
    //
    // Summary:
    //     A green progress indicator is displayed in the taskbar button.
    Normal = 2,
    //
    // Summary:
    //     A red progress indicator is displayed in the taskbar button.
    Error = 3,
    //
    // Summary:
    //     A yellow progress indicator is displayed in the taskbar button.
    Paused = 4,
}

I think the 'slickest' ways to do this are the ways you already mentioned, either with a converter or manually


text:
Q: how does this perpetuity relate to the infinite sum $1+x+x^2+\cdots$ You are given that $v=0.9$. You are also given a non-level perpetuity that pays the amount of
$\frac{1}{k(k+1)}$ at times $k=1,2,3,\ldots$. Find the present value of this perpetuity.
I am given that integrating both sides of the function $1+x+x^2+\cdots=\frac{1}{(1-x)}$ as $|x|\lt 1$ should help solve this. (which is $x+\frac{x^2}{2}+\frac{x^3}{3}+\cdots = -\ln(1-x)+C$)
I get $\frac{v}{1(1+1)} + \frac{v^2}{2(2+1)} + \frac{v^3}{3(3+1)} + \cdots$
I have tried factoring $\frac{v}{2}$ which gives me $1+\frac{v}{3} + \frac{v^2}{6}+\cdots$ to get it into a form that makes the hint useful.
Am I missing something?

A: The present value is
$$
PV=\sum_{k=1}^\infty \frac{v^k}{k(k+1)}=\sum_{k=1}^\infty \left(\frac{1}{k}-\frac{1}{k+1}\right)v^k=\sum_{k=1}^\infty \frac{v^k}{k}-\sum_{k=1}^\infty \frac{v^k}{k+1}
$$
We have
$$
\sum_{k=1}^\infty \frac{v^k}{k}=-\log(1-v)
$$
and
$$
\sum_{k=1}^\infty \frac{v^k}{k+1}=\frac{1}{v}\sum_{k=1}^\infty \frac{v^{k+1}}{k+1}=\frac{1}{v}\sum_{n=2}^\infty \frac{v^{n}}{n}=\frac{1}{v}\left(\sum_{n=1}^\infty \frac{v^{n}}{n}-v\right)=\frac{1}{v}\left(-\log(1-v)-v\right)
$$
So we find
$$
PV=\sum_{k=1}^\infty \frac{v^k}{k(k+1)}=\left(\frac{1}{v}-1\right)\log(1-v)+1=0.744157
$$


text:
Q: How to update golang on codeanywhere.com with Ubuntu How to update golang on codeanywhere.com with Ubuntu 14.04?
The default container uses the version from Ubuntu repos, instead of golang PPA.
As of writing it's 1.6 and the newest version is 1.9.

A: (can't comment yet) Just an additional information, the steps in Paweł Prażak's answer work when you run on a Blank Container. If you run them on a Go predefined stack it won't update.
I also recommend to change the GOPATH value to your workspace, running
export GOPATH=$HOME/go

Then run go env to check if the values are correctly updated.
Thanks for the answer by the way, Paweł!

A: You can easily install the latest golang release in the container by using this script:
git clone https://github.com/udhos/update-golang
cd update-golang
sudo ./update-golang.sh

Full details: https://github.com/udhos/update-golang

A: Create and new Blank Container with Ubuntu:

Connect to the container with SSH.
Follow the instructions on the official wiki.
First install the add-apt-repository support:
sudo apt-get update
sudo apt-get install -y software-properties-common

Now install the recent version of golang (refer to the wiki for up to date instructions):
sudo add-apt-repository ppa:gophers/archive
sudo apt-get update
sudo apt-get install golang-1.9-go

Make sure to put the binary on PATH, e.g.:
sudo ln -s /usr/lib/go-1.9/bin/go /usr/local/bin/go

Now the newer version should be available:
$ go version
go version go1.9.2 linux/amd64

Add $GOPATH pointing to the workspace and add $GOPATH/bin to $PATH in ~/.profile:
cat << EOF >> ~/.profile
export GOPATH="\$HOME/workspace"
export PATH="\$GOPATH/bin:\$PATH"
EOF

Apply the new ~/.profile:
. ~/.profile

Also make is missing, if you need it:
sudo apt-get install build-essential


text:
Q: Merge two 'range' tables in microsoft access I have two tables recording parameters over a depth range with different intervals.  Each table has DEPTH_FROM and DEPTH_TO fields as well as a Primary ID. I need to assign PARAMETER to the PARAMETER A ranges.
Can I do this using a subquery? If I need to split records to then I am willing to (I just don't know how). Alternatively, I'd just like to know which 'bin' the RANGE_B.DEPTH_FROM record falls into.
LOCATION
POINTID   X   Y   Z
A123  987654  456788  345

RANGE_A
POINTID   Depth_from  Depth_to  Property_A  PROPERTY_B
A123   0  10  AAA  ???
A123  10  17  BBB  ???
A123  17  30  CCC  ???

RANGE_B
POINTID   Depth_from  Depth_to  Property_B
A123   0   7  ZZZ
A123   7  15  CCC
A123  15  30  VVV

A: It is easy enough to get a bin:
SELECT
   RANGE_B.Depth_from,
   RANGE_B.Depth_to,
   RANGE_A.Depth_from,
   RANGE_A.Depth_to,
   RANGE_A.Property_A
FROM RANGE_A, RANGE_B
WHERE RANGE_B.Depth_from Between [RANGE_A].[Depth_from]
      And [RANGE_A].[Depth_to]

If you would like to explain a little more, an answer closer to what you need may be possible.


text:
Q: Telnet validate email, 550 MI:SPF error When I try validating an email through telnet, using:
Telnet MX.server.for.email.i.want.to.validate.com 25

HELO Buddy

MAIL FROM:  example email address

I get a 550 MI:SPF error, telling me that my IP address does not match the valid sender. In other words, it looks like a spoofed email.
Given that I'm just running Telnet from my Windows desktop, how do I set up a valid request to validate emails with?
Are there any email services that can relay through Telnet to check the validity of an email address without sending an email?

A: Unfortunately you are running into a minefield.
The reason you are having an issue is because the domain name for YOUR email has a restriction saying you cant send email this way (Your domain has an SPF record saying you cant send email except from certain servers). Modifying your SPF record - which is not a great idea - will allow you to bypass this issue.
Telnet is a protocol that does little more then open a tcp session on a given port  There is no concept of relaying mail through it - only opening a tcp connection.
There are websites like mxtoolbox.com that can help with all sorts of testing of mail related.issues.
Most mail servers have disabled user verification because it attracts spammers and reduces security, so you often cant check the validity if an email address without sending an email.

A:
I get a 550 MI:SPF error, telling me that my IP address does not match the valid sender. In other words, it looks like a spoofed email.

Of course it does – you're trying to use someone else's address in the Envelope-From. That's practically the definition of spoofed.

Given that I'm just running Telnet from my Windows desktop, how do I set up a valid request to validate emails with?

Specify the test address as the recipient, i.e. in RCPT.
For the sender, instead use an address belonging to a domain that either allows your desktop PC's IP address, or doesn't have SPF restrictions at all. Ideally this should be a domain that you actually have the rights to. (Note that subdomains can have their own SPF records independently from the parent domain.)

Are there any email services that can relay through Telnet

"relay through telnet" is a nonsensical requirement. Mail delivery over SMTP does not involve Telnet at all.
You're just using the telnet command because it also works as a raw TCP client, but other software and services have no need for this – they make their own TCP connections through the OS, and they directly send the same commands that you're typing in.


text:
Q: Check if any of the value in resultant array similar to values of existing array with codeigniter I really need help to display a month list view in which deposit received month should be green in color and no-deposit month should be in red color.
I have stuck in comparing the array values. and I am using codeigniter.
I have a table with start-date and end-date by using this I have created an array to display all months in between these dates. Please find the code which I have used to do it below:
$datefrom = strtotime($showrangecalendar['chitdate_start']);
$dateto = strtotime($showrangecalendar['chitdate_end']);

$start_date = date('Y-m-d', $datefrom);
$end_date =  date('Y-m-d', $dateto);
$day = 2.628e+6; // Day in Months
$format = 'Y-F'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
    $days[] = date($format, ($sTime + ($d * $day)));
}

This code got me the Days list and I have displayed this using foreach statement to a table.
Now I have another table (accounts) with columns such as ID, Book_number, Deposit_Amount and Deposit_Month. Here the problem starts I have fetched data from "accounts" and loaded to my view using the below code from controller
$data['show_account']= $this->Accounts_model->get_all_accounts($sess_data);

My Model (Accounts_Model) is as shown below:
public function get_all_accounts($id)
{
    $this->db->select("*");
    $this->db->order_by('book_id','desc');
    $this->db->from("accounts");
    $this->db->where('bh_id',$id);
    $query = $this->db->get();
    return $query->result();
}

If I run the belowcode:
foreach($show_account as $values){

  echo $values->deposit_month;
 }

Its getting me the array result of all deposit month. Suppose I have data as 2018-Sep and 2018-Oct, These 2 months column should turn green in the above mentioned $days array.
Hope I have explained my requirement clearly. Please help me with this as I am already spent long hours in this.
Thanks in Advance.
Updated:
Now could you please check my model as follows:
public function get_dep_month($bh_id)
{
    $this->db->select('deposit_month');
    $this->db->from('accounts');
    $this->db->where('bh_id',$_SESSION['bh_id']);
    $this->db->order_by('deposit_month','asc');
    $query = $this->db->get();
    return $query->result_array();
}

And My Controller is as follows:
$sess_data = $this->session->userdata('bh_id');
    $data['depM_array'] = $this->Accounts_model->get_dep_month($sess_data);

Now please check my View as follows:
 <?php

                // option 2
                foreach($days as $day) { // using your already exist $day for-loop for display
                    if (!in_array($day, $depM_array)){
                       $calhilight = "calgreen";
                    }
                    else{
                      $calhilight = "calred";
                    }

            ?>
              <li class="<?php echo $calhilight; ?>"><?= $day ?>

            <?php
                }
            ?>

But as my doposit_month column having only 2 values ie: 2018-Sep and 2018-Oct, Instead of getting green color for those 2 values, I am getting Green for who li element. Not getting where I have done wrong.
This is the Current page view which I am getting, Actually I am expecting a calendar view with 2 green fields for 2018-Sep and 2018-Oct and all other fields in Red
Performed Var Dumb in arrays:
Pls check this screenshot
FYI:
Below is the code from where I am getting $days array.
 <?php
$datefrom = strtotime($showrangecalendar['chitdate_start']);
$dateto = strtotime($showrangecalendar['chitdate_end']);

$start_date = date('Y-m-d', $datefrom);
$end_date =  date('Y-m-d', $dateto);
$day = 2.628e+6; // Day in Months
$format = 'Y-F'; // Output format (see PHP date funciton)
$sTime = strtotime($start_date); // Start as time
$eTime = strtotime($end_date); // End as time
$numDays = round(($eTime - $sTime) / $day) + 1;
$days = array();
for ($d = 0; $d < $numDays; $d++) {
    $days[] = date($format, ($sTime + ($d * $day)));
}

?>
Here $start_date & $end_date is fetching from another table named chitdate.
Thanks Again.

A: You can use array-diff or simple for-loop.
Consider the following simple example:
$days = array("2018-September", "2018-October", "2018-November", "2018-December");
$deposit_month = array("2018-September", "2018-October");

// option 1:
$diff = array_diff($days, $deposit_month);
// now $diff has: "2018-November" and "2018-December"

// option 2
foreach($days as $day) { // using your already exist $day for-loop for display
    if (!in_array($day, $deposit_month))
        // color in red as not found in "deposit_month"
    else
        // color in green
}

Nicer writing for that if can be as:
$color = in_array($day, $deposit_month) ? "Green" : "Red";


text:
Q: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other) My system is macOS 10.13.1
I was try import pycurl is error
ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)

I tried these two methods
sudo pip uninstall pycurl
export PYCURL_SSL_LIBRARY=openssl
sudo pip install pycurl

or
sudo pip uninstall pycurl
sudo pip install --compile --install-option="--with-openssl" pycurl

Ive tried multiple variations of this, but none of them seem to work. Any ideas?

A: On MacOS Catalina (10.5.2) you may have followed all the guidelines and got a similar error:
ImportError: pycurl: libcurl link-time ssl backend (none/other) is different from compile-time ssl backend (openssl)

This is a result of curl missing openssl, which doesn't come with MacOS now. As described in https://blog.birkhoff.me/switching-to-the-openssl-version-of-curl/
To fix:
$ brew upgrade
$ brew uninstall curl
$ brew install curl-openssl
$ echo 'export PATH="/usr/local/opt/curl-openssl/bin:$PATH"' >> ~/.zshrc


text:
Q: How to look through key/value pairs in object for specific key? I'm brand new to Javascript and just learning the basics.  Say that I have an array representing the names of cards in a deck like this:
var deckNames = [
  "sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ", "sK",
  "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "hJ", "hQ", "hK",
  "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "cJ", "cQ", "cK",
  "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ", "dQ", "dK",
  ];

along with an Object with the values of each card in the deck like this:
var deckValues = {
  sA: 11, s2: 2, s3: 3, s4: 4, s5: 5, s6: 6, s7: 7, s8: 8, s9: 9, s10: 10, sJ: 10, sQ: 10, sK: 10,
  hA: 11, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6, h7: 7, h8: 8, h9: 9, h10: 10, hJ: 10, hQ: 10, hK: 10,
  cA: 11, c2: 2, c3: 3, c4: 4, c5: 5, c6: 6, c7: 7, c8: 8, c9: 9, c10: 10, cJ: 10, cQ: 10, cK: 10,
  dA: 11, d2: 2, d3: 3, d4: 4, d5: 5, d6: 6, d7: 7, d8: 8, d9: 9, d10: 10, dJ: 10, dQ: 10, dK: 10,
};

I've written a "deal" function that randomly selects a card from the "deckNames" array.  I have two questions:

*

*I am trying to write a function that can go through the "deckValues" object and return the value it finds.  How would I go about looking in the "deckValues" object to find the name of the card that was dealt and then return that associated value?

*Am I being redundant by having an array just for the names and having an Object that has the names already with the values associated with them?

A: The deckValues properties can be accessed by name in two ways:
var storeValue = deckValues.sA;
var storeValue = deckValues['sA'];

So to look at the values using your deckNames array you could do this:
var storeValue = deckValues[deckNames[0]];

You could easily place the above statement in a loop and replace the 0 with a variable that iterates with the loop.
You don't really need to have an array and an object you can loop through object properties.
for(var name in deckValues) {
    var storeValue = deckValues[name];
    console.log('Deck name is ' + name + ' and the value is ' + storeValue);
}

A: Try:
console.log(deckValues["sA"]);

which will log the value "11", and so forth.
Yes, likely you can do away with the deckNames.

A: The automate version.

var deckNames = [
  "sA", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "sJ", "sQ", "sK",
  "hA", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "hJ", "hQ", "hK",
  "cA", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "cJ", "cQ", "cK",
  "dA", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "dJ", "dQ", "dK"
  ];

var deckValues = {
  sA: 11, s2: 2, s3: 3, s4: 4, s5: 5, s6: 6, s7: 7, s8: 8, s9: 9, s10: 10, sJ: 10, sQ: 10, sK: 10,
  hA: 11, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6, h7: 7, h8: 8, h9: 9, h10: 10, hJ: 10, hQ: 10, hK: 10,
  cA: 11, c2: 2, c3: 3, c4: 4, c5: 5, c6: 6, c7: 7, c8: 8, c9: 9, c10: 10, cJ: 10, cQ: 10, cK: 10,
  dA: 11, d2: 2, d3: 3, d4: 4, d5: 5, d6: 6, d7: 7, d8: 8, d9: 9, d10: 10, dJ: 10, dQ: 10, dK: 10
};

var givenKey = 'c6'; //you can change this
var result;

for (var key in deckValues) {
 if (key == givenKey) {
  result = deckValues[key];
  }
}

console.log(result);


text:
Q: While loop Ignores If Statement I am generating 'key values' that will help the functions encrypt and decrypt do their job.
The 'if ans == e' statement is being run and does return a output but ignores the 'k = True' statement, causing the program to go in a infinite loop on the encrypt function. Does anyone know why it is doing this?
ans = input("Would you like to decrypt or encrypt your message (e/d)? ")
key = Generate.gen.keys(self)

k = False
while not k:

    if ans == "e":
        encrypt(key[0], key[1])
        k = True

    if ans == "d":
        decrypt(key[0], key[2])
        k = True

    else:
        k = False

def encrypt(n, e):
    output = []
    plain_text = input("Please enter message: ")
    raw = list(plain_text)
    print(raw)

    for char in raw:
        ascii_val = ord(char)
        pub = ascii_val ** e % n
        print(pub)
        output.append(pub)
    print(output)

Many thanks,
Callum

A: if ans == "e":
    encrypt(key[0], key[1])
    k = True
if ans == "d":
    decrypt(key[0], key[2])
    k = True
else:
    k = False

If you read your code, your logic is as follows.

*

*If ans == 'e' set k=true

*If ans == 'd' set k=true

*

*If ans != 'd' set k=false

If ans == 'e' is true, ans cannot == 'd' and so the else case is run which sets k back to false.
Consider using an elif for ans == 'd'
elif ans == 'd':

A:
k = False
while not k:
    if ans == "e":
        # ...
        k = True

If ans == "e" is true, then k = True will indeed be executed.
But then, the next if/else statement comes.

    if ans == "d":
        # ...
    else:
        k = False

If ans was "e", it will not simultaneously be "d". Therefore, the else part will be executed which sets k back to False.
You need to use elif ans == "d" so that this part is skipped if ans == "e" was true before.


text:
Q: How do I view form code history? I'm working on a C# desktop application for a class, using Visual Studio Online source control system. It gave me a choice of Team Foundational Server or Git, and I choose Git because I've heard of it and my professor recommends it. This is my first time using these features and I'm finding them a little confusing.
I can view the history of most of the files I'm working with, and revert to old versions, but I can't seem to do that for my form code. I think it has to do with what files are attached to source control, indicated by the blue lock icons.
Here's a screenshot of what I'm talking about:

I would like to be able to see the history of Production Buddy.cs, what am I doing wrong here? I can see Production Buddy.Designer.cs's history, so I may be not fully understanding what's going on here.
Thanks!

A: The screenshot shows there was neither red tick or blue tick. Which indicates that the file was not under source control. This happened may be because you copy pasted the file or the solution was on offline mode or solution file was updated when you took latest which replaced the entry of Production Buddy.cs file, and since it was not on the server there was no server history for that file.
I would recommend using Source Control Explorer when you have to compare the files.


text:
Q: UpdatePanel on just one gridview column? Is it possible to put UpdatePanel on just one of Gridview Columns?
Thanks.

A: The UpdatePanel would have to update several disjointed <td> elements instead of a single <table>. To my knowledge, that's not possible.
But maybe you could put one UpdatePanel with UpdateMode set to Always around the contents of each <td> (using e.g. a TemplateField).


text:
Q: c# EWS 2007 Address from empty I'm working on a WinForms Application that uses EWS to read mails of our Exchange Server. The Exchange is at Version 2007. I could successfully read, move, delete and send emails through EWS. I'm using Autodiscover to authenticate and select the Mailbox. The only problem is that I never get any sender e-mail address. The only thing I get is the name of the sender but no address.
This is my code so far:
Service1 = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
Service1.Credentials = new WebCredentials(Properties.Settings.Default.Username, Properties.Settings.Default.Password);
Service1.Url = new Uri(Properties.Settings.Default.Serviceurl);
EmailMessage messageAtt = EmailMessage.Bind(Service1, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.IsRead));
EmailMessage messageData = (EmailMessage)item;

foreach (Attachment attachment in messageAtt.Attachments)
{
    String from = messageData.Sender.Address.ToString();
}

This is what I get when I debug:

Can anyone give me a suggestion what I am mistaking here? Is there a Problem with what I wrote or could it even be a set up problem of the exchange Server?

A: The problem seems to be the definition of the EmailMessage object:
By defining the EmailMessage with explicit conversion not all attributes are geting transfered to the new object. If you try it with the upper EmailMessage object which gets defined by the .Bind() method, it wont work either. The reason that happens is due to the PropertySet passed as 3rd parameter. The only solution I found is to create a 3rd object:
EmailMessage messageInfo = EmailMessage.Bind(useService, item.Id);

The disadvantage of this Object is, that you won't be able to see if the item has an attachement or not.
Hope this helps anyone not wasing his time on a stupid mistake like that ;)


text:
Q: Simulate taking USB cable in and out I have a MacBook at home, where I have a webcam connected to.
The problem is I'm not at home and the surveillance software I'm using can't see it.
Is it possible to simulate taking the USB cable out and putting it back in again?

A: Try
sudo kextunload -b "com.apple.driver.usb.AppleUSBEHCIPCI"; sleep 5; sudo kextload -b "com.apple.driver.usb.AppleUSBEHCIPCI"

Works on my system, just tested it. I had to run the command 3 times though because for 2 times my usb camera didn't reconnect correctly, no idea why that happened.
Or similar to this with the full path
sudo kextunload /System/Library/Extensions/IOUSBMassStorageClass.kext
sudo kextload /System/Library/Extensions/IOUSBMassStorageClass.kext

Oh well, this work


text:
Q: Non-existent class: CI_Curl I am trying to use this Curl Library from this site.
Link to the Curl Library
They have clearly stated to put my Library file inside
 ci_demo > system > libraries > curl.php

I have done the same. When I try to load into my Controller it throws me this error: Non-existent class: CI_Curl.
My code is :
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');

    }

    public function getAllUsers(){

    $this->load->library('curl');

//  Setting URL To Fetch Data From
$this->curl->create('https://www.formget.com/');

//  To Temporarily Store Data Received From Server
$this->curl->option('buffersize', 10);

//  To support Different Browsers
$this->curl->option('useragent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 (.NET CLR 3.5.30729)');

//  To Receive Data Returned From Server
$this->curl->option('returntransfer', 1);

//  To follow The URL Provided For Website
$this->curl->option('followlocation', 1);

//  To Retrieve Server Related Data
$this->curl->option('HEADER', true);

//  To Set Time For Process Timeout
$this->curl->option('connecttimeout', 600);

//  To Execute 'option' Array Into cURL Library & Store Returned Data Into $data
$data = $this->curl->execute();

//  To Display Returned Data
echo $data;
}
//and so on

A: change class name of curl:
class Curl {

to
class CI_Curl {


text:
Q: Rails: accessing controller instance variables in rpec test In an Rspec controller test I want to check the values of instance variables in my the controller that I am testing.
For example,
controller:
class ThingsController < ApplicationController
  def index
    @things = Thing.all
  end
end

spec:
RSpec.describe UsersController, type: :controller do
  describe 'GET #index' do
    expect(@things).to_not be_nil
  end
end

How do I access @things in the above example?

A: This should do the trick:
expect(assigns(:things)).to_not be_nil

More likely you'll want something like:
let(:thing) { ... }
...
expect(assigns(:things)).to eq([thing])


text:
Q: How to select data from table selected in dropdownlist? I have a dropdownlist on a page and in a dropdownlist I have names of the tables in database.
I don't know how to insert data from the selected table in the gridview or datalist.
I tried with using the code from another c# project I did in school, but it didn't work
edit: answer added here
protected void Button1_Click(object sender, EventArgs e)
{

    OleDbConnection con = new OleDbConnection(connectionString);
     OleDbDataAdapter da = new OleDbDataAdapter (string.Format("SELECT * from {0}", dropDownList.SelectedValue), con);
    DataSet ds = new DataSet();
    da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
    da.Fill(ds);

    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
    con.Close();
}

A: You can tell the code to put the dropdowlists selected item's value in the query as follows:
protected void Button1_Click(object sender, EventArgs e)
{
    OleDbConnection con= new OleDbConnection(connectionString);

    SqlDataAdapter da = new SqlDataAdapter(string.Format("SELECT * FROM {0}",DropDownList1.SelectedValue), con);
    DataSet ds = new DataSet();
    da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
    da.Fill(ds);

    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
    con.Close();
}

I've tested this before posting it and it works on my machine. When you so if you can not get it worked the problem should be somewhere else.

A: That is very easy to do. I assume your dropdownlist is in your gridview which is also a asp gridview. If this is the case then in the event you have catching the selectedindexchange or by button click. You will have to find the dropdown in the gridview and then use the selectedvalue property. It will look like this to find it(place this in your event handler)
Dim ddl as dropdownlist = gridview.row(e.rowindex).findcontrol("dropdownID")
Dim val = ddl.selectedvalue
The only changes that might have to be made in regards to finding the control is depending on what rowtype the dropdown is in and also the event being used. If the above wont find the control you can try gridview.row.findcontrol("dropdownID")
Once you get the value, you can call the method for the insert and pass it as a parameter :)


text:
Q: Trigger event once dropdown item is selected on jQuery combobox I'm using the autocomplete combobox from the jQuery UI library to create a couple text fields that also accept dropdowns -- basically a hybrid text/dropdown input. I customized it though so it also accepts free text input, not just items in the dropdown array.
When the user selects an item from the dropdown, I'd like to trigger a function that populates the rest of the form based on the input. I don't want this function to trigger when the user types in a value manually. I'm not sure though how to bind an event specifically to the user selecting an item from the dropdown.
Here's a Fiddle: http://jsfiddle.net/AhDHk/
HTML:
    <input type="text" name="realtor-name" id="lp-realtor-name" value="" class="text ui-widget-content ui-corner-all" />

JS:
// adds the dropdown, dropArray is the list of items for the dropdown, id is the ID of the html input.

function textDropdown(dropArray, id) {
var $input = $(id).autocomplete({
    source: dropArray, // this is an array fetched with AJAX of all the items for the dropdown
    minLength: 0
}).addClass("ui-widget ui-widget-content ui-corner-left");

$("<button type='button'> </button>")
    .attr("tabIndex", -1)
    .attr("title", "Show All Items")
    .insertAfter($input)
    .button({
        icons: {
            primary: "ui-icon-triangle-1-s"
        },
        text: false
    })
    .removeClass("ui-corner-all")
    .addClass("ui-corner-right ui-button-icon lp-drop-button")
    .click(function() {
        // close if already visible
        if ($input.autocomplete("widget").is(":visible")) {
             $input.autocomplete( "close" );
             return;
        }
        $(this).blur();
        $input.autocomplete("search", "" );
        $input.focus();
    });

$("form").submit(function(e) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
    alert($(this).serialize());
});
}

A: Here is how you can handle it:
var $input = $(id).autocomplete({
    source: dropArray, // this is an array fetched with AJAX of all the items for the dropdown
    minLength: 0,
    select: function(event, ui) { alert('test');}
}).addClass("ui-widget ui-widget-content ui-corner-left");

Possible duplicate of: jQuery UI Autocompleteselect

A: The select event, here.
function textDropdown(dropArray, id) {
var $input = $(id).autocomplete({
    source: dropArray, // this is an array fetched with AJAX of all the items for the dropdown
    minLength: 0,
    select:function(a,b){
          alert(b.item.value + 'selected');
    }
}).addClass("ui-widget ui-widget-content ui-corner-left");


text:
Q: need help in deleting duplicate columns from a table i have a table as follow
| sr_no | id | content |
|  1    |200 |   abc   |
|  2    |201 |   xyz   |
|  3    |202 |   aaa   |
|  4    |200 |   bbb   |
|  5    |300 |   ccc   |
|  6    |202 |   ddd   |

where sr_no is primary key.. now i want to remove the one of the row which have same id so the output will be
| sr_no | id | content |
|  1    |200 |   abc   |
|  2    |201 |   xyz   |
|  3    |202 |   aaa   |
|  5    |300 |   ccc   |

with all unique values in id column

A: This subquery returns all the min sr_nos for each id and these are the rows that you want to keep:
select min(sr_no) sr_no
from tablename
group by id

So you can delete all the other sr_nos:
delete from tablename
where sr_no not in (
  select sr_no from (
    select min(sr_no) sr_no
    from tablename
    group by id
  ) t
);

See the demo.
Or with a self join:
delete t1
from tablename t1 inner join tablename t2
on t2.id = t1.id and t2.sr_no < t1.sr_no;

See the demo.
Results:
| sr_no | id  | content |
| ----- | --- | ------- |
| 1     | 200 | abc     |
| 2     | 201 | xyz     |
| 3     | 202 | aaa     |
| 5     | 300 | ccc     |

A: So this issue have more solutions, which dependent of different condition;)
one of them you can create new dublicate table based on distinct data of origin table, after delete original table -> after rename duplicate to original...
so but  based on this question, simple
try this:
  delete t1 FROM sample t1
  INNER  JOIN sample t2
     WHERE
       t1.sr_no < t2.sr_no AND
       t1.id = t2.id