text:
Q: Accessing apache2 virtual hosts using a browser and Linux O/S I am developing multiple websites on my apache server and setup apache2 virtual servers:
/var/www/site1
/var/www/site2
/var/www/site3

The host O/S is Linux and does not have a window manager. I want to connect from a remote machines browser and access site1, site2 and site3. I didn't buy any domain names and don't want to at this point. How can I access site1, site2 or site3?
Under apache2 I set the default sites-enabled to be site1 so when I enter the IP or my /etc/host name equivalent (site1) on the browser URL bar I get site1. I tried site2.site1 in the URL bar and that only gets me site1? How can I browse to site2 and site3?

A: When you defined 3 virtual hosts on apache and named them site1, site2 and site3, and then used /etc/hosts and provide mutliple entries with those names pointing to the same IP, your setup should work. When you enter either site1.domain or site2.domain you should get the desired sites. You may look into apache error.log or access.log.

A: You would have to setup virtual hosts. Check Apache Documentation
In case you would have to configure alias check apache documentation

A: All I need to do is add my site domain names to my /etc/hosts file. Say my apache2 server is on 192.168.0.10 then in /etc/hosts add:
192.168.0.10   site1 site2 site3
Then when the client browser gets the site1 URL it will re-direct to my apache2 server and it will then direct it to the correct virtual server.

A: Ok the way I can do this is using ports. In the /etc/apache2/ports.conf file I can setup another port:
NameVirtualHost *:591
NameVirtualHost *:80
Listen 80
Listen 591

Then in the apache2 virtual server site file change the :80 port to :591
Restart apache2 and voila.
I can then send my friend:
http://192.168.0.10:591

and its directed to site3 and the default
http://192.168.0.10

will load site1


text:
Q: How to fix 403 error when trying to access a symbolic link? Related to this question Why isn't my deployed Laravel 8 application finding images in the storage directory through a symbolic link?.
I am using Laravel to build an application and after deployment I set up a symbolic link to access my public storage. However, when I try to access these files I get a console error that looks like this,

test.jpg:1 GET http://website.com/storage/imgs/test.jpg 403 (Forbidden).

I imagine the reason I am getting the 403 error is because I can't follow symbolic links on SiteGround.
The permission for the symbolic link is 777, for the imgs directory it's 755, and for the image it's 644. Every answer I have seen has been talking about changing the apache config and I am not sure how to do that on SiteGround unless I just need to create my own? I had to create my own .htaccess file to change those settings on SiteGround. If so what file would I need to make, where would I put the file, and what would I write in it to allow it to follow the symbolic link if this is the case?
For all I know that's not even why it's not working so any other insight on what might be going on would be greatly appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make inline div elements shrink width when parent shrinks Here is a jsfiddle showing the behavior I want to implement:
JSFiddle That Uses Flex Layout
See JSFiddle For Code

Image Showing Rightmost Div Displaying Ellipsis
You see that I have multiple div elements displayed in a row.  Each div displays some text.  As the parent div is resized narrower, I want the rightmost currently displayed div to shrink (displaying ellipsis).  Notice that as you shrink the fiddle frame width, or shrink the browser, only the rightmost div is shrunk, displaying the ellipsis.
The jsfiddle uses flex layout to do this, but I need a solution that does not use flex layout or JavaScript.
I have tried messing around with making each div use display:inline-block, and a few other techniques, but no luck.

A: I think you want like that. kindly check demo
.parent
 {
  display: table;
 }
.child
 {
 display: table-cell;
 }

A: I figured it out and updated the JSFiddle to show how to do it by simply using display:inline. The flex solution was far more complicated than it needed to be.


text:
Q: Can we set keybindings in GDB? Is it possible to bind a command to a single button in GDB, F12 for example?
(as usual, don't try to sell emacs or find out "what are you trying to do")

A: gdb uses the readline library, so you could put the following in ~/.inputrc to bind F12 to the continue command:
"\e[24~":"continue\r"


text:
Q: Scalable loop over neighbours It is well-known, that if one wants to layout square grid(aka matrix) of real numbers he can use array with row-major order. Let's draw neighbourhood of some element i:
...................................
...|i-width-1|i-width|i-width+1|...
...|   i-1   |   i   |   i+1   |...
...|i+width-1|i+width|i+width+1|...
...................................

Let us for simplicity assume that i somewhere in the middle of square grid, so no bordering issues.(We can add %(width*height) and get connected on borders grid). So if one wants to do something with each element in neighbourhood of i'th element one should do:
//function which does something with element at idx
void DoSomethinWithElement(size_t idx);

//left neighbour
DoSomethinWithElement(i-1);
//right neighbour
DoSomethinWithElement(i+1);
//top neighbour
DoSomethinWithElement(i-width);
//bottom neighbour
DoSomethinWithElement(i+width);

I want to generalize this algorithm for any type of regular polygon grid (i.e. triangle, square, pentagonal, hexagonal etc.) Regular means that it constructed only from one type of polygon (i.e only from triangles).
How to generalize for any type of polygon grid:
 1. Layout of other grid in array?
 2. These N(for square mesh four) statements in a loop?
The problem "How to find all neighbors of a tile in a polygonal grid?" is solved quickly using graphs. But I want to use arrays so I could copy them to graphics card with CUDA.
Examples of grids:

*

*

*

*

A:
I want to generalize this algorithm for any type of regular polygon grid (i.e. triangle, square, pentagonal, hexagonal etc.)

Your definition of regular polygon grid is unusual. Typically you may not rotate or mirror the faces of the grid (tiling) for it to be considered regular. There are only 3 regular tilings (triangle, square, hexagon). All pentagonal tilings require mirroring or rotation or both.
Let's simplify your problem to this: "How to find all neighbors of a face in a polygonal grid?" Once you've got that figured out, it's trivial to call a function on each neighbor.
Grids are graphs with certain limitations. It is possible to generalize the search for neighbors by representing the grid with a general graph. The vertices of the graph represent the faces and they have edges to their neighbors. Graph of a grid is a planar graph. When the grid is represented by a graph, the problem becomes: "Given a vertex in a graph, how do I find all adjacent vertices?"
Note that the vertices and edges of the graph are not the same thing as the vertices and edges of the grid. For example, the grid-vertices of a hexagonal grid have three connected edges, while the faces have six neighboring faces and therefore the graph-vertices have six edges each.
One way to represent graphs is the adjacency list. In this representation, you simply need to look up the adjacency list of the vertex to find all it's neighbors.

But I want to use arrays

Well since the size of each adjacency list is constant, they can be implemented with arrays like in decltype_auto's answer. Or you can represent the graph with an adjacency matrix.
But if you want a generic algorithm for any tabular representation of a grid, then I think that you've painted yourself into a corner with that requirement. Each representation is different and you'll need a different algorithm for each.

A: You can represent the adjacencies of K-polygonal grid of polygon count N by a 1D vector v of N*K length, or a 2D NxK matrix M. Use std::size_t -1, a nullptr or whatever suites the reference type you've stored in v or M to indicate missing neighbors at the border.
Given such a NxK matrix M:
For the neighbors of polygon n you iterate from M[n][0] to M[n][K-1], fetch the neighbors by whatever reference you've stored in M, and apply whatever function you want on them.


text:
Q: how to use payment gateway in iOS app without getting rejected by apple? I am facing a problem while attaching the payment gateway. I don't want to use the in app purchase but apple don't allow any other gateway.
so any help? anybody?

A: Download leatest Sdk from here https://github.com/paypal/PayPal-iOS-SDK

A: Also you can use authorize .net payment gateway which is secure and easy.


text:
Q: Computer Architecture: Cache Speed Analysis I have this question on my exam study guide and cannot figure out how to do it:
Consider three processors with different cache configurations:
Cache 1: Direct mapped with one-word blocks
Cache 2: Direct mapped with four-word blocks
Cache 3: Two-way set associative with four-word blocks
The following miss rate measurements have been made:
Cache 1: Instruction miss rate is 4%; data miss rate is 6%
Cache 2: Instruction miss rate is 2%; data miss rate is 4%
Cache 3: Instruction miss rate is 2%; data miss rate is 3%
a) For these processors, one-half of the instructions contain a data reference. Assume that cache miss
penalty is 6 plus the block size in words. The CPI for this workload was measured on processor with
cache 1 and was found to be 2.0. Determine which processor spends most cycles on a cache miss. Show
your work.
b) The cycle times for the processors above are 420ps for the first and second processors and 310ps for the third processor. Determine which processor is the fastest and which is the slowest. Show your work.
For part A, I found the penalties to be 7, 10, and 10 for caches 1, 2, and 3 respectively, by using 6+1, 6+4, and 6+4.  From this I would assume that the most cycles are spend on caches 2 and 3, but that would completely answer part A and the info about CPI never came into play.  Does that seem right?
I haven't done anything with part B yet because I think that depends on part A.


text:
Q: I would like to create a field that reflects the sequence each record was created in? I would like to create a field that reflects the sequence each record was created in?
I created a point feature that I added records in the specific sequence that I want them to be numbered in. But My attribute table does not give me the sequence I created each record in the ID on all the records is Null.
I don't know Python script well so I'll require detailed explanation please?

A: No need for python. Create a new field with Field calculator and the expression $id. It stores the order in which features were added.


text:
Q: Assign text to a parent's textview I have Tab Layout that contains a TextView.  I'd like to assign some text at runtime to the TextView.  I thought this would work:
    ((TextView)getParent().findViewById(R.id.status)).setText("Some Text");

but the text is never set.
This is my layout:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0dp"

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:background="@drawable/tab_bg_selector"
     />
     <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="0dp"
     />
        <TextView
    android:id="@+id/status"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    android:text="Last Updated"
    android:layout_alignParentBottom="true"
    android:background="#cccccc"
/>
</LinearLayout>
 <RelativeLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="10dp"
    android:layout_alignParentBottom="true">
<TextView
    android:id="@+id/status"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    android:background="#cccccc"
    />
 </RelativeLayout>
</TabHost>

A: try this:
((TextView)this.findViewById(R.id.status)).setText("Some Text");


text:
Q: Value retrieval from KeychainItem I tried retrieving a string from the KeyChainItem,  which is stored as below:
@property (nonatomic, strong) KeychainItemWrapper *account;
if (account == nil) {
  account = [[KeychainItemWrapper alloc] initWithIdentifier:@"test" accessGroup:nil]
       }

[account setObject:self.username forKey:(__bridge id)(kSecAttrAccount)];
[account setObject:@"c6a07d48aabf35b26e1623fb" forKey:(__bridge id)(kSecValueData)];

When I retrieved it as below:
  KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"test" accessGroup:nil];
        self.account = wrapper;
    }

    NSString *prevUsername = [account objectForKey:(__bridge id)(kSecAttrAccount)];
    NSString *token = [account objectForKey:(__bridge id)(kSecValueData)];

I received the following value for NSLog(@"%@",token);
<63346264 32636462 64653234 34313862 38633537 31326235 66653464 63303731>

How do I retreive the string that I saved? Am I doing anything wrong here?

A: Try this:
NSData *nameData= [account objectForKey:(__bridge id)(kSecAttrAccount)];
NSData *tokenData = [account objectForKey:(__bridge id)(kSecValueData)];

NSString *prevUsername = [[NSString alloc] initWithData:nameData encoding:NSUTF8StringEncoding];

NSString *token = [[NSString alloc] initWithData:tokenData encoding:NSUTF8StringEncoding];


text:
Q: Deploy Scrapy Spider to Heroku: Requirement.txt Issue I want to deploy a scrapy spider to Heroku, but there is some issue with the library dependencies. My pandas and json versions don't seem compatible with Python or is there some issue with finding the versions?
The error code is as below.
remote: -----> Requirements file has been changed, clearing cached dependencies
remote: -----> Installing python-3.7.10
remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
remote:        Collecting scrapyd-client@ git+https://github.com/iamumairayub/scrapyd-client.git@c4575befa450aa3054c893a8895086d1fb449405
remote:          Cloning https://github.com/iamumairayub/scrapyd-client.git (to revision c4575befa450aa3054c893a8895086d1fb449405) to /tmp/pip-install-r4xii8wu/scrapyd-client_a6a6d5c7060a46a39d19d858c809ec1b
remote:          Running command git clone --filter=blob:none --quiet https://github.com/iamumairayub/scrapyd-client.git /tmp/pip-install-r4xii8wu/scrapyd-client_a6a6d5c7060a46a39d19d858c809ec1b
remote:          Running command git rev-parse -q --verify 'sha^c4575befa450aa3054c893a8895086d1fb449405'
remote:          Running command git fetch -q https://github.com/iamumairayub/scrapyd-client.git c4575befa450aa3054c893a8895086d1fb449405
remote:          Resolved https://github.com/iamumairayub/scrapyd-client.git to commit c4575befa450aa3054c893a8895086d1fb449405
remote:          Preparing metadata (setup.py): started
remote:          Preparing metadata (setup.py): finished with status 'done'
remote:        Collecting pandas==1.3.5
remote:          Downloading pandas-1.3.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.3 MB)
remote:        ERROR: Ignored the following versions that require a different python version: 1.4.0 Requires-Python >=3.8; 1.4.0rc0 Requires-Python >=3.8; 1.4.1 Requires-Python >=3.8; 1.4.2 Requires-Python >=3.8; 1.4.3 Requires-Python >=3.8
remote:        ERROR: Could not find a version that satisfies the requirement json==2.0.9 (from versions: none)
remote:        ERROR: No matching distribution found for json==2.0.9
remote:  !     Push rejected, failed to compile Python app.
remote:


text: Q: Can I rebuild a failed raid 1 hdd with the same hdd that failed before? everyone. I've made a mistake by detach one of the raid 1 hdd. And now it's a raid failure. Can I rebuild the raid with this hdd again? I've clean all the hdd trough diskpart on another pc. When i put back the hdd to the raid slot, it not syncing. What should i do?


text:
Q: Placing password visibility icon inside password field I have this following code.

              Enter your password
              <input
                id="loginPassword"
                type="password"
                class="form-control"
                placeholder="Enter your password"
              />

When I do this the password visibility icon is placed as in the image given below.

How do I place the visibility icon within password field.

A: Using marketwatch.com's login as an example, you would have to make the css property 'position' to "absolute" for the  tag. This will allow you to place it inside the input box. Perhaps something like this:
.bi-eye-slash {
    width: 25px;
    height: 25px;
    position: absolute;
    z-index: 200;
    top: 28px;
    right: 10px;
    cursor: pointer;
}

A: I found the answer to my own question. Well, we have to group the input and the icon is the way to do it, and below is the code.
.input-group-addon i {
    margin-left: -30px;
    cursor: pointer;
    z-index: 200;
    position: absolute;
    font-size: large;
    color: #6c757d;
  }
 <link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css"
/>

                  Enter your password

                    <input
                      id="loginPassword"
                      type="password"
                      class="form-control"
                      placeholder="Enter your password"
                    />


text:
Q: Python : looking for items from a list that exist in another list I want to calculate the bias between two curves but I have values of the first curve that are not in the second curve. So, I try to eliminate the values of the first curve that are not defined by the second curve. How will I proceed? Thank you for answering me.

A: Assuming you have your values in 2 lists:
new_values = [val for val in list1 if val not in list2]


text: Q: Eddington's measurement and dark matter On May 29th 1919 Eddington measured a shift in starlight that confirmed a General Relativity prediction. The results were duplicated two times, once by the Lick observatory and again by Yerkes observatory. Yet, none of these measurements considered dark matter. How is it possible to get a correct lensing measurement and not consider dark matter?


text:
Q: Basic questions about linear regression example from NVIDIA DIGITS I've a lot of values from all days over one entire year. I'm wanna verify if they have a kind of similarity for each month (verify if these days values correspond to the correct month and/or predict for future same months from another future year). From the https://github.com/NVIDIA/DIGITS/tree/master/examples/regression and the alternative method: manually creating LMDB files, what can I do? I've to put all these values from all days over one entire year into the val_db and train_db? After this, generate one test image for each month with all days from these months? Or I've to make a val_db and train_db for each month separately? Thank you.

A: Honestly DIGITS might be a little overkill for you. You don't need much computation power to train a little logistic regression problem and the results should be pretty easy to interpret.
But, if you want to forge ahead with DIGITS, you'll have to

*

*Format your data as a CxHxW data blob (maybe just 1x1xN where N is the number of features you have)

*Format your label as a CxHxW data blob (maybe just 1x1x1)

*Create a Caffe model that works for simple logistic regression (maybe just a single inner-product layer?)

To get help with this, please post on our user group instead of here on SO (following the README).


text:
Q: VSTO Remapping the close window button I'm creating a vsto excel add-in and I'm trying to find a way to either change the current functionality or add the ability to call a function when the close window button is pressed for the current spreadsheet. Does anyone know if this is possible or have any suggestions? I haven't been able to find much of anything thus far.

A: The Workbook class has an event called BeforeClose, which you can use to detect when a workbook is being closed. You can also use this event to stop it from being closed by setting the Cancel parameter to true.
To detect this event on the current workbook, you have to attach an event handler for the BeforeClose event on the current workbook.
The simplest way is to attach an event handler to the BeforeClose event when the Application.WorkbookActivate is raised. And detach it from the previously active workbook.
e.g.
private Workbook _activeWorkbook = null;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    Application.WorkbookActivate += Application_WorkbookActivate;

    // Attach to the BeforeClose event on the Workbook that
    // was created when Excel started
    _activeWorkbook = Application.ActiveWorkbook;
    if (_activeWorkbook != null)
    {
        _activeWorkbook.BeforeClose += ActiveWorkbook_BeforeClose;
    }
}

private void Application_WorkbookActivate(Microsoft.Office.Interop.Excel.Workbook Wb)
{
    if (_activeWorkbook != null)
    {
        _activeWorkbook.BeforeClose -= ActiveWorkbook_BeforeClose;
        Marshal.ReleaseComObject(_activeWorkbook);
    }

    _activeWorkbook = Wb;
    _activeWorkbook.BeforeClose += ActiveWorkbook_BeforeClose;
}

private void ActiveWorkbook_BeforeClose(ref bool Cancel)
{
    Cancel = MessageBox.Show("Do you want to close the workbook?", "Close Workbook", MessageBoxButtons.YesNo) != DialogResult.Yes;
}

So if you want to change the current functionality or add the ability to call a function when the close window button is pressed for the current spreadsheet, add your code in the ActiveWorkbook_BeforeClose method.


text:
Q: Copy a Worksheet if the Cell Value equals a certain string using row and column indexes The purpose of this is to find the column who has the header "Type Test" and loop through that column, in this case B to find all unique value cells. If the string in column B is unique and does not replace, I need it to make a copy of the worksheet whose name matches the trial name in column A. So for Test 1 who has a row index of 3 and a column index of 2, will make a copy of the worksheet in the current workbook called "DEF" and rename the copy to be "Test 1"
For example here is my data

*

*
 A            B

*
 Trial     Type_Test

*
 DEF        Test 1

*
 ABC        Test 3

*
 ABC        Test 10

*
 DEF        Test 14

*
 ABC        Test 10

However, I dont want to make a copy of the sheet ABC if the column B values repeat for column A, so since rows 3 and 5 are the same, I only want to make copies of ABC sheet twice, once for row 2 and once for row 3. Row 5 can be ignored since it is the same as row 3.
I have written a code that does the first part regarding make a sheet and renaming it, I just cant get the copy the other worksheet part.
Public Sub Main()

Dim srtsht As Variant, sysnum As Variant, arr As Variant, partnum As Variant
Dim wsh As Worksheet

    srtsht = Sheets("Sheet1").Range("E2:E15")

    With CreateObject("scripting.dictionary") ' store data in array where each item is associated with a unique key
        For Each sysnum In srtsht
            arr = .Item(sysnum)
        Next sysnum
    For Each value In .Keys
        On Error Resume Next
        If value <> "" Then
            Set wsh = Nothing ' clear the variable wsh
            Set wsh = Worksheets(CStr(value)) ' try to set wsh to the sheet with Value as name
            On Error GoTo 0
            If wsh Is Nothing Then

            Call position

            If Worksheets("Sheet1").Cells(A_row,A_col).Value = "ABC" Then
            Worksheets("ABC").Copy After:=ActiveSheet
            wsh = Worksheets("Sheet1").Cells(A_row,A_col).Values
            Worksheets("ABC (2)").name = wsh
            wsh.name = CStr(Value)
            End If
            Else
               MsgBox "Sheet" & Values & "already exists.", vbInformation
            End If
          End If
       Next Value
     End With
End Sub

Sub position ()
Dim syswaivernum As Range, partnumber As Range

For Each syswaivernum In Worksheets("Sheet1").Range("A1:Z20")
        If syswaivernum.value = "Number(s)" Then
        sysnumcol = syswaivernum.Column
        sysnumrow = syswaivernum.Row
        End If
    Next syswaivernum
For Each partnumber In Worksheets("Sheet1").Range("A1:Z20")
        If partnumber.value = "Part" Then
        A_col = partnumber.Column
        A_row = partnumber.Row
    End If
Next partnumber

End Sub

A: Try this - see comments inline:
Public Sub Main()

    Dim wb As Workbook, tst As String, wsName As String
    Dim c As Range, ws As Worksheet, dict As Object

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet1")

    Set dict = CreateObject("scripting.dictionary")
    For Each c In ws.Range("E2:E15").Cells
        tst = c.Value
        If Not dict.exists(tst) Then 'first time seeing this value?
            dict.Add tst, True '###
            If Not SheetExists(tst) Then
                wsName = c.EntireRow.Columns("A").Value    'sheet to be copied
                If SheetExists(wsName) Then 'if there's a sheet for wsName
                    wb.Worksheets(wsName).Copy After:=ws       'copy the sheet
                    wb.Worksheets(ws.Index + 1).Name = tst  '### rename the copy
                End If
            Else
                MsgBox "Sheet '" & wsName & "' already exists"
            End If
        End If
    Next c
End Sub

'Does a sheet named `SheetName` exist?
'  Defaults to checking `ThisWorkbook` if `wb` is not specified
Function SheetExists(SheetName As String, _
                     Optional wb As Excel.Workbook) As Boolean
    If wb Is Nothing Then Set wb = ThisWorkbook
    On Error Resume Next
    SheetExists = Not wb.Sheets(SheetName) Is Nothing
End Function


text:
Q: How to replace the server in an appium mobile app functional test? We have been writing our mobile app tests with Calabash/Xamarin.UITest for a while using backdoor methods to redirect our app's base api url to a mock HTTP server to make tests repeatable without incurring unnecessary server costs.
As Xamarin has announced they are phasing out Calabash (and Xamarin.UITest with it, as it relies on the Calabash server component) we have been working on migrating our test suite to Appium to comply with Xamarin's recommendations. Our simpler tests were migrated easily but a lot of our testing relies on said mock HTTP server with backdoor configuration which Appium does not seem to support, rendering our tests impossible to port without a way to recompile our app with the mock HTTP server address built in, which quite frankly, sucks.
Anyone knows an alternative to said backdoor method? Or an alternative to the whole mock HTTP server overall?
We want our tests to run in parallel in the Xamarin Test Cloud service so issuing a QA/Test environment for this is completely undesirable.


text:
Q: How to make a bootstrap dropdown parent link clickable A parent link of a bootstrap dropdown isn't clickable by default so the link isn't working.
This is the html code:

MyLink

        item 1

        item 2

I want /myLink to clickable. How do I fix that?

A: Add this code to you page and parent links will work:

A: I found that the easiest way to do it in bootstrap 4 is by deleting the "data-toggle" attribute from the parent element!


text:
Q: Find out the factors of this expression by long division. Two factors of the expression $x^4 - 5x^3 + 5x^2 + 5x - 6$ are $ (x+1) $ and $ (x - 3)$ .
Find the other two factors by long division.

A: We have $x^4 - 5x^3 + 5x^2 + 5x -6 \equiv (x^2-2x-3)(x^2-3x+2)$. The method is as follows:
$$\begin{array}{ccc|ccccc}
& & &x^2 & -3x & +2 \\
\hline x^2 & -2x & -3 & x^4 & -5x^3 & +5x^2 & 5x & -6 \\
&  &  & x^4 & -2x^3 & -3x^2 &  \downarrow&  \downarrow\\
\hline &  &  &  & -3x^3 & +8x^2 & 5x &  \downarrow\\
&  &  &  & -3x^3 & +6x^2 & 9x &  \downarrow\\
\hline &  &  &  &  & +2x^2 & -4x & -6 \\
&  &  &  &  & +2x^2 & -4x & -6 \\
\end{array}$$

A: This is pretty straightforward: Divide your polynomial by $(x + 1)(x - 3) = x^2 -2x -3$. Long division of a polynomial by another polynomial works just like long-division of numbers works.
Review the process of polynomial long division and study the examples.
Then give it a try with your polynomials.

A: With the given polynomial $x^4 - 5x^3 + 5x^2 + 5x - 6$, long division by $x+1$ and $x-3$ is accomplished in much the same way as when using long division between numbers.  Taking the comment-suggested divisor as $x^2-2x-3$, we have:
$$x^2-2x-3\mid x^4 - 5x^3 + 5x^2 + 5x - 6$$
$$x^2(x^2-2x-3)=x^4-2x^3-3x^2$$
$$(x^4 - 5x^3 + 5x^2 + 5x - 6)-(x^4-2x^3-3x^2)=-3x^3+8x^2+5x-6$$
$$-3x(x^2-2x-3)=-3x^3+6x^2+9x$$
$$(-3x^3+8x^2+5x-6)-(-3x^3+6x^2+9x)=2x^2-4x-6$$
and finally
$$2(x^2-2x-3)=2x^2-4x-6$$
So we have
$$x^4 - 5x^3 + 5x^2 + 5x - 6 = (x^2-2x-3)(x^2-3x+2)=(x+1)(x-3)(x-1)(x-2)$$
Writing out the division symbol and how "pulling down" each successive term works isn't easy for me with MaxJAX, but the process should be clear.

A: If you are confused on how to do long division, here is a good example which will make things easier for you.

A: $\begin{eqnarray} (x^2\!-\!2x\!-\!3)(x^2\!-\!bx\!+\!c) &=& x^4\ -\color{#0a0}{\ 5}\,\ x^3\! +\! 5x^2\! +\! 5x\! \color{#c00}{-\! 6} \\
&=& x^4\!\! -\! (\color{#0a0}{b\!+\!2})x^3+\ \cdots\ \color{#c00}{-{3}c}\end{eqnarray}$ $\ \Rightarrow\ $ $\color{#0a0}{b=3},\,\ \color{#c00}{c=2}$
Alternatively, if the roots are $\,3,-1,r,s\,$ then, by Vieta, $\,\color{#0a0}5 = 3\!-\!1\!+\!r\!+\!s,\,\  \color{#c00}{{-}6}= 3(-1)rs,\,$ hence $\,\color{#0a0}{r\!+\!s = 3},\,\ \color{#c00}{rs = 2}\ $ thus $\, (x\!-\!r)(x\!-\!s) = x^2-(\color{#0a0}{r\!+\!s})x+\color{#c00}{rs} = x^2-\color{#0a0}3x+\color{#c00}2$


text:
Q: trying to understand the jwt authentication flow so i'm trying to understand the flow of jwt authentication, and i have some holes, this is what i got:

*

*user logins

*user gets jwt access token and refresh token(server doesn't keep any of them)

*access token lasts for 5 mins and refresh token for 7 days

*access token expires

*user sends refresh token to server

*server checks:

*

*if the access token's(the expired one) user id == refresh token's user id

*verifies that the refresh token isn't expired

*maybe verifies that the access token is expired(not sure)

*if all those conditions are ok, the server sends a new access token to the client

*user proceeds as usual

*refresh token expires

*refresh token needs verification to send a new one

My questions are:

*

*how do the user finds out that the access token expired?
maybe the client app counts the minutes?
or maybe client tries to use the access token and then get a "token expired" response?

*are all the conditions in step 6 enough?
what if someone gets the refresh token from the client, how do i protect against that?
also does condition 3 supposed to be checked?

*how does the server verifies the refresh token?
thanks!

A: *

*No, this is not the client who check the token expiration, this is a server side operation. And no, of course, this is not the client app who check the expiration, counting the minutes. Yes client send a token and get a possible "token expired" response.

*Simple like that, if the token is valid, you're good to go. If not (expired, wathever) you're not. The expiration date is in the token payload itself. And you are supposed to encrypt your transmission between server and client.

*The server verify the refresh token the same way he verify any token. Verification usually on login/password on user database to check authorization. This is just a facility to renew a jwt token.
To sum up, the jwt authentication flow is simpler than that:

*

*The client send a request with authentication

*The server respond with an accreditation token

*The client use that token to dialog with the app

*If jwt token expires, client sends a refresh token to renew it (optional)

A: A JSON Web Token consists of 3 parts, i.e. Header, Payload and Signature. Header and Payload are not encrypted rather just encoded (base64), meaning that a client can simply decode these parts.
So to answer your first question -> the client would simply decode the payload part and read the exp-property from the registered claims. If you're using the node-jsonwebtoken library this would look something like:
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)

In order for the server to verify the token, you must provide the secret or the public key from the key pair which was used to sign the JWT. Using node-jsonwebtoken this would work as follows:
// verify a token asymmetric
const cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});

OR

// verify a token symmetric using secret
const decoded = jwt.verify(token, 'mySecret');


text:
Q: How can I format a txt file in python so that extra paragraph lines are removed as well as extra blank spaces? I'm trying to format a file similar to this: (random.txt)
        Hi,    im trying   to format  a new txt document so
that extra     spaces between    words   and paragraphs   are only 1.

   This should make     this txt document look like:

This is how it should look below: (randomoutput.txt)
Hi, I'm trying to format a new txt document so
that extra spaces between words and paragraphs are only 1.

This should make this txt document look like:

So far the code I've managed to make has only removed the spaces, but I'm having trouble making it recognize where a new paragraph starts so that it doesn't remove the blank lines between paragraphs. This is what I have so far.
def removespaces(input, output):
    ivar = open(input, 'r')
    ovar = open(output, 'w')
    n = ivar.read()
    ovar.write(' '.join(n.split()))
    ivar.close()
    ovar.close()

Edit:
I've also found a way to create spaces between paragraphs, but right now it just takes every line break and creates a space between the old line and new line using:
m = ivar.readlines()
m[:] = [i for i in m if i != '\n']
ovar.write('\n'.join(m))

A: You should process the input line-by line.  Not only will this make your program simpler but also more easy on the system's memory.
The logic for normalizing horizontal white space in a line stays the same (split words and join with a single space).
What you'll need to do for the paragraphs is test whether line.strip() is empty (just use it as a boolean expression) and keep a flag whether the previous line was empty too.  You simply throw away the empty lines but if you encounter a non-empty line and the flag is set, print a single empty line before it.
with open('input.txt', 'r') as istr:
    new_par = False
    for line in istr:
        line = line.strip()
        if not line:  # blank
            new_par = True
            continue
        if new_par:
            print()  # print a single blank line
        print(' '.join(line.split()))
        new_par = False

If you want to suppress blank lines at the top of the file, you'll need an extra flag that you set only after encountering the first non-blank line.
If you want to go more fancy, have a look at the textwrap module but be aware that is has (or, at least, used to have, from what I can say) some bad worst-case performance issues.

A: The trick here is that you want to turn any sequence of 2 or more \n into exactly 2 \n characters. This is hard to write with just split and join—but it's dead simple to write with re.sub:
n = re.sub(r'\n\n+', r'\n\n', n)

If you want lines with nothing but spaces to be treated as blank lines, do this after stripping spaces; if you want them to be treated as non-blank, do it before.
You probably also want to change your space-stripping code to use split(' ') rather than just split(), so it doesn't screw up newlines. (You could also use re.sub for that as well, but it isn't really necessary, because turning 1 or more spaces into exactly 1 isn't hard to write with split and join.)

Alternatively, you could just go line by line, and keep track of the last line (either with an explicit variable inside the loop, or by writing a simple adjacent_pairs iterator, like i1, i2 = tee(ivar); next(i2); return zip_longest(i1, i2, fillvalue='')) and if the current line and the previous line are both blank, don't write the current line.

A: split without Argument will cut your string at each occurence if a whitespace ( space, tab, new line,...).
Write
    n.split(" ")
and it will only split at spaces.
Instead of writing the output to a file, put it Ingo a New variable, and repeat the step again, this time with
m.split("\n")

A: Firstly, let's see, what exactly is the problem...
You cannot have 1+ consecutive spaces or 2+ consecutive newlines.
You know how to handle 1+ spaces.
That approach won't work on 2+ newlines as there are 3 possible situations:
  - 1 newline
  - 2 newlines
  - 2+ newlines
Great so.. How do you solve this then?
There are many solutions. I'll list 3 of them.

*

*Regex based.
This problem is very easy to solve iff1 you know how to use regex...
So, here's the code:
s = re.sub(r'\n{2,}', r'\n\n', in_file.read())

If you have memory constraints, this is not the best way as we read the entire file into the momory.

*While loop based.
This code is really self-explainatory, but I wrote this line anyway...
s = in_file.read()
while "\n\n\n" in s:
    s = s.replace("\n\n\n", "\n\n")

Again, you have memory constraints, we still read the entire file into the momory.

*State based.
Another way to approach this problem is line-by-line. By keeping track whether the last line we encountered was blank, we can decide what to do.
was_last_line_blank = False
for line in in_file:
    # Uncomment if you consider lines with only spaces blank
    # line = line.strip()

    if not line:
        was_last_line_blank = True
        continue
    if not was_last_line_blank:
        # Add a new line to output file
        out_file.write("\n")
    # Write contents of `line` in file
    out_file.write(line)

    was_last_line_blank = False

Now, 2 of them need you to load the entire file into memory, the other one is fairly more complicated. My point is: All these work but since there is a small difference in ow they work, what they need on the system varies...
1 The "iff" is intentional.

A: Basically, you want to take lines that are non-empty (so line.strip() returns empty string, which is a False in boolean context). You can do this using list/generator comprehension on result of str.splitlines(), with if clause to filterout empty lines.
Then for each line you want to ensure, that all words are separated by single space - for this you can use ' '.join() on result of str.split().
So this should do the job for you:
compressed = '\n'.join(
    ' '.join(line.split()) for line in txt.splitlines()
        if line.strip()
    )

or you can use filter and map with helper function to make it maybe more readable:
def squash_line(line):
    return ' '.join(line.split())

non_empty_lines = filter(str.strip, txt.splitlines())
compressed = '\n'.join(map(squash_line, non_empty_lines))

A: To fix the paragraph issue:
import re
data = open("data.txt").read()

result = re.sub("[\n]+", "\n\n", data)
print(result)


text:
Q: Is it possible to use server-side events to notify an iOS user despite my app not running, without using Apple Push Notification Service? I am considering using EventSource (server-sent events) to send notifications to my iOS App users, instead of APNS. This is great when app is active, but is it possible to ensure these users receive my messages when my app is not currently running on their device? Or is the only way to do this APNS?

A: If you need your events to arrive in real-time (like a messaging system), then APNS is probably your best bet. APNS is the only way to send realtime messages from a server to your app. However, it is wise to know that there are downsides to push notifications.
If you don't care about real-time events (not a messaging system), or if it's okay if you get the events a bit delayed, you can use background fetching to periodically poll your server for new events.
Objc.io has a great article discussing some of these: http://www.objc.io/issue-5/multitasking.html


text:
Q: If $\,f''(x) \ge f(x)$, for all $x\in[0,\infty),$ and $\,f(0)=f'(0)=1$, then is $\,f(x)>0$? Let $f:[0,\infty) \to \mathbb R$ be a twice differentiable function, such that
$\,f''(x) \ge f(x)$, for all $x\in\ [0,\infty)$, and
$ f(0)=f'(0)=1$. Can we deduce that $f$ is increasing?
I feel like it is, but I cannot see it. I can only show that to get it increasing it is enough to show that $f$ is non negative .

A: The following treatment is a standard way of dealing with ordinary differential inequalities using the ideas behind the proof of Grönwald's inequality:
\begin{align*}
f''\ge f &\quad\Longrightarrow\quad f''+f'\ge f'+f \\
&\quad\Longrightarrow\quad \mathrm{e}^{-x}\big((\,f''+f')-(\,f'+f\,)\big)\ge 0 \\ &\quad\Longrightarrow\quad
\big(\mathrm{e}^{-x}(\,f'+f\,)\big)'\ge 0
\end{align*}
and thus, for all $x\ge 0$
$$
\mathrm{e}^{-x}\big(f'(x)+f(x)\big)\ge f'(0)+f(0)=2.
$$
Hence $\,f'(x)+f(x)\ge 2 \mathrm{e}^{x}$ and consequently
$$
\big(\mathrm{e}^{x}f(x)\big)'=\mathrm{e}^{x}\big(\,f'(x)+f(x)\big)
\ge 2\mathrm{e}^{2x}\quad\Longrightarrow\quad \mathrm{e}^{x}f(x)-f(0)
\ge \int_0^x 2\mathrm{e}^{2t}\,dt=\mathrm{e}^{2x}-1
$$
and finally
$\,f(x)\ge \mathrm{e}^{x},\,$ for all $x\ge 0$.
Since $\,f''(x)\ge f(x)\ge\mathrm{e}^x$, then $\,f'(x)-f'(0)= \int_0^x f''(t)\,dt=\int_0^x\mathrm{e}^t\,dt=\mathrm{e}^x-1$, and thus $\,f'(x)\ge\mathrm{e}^x$, which implies that $f$ is strictly increasing.


text:
Q: Why is my Azure DevOps Migration timing out after several hours? I have a long running Migration (don't ask) being run by an AzureDevOps Release pipeline.
Specifically, it's an "Azure SQL Database deployment" activity, running a "SQL Script File" Deployment Type.
Despite having configured maximums in all the timeouts in the Invoke-Sql Additional Parameters settings, my migration is still timing out.
Specifically, I get:

We stopped hearing from agent Hosted Agent. Verify the agent machine is running and has a healthy network connection. Anything that terminates an agent process, starves it for CPU, or blocks its network access can cause this error.

So far it's timed out after:

*

*6:13:15

*6:13:18

*6:14:41

*6:10:19

So "after 6 and a bit hours". It's ~22,400 seconds, which doesn't seem like any obvious kind of number either :)
Why? And how do I fix it?

A: It turns out that AzureDevOps uses Hosting Agents, to execute each Task in a pipeline, and those Agents have innate lifetimes, independent from whatever task they're running.
https://learn.microsoft.com/en-us/azure/devops/pipelines/troubleshooting/troubleshooting?view=azure-devops#job-time-out

A pipeline may run for a long time and then fail due to job time-out. Job timeout closely depends on the agent being used. Free Microsoft hosted agents have a max timeout of 60 minutes per job for a private repository and 360 minutes for a public repository. To increase the max timeout for a job, you can opt for any of the following.

*

*Buy a Microsoft hosted agent which will give you 360 minutes for all jobs, irrespective of the repository used

*Use a self-hosted agent to rule out any timeout issues due to the agent
Learn more about job timeout.

So I'm hitting the "360 minute" limit (presumably they give you a little extra on top, so that no-one complains?).
Solution is to use a self-hosted agent. (or make my Migration run in under 6 hours, of course)


text:
Q: How can you make a C program add line numbers to a file's contents. E.g., "1. #include  2. #include ", etc.? #include <stdio.h>
#include <stdlib.h>

int process_stream(FILE *fpntr);
char *fgetline(FILE *fpntr);

int main(int argc, char* argv[]) {

    FILE *fpntr;
    char filename[100], c;
    int a = 0;

    printf("Please enter a file name/directory: \n");
    scanf("%s", filename);

    fpntr = fopen(filename, "r");
    if (fpntr == NULL) {
        printf("cannot open file \n");
        exit(0);
    }

    //read contents from file
    c = fgetc(fpntr);
    while (c != EOF){

        printf ("%c", c);
        c = fgetc(fpntr);
        if (c == '\n')

            {
                a++;
                printf("%d", a);
    }}

    fclose(fpntr);
    return 0;
    exit (0);
}

A: Firstly, implement just as what you says.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

    FILE *fptr;
    char filename[100];
    int c;
    int lineNumber = 1;

    printf("Please enter a file name/directory: \n");
    scanf("%99s", filename);

    // Open the file
    fptr = fopen(filename, "r");
    if (fptr == NULL) {
        printf("cannot open file \n");
        exit(0);
    }

    //read contents from file
    // While ((c = read a character) is not EOF)
    while ((c = fgetc(fptr)) != EOF){
        // If (c is \n)
        if (c == '\n') {
            // Print "lineNumber", then increment it
            printf("%d. ", lineNumber);
            lineNumber++;
        }
        // Print c
        printf ("%c", c);
    // End while
    }

    // Close the file
    fclose(fptr);
    return 0;
}

Unfortunately, this code won't work well and its output is
#include <stdio.h>1.
#include <stdlib.h>2.
int hoge;3.
int fuga;4.

when the input file is
#include <stdio.h>
#include <stdlib.h>
int hoge;
int fuga;

The fault is that you are printing line numbers at the end of lines.
They should be at the beginning of lines.
I would use a flag that indicates beginning of lines.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

    FILE *fptr;
    char filename[100];
    int c;
    int lineNumber = 1;
    int isBeginningOfLine = 1;

    printf("Please enter a file name/directory: \n");
    scanf("%99s", filename);

    fptr = fopen(filename, "r");
    if (fptr == NULL) {
        printf("cannot open file \n");
        exit(0);
    }

    //read contents from file
    while ((c = fgetc(fptr)) != EOF){
        if (isBeginningOfLine) {
            print("%d. ", lineNumber);
            isBeginningOfLine = 0;
        }
        if (c == '\n') {
            lineNumber++;
            isBeginningOfLine = 1;
        }
        printf ("%c", c);
    }

    fclose(fptr);
    return 0;
}

Now I get
1. #include <stdio.h>
2. #include <stdlib.h>
3. int hoge;
4. int fuga;


text:
Q: Exclude manylinux wheels when downloading from pip At $company we run an internal pypi server to shield ourselves from public pypi downtime.  We also build wheels to avoid installation overhead for binary packages.  One common task is to import packages from public pypi which essentially boils down to:
pip install --download . --no-binary :all: $PACKAGE  # download a source distribution

and
pip wheel $PACKAGE  # build a binary distribution (or use a cached version that's already on our internal pypi)

Under the latest pip, this may download / install manylinux wheels during the pip wheel phase.  Due to bundling .so files inside the wheel, these are incompatible with our security requirements at $company.  How can we continue the same workflow while avoiding the manylinux wheels?
Currently we're downgrading to pip<8, but this seems non-ideal

A: Workaround
As a workaround you can create file _manylinux.py in current workdir, or in the site-packages with following content:
manylinux1_compatible = False

This will ensure that manylinux1 wheels won't be downloaded when you run your commands:
pip wheel -w path/to/wheeldir -f path/to/wheeldir -r requirements.txt

You don't really need to use two commands pip install --download and pip wheel, but you can use single command above. (please note, that pip install --download is deprecated in favor of pip download command).
Command as I suggested will:

*

*Check if wheel already exists in path/to/wheeldir and will not touch that wheel.

*If new version was detected in requirements file (or you can replace -r requirements.txt with package and exact version package==X.X.X) and wheel is universal -- it will download that wheel and store it into path/to/wheeldir.

*If package requires compiling (example numpy, or matplotlib) -- source tgz will be downloaded and pip will build the wheel, and resulting wheel will be stored in the path/to/wheeldir.

I've tested this solution, which was [suggested in the pypa/pip#3689. It is not the solution we need, but it is workable and I use it.
Where can you put _manylinux.py file?
PIP attempts to import _manylinux module.
Q: Where Python will look for it?
A: Python follows the module search path.
So you can put your file in following locations:

*

*current work dir.

*Path in your PYTHONPATH.

*Installation default path.

First two paths are simple, but how you find your installation default path? Simply run following command:
python -c "import os.path as p;print(p.dirname(p.realpath(p.__file__)))"

Hope, this helps.

A: For those looking for an installable workaround, I've created no-manylinux
The usage is relatively straightforward:
# First install no-manylinux
pip install no-manylinux
# Now subsequent invocations of pip will ignore manylinux wheels
pip install ...
# To restore the original behaviour, simply `pip uninstall no-manylinux`

It works by installing a _manylinux.py file with manylinux_compatible = False as the contents

A: You seem to want to use only source distributions and not wheels when using wheels. To do this add this --no-use-wheel to your pip command.
This sounds a bit counter intuitive to use this when building a wheel, but it really means Do not Find and prefer wheel archives when searching indexes and find-links locations. This should force the fetching of remote source dists instead of wheels during the wheel phase for any of the deps you depend on.


text:
Q: Publishing with Multiple Context I am trying to publish a project that uses two DB connection strings and Migration Contexts:
DefaultConnection - Created automatically when starting the project and contains the user tables
AmscanContext - Generated when creating the Entity Model using Code First from an Existing database
I enabled and added two migrations for each one using a different folders and updated the databases (commenting out the create tables for the database I imported)
All works well locally and I have even added some authentication and canEdit rules to the controllers.
I have set up the connection strings to create two new databases and mentioned in the comment below. Here is the configuration.cs for each migration.
This is the App data:
namespace AMScan.Migrations.AmscanContext
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

internal sealed class Configuration : DbMigrationsConfiguration<AMScan.Models.AmscanContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        MigrationsDirectory = @"Migrations\AmscanContext";
    }

    protected override void Seed(AMScan.Models.AmscanContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

}
This is the User data:
namespace AMScan.Migrations.ApplicationDbContext
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
internal sealed class Configuration :      DbMigrationsConfiguration<AMScan.Models.ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        MigrationsDirectory = @"Migrations\ApplicationDbContext";
    }

    protected override void Seed(AMScan.Models.ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

}
Not sure if this tells you much. If there are any specific files you would like me to post please let me know.

A: I have managed to get this working. I took the following steps:

*

*Create new project and add the data entity model using Code First on Exiting Database.

*Create a Controller item

*Enable Migrations for each context using -MigrationsDirectory switch (see here for more info).

*Add each of the migrations and update the database.

*Publish the solution to azure creating a new website and TWO new databases making sure to check Execute Code First Migrations for both.

*Click Register and create an account (this creates the IdentityModel user database

*View the index of the controller you created (This created the app database)

This video was also very useful to learn about using code first on existing databases
I hope this will make sense any anyone looking for help. I am new to this and appreciate the help offered in this post and the other post I have read.
Cheers,
Kevin.


text:
Q: How to parse each row of an excel using Azure Data Factory here is my requirement:

*

*I have an excel with few columns in it and few rows with data

*I have uploaded this excel in Azure blob storage

*Using ADF I need to read this excel and parse the records in it one by one and perform an action of creating dynamic folders in Azure blob.

*This needs to be done for each and every record present in the excel.

*Each record in the excel has some information that is going to help me create the folders dynamically.

Could someone help me in choosing the right set of activities or data flow in ADF to do this work?
Thanks in advance!

A: This is my Excel file as a Source.

I have created folders in Blob storage based on Country column.
I have selected DataFlow activity.

As shown in below screenshot, Go to Optimize tab of Sink configuration.
Now select Partition option as Set Partition.
Partition type as Key.
And Unique value per partition as Country column.
Now run Pipeline.

Expected Output:-

Inside these folders you will get files with corresponding data.


text:
Q: How to open a new page using sessionid and response object I have a situation where a customer logs in my website with credentials. With that credentials I did get the sessionid for another internal website. I am trying to open a website using the sessionid, so that customer don't have to login again to that internal website.
I do have the sessionid and I have stored in a httpcookie like below.
 HttpCookie mycookie = new HttpCookie("xyz");
        mycookie.Value = sessionId;
        mycookie.Expires = DateTime.Now.AddHours(9);

How to open website using the sessionid?

A: Just add the cookie to the response:
public ActionResult Foo()
{
    HttpCookie mycookie = new HttpCookie("xyz");
    mycookie.Value = sessionId;
    mycookie.Expires = DateTime.Now.AddHours(9);
    Response.AppendCookie(mycookie);
    ...
}


text:
Q: Grails security filter all action but except one I'm gonna create a security filter for my project. I check if !session.user then redirect to action error.
Here is my current code:
all(controller: 'accounting|installation|installer|sales|service|serviceOrder|document', action: '*') {
            before = {
                if (!session.user) {
                    redirect(controller: 'installation', action: 'errors')
                    return false
                }
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }

However the point is that session.user being created in controller 'installation' and action 'index'. So how can I filter without index action?
Any suggestions  will be appreciated. Thanks.

A: You can use invert:true
e.g
def filters = {
    allExceptIndex(controller:"installation",action:"index",invert:true) {
        before = {
        }
        after = { Map model ->
        }
        afterView = { Exception e ->
        }
    }
}

For further reference see Blog

A: Try this
all(controller: 'accounting|installation|installer|sales|service|serviceOrder|document', action: '*') {
        before = {
         if (!(controllerName == 'installation' && actionName == 'index')) {
            if (!session.user) {
                redirect(controller: 'installation', action: 'errors')
                return false
            }
          }
        }
        after = { Map model ->

        }
        afterView = { Exception e ->

        }
    }

A: Hope I have understood your question ,Since you want to exclude action index then ,try this ..
all(controller: 'accounting|installation|installer|sales|service|serviceOrder|document', action: '*',actionExclude:'index'){....

Regards


text:
Q: convert nu.XOM.Element to org.w3c.dom.Element Is it possible to convert nu.XOM.Element to org.w3c.dom.Element?
Am trying to construct XML using XOM APIs. But few of my legacy APIs expects org.w3c.dom.Element. So, I just want to know if I can convert.
Thank You :)

A: There is the nu.xom.converters.DOMConverter class, which provides a way of translating an entire XOM document into a corresponding DOM document, but you can't do it for individual elements, probably because a W3C Element can't exist without a parent Document.

A: XOM Document:
final nu.xom.Element root = new nu.xom.Element("root");
root.appendChild("Hello World!");
final nu.xom.Document xomDoc = new nu.xom.Document(root);

using DOMConverter:
final DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final DOMImplementation impl = builder.getDOMImplementation();
final Document w3cDoc= DOMConverter.convert(xomDoc, impl);

A: public static org.w3c.dom.Document xomToDom(Element elem) {
    try {
        elem = (Element)elem.copy();
        return
        DOMConverter.convert(new Document(elem),
                DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation());
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}


text:
Q: Javascript making elements I have made an 'IFRAME' element through javascript, but now I want to add the css to that iframe , I have made another src , which is included in the website body, so its working fine, but the style doesn't work, Now, I have to add the style sheet to that frame which I have in another file  but I don't know how to do it, can anyone please.

A: Set options  X_FRAME_OPTIONS - ALLOWALL on backend.

A: Just pass the style along with the iframe... no need for seperation.
iframeTag = document.createElement('iframe');
iframeTag.width = '1px';
iframeTag.height = '1px';
iframeTag.frameborder = '0';
iframeTag.style = '##INSERT STYLE';


text:
Q: Does Spring Adds HSTS header for every response? Hie, I was going through various spring-security modules. and I was keen about HSTS (HTTP strict transport security) and at the same time performance.
Does spring Adds HSTS headers for every request it hits or it only for the first time?
is there the way to optimize it? I know optimizing security is a crazy idea but out of Curiosity, I am asking this.
Even I have gone through spring-security docs. but docs don't say any information about this.
I strongly feel that there is no need for spring to send HSTS header for every response.

A: By default the HSTS header is added to secure requests. You can customize this behaviour by setting a custom RequestMatcher. Then the header will only be sent back if the request matches your customization.
For example:
http
    .headers()
        .httpStrictTransportSecurity()
            .requestMatcher(new AntPathRequestMatcher("/api/**"));

You can read more in the HSTS header configuration section of the documentation.


text:
Q: Tizen 2.3.2 push notifications I'm trying to develop a watch app for the Gear S3 Frontier. I had been mistakenly testing with the Tizen emulator on Tizen 3.0, but have discovered that my push notification implementation does not work in 2.3.2 (which is what is on the S3 now). I have checked and rechecked against every example I could find, but cannot seem to receive push notifications. It works fine with 3.0, but the altered version that uses the 2.3.2 method of connecting simply never receives any notifications. The Samsung push API reports success when my server sends, but I never get anything on the watch or emulator in 2.3.2. I saw that this post asks a similar questions but was never fully answered and I don't have the rep to comment on it. Does someone have a working example of this?

A: I solved it. I discovered an error in the logs that indicated that it was looking for the "appData" field. The documentation says that you can include EITHER "appData" or "message", but it appears that you must have BOTH present in 2.3.2. Tizen 3.0 doesn't seem to care.


text:
Q: Defining a date from a column in Python I have a table of codes and dates that is continuously growing from another source, e.g.

Code
Name
Date

RM1377
a
30/07/2022

RM1377
b
30/07/2022

RM1377
c
30/07/2022

RM1377
d
30/07/2022

RM1378
e
07/08/2022

RM1378
f
07/08/2022

RM1378
g
07/08/2022

RM1378
h
07/08/2022

And I want to be able to enter a Code into an input, and then retrieve the date associated with the Code, so that I can query on it.
How can I define DM1377 as always being 30/07/2022, and account for DM1389 potentially being in the table with another date?
I.e. instead of cruise_date = datetime.date(2022, 7, 30) I imagine it would be something like cruise_date = datetime.date(Voyage_date)
from traceback import print_tb
import pandas as pd
from dateutil.relativedelta import relativedelta
import datetime

#voyage_id = input('Voyage ID:')

# Retrieve the data and assign headers
df = pd.read_csv("dcl_manifest_20220729.csv", usecols=[0,2,5,6,7,8], names=['Cruise', 'Booking reference', 'First name', 'Last name', 'DoB', 'Cancellation'])
df[['Cruise', 'Booking reference', 'First name', 'Last name', 'DoB', 'Cancellation']]

# Convert DoB column to dates
df["DoB"] = pd.to_datetime(df["DoB"])

# Define the cruise date
cruise_date = datetime.date(2022, 7, 30)

# Calucate 5 years ago to indentify under 5s
years_ago = cruise_date - relativedelta(years=5)

# Query under 5s and print the output
u5 = df.query('DoB > @years_ago & Cruise == "DM1377" & Cancellation == "No"')
print("Number of under 5s: " + str(len(u5.index)))


text:
Q: How to regroup commands in a shell to avoid repeated redirections? I have a script where I output three things into a file. I'd like to call the > operator only once. Is there a way to describe a block of instructions? Should I use a function?
#!/bin/sh

for i in $(ls src)
 do
  f=${i%.*}
  echo 'first bit' > dist/$i.htm
  perl myScriptThatOutputsSecondBit.pl >> dist/$i.htm
  echo 'third bit' >> dist/$i.htm
 done

A: Use compound/group command:
To run it in a current-shell,
 {echo 'first bit';perl myScriptThatOutputsSecondBit.pl;echo 'third bit';} > dist/$i.htm

To run it in a sub-shell,
 (echo 'first bit';perl myScriptThatOutputsSecondBit.pl;echo 'third bit') > dist/$i.htm

A: Write a simple log function, this would be more efficient. e.g.
log(){
   echo $1 >> dist/$i.htm
}

and then call it from the script:
for i in $(ls src)
do
    f=${i%.*}
    log 'first bit'
    perl myScriptThatOutputsSecondBit.pl >> dist/$i.htm
    log 'third bit'
done


text:
Q: Android - have IME enter key submit? Is there a way to have the Enter key submit my form?  Right now I have a Log In button that is sent using an addListenerButton()... Can I somehow link the Enter key to that as well?  I think the code from my .java is irrelevant, but I can always post it if requested.
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/back"
android:background="@drawable/a_hdpi">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:padding="10dp"
    android:background="@drawable/linearlayout_bg" >

<EditText
    android:id="@+id/username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_top_bg"
    android:padding="10dp"
    android:hint="Username"
    android:textColorHint="#cccccc"
    android:drawableLeft="@drawable/user"  />

<EditText
    android:id="@+id/password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/edittext_bottom_bg"
    android:layout_marginTop="-2dp"
    android:padding="10dp"
    android:hint="Password"
    android:singleLine="true"
    android:textColorHint="#cccccc"
    android:drawableLeft="@drawable/password"
    android:password="true"
    android:imeOptions="actionSend" />

<Button
    android:id="@+id/submit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:layout_margin="4dp"
    android:text="Submit"
    style="@style/DefaultButtonText"
    android:background="@drawable/button_default_bg" />

A: This can be done using the following apis:
android:imeActionId with the following attributes android:imeOptions. Use this with the setOnEditorActionListener() method
Also this example might help you: http://developer.android.com/guide/topics/ui/controls/text.html#ActionEvent
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});

A: Yes, find a reference to your EditText for which you have added android:imeOptions="actionSend" and set the onEditorActionListener to trigger the method or button onClick for login that you want to trigger.
EditText yourEditText = findViewById(R.id.password);
yourEditText.setOnEditorActionListener(new OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            login(); // YOUR LOGIN METHOD HERE
            return true;
        }
        return false;
    }
});


text:
Q: Find value range of $2^x+2^y$ Assume $x,y \in \Bbb{R}$ satisfy $$4^x+4^y = 2^{x+1} + 2^{y+1}$$, Find the value range of $$2^x+2^y$$

I know $x=y=1$ is a solution of $4^x+4^y = 2^{x+1} + 2^{y+1}$ , but I can't go further more. I can only find one solution pair of $4^x+4^y = 2^{x+1} + 2^{y+1}$. It seems very far from solve this question...

A: Let $a = 2^x, b = 2^y$. Use some algebraic manipulation to arrive at $(a - 1)^2 + (b - 1)^2 = 2$
This is a circle of radius $\sqrt{2}$ centered at $(1, 1)$, and we want to find the minimum and maximum values of $a + b$.
So $a + b = M \rightarrow b = -a + M$, which is the equation of a line with slope $-1$. The maximum and minimum will be when we find the maximum and minimum y-intercept of this line such that it intersects at least one point on the circle with $a, b > 0$
It's tangent to the circle at the top right when $a = b = 2$ which gives a value of $M = 4$. The smallest y-intercept occurs at $m = 2$, however, we do not include $2$ because it makes one of the coordinates zero. This establishes $(2, 4]$ as the range.

A: So, then the another solution:
let $f(x) = 2^x$. Then we can go to that form of equation:
$$(f(x)-1)^2 + (f(y)-1)^2 = 2$$
We got a circle. If we consider points of intersection of this circle with a lines $$f(x)+f(y) = const$$ we can get an answer.
We should also be polite with restrictions $f(x),f(y) > 0$.
If we draw a picture, we will conclude that range is (2, 4].

A: Cauchy-Schwarz inequality allows us to conclude $$((a-1)^{2}+(b-1)^{2})(1+1) \geq (a-1+b-1)^{2}$$ and hence $4\geq (a+b-2)^{2}$ and finally $a+b \leq 4$ with equality holding only when $a=b=2$.

A: Set $a=2^x$, $b=2^y$, then the problem is equivalent to finding the range of $a+b$ where $a,b>0$ and
$$a^2+b^2=2a+2b$$
Without loss of generality $a\ge b$ and we can make the substitution $c=a+b$, $d=a-b$, so now $c>d\ge0$, and we require
\begin{align*}\left(\frac{c+d}2\right)^2+\left(\frac{c-d}2\right)^2&=(c+d)+(c-d)\\
c^2+2cd+d^2+c^2-2cd+d^2&=8c\\
c^2+d^2&=4c\end{align*}
Observe that
$$c^2\le c^2+d^2=4c\Longleftrightarrow c(c-4)\le0\Longleftrightarrow c\le4$$
and
$$2c^2>c^2+d^2=4c\Longleftrightarrow c(c-2)>0\Longleftrightarrow c>2$$
It's easy to see all such values can be attained and the answer is the interval $(2,4]$.

A: Let us denote $2^{x}=a,2^{y}=b,$where $a,b\in
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion
^{+}$. Then we have $a^{2}+b^{2}=2(a+b)$ which is equivalent to $%
(a-1)^{2}+(b-1)^{2}=2.$So we take the part of the circle  with center $M(1,1)
$ and radius $r=\sqrt{2}$ in the first district of the plane as the domain of the
function $f(a,b)=a+b$. We are looking for maxium and minium values of $f$ in
the given domain. Any point $(a,b)$ in the domain is $\sqrt{a^{2}+b^{2}}$
units far from $(0,0)$ which is also in the given circle (though not in
domain). We also know that two points on a circle are at most diameter
length far from each other. So $\sqrt{a^{2}+b^{2}}=2\sqrt{2}$ at most. Thus $%
a^{2}+b^{2}=8.$ Then we have $2(a+b)=8$ and finally $a+b=4$ at maximum. We
look at the edges (because they are closer to (0,0) ) of the domain for
mininum value which is at $(2,0)$ or $(0,2)$. Then $a+b$ converges to $2$ at
minimum. We have the value range $(2,4]$.

A: You have
$$(2^x+2^y)^2=4^x+4^y+2^{x+y+1}=2^{x+1}+2^{y+1}+2^{x+y+1}$$
If $a=2^x$, $b=2^y$, then
$$(a+b)^2=2(a+b+ab)>2(a+b)$$
so $a+b>2$.
I'm looking for an upper bound. If I find it, I'll edit this answer.

A: Let $\delta x = y-x$ and $x\ge y$. Then
$$4^x(1+4^{\delta x}) = 2^{x+1}(1+2^{\delta x})$$
then from factorization we can claim that:
$$2x = x+1 ~\text{and}~~ 4^{\delta x} = 2^{\delta x}$$
So, we get $x = y = 1$.


text:
Q: Riemann + print an event/alert if it occurs more than 2 times in 5min I am getting logs from logstash and sending messages which contains ERROR to riemann server.
logsash message : message" => "Jul 10 04:34:47 : [ERROR] [host] Sample abc123"

In riemann I need to write a logic to find if the same ERROR occurs more than 2 times for the same sample(i.e sample abc 123) in 5min then I have to alert /print on the console(currently I am trying to print to test)
below is my logic to achieve this, currently it prints only nil and not the message, can some one please help me here.
(by [:message]

 ;; over time windows of 5 seconds...
    (fixed-time-window 5

        ;; calculate the average value of the metric and emit an average (summary) event
        (combine folds/mean

            ;; collect the summary event over the last 3 fixed-time-windows
            (moving-event-window 2

                ;;find the summary event with the minimum average metric
                (combine folds/minimum
                     (where (> metric 2.0)
                       prn
                       ;;(email "xyz")
                     )
                )
            )
        )
    )
)

(It prints message every 2sec, if I use just fixed-time-window and nothing else but I want to print only if same sample occurs 2times in 5min)
Riemann event for example:
:service "logstash",
:time 1468920656,
:state "critical",
:host "0.0.0.0",
:ttl nil,
:message "Jul 11 04:34:47  <hostname>: [ERROR] [xyz] - Sample abc123 causes problem for ...""


text:
Q: dynamic return type of a function How can I create a function that will have a dynamic return type based on the parameter type?
Like
protected DynamicType Test(DynamicType type)
{

return ;

}

A: Actually,  assuming that you have a known set of parameters and return types, it could be handled with simple overloading:
protected int Test(string p) {   ...  }
protected string Test(DateTime p ) { .... }

A: You'd have to use generics for this. For example,
protected T Test<T>(T parameter)
{

}

In this example, the '<T>' tells the compiler that it represents the name of a type, but you don't know what that is in the context of creating this function. So you'd end up calling it like...
int foo;

int bar = Test<int>(foo);

A: Whilst the accepted answer is good, it has been over two years since it was written, so, I should add that you can use:
protected dynamic methodname(dynamic input)
{
    return input;
}

Input will be returned as the same type, and you do not need to call the method as a generic.
Reference:
https://msdn.microsoft.com/en-us/library/dd264736.aspx

A: Then you need use generics.
protected T Test(T type) {

return type;

}

A: C# is not a dynamic language. To tackle this problem in C# you can return a generic object and typecast later to whatever you think the value should be -- not recommended. You can also return an interface, this way you don't really care about a specific class instance. As others have pointed out you can also use generics. It really depends on what you need / want to do inside the body of the function since all the methods above have their own limitations.


text:
Q: Remove session variable when user leaves page
*

*I have a page that sets a session variable to hold a list of lookups from the database for the page when the page is loaded.

*The page also will need to access that list of lookups when Ajax calls are made from the browser.
I'd like to not load the list of lookups from the database for each Ajax call, but I would like to remove the list of lookups from the session if the user leaves the page.  Is there a best practice or recommended strategy for doing this?

A: You can clear the session variable with javascript using something like this
window.onbeforeunload = cleanup;
function cleanup()
{
    // Clear session variable here
}

However, this isn't foolproof since the user could always disable javascript, etc. Usually this won't be an issue since the session variable will have a timeout anyway. If you are really concerned, you should remove any current sessions on page load.
Another option, depending on your situation, is to use the Caching.Cache class to hold the values. When you insert the values into the cache, you can set them to expire after a TimeSpan, and just set it for pretty short, like 5 minutes or so.
Note that while sessions are per user, their is only one cache per server instance.


text:
Q: how to fix the positions of random points in latex? I'm using the presentation mode in beamer. There's a frame about random stars distributed in a rectangle. I made a pause effect on that slide. However, the next frame would give me a different distribution of random stars. How can I fix the positions of that random stars and also keep the pause effect??

\documentclass{beamer}

\mode<presentation> {
\usetheme{boxes}
\usecolortheme{rose}}

\usepackage{graphicx} % Allows including images
\usepackage{booktabs} % Allows the use of \toprule, \midrule and \bottomrule in tables
\usepackage{tikz}
\usepackage{xcolor}
\usepackage{pgfplots}
\usepackage{amsmath}
\usepackage{amssymb}

\begin{document}

\begin{frame}
\begin{figure}
\centering
\begin{tikzpicture}[scale=0.7]
\filldraw[fill= blue!40, very thick,opacity=0.8] (0,0) rectangle (6,6);\pause
\draw plot [blue!80, only marks, mark=star, mark size=3, domain=0:6, samples=300] (\x,{0.5*6+0.5*rand*6});\pause
\draw[color=red!80,very thick] (2,1) circle (0.5);
\end{tikzpicture}
\end{figure}

\end{frame}
\end{document}

A: Some explanation could be found here. I will do it again because your example is more interesting.

\documentclass{beamer}
\usepackage{pgfplots}

\begin{document}
\makeatletter
\def\pgfmathsaveseed{\xdef\pgfmath@savedseed{\pgfmath@rnd@z}}
\def\pgfmathloadseed{\xdef\pgfmath@rnd@z{\pgfmath@savedseed}}
\def\beamerframeseed{\only<1>{\pgfmathsaveseed}\only<2->{\pgfmathloadseed}}
\begin{frame}
    \beamerframeseed
    \centering
    \begin{tikzpicture}[scale=1.5]
        \filldraw[fill= blue!40, very thick,opacity=0.8] (0,0) rectangle (6,6);\pause
        \draw plot[blue!80,only marks,mark=star,mark size=3,domain=0:6,samples=60](\x,{0.5*6+0.5*rand*6});\pause
        \draw plot[blue!80,only marks,mark=star,mark size=3,domain=0:6,samples=60](\x,{0.5*6+0.5*rand*6});\pause
        \draw plot[blue!80,only marks,mark=star,mark size=3,domain=0:6,samples=60](\x,{0.5*6+0.5*rand*6});\pause
        \draw plot[blue!80,only marks,mark=star,mark size=3,domain=0:6,samples=60](\x,{0.5*6+0.5*rand*6});\pause
        \draw plot[blue!80,only marks,mark=star,mark size=3,domain=0:6,samples=60](\x,{0.5*6+0.5*rand*6});\pause
        \draw[color=red!80,very thick] (2,1) circle (0.5);
    \end{tikzpicture}
\end{frame}
\end{document}


text:
Q: choose ODF vs OOXML I just found out about the "war" between ODF and OOXML and I was wondering which was "winning" and whether I should support one over the other in an project that I am about to start up soon.  I have a bias toward The Document Foundation as I used to contribute to LibreOffice, but that does not mean that choosing them is the best business decision.
Does it matter? Should I support one? both?choose ODF vs OOXML

A: The obvious choice is ODF, both for technical interoperability and moral principle.
The OOXML format was created by Microsoft and, according to this blog, is flawed by design.
Although it's a question with many subjective aspects, Microsoft is known for conducting dubious actions regarding the voting process on normative commitees and taking abusive advantage of their dominant place in the software industry.
This thread on slashdot gives interesting insight on how the ISO standard is being debated in the IT world.


text:
Q: using mailR on shinyapps.io I have a Shiny app that successfully sends email using the Mailtrap SMTP server through a call to mailR::send.mail, when I run it locally.
When I deploy this app on shinyapps.io it fails.
I have read sendmailR won't work on shinyapps.io.  Is mailR the same?
Perhaps this is a problem with configuring R to look at the correct JDK, since mailR depends on rJava?


text:
Q: How i decrypt my password using EncryptionAlgorithm(sunbeen_V1) I encrypt my password using this syntax in java
EncryptionAlgorithm algorithm =  EncryptionAlgorithmFactory.getEncryptionAlgorithm(EncryptionAlgorithmFactory.SUNBEEN_V1);
String encryptedPassword = algorithm.encrypt(password);
Input : 123
output in encrypted : QL0AFWMIX8NRZauqi4sKCKuhiiIynqH/XF7L277vIQGDCwgjAQCpAA==.
my question is how i decrypt my password using SUNBEEN_V1
i also search in google sunbeen_V1 did not get any search result.
Any Idea regarding sunbeen_V1.
thanks.


text:
Q: Remove Tap gesture from UITextField inside a UITableViewCell Basically what I want to achieve is having a UITextField inside a custom UITableViewCell while this textfield should only triggers on long press. So if the user just taps once on the textfield, the cell should triggers its delegate method didSelectRow.
So far I added a long press on my textfield and removed all others gestures. So my textfield correctly triggers when I'm long pressing it. But the problem is that when I'm just tapping on the textfield, the cell doesn't get triggered and the didSelectRow method doesn't get called. If I tap outside of my textfield, the method is correctly called ofc.
Here is my code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomCell";

    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.nameTextField.gestureRecognizers = nil;

    UILongPressGestureRecognizer *longPressTextField = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleCellTextFieldLongPress:)];
    [cell.nameTextField addGestureRecognizer:longPressTextField];

    return cell;
}

I tried different things with the UIGestureRecognizerDelegate but none seemed to work :(.
Any ideas appreciated ! Thx !

A: You should be able to accomplish this by just having your activators on the cell itself. Because your UITextField is still accepting user input, it will be stopping the underlying cell from receiving the touch.
You could get around this by adding the UILongPressGestureRecognizer to the CustomCell object and setting:
cell.nameTextField.userInteractionEnabled = NO;

A: Well I finally found a working solution.
I added a transparent view on top of my UITextField and I added my long press recognizer on this view. By this way the tap gesture goes "through" the transparent view and my cell get correctly selected :-)
Thx anyway !


text:
Q: Defining cons, car and cdr with lambda - how does it work? I can't seem to explain how this definition of cons, car and cdr works:
(define (p-cons x y)
   (lambda (proc) (proc x y)))

(define (p-car proc)
   (proc (lambda (p q) p)))

(define (p-cdr proc)
   (proc (lambda (p q) q)))

I understand that the first procedure returns a procedure which takes a procedure as an argument, and applies this procedure to the two arguments x y. What I don't understand is how car and cdr works:
(p-car (p-cons "foo" "bar")) -> foo
(p-cdr (p-cons "foo "bar")) -> bar

If someone could explain how this works I would appreciate it! How does the lambda-expression in 'car' and 'cdr' get the 'p' and 'q' variables for exemple?

A: Just do a substitution:
(p-car (p-cons "foo" "bar"))

;substituting p-cons:
(p-car (lambda (proc) (proc "foo" "bar")))

;substituting p-car:
((lambda (proc) (proc "foo" "bar")) (lambda (p q) p))

((lambda (p q) p) "foo" "bar")

"foo"

And similarly for p-cdr.
Essentially p-cons just creates a lambda which expects a procedure which will pick the appropriate stored value. p-car picks the first, p-cdr the second.


text:
Q: opengl rotation can't see back face I'm trying to draw a grid face and rotate it in various directions responding to mouse input, my code include enable GL_DEPTH_TEST, GL_NORMALIZE, I draw the grid face by glEnableClientState(GL_VERTEX_ARRAY), glEnableClientState(GL_NORMAL_ARRAY).
GL_VERTEX_ARRAY draw had tested,but when I enable GL_CULL_FACE, rotation  can't see the back face,This is front and back face .

This is the code to init OpenGL:
 def initializeGL(self):
    glEnable(GL_DEPTH_TEST)   # Depth testing must be turned on
    glEnable(GL_LIGHTING)     # Enable lighting calculations
    glEnable(GL_LIGHT0)      # Turn on light #0.

    glEnable(GL_NORMALIZE)

    # Setup polygon drawing
    glShadeModel(GL_SMOOTH)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    glEnable(GL_CULL_FACE)   # question sentence
    glCullFace(GL_BACK)

    # Clear to black
    glClearColor(0.0, 0.2, 0.3, 1.0)

The is the function of draw:
 def drawTriangles(data):
    # data shape like (n,3,3), only the triangles vertex data
    N = np.cross(data[:, 0, :] - data[:, 1, :], data[:, 0, :] - data[:, 2, :])
    N = N / np.linalg.norm(N)
    N = N.reshape([-1, 1, 3])
    N = np.hstack([N, N, N]).reshape([-1, 3])
    glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_NORMAL_ARRAY)
    glVertexPointer(3, GL_DOUBLE, 0, data)
    #specify the normal vector for every triangle, N shape like (n,3)
    glNormalPointer(GL_FLOAT, 0, N)
    glDrawArrays(GL_TRIANGLES, 0, data.shape[0] * data.shape[1])
    glDisableClientState(GL_VERTEX_ARRAY)
    glDisableClientState(GL_NORMAL_ARRAY)

other information: I use PyOpenGL+PyQt

A:
but when I enable GL_CULL_FACE,rotation can't see the back face,This is front and back face.

That's the whole purpose of face culling: Suppressing the rendering of a particular side of a primitive. If you want to see both sides, you must disable face culling.


text:
Q: Extract certificate chain from .pfx I have a .pfx file that I exported from Windows Server 2008. It includes the private key and certificate chain.
Using openssl I've been able to extract the private key and public certificate but I also need the full certificate authority chain. How can this part be extracted?
The purpose is to move the certificate to AWS EC2 Load Balancer. Only way I've been able to do this so far is exporting the chain certificates using Chrome.

A: With the pkcs12 context in openssl you can specify what components you want from the pfx file. If you don't want the signed certificate but just issuer certificates, try this:
openssl pkcs12 -in mycerts.pfx -cacerts -out myissuercerts.cer


text:
Q: jquery , razor view, and sql database I am new to asp.net and razor. I am trying to get the field called product to have autocomplete with results from the database.
I have created autocomplete.cs model and the ticket controller was already in project so i just added the action. Then the new.cshtml I had added the code.  I am lost on what is wrong. Any help is appreciated.
The issue is when i go to new.cshtml page and jquery does not work and textbox does nothing. It screws up the hidden fields which i used jquery to hide. It shows up.
Here is the auto complete.cs
using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;

namespace HelpDesk.Models
{
public class PartNumber
{
    public string[] GetPartNumber()
    {
        List<string> partnumber = new List<string>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RASConnectionString"].ConnectionString))
        {
            con.Open();
            SqlCommand comm = new SqlCommand("select * from pltjones.dbo.inv_master", con);
            SqlDataReader reader = comm.ExecuteReader();

            while (reader.Read())
            {
                partnumber.Add(reader["part_no"].ToString());
            }
        }
        return partnumber.ToArray();
    }
}

Then here is the ticket controller that was already made in this application. I am doing a snipplet of what i added.
  public ActionResult Autocomplete(string term)
    {
        var items = new PartNumber().GetPartNumber();

        var filteredItems = items.Where(
            item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
            );
        return Json(filteredItems, JsonRequestBehavior.AllowGet);
    }

Here is the razor view new.cshtml


text:
Q: I plan to use jsfiddle for html demos on my site, but how can I store my actual code? My site will feature dozens and dozens of front end live demos ( html pages with cross browser bugs ), but instead of just throwing it on jsfiddle.net and linking to demos from articles I would actually like to store them in a database or organized dynamically generated flat files.
Example:
http://site/css-bug/ will feature an article on a certain bug in X browser. I can have many ( demos ) to one ( bug/article ). They will contain HTML, CSS and some Javascript.
Another possibility I was pondering about was making my own jsfiddle.net clone, and in doing so I would have to mimic the way jsfiddle stores them ( however it does ). I'm thinking this is the best route to go, but would appreciate advice.
Background info:
As of now I am manually making static html files in directories and linking to them, and I am using Django for my application which links to these demos ( which reside on a media server ).

A: You can use jsFiddle for that.
To get the files locally you can get the parts of the saved fiddle using an undocumented API (this mean it may disappear and not be valid). Add /show_js/ or /show_html/ or /show_css/ to the end of the url.
You may wait some time until we will add export to gists on github (implementing this shouldn't take very long, but we want hit beta first).
To increase the speed of loading the example it would be great if you'd load the embedded version on demand. Display [Show example] button which will create an iframe with embedded fiddle. We plan to write cross-browser support for that as well.


text:
Q: Type conversion error from LabeledPoint in pyspark.mllib, for using linear regression model in pyspark.ml I have the following code for linear regression using pyspark.ml package. However I get this error message for the last line, when the model is being fit:

IllegalArgumentException: u'requirement failed: Column features must
  be of type org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 but was
  actually org.apache.spark.mllib.linalg.VectorUDT@f71b0bce.

Does anyone has an idea what is missing?
Is there any replacement in pyspark.ml for LabeledPoint in pyspark.mllib?
from pyspark import SparkContext
from pyspark.ml.regression import LinearRegression
from pyspark.mllib.regression import LabeledPoint
import numpy as np
from pandas import *

data = sc.textFile("/FileStore/tables/w7baik1x1487076820914/randomTableSmall.csv")

def parsePoint(line):
    values = [float(x) for x in line.split(',')]
    return LabeledPoint(values[1], [values[0]])

points_df = data.map(parsePoint).toDF()

lr = LinearRegression()

model = lr.fit(points_df, {lr.regParam:0.0})

A: The problem is that newer versions of spark have a Vector class in linalg module of ml and you do not need to get it from mllib.linalg. Also the newer versions do not accept spark.mllib.linalg.VectorUDT in ml. here is the code that would work for you :
from pyspark import SparkContext
from pyspark.ml.regression import LinearRegression
from pyspark.ml.linalg import Vectors
import numpy as np

data = sc.textFile("/FileStore/tables/w7baik1x1487076820914/randomTableSmall.csv")

def parsePoint(line):
    values = [float(x) for x in line.split(',')]
    return (values[1], Vectors.dense([values[0]]))

points_df = data.map(parsePoint).toDF(['label','features'])

lr = LinearRegression()

model = lr.fit(points_df)

A: Spark newer versions don't accept spark.mllib.linalg.VectorUDT (you do not need to get it from mllib.linalg).
try to replace
from pyspark.mllib.regression import LabeledPoint
by:
from pyspark.ml.linalg import Vectors


text:
Q: How to align specific text with image I am trying to align only 1 paragraph to the right of an image as opposed to all paragraphs. Is there a way to do this without tables. Would using tables for this be considered poor design?
As it is right now both my paragraph and my article footer align to the right of an image. I would like my article footer to be below the image while the paragraph is to the right of the image.

echo '
';
echo '';
echo '
'.$row['postTitle'].'
';
echo '';
echo '
Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).'
';

echo '
'.$row['postDesc'].'
';

echo '';
echo '
Read More
';
echo '';

echo '
';

A: First of all, I would suggest you to take the lazy server term into account: give all the workload that you can to the client (browser).
Solution
Put your image and its description within a container element.

Set the display property of your img and description container element to inline-block.

HTML

Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum

CSS
#together {
    border:3px solid #111;
}
.left {
    display:inline-block;
    width:200px;
    clear:left;
}
.right {
    display:inline-block;
    clear:right;
    margin-left:50px;
    width:200px;
}

Live Demo

A: It's not that simple. There is valign property, but in every browser it is being displayed in different way. Use style="float:left" on image instead of align, should do the job.