text:
Q: "This app can't run on your PC!", when build cordova app visual studio 2015 When i try to build the cordova app in visual studio, "This app can't run on your PC!" error shown and when hit close it appears again. (First image)
This error also happen when i try to open config.xml, a messege shown in bottom of visual studio: this item does not support previewing! and "This app can't run on your PC!" error shown again too. (second image)
I'm in Windows 10 build 10586.420 and Visual studio 2015 update 3.

A: The root cause of this error, which was not clear from the message on the screen, was a corrupted download of the node.exe file (where the download only pulled down a part of the package). This was likely because of quitting VS midway through installation, or just a bad install.
After diagnosing the user's machine, we fixed the error by manually deleting node.exe. However, the real solution is to "clear cordova cache" in Tools -> Options -> Tools for Apache Cordova -> Clear Cordova cache--as seen below.

Disclosure: I work at Microsoft on the Visual Studio Tools for Apache Cordova team, and if anyone has more setup/install problems, please follow up with me at lizhong [at] microsoft [dot] com.

A: I had disk corruption.
I was getting this error continuously. I was not able to run any exe program.
After I fixed the corrupted part of the disk, the issue got solved.


text:
Q: open different div content into same container jquery A little new to JQuery, I'm trying to have multiple links that open different related content into the same container.
JSFiddle

A: You can use data-* synatx of HTML5 to do it:
HTML:
link 1
link 2
link 3

content 1

content 2

content 3

Javascript:
$('.link').toggle(function() {
    $('.linkdetails[data-link=' + $(this).data('link') + ']').animate({
        width: '200px'
    }, 300);

}, function() {
    $('.linkdetails[data-link=' + $(this).data('link') +']').animate({
        width: '0px'
    }, 300);

});

JSFiddle DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to generate table rows based on data in database I am trying to take this style of code and generate based on how many machines are returned from the database.
I have this:

    <?php echo $array[0]; ?> #1

    sets 1 reps 50

    weight 25
    <?php echo $array[1]; ?> #2

    sets 1 reps 100

    weight 40

    <?php echo $array[2]; ?> #3

    sets 2 reps 25

    weight 20
    <?php echo $array[3]; ?> #4

    sets 3 reps 25

    weight 30

Here is the database code to retrieve the machines from the database:
$sql1 = "SELECT m1.machine_id, m2.* FROM userPlanDetail AS m1 LEFT JOIN machines AS m2 ON    m1.machine_id = m2.machine_id WHERE `user_id` = '$user_id1' AND `cardio` = 0";
$retval1 = mysql_query( $sql1, $conn );
$array = array();

while ($row = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
    $array[] = $row['machine_name'];
}

I want the code to detect how many machines are in the database that aren't cardio machines and generate the number of table rows accordingly.
Here is a visual representation:

A: Since you are loading all of your results into an array you can use array_chunk to break the array into rows and then output accordingly.
 $array = array_chunk($array, 4);
 echo '
';
 foreach($array as $row){
     echo "
";
     foreach($row as $cell){
        // echo out your tds for format each cell here.
     }
     echo "
";
 }
 echo '
';

A: <?php
    for ($x=0; $x<sizeOf($array); $x++) {
        echo '
Array Data Here
';
    }
?>

A: Updated for hard-coded machine attributes (not really a good idea)
$machine_atts = array(
    'bicep curl' => array( 'sets' => 1, 'reps' => 50, 'weight' => 25 ),
    'cable chest press' => array( 'sets' => 1, 'reps' => 100, 'weight' => 40 ),
    'lat pulldown' => array( 'sets' => 2, 'reps' => 25, 'weight' => 20 ),
    'tricep extension' => array( 'sets' => 3, 'reps' => 25, 'weight' => 30 ),
);
$sql1 = "SELECT m1.machine_id, m2.* FROM userPlanDetail AS m1 LEFT JOIN machines AS m2 ON    m1.machine_id = m2.machine_id WHERE `user_id` = '$user_id1' AND `cardio` = 0";
$retval1 = mysql_query( $sql1, $conn );
$array = array();

$i=0;
while ($row = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
    $i++;
    $sets = $machine_atts[$row['machine_name']]['sets'];
    $reps = $machine_atts[$row['machine_name']]['reps'];
    $weight = $machine_atts[$row['machine_name']]['weight'];
    $array[] = ''.$row['machine_name'].'> '.$i.'
sets '.$sets.' reps '.$reps.'
weight '.$weight.'	';
}

echo '
';
foreach ( array_chunk( $array, 2 ) as $chunk )
    echo '
' . implode('', $chunk ) . '
';
echo '
';

Original Answer
Assuming the number of sets, number of reps, and weight are in the results set of the query:
$sql1 = "SELECT m1.machine_id, m2.* FROM userPlanDetail AS m1 LEFT JOIN machines AS m2 ON    m1.machine_id = m2.machine_id WHERE `user_id` = '$user_id1' AND `cardio` = 0";
$retval1 = mysql_query( $sql1, $conn );
$array = array();

$i=0;
while ($row = mysql_fetch_array($retval1, MYSQL_ASSOC)) {
    $i++;
    $array[] = ''.$row['machine_name'].'> '.$i.'
sets '.$row['sets'].' reps '.$row['reps'].'
weight '.$row['weight'].'	';
}

echo '
';
echo '
' . implode('

', array_chunk( $array, 2 ) ) . '
';
echo '
';


text:
Q: VBA Copy criteria and Paste Criteria I think my biggest problem here is that I don't know exactly how to ask what I am looking for.
I am trying to look up information in a column in(workbook A) using criteria. For instance, I need to look up a site name which we will call "Site X". If column 2 meets this criterion I want to select a range of cells and copy.
Once I have selected the range of cells I want to activate (workbook b) which will already be open in my macro process, select the correct sheet, find "Site x" in a specific column, compare the date in a column in (workbook A) and (workbook b), then place the copied data in the correct location in the existing data source.
I have found plenty of code that can do the first part of my problem, however, the paste criterion has me stumped. My apologies If this is already answered in this forum. Please direct me to a link if able.
Here is some of the code I am attempting to use.
Sub Part3Transfer1()

Dim LastRow As Integer, i As Integer, erow As Integer

LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To LastRow

If Cells(i, 2) = "Site x" Then
Range(Cells(i, 5), Cells(i, 17)).Select
Selection.Copy

Workbooks("InstanceOnePartTwo.xlsb").Activate
Worksheets("sheet1").Activate

If Cells(i, 2) = "Site X" Then
Range(Cells(i, 68), Cells(i, 81)).Select
Selection.Paste

Next i
End If
End Sub

A: Well this is not exactly an answer, but I thought I'd give you some pointers, I've tried commenting the code with some things that may help you,... (I may get corrected on these, but I would welcome some more pointers), you should definitely look into With Statements to clarify which workbook and worksheets you are working with:
Sub Part3Transfer1()
Dim LastRow As Long
Dim i As Long
'these are declared as Long because there are more cells in Excel than there are Integer values.
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
'*** LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row ***'
'To find the last row, its usually better to declare which Sheet by either
'their code name (ie. Sheet1 or Sheet2) or by declaring them by name (such as, Sheets("Sheet1"))

For i = 2 To LastRow
    If Cells(i, 2) = "Site x" Then ' better to declare the Sheet and workbook when refering to Cells as you are moving things from workbook to workbook
                                    ' like Sheet1.Cells or Sheets("Sheet1").Cells
        Range(Cells(i, 5), Cells(i, 17)).Copy 'its considerably faster not to use Select
        'Sheet1.Range(Cells(i, 5), Cells(i, 17)).Copy
    End If

    Workbooks("InstanceOnePartTwo.xlsb").Activate
    Worksheets("Sheet1").Activate
'by activating the workbook and sheet above, it assumes that the file are already open,
'so if they is isn't open I'm sure you'll see an error, but you could change the active for an alternative
'to actually open the workbook for you?

    If Cells(i, 2) = "Site X" Then 'You should declare the workbook and Sheet when refering to Cells so it doesn't unintentionally pick the cells from the ActiveSheet
    'something like before Worksheets("Sheet1").Cells(i, 68), Worksheets("Sheet1").Cells(i,80))

        Range(Cells(i, 68), Cells(i, 81)).PasteSpecial xlPasteValues
        'use PasteSpecial with xlPasteValues to paste after your copy

        'the range of your copy statement selects a smaller range than the range you are pasting into
        'so you won't get an error, but I'm pretty sure they should be the same size (ie. from column 5 to 17 to copy
        'columns 68 to 81,...?

        'Consider using With statements, instead of this, but this will
        'show you how to refer to a cell in a specific workbook:
        'Workbooks("MySpreadsheet.xlsx").Worksheets("Sheet1").Range("A1").Value = "Hello"

    End If
Next i
End Sub


text:
Q: sync gradle in android studio 3.6.1 I have tried to sync an android project in android studio 3.6.1 now it shows the ERROR
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ':classpath'.
AND
Caused by: org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find com.android.tools.build:gradle:3.6.1.
My gradle-wrapper.properties
#Sat Mar 14 13:13:04 IRST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip

My build.gradle
// Top-level build file where you can add configuration options common to all
sub-projects/modules.

buildscript {

repositories {
    mavenLocal()
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.6.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    }
}

allprojects {
repositories {
    google()
    jcenter()

}
}

task clean(type: Delete) {
delete rootProject.buildDir
}


text:
Q: Identify Queries causing space issue I have around 1 TB of space for my tempdb in my SQL Server 2014.
In the morning I see some alerts saying the "tempdb was Full". I know there are many queries run over night and there are few queries which create a lot of temp tables and temp variables in tempdb. In morning I do not see any queries running and the tempdb in normal state.
Is there a way to get the list of queries which are causing the tempdb issue? Or any way to check the queries ran last night?

A: You will need to run this query as per your frequency and dump them into some table for later analysis..
SELECT
  sys.dm_exec_sessions.session_id AS [SESSION ID]
  ,DB_NAME(database_id) AS [DATABASE Name]
  ,HOST_NAME AS [System Name]
  ,program_name AS [Program Name]
  ,login_name AS [USER Name]
  ,status
  ,cpu_time AS [CPU TIME (in milisec)]
  ,total_scheduled_time AS [Total Scheduled TIME (in milisec)]
  ,total_elapsed_time AS    [Elapsed TIME (in milisec)]
  ,(memory_usage * 8)      AS [Memory USAGE (in KB)]
  ,(user_objects_alloc_page_count * 8) AS [SPACE Allocated FOR USER Objects (in KB)]
  ,(user_objects_dealloc_page_count * 8) AS [SPACE Deallocated FOR USER Objects (in KB)]
  ,(internal_objects_alloc_page_count * 8) AS [SPACE Allocated FOR Internal Objects (in KB)]
  ,(internal_objects_dealloc_page_count * 8) AS [SPACE Deallocated FOR Internal Objects (in KB)]
  ,CASE is_user_process
             WHEN 1      THEN 'user session'
             WHEN 0      THEN 'system session'
  END         AS [SESSION Type], row_count AS [ROW COUNT]
FROM
  sys.dm_db_session_space_usage
INNER join
  sys.dm_exec_sessions
ON  sys.dm_db_session_space_usage.session_id = sys.dm_exec_sessions.session_id

I personally prefer  tracking this using extended events..Below is the way to track using extended events..You can see the full demo on brentozar
CREATE EVENT SESSION [PublicToilet] ON SERVER
ADD EVENT [sqlserver].[database_file_size_change] (
    ACTION ( [sqlserver].[session_id], [sqlserver].[database_id],
    [sqlserver].[client_hostname], [sqlserver].[sql_text] )
    WHERE ( [database_id] = ( 2 )
            AND [session_id] > ( 50 ) ) ),
ADD EVENT [sqlserver].[databases_log_file_used_size_changed] (
    ACTION ( [sqlserver].[session_id], [sqlserver].[database_id],
    [sqlserver].[client_hostname], [sqlserver].[sql_text] )
    WHERE ( [database_id] = ( 2 )
            AND [session_id] > ( 50 ) ) )
ADD TARGET [package0].[asynchronous_file_target] (  SET filename = N'c:\temp\publictoilet.xel' ,
                                                    metadatafile = N'c:\temp\publictoilet.xem' ,
                                                    max_file_size = ( 10 ) ,
                                                    max_rollover_files = 10 )
WITH (  MAX_MEMORY = 4096 KB ,
        EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS ,
        MAX_DISPATCH_LATENCY = 1 SECONDS ,
        MAX_EVENT_SIZE = 0 KB ,
        MEMORY_PARTITION_MODE = NONE ,
        TRACK_CAUSALITY = ON ,
        STARTUP_STATE = ON );
GO

You may also want to check this link..
https://technet.microsoft.com/en-us/library/ms176029(v=sql.105).aspx
References:
https://dba.stackexchange.com/questions/13911/how-to-find-the-sql-statements-that-caused-tempdb-growth

A: I am using Query Store
Select the Metric as "Temp DB Memory Used (KB)" and Statistic as "Max".
Then I found the query that kill TempDB.
Hope this help


text:
Q: When I delete an object, are objects referenced within deleted as well? I have a main object. It holds a lot of arrays holding other objects. I wonder, when I delete the main object, will all the memory be released( main objects and the arrays and the objects(elements) of arrays )? For example:
Fruit^  my_fruit = gcnew Fruit;
Apple^  first_apple = gcnew Apple;
Apple^  second_apple = gcnew Apple;
my_fruit->AppleList->Add(first_apple);
my_fruit->AppleList->Add(second_apple);

// some operations

delete my_fruit; // **is it enough to avoid memory leak, is it necessary to delete first and second apple objects?**

A: Since your Fruit and Apple objects are instantiated by gcnew, and your list is managed type as well, you won't need to call delete on the fruit object; the garbage collector will take care of it.
If on the other hand, say the list in the Fruit object was unmanaged type, then yes you would need explicit memory deallocation code to free the list since the garbage collector doesn't know or care about the memory allocated for that list.
The best practice would be to define a destructor for the Fruit class, and put the delete list code in there. The delete call to Fruit will automatically call the destructor
http://msdn.microsoft.com/en-us/library/248aa748(v=vs.80).aspx
(edited after Matt's correction)

A: The delete call will not release the memory.  Memory allocated with gcnew will be freed by the garbage collector (not by your call to delete).  Calling delete will call the destructor (which is analogous to Dispose in C#).  See the following:
http://bytes.com/topic/net/answers/735989-gcnew
http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/19e35d8c-94c2-4ea0-8e27-8e5cb94e898e/
http://msdn.microsoft.com/en-us/library/ms177197(VS.80).aspx

A: You do not have a memory leak.  With managed types, memory is freed by the garbage collector (as Matt and sp1ky have already stated).  The delete keyword is used to dispose the object.
Using delete on a list will not dispose any objects contained inside that list.  However, you aren't using it on the list, but on the parent object.  So it depends on whether the parent object is written to automatically dispose its children.

A: Except for quite unusual programs, garbage collection will happen "often enough" that there is no need to manually deallocate objects. The only problem you might have is if you are holding onto references to large objects longer than you need to.
e.g. If you load and process two huge collections in the same function, and you store them in two different variables, the variable holding the first collection will still be live when you process the second collection. If you don't actually need the first collection anymore, the garbage collector might not notice until you return from the function and then both collections go out of scope. That might not be soon enough if the two collections don't both fit into memory at the same time.
What you can do to address this is try to break up your code into smaller units, so that you don't hold on to references to things much longer than you need to. Sometimes you can't do that without destroying the logical structure of your code, but remember that you can always assign to a variable so that it no longer holds a reference to the large object, which will then be eligible for garbage collection.
This is a bit like manually deallocating the object, except that the garbage collector takes care of whatever else was referenced from that object for you, and you can code it the same way even if you can't be sure whether the object is needed elsewhere in the program. If you were managing the memory manually you would be forced to come up with some strategy for communicating whether the object is still needed, or keep it "just in case" (which would be a memory leak, as if no other part of the program is using it no one would ever free it). With the GC figuring that out for you, you just remove your reference and if the object is needed elsewhere it will stick around, and if not it will be removed some time soon.


text:
Q: Types of authentication in OAuth2 in Spring: How does authentication via user credentials work? I am currently trying to implement a web service (API) with OAuth2 authentication using Spring Security OAuth. As far as I understood, given a user, a client app and a server, the authentication process is as follows:

*

*User requests resource from server via client

*Client retrieves request token from server

*Server responds with a temporary request token and a redirect URL

*Client loads web page (redirect URL) and lets user enter credentials in order to authenticate the request token. The form inputs are sent to the server, input is unknown to client.

*Server replies with an authorization code, which is handed to the client

*Client uses authorization code to retrieve an access token (and, optionally, a refresh token if one was requested)

*User hands access token to client

*Client uses access token to retrieve requested resource

In Spring OAuth, there are three grant types to request an access token:
Authorization Code, which is the method I described above, refresh token, and user credentials. I don't know how retrieval by user credentials works, is it similar to retrieval via refresh token?

A: A couple of statements you are making above are incorrect. Probably it's a good idea if you have another look into the OAuth2 spec: https://www.rfc-editor.org/rfc/rfc6749
To concentrate on your question I just refer to the last paragraph of your question here after.
OAuth2 supports 4 grant types, namely 'Authorization Code', 'Implicit', 'Resource Owner Password Credentials' and 'Client Credentials'. The one you are refering to as 'user credentials' would be 'Resource Owner Password Credentials'. In this grant type you loose OAuth's benefit of not having to hand over resource owner (aka user) credentials to the client. However it still has the benefit of not having to store the password on the client and sending it for each resource request, since a token is used instead. The process flow is as following:

*

*resource owner sends credentials to client

*client sends credentials to authorization server

*server returns access token (and optinally a
refresh token)

*client uses access token in subsequent request to
ressource server

So yes, you could say that the flow of the Resource Owner Password Credentials grant is similiar to the flow when a client already has a valid refresh token (from which ever grant).


text:
Q: What do I put in the form action attr on top of form wordpress I created an html form, but have no clue, what I must put in the <form action = on top of the form. Does the user info go to the database, or to a file in wordpress. I am not sure what to put there. At the moment, I do not have this site live. It's local by flywheel, but would just like to know. If anyone can help me here with this. Thanks

A: There's a great article on Sitepoint that describes how to handle POST forms in WordPress:
https://www.sitepoint.com/handling-post-requests-the-wordpress-way/


text:
Q: add spinning effect to image I have this floating circle with a logo. Is there a way to make it sway left and right as a 3d image? I have added a minimalistic reproducible example showing what I have at the moment. If anything is unclear, feel free to ask questions.
I want it to go sway to the left, then to the right and make it 3d. I am not sure how to transform this into a 3d image or add the effect. Can anyone help me?
I know understand that you have to use an SVG if I want this effect to occur. Here is an example of the effect. Look at the icons on the landing page of this website matruecannabis.com/en

body, html {
  height: 100%;
  margin: 0;
  padding: 0;
  background: #ffc60b;
}

@-webkit-keyframes float {
  0% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
  50% {
    box-shadow: 0 25px 15px 0px rgba(0, 0, 0, 0.2);
    -webkit-transform: translatey(-20px);
            transform: translatey(-20px);
  }
  100% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
}

@keyframes float {
  0% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
  50% {
    box-shadow: 0 25px 15px 0px rgba(0, 0, 0, 0.2);
    -webkit-transform: translatey(-20px);
            transform: translatey(-20px);
  }
  100% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
}
.container {
  width: 100%;
  height: 100%;
  display: -webkit-box;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
          flex-direction: column;
  -webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;
}

.avatar {
  width: 150px;
  height: 150px;
  box-sizing: border-box;
  border: 5px white solid;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
  -webkit-transform: translatey(0px);
          transform: translatey(0px);
  -webkit-animation: float 3s ease-in-out infinite;
          animation: float 3s ease-in-out infinite;
}
.avatar img {
  width: 70%;
  height: auto;
  position: absolute;
  top: 45%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Floating Logo</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
  <link rel="stylesheet" href="style.css">

A: Is this anything like what you're after?
Just animating transform: translateX on the  tag:

body,
html {
  height: 100%;
  margin: 0;
  padding: 0;
  background: #ffc60b;
}

@keyframes float {
  0%,
  100% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    transform: translateY(0);
  }
  50% {
    box-shadow: 0 25px 15px 0px rgba(0, 0, 0, 0.2);
    transform: translateY(-20px);
  }
}

@keyframes horizontal {
  0%,
  100% {
    transform: translateX(-20px);
  }
  50% {
    transform: translateX(20px);
  }
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

a {
  animation: horizontal 10s cubic-bezier(.81,.14,.57,.73) infinite;
}

.avatar {
  position: relative;
  width: 150px;
  height: 150px;
  box-sizing: border-box;
  border: 5px white solid;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
  transform: translate(0px, 0px);
  animation: float 3s ease-in-out infinite;
}

.avatar img {
  width: 70%;
  height: auto;
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

Or maybe a bit faster?

body,
html {
  height: 100%;
  margin: 0;
  padding: 0;
  background: #ffc60b;
}

@keyframes float {
  0%,
  100% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    transform: translateY(0);
  }
  50% {
    box-shadow: 0 25px 15px 0px rgba(0, 0, 0, 0.2);
    transform: translateY(-20px);
  }
}

@keyframes horizontal {
  0%,
  100% {
    transform: translateX(-10px);
  }
  50% {
    transform: translateX(10px);
  }
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transform: translateZ(0)
}

a {
  animation: horizontal 3s cubic-bezier(.3, .5, .7, 1.73) infinite;
}

.avatar {
  position: relative;
  width: 150px;
  height: 150px;
  box-sizing: border-box;
  border: 5px white solid;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
  transform: translate(0px, 0px);
  animation: float 3s ease-in-out infinite;
}

.avatar img {
  width: 70%;
  height: auto;
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

With 3d turning:

body,
html {
  height: 100%;
  margin: 0;
  padding: 0;
  background: #ffc60b;
}

@keyframes float {
  0%,
  100% {
    box-shadow: 6px 7px 10px -2px rgba(0, 0, 0, 0.6);
    transform: translateY(0) skew(-2deg) rotateY(15deg);
    background-color: rgb(255, 198, 41);
    filter: brightness(0.9);
  }
  50% {
    box-shadow: -10px 25px 15px 0px rgba(0, 0, 0, 0.2);
    transform: translateY(-20px) skew(2deg) rotateY(-20deg);
    background-color: rgb(245, 190, 41);
    filter: brightness(1.1);
  }
}

@keyframes horizontal {
  0%,
  100% {
    transform: translateX(-10px);
  }
  50% {
    transform: translateX(10px);
  }
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  // Hardware acceleration
  transform: translateZ(0);
}

a {
  animation: horizontal 3s cubic-bezier(.3, .5, .7, 1.73) infinite;
}

.avatar {
  position: relative;
  width: 150px;
  height: 150px;
  box-sizing: border-box;
  border: 5px white solid;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
  transform-origin: top;
  animation: float 3s ease-in-out infinite;
}

.avatar img {
  width: 70%;
  height: auto;
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

A: Here's quick way to do it.

body, html {
  height: 100%;
  margin: 0;
  padding: 0;
  background: #ffc60b;
}

@-webkit-keyframes float {
  0% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
  50% {
    box-shadow: 0 25px 15px 0px rgba(0, 0, 0, 0.2);
    -webkit-transform: translatey(-20px);
            transform: translatey(-20px);
  }
  100% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
}

@keyframes float {
  0% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
  50% {
    box-shadow: 0 25px 15px 0px rgba(0, 0, 0, 0.2);
    -webkit-transform: translatey(-20px);
            transform: translatey(-20px);
  }
  100% {
    box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);
    -webkit-transform: translatey(0px);
            transform: translatey(0px);
  }
}
.container {
  width: 100%;
  height: 100%;
  display: -webkit-box;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
          flex-direction: column;
  -webkit-box-pack: center;
          justify-content: center;
  -webkit-box-align: center;
          align-items: center;
}

.avatar {
  width: 150px;
  height: 150px;
  box-sizing: border-box;
  border: 5px white solid;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 5px 15px 0px rgba(0, 0, 0, 0.6);

}

.rotate {
  animation: rotation 8s infinite linear;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Floating Logo</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
  <link rel="stylesheet" href="style.css">

A: To make 3d image, you can make a gif-image
The easiest for coding is to make a insert gif-image instead of the logo/icon.
The gif-file is an animated images itself and no need to code anything.
It might be a bit of work for whoever has to make the gif(animated images), but it's easy if you know how.
There are plenty of resources on how to make a gif and also tools to make a gif online as well.
HTML example (simply added the src-path to gif-image online):

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Click image and say hi to google


text:
Q: Kivy - Buildozer - нет компиляции в Colab Пытаюсь сделать в колабе арк файл, но появляется ошибка No module named '_ctypes'
Все необходимое загружено в таком порядке

*

*!pip install buildozer

*!pip install cython==0.29.19

*!sudo apt-get install -y
python3-pip
build-essential
git
python3
python3-dev
ffmpeg
libsdl2-dev
libsdl2-image-dev
libsdl2-mixer-dev
libsdl2-ttf-dev
libportmidi-dev
libswscale-dev
libavformat-dev
libavcodec-dev
zlib1g-dev

*!sudo apt-get install -y
libgstreamer1.0
gstreamer1.0-plugins-base
gstreamer1.0-plugins-good

*!sudo apt-get install libffi-dev

*!sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev libffi6

*!apt-get update
Все варианты решения в инете касаются обновления питона и установки libffi
Может есть еще какие наработки?

A: Нашелся рабочий блокнот Колаба со всеми нужным скриптами для компиляции
https://colab.research.google.com/drive/1b9gMzs6XAtxCtahxei4N0fWZk7xiPlVw?usp=sharing


text:
Q: Use Apache To Run SSL On Port 8980 Specifically I have a web service which I access by typing the following URL exactly as is (character for character):
http://10.115.252.127:8980/opennms/login.jsp
The website files are served from /opt/opennms/jetty-webapps/opennms/
My objective is to use Apache (httpd.conf) to force any traffic to this URL to use SSL and no longer HTTP.

*

*I have successfully installed the SSL certificates with no issues.

*I have configured a VirtualHost directive to redirect port 80 to 443

*Only sites under /var/www/html/* are being successfully redirected.

Example: http://10.115.252.127/numbers successfully redirects to https://10.115.252.127/numbers
http://10.115.252.127/charts successfully redirects to https://10.115.252.127/charts
But, when I type in the URL http://10.115.252.127:8980/opennms/login.jsp it is always served as HTTP...how do I make it served as HTTPS like the others? I have checked the forums and all the posts assume you will always be redirecting port 80 and dont say anything about how to use SSL in the scenario I explained.  I have the same issue with another service running on port 3000 http://10.115.252.127:3000/login
===extract from my httpd.conf===
<VirtualHost *:80>
ServerName 10.115.252.127
Redirect permanent / https://10.115.252.127/
</VirtualHost>

<VirtualHost *:443>
        SSLEngine on
        SSLCertificateFile /etc/httpd/conf/ssl.crt/cert_mtocb2500lbscorp.crt
        SSLCertificateKeyFile /etc/httpd/conf/ssl.key/mtocb2500-lbscorp.key
        ServerName 10.115.252.127
        #Documentroot /var/www/html
</VirtualHost>

A: Based on your confirmation of my understanding, here is what you can do:
############################################################################
Listen 80

# All connections on port 80 are redirected to port 443
<VirtualHost *:80>
    ServerName www.example.com
    CustomLog "logs/80_access.log" combined
    ErrorLog "logs/80_error.log"

    Redirect permanent / https://www.example.com

    # No documentRoot, no content
</VirtualHost>

############################################################################
Listen 443

# All URI are answered from the documentRoot directory
# EXCEPT /openms, which is proxied to :8980
<VirtualHost *:443>
    ServerName www.example.com

    # temporary, remove when tests done
    LogLevel debug
    CustomLog "logs/443_access.log" combined
    Errorlog "logs/443_error.log"

    SSLEngine on
    SSLCertificateFile /etc/httpd/conf/ssl.crt/cert_mtocb2500lbscorp.crt
    SSLCertificateKeyFile /etc/httpd/conf/ssl.key/mtocb2500-lbscorp.key

    # For your redirection to 8980
    ProxyPass           /opennms    "https://www.example.com:8980/"
    ProxyPassReverse    /opennms    "https://www.example.com:8980/"

    documentRoot "/yourdir/apache/htdocs"
    DirectoryIndex index.html
</VirtualHost>

Prerequisites

*

*you must load proxy modules

*you must load rewrite module

*port 8980 is linked to some other software.  Apache does not handle 8980.


text:
Q: Make Ace the highest rank card in a deck of cards I have created this Card game, it works good, but I haven't being able to make the Ace the highest ranked card. Every time a player has ACE, he lost to the other player, and I can't figure out how to make this work correctly. I tried to use in the first statement if (c1.Value > c2.Value || c.Value=="Ace") and it didn't work.
using System;
using System.Collections.Generic;

namespace PTCB12WARGAME2
{

    class Card
    {
        public string Name;
        public int Value;
        public string Suit;
        public override string ToString() { return string.Format("{0} of {1}", Name, Suit); }
    }
    class DeckOfCards
    {
        static void Main(string[] args)
        {

            List<Card> DeckOfCards = new List<Card>()
                {
                    new Card { Name="Ace", Value=1, Suit="Heart"},
                    new Card{Name="two",Value=2,Suit="Heart"},
                    new Card{Name="three",Value=3,Suit="Heart"},
                    new Card{Name="four",Value=4,Suit="Heart"},
                    new Card { Name="five", Value=5, Suit="Heart"},
                    new Card{Name="six",Value=6,Suit="Heart"},
                    new Card{Name="seven",Value=7,Suit="Heart"},
                    new Card{Name="eight",Value=8,Suit="Heart"},
                    new Card { Name="Nine", Value=9, Suit="heart"},
                    new Card{Name="ten",Value=10,Suit="Heart"},
                    new Card{Name="jack",Value=11,Suit="Heart"},
                    new Card{Name="queen",Value=12,Suit="Heart"},
                    new Card { Name="king", Value=13, Suit="heart"},
                    new Card { Name="Ace", Value=1, Suit="Spades"},
                    new Card{Name="two",Value=2,Suit="Spades"},
                    new Card{Name="three",Value=3,Suit="Spades"},
                    new Card{Name="four",Value=4,Suit="Spades"},
                    new Card { Name="five", Value=5, Suit="Spades"},
                    new Card{Name="six",Value=6,Suit="Spades"},
                    new Card{Name="seven",Value=7,Suit="Spades"},
                    new Card{Name="eight",Value=8,Suit="Spades"},
                    new Card { Name="Nine", Value=9, Suit="Spades"},
                    new Card{Name="ten",Value=10,Suit="Spades"},
                    new Card{Name="jack",Value=11,Suit="Spades"},
                    new Card{Name="queen",Value=12,Suit="Spades"},
                    new Card { Name="king", Value=13, Suit="Spades"},
                    new Card { Name="Ace", Value=1, Suit="Diamonds"},
                    new Card{Name="two",Value=2,Suit="Diamonds"},
                    new Card{Name="three",Value=3,Suit="Diamonds"},
                    new Card{Name="four",Value=4,Suit="Diamonds"},
                    new Card { Name="five", Value=5, Suit="Diamonds"},
                    new Card{Name="six",Value=6,Suit="Diamonds"},
                    new Card{Name="seven",Value=7,Suit="Diamonds"},
                    new Card{Name="eight",Value=8,Suit="Diamonds"},
                    new Card { Name="Nine", Value=9, Suit="Diamonds"},
                    new Card{Name="ten",Value=10,Suit="Diamonds"},
                    new Card{Name="jack",Value=11,Suit="Diamonds"},
                    new Card{Name="queen",Value=12,Suit="Diamonds"},
                    new Card { Name="king", Value=13, Suit="Diamonds"},
                    new Card { Name="Ace", Value=1, Suit="Clubs"},
                    new Card{Name="two",Value=2,Suit="Clubs"},
                    new Card{Name="three",Value=3,Suit="Clubs"},
                    new Card{Name="four",Value=4,Suit="Clubs"},
                    new Card { Name="five", Value=5, Suit="Clubs"},
                    new Card{Name="six",Value=6,Suit="Clubs"},
                    new Card{Name="seven",Value=7,Suit="Clubs"},
                    new Card{Name="eight",Value=8,Suit="Clubs"},
                    new Card { Name="Nine", Value=9, Suit="Clubs"},
                    new Card{Name="ten",Value=10,Suit="Clubs"},
                    new Card{Name="jack",Value=11,Suit="Clubs"},
                    new Card{Name="queen",Value=12,Suit="Clubs"},
                    new Card { Name="king", Value=13, Suit="Clubs"},

                };

            Console.WriteLine("Each player is flipping over 1 card and whomever has the highest card wins");
            Console.ReadLine();

            for (int i = 0; i < DeckOfCards.Count; i++)
            {
                Console.WriteLine(DeckOfCards[i]);
            }

            Console.WriteLine();
            Random random = new Random();

            List<Card> deckOfPlayer1 = new List<Card>();
            List<Card> deckOfPlayer2 = new List<Card>();

            do
            {
                Console.WriteLine("Let's flip cards");
                string userAnswer = Console.ReadLine();
                if (userAnswer == "quit")
                    break;
                int r1;
                r1 = random.Next(0, DeckOfCards.Count);
                Card c1 = DeckOfCards[r1];
                deckOfPlayer1.Add(c1);
                DeckOfCards.RemoveAt(r1);

                int r2;
                r2 = random.Next(0, DeckOfCards.Count);
                Card c2 = DeckOfCards[r2];
                deckOfPlayer2.Add(c2);

                DeckOfCards.RemoveAt(r2);

                Console.WriteLine("Player1 has: {0}", c1);
                Console.WriteLine("Player2 has: {0}", c2);

                if (c1.Value > c2.Value)
                {
                    Console.WriteLine("Player1 wins");
                }
                else if (c1.Value < c2.Value)
                {
                    Console.WriteLine("Player2 wins");
                }
                else if (c1.Value == c2.Value)
                {
                    Console.WriteLine("Its a tie! Next three card in deck are played face down, 4th card face up," +
                        "woemer has the highest card wins");
                }
            } while (DeckOfCards.Count > 0);

        }
    }
}

I

A: What I was trying to say in the comments is, in a case like this it's helpful to test for equality first, then test for one value greater than the other. If neither of those are true, then the else case handles the last possible state without needing a test condition.
As far as testing for the Ace is concerned, you can either special-case a condition to check for its value, or give it the highest value in the first place (instead of the lowest).
For example:
if (c1.Value == c2.Value)
{
    Console.WriteLine("Its a tie! Next three card in deck are played face down, " +
        "4th card face up, whoever has the highest card wins");
}
else if (c1.Value == 1 || (c1.Value > c2.Value && c2.Value != 1))
{
    Console.WriteLine("Player1 wins");
}
else
{
    Console.WriteLine("Player2 wins");
}

As a side note, you can shorten your code a lot if you create an array of names and an array of suits, as you can simply use nested loops to populate your deck of cards list:
var names = new [] { "Ace", "Two", "Three", "Four", "Five", "Six",
     "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

var suits = new [] { "Hearts", "Clubs", "Diamonds", "Spades" };

var cards = new List<Card>();

// Populate our deck of cards with two nested loops
foreach(var suit in suits)
{
    // We use a 'for' loop here instead of 'foreach' so we can use the index to
    // populate the Value (which is always one more than the index of the name)
    for(int i = 0; i < names.Length; i++)
    {
        cards.Add(new Card { Name = names[i], Value = i + 1, Suit = suit });
    }
}

A: How does this look? (Edited down the code)
if (c1.Value == c2.Value) {
    //Tie
}
else if (c1.Value ==1) {
    //c1 wins
}
else if (c2.Value == 1) {
    //c2 wins
}
else if (c1.Value > c2.Value) {
    //c1 wins
}
else {
    //c2 wins
}


text:
Q: Why doesn't work when regex entering 1 letter after the optional character? I've custom regex pattern for check correct username on url:
^[@](?:[a-z][a-z0-9_]*[a-z0-9])?$

This pattern work when I write usernames:
@username
@username_16
@username16

But not work when I write:
@u

First part of question:
How to rewrite this pattern for work in @u?
Second part of question:
How control characters limit or length after @ symbol?

A: The [a-z] and [a-z0-9] are obligatory patterns inside the optional group, hence if there is something after @, there must be two chars at least.
Besides, your regex also matches a string that equals @.
To fix all these issues you may use
^@[a-z](?:[a-z0-9_]*[a-z0-9])?$

See the regex demo.
Now, to restrict the length of a string after @ symbol, you may insert a (?=.{x,m}$) positive lookahead right after @. Say, to only match 3 or 4 chars after @, use:
^@(?=[a-z0-9_]{3,4}$)[a-z](?:[a-z0-9_]*[a-z0-9])?$
  ^^^^^^^^^^^^^^^^^^^

Or, since the consuming pattern will validate the rest
^@(?=.{3,4}$)[a-z](?:[a-z0-9_]*[a-z0-9])?$
  ^^^^^^^^^^^

See this regex demo
Details

*

*^ - start of string

*(?=.{3,4}$) - a positive lookahead that requires any 3 or 4 chars other than line break chars up to the end of the string immediately to the right of the current location (i.e. from the string start here)

*@ - a @ char

*[a-z] - a lowercase ASCII letter

*(?:[a-z0-9_]*[a-z0-9])? - an optional non-capturing group matching 1 or 0 occurrences of

*

*[a-z0-9_]* - 0+ lowercase ASCII letters, digits or _

*[a-z0-9] - a lowercase ASCII letter or  digits

*$ - end of string.


text:
Q: Whether there is significant difference between two gender groups A data set contains 5 columns:

There are 16 people in the dataset(using subjectID to identify them). Each year, when these people were ages 11, 12, 13, 14, and 15, they provided us a score $y$. We now want to know whether there is a significant difference between male and female people (in their average $y$ score). How could I do? I found that this dataset does not meet the normality assumption. And in "Male" group, say subject 45 will appear 5 times, subject 268 will appear 5 times as well... Could I just use the mean of this "Male" group to make comparison with the mean of "Female" group?
And I also wonder if I can use a fixed effect model to compare these two groups:

We can see the difference between "Male" group and "Female" group is 0.13521, and it is not significant at 5% level as its p-value=0.228 (cannot reject $H_0$:"genderM"=0). So could I just say the difference is not significant?

A: Each measurement occasion is nested with an individual. There are a variety of ways to handle this issue: mixed effects models and cluster-robust standard errors are a few of them.
In a mixed effect model (aka multilevel model), you model each outcome value as a function of an intercept, (centered) age, and a measurement residual. You then model the intercept (and maybe also the slope of age) as a function of gender and an intercept (and slope) residual. The coefficient on gender is the effect of gender on the average outcome for an individual. The models look as follows:
$$y_{it} = \beta_{0t}+\beta_{1i}X^{age}_{it}+\epsilon_{it}\\
\beta_{0i}=\gamma_{00}+\gamma_{01}X^{gender}_{i}+u_{0i}\\
\beta_{1i}=\gamma_{10}+\gamma_{11}X^{gender}_{i}+u_{1i}
$$
where $i$ indexes unit-ID and $t$ indexes measurement occasion for individual $i$. The third line can be replaced by $\beta_{1i}=\gamma_{10}+u_{1i}$ if you don't think the effect of age depends on gender but varies for each individual or $\beta_{1i}=\gamma_{10}$ if you think the effect of age is constant for all individuals.
To use cluster-robust standard errors, simply run the model $y_j=\beta_0+\beta_1X^{age}_{j}+\beta_2X^{gender}_{j}+\beta_3X^{age}_{j}X^{gender}_{j}+\epsilon_j$ where $j$ indexes each row in the data set, and then request a cluster-robust standard error with unit-ID as the clustering variable. If age is centered, $\beta_2$ will be the effect of gender on the outcome.


text:
Q: How to organize large Rails application? I am working on a large(ERP level) Rails project. We have 150 tables and more than 150 models. It takes minutes to find a model. Should we add all models under the models folder or should we put them in different subfolders? Same thing goes for controllers and views.

A: I think you are running into the limitations of a single Rails application.  Much like having too much code in one module, it sounds like you have too many modules in one application.
You should consider breaking it up into multiple applications using a service model, or you might also go the route of plugins or even better look at the new Engine framework.
This will benefit you multiple ways.  It will force you to exercise good encapsulation and have good testable interface points between pieces.
Good Luck

A: I don't think it is necessary.
Doing the namespace route you mention (for models under separate directories) is what i would do.
I would also analyze the current performance issue further.
Just having 150 models/tables should not cause more than a fraction of a second to be able to find and use the model!  Is it actually the db query itself that takes a long time (when not cached)?  That can be addressed in many ways (splitting data, aggregating data, adding indexes, changing queries to be more performant, etc.
You may or may not need to do controllers and views under separate directories.
To access things arranged this way you just use ::, e.g. if you put lots of models about bedrooms and attics and basements, etc. under a subdirectory 'buildings' and then want to access it in the controller, use ::, e.g. attics = Buildings::Attic.all


text:
Q: What (Valar?) couple had greater strength together? In the Silmarillion, I'm almost sure I remember reading about a pair of people described whose powers were stronger when they were together. I think that they were a married Valar couple. As I remember it being described, it wasn't that they were actually co-laboring together, but simply that being near each other, they were stronger in their individual Valar abilities. (this would be somewhere towards the beginning of the book)
I've searched on google and here and can't find anything about it. I also tried thumbing back through the Silmarillion (I'm currently reading it), but couldn't find it. Does anyone know who this couple is, and maybe even where in the book I can find it?
If this goes without an answer, I may reread the book until I find it and answer my own question, but was hoping someone would know right where that was.

A: I believe you're referring to Manwë and Varda. From Valaquenta:

Manwë and Varda are seldom parted, and they remain in Valinor. Their halls are above the everlasting snow, upon Oiolossë, the uttermost tower of Taniquetil, tallest of all the mountains upon Earth. When Manwë there ascends his throne and looks forth, if Varda is beside him, he sees further than all other eyes, through mist, and through darkness, and over the leagues of the sea. And if Manwë is with her, Varda hears more clearly than all other ears the sound of voices that cry from east to west, from the hills and the valleys, and from the dark places that Melkor has made upon Earth.
The Silmarillion II Valaquenta "Of the Valar"

Many of the Valar couples have powers that are in some way complimentary (e.g. Aulë the Smith and Yavanna the Gardener, Mandos the Judge and Vairë the Weaver of Fate, etc.), but this is the only time I can think of where one of a pair is explicitly said to make the other stronger.

*

*Although not explicitly called out in quite the same way, Beren and Lúthien may also meet these criteria. Apart they're still rather exceptional examples of their respective races, but together they accomplish the unprecedented (and unrepeated) feat of stealing a Silmaril from Morgoth's crown.


text:
Q: Como mostrar imagem no angular 2+? Esse código está funcionando perfeitamente em uma outra;

Porém estou utilizando o mesmo código em outra página e a imagem não aparece como vocês podem ver abaixo;

      {{ restaurant.name }}
       {{ restaurant.rating }}
      {{ restaurant.category }}
      {{ restaurant.deliveryEstimate }}

Como faço para a imagem ser visualizada em tela?
O banco de dados que estou utilizando é o MongoDB.
Essa aqui é a imagem;


text:
Q: Access java variables from javacode to javascript code I am working on a Phonegap application . Here I want to access java variables in javascript code .I can access functions from javacode to javascript code here.So I think it should be possible to access java variables from javacode to javascript code . How can I do that . I have visited many post on Overflow but did't help .
I am putting sample code here .

JavaCode

class A
{
    String a, b ;
    A()
    {
       a = "phonegap";
       b=  "application" ;
    }

}

Javascript Code :

<HTML>
  <script type= "text/javascript">

  //Here I want to access java variables a and b .

  </script>

A: java
myWebView.loadUrl("javascript:callJS('things from java')")

js
function callJS(str){
  console.log(str)
}


text:
Q: python3 for loop don't work with urlopen I'm curently working on a program that reads the log error file and takes the file from command line argument then I have to print most repeating 25 errors.
For instance;
(this is a really large file so I will just copy & paste couple lines to make this clear)
[Sun Oct 09 14:15:52 2011] [error] [client 64.15.156.151] script '**/var/www/html/myip.php**' not found or unable to stat

[Sun Oct 09 14:16:25 2011] [error] [client 64.15.156.151] script '**/var/www/html/myip.php**' not found or unable to stat

[Sun Oct 09 14:18:42 2011] [error] [client 123.166.54.36] File does not exist: **/var/www/html/deny2**

[Sun Oct 09 14:26:48 2011] [error] [client 66.249.68.178] File does not exist: **/home/ms10694/public_html/homepage/Midterm Project/zengarden-sample.html**

[Sun Oct 09 14:29:59 2011] [error] [client 64.15.156.151] script '**/var/www/html/myip.php**' not found or unable to stat

[Sun Oct 09 14:30:23 2011] [error] [client 38.99.97.53] File does not exist: /var/www/html/robots.txt**

[Sun Oct 09 14:30:23 2011] [error] [client 38.99.97.53] File does not exist: **/var/www/html/favicon.ico**

I need to search in for loop those bolded addresses and find most repeating 25 errors.
My code searches for any line includes '/var.....+' but for some reason it does keep printing only very first ' /var...+ ' on log error file.
What am I missing here?
#!/usr/bin/env python3
import urllib.request
import re
import sys
import os

Argument = sys.argv[1]

LogErrorFile = urllib.request.urlopen(Argument)

InBytes = LogErrorFile.read()

InString = InBytes.decode("utf8")

#for s in InString:
text = InString
for s in InString:
 FindLines = re.findall('/var.+', text)
 print (FindLines[0])

A: There's a lot going on here so I'll give you a slightly simplified version of what you're looking for:
import io
import re
from sys import argv

in_file = argv[1]

with io.open(in_file, 'r', encoding='utf-8') as my_file:
  for line in my_file:
    print(re.findall('\/var.*', line))

Why does it keep printing the first /var line?

Because you ask it to with the zero here:
FindLines[0]

It's not clear how you're defining "error" (whole line? just a piece?) so I'm not pulling the most common errors. And that type error file isn't usually retrieved remotely so I didn't include urllib. Instead I assumed it was local and used the io module.
Hope that helps!


text:
Q: Get list of unique multi-sets How can I uniquify the following list in Python:
all_the_ways = [(5,), (2, 2, 1), (2, 1, 2), (2, 1, 1, 1), (1, 2, 2),\
                (1, 2, 1, 1), (1, 1, 2, 1), (1, 1, 1, 2), (1, 1, 1, 1, 1)]

Desired output is:
[(5,), (2, 2, 1), (2, 1, 1, 1), (1, 1, 1, 1, 1)]

i.e. I need to get rid of tuples that have the same set of numbers but in different order.
I tried
set(all_the_ways)

but it only transpose elements.
And when I do
list(map(set, all_the_ways))

the things getting only worse:
[{5}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1, 2}, {1}]

In other words I need to convert inner tuple to a collection that allows multiple equal items (set is not suitable) and for which permutations of elements don't change the collection itself (kinda like C++'s multiset)

A: How about this:
list(set(tuple(sorted(s)) for s in all_the_ways))

Output:
[(1, 2, 2), (5,), (1, 1, 1, 1, 1), (1, 1, 1, 2)]

It will mangle the order of each tuple though. I'm assuming that doesn't matter, as tuples containing the same set of numbers are considered the same for your case. What this implies is that in the end, the output list might contain tuples that are not among the original input, for example (credit to @thefourtheye):
all_the_ways = [(2, 1, 2), (2, 2, 1)]
# Output: [(1, 2, 2)]

This may or may not be a problem, and if it is, you can use the more robust solutions which are already mentioned in the other excellent answers.

A: Use collections.Counter() to identify the unique multisets:
>>> from collections import Counter

>>> all_the_ways = [(5,), (2, 2, 1), (2, 1, 2), (2, 1, 1, 1), (1, 2, 2),\
                (1, 2, 1, 1), (1, 1, 2, 1), (1, 1, 1, 2), (1, 1, 1, 1, 1)]
>>> result = []
>>> seen = set()
>>> for tup in all_the_ways:
        key = tuple(sorted(Counter(tup).items())) # unique signature
        if key not in seen:
            result.append(tup)
        seen.add(key)

>>> result
[(5,), (2, 2, 1), (2, 1, 1, 1), (1, 1, 1, 1, 1)]

A: If the Order doesn't matter you can use this
from collections import Counter
>>> {frozenset(Counter(tup).items()):tup for tup in data}.values()
# [(1, 2, 2), (1, 1, 1, 2), (1, 1, 1, 1, 1), (5,)]

If you want to maintain the Order,
from collections import Counter, OrderedDict
OrderedDict([frozenset(Counter(tup).items()),tup] for tup in data).values()
# [(5,), (1, 2, 2), (1, 1, 1, 2), (1, 1, 1, 1, 1)]

In both the solutions we rely on frozenset, because the set objects are not hashable as they are mutable. In the first case, we construct a dictionary with the frequency of the numbers (determined with Counter) as the key and the current tuple as the value corresponding to that. Once the dictionary construction is completed, we take all the values, which correspond to the  tuples.
In the second case, we simply use OrderedDict to maintain the order.

A: May be this?:
result = {tuple(sorted(x)) for x in all_the_ways}

A: Try
from collections import OrderedDict
print OrderedDict.fromkeys(map(lambda x: tuple(sorted(x)), all_the_ways)).keys()

or
print set(map(lambda x: tuple(sorted(x)), all_the_ways))

A: I take it that you consider two elements "equal" if they contain the same values, regardless of the order.
So you can "canonicalize" each tuple by sorting it, convert back to tuples (so they are hashable), and remove duplicates using set again:
set( tuple(sorted(tup)) for tup in all_the_ways )

You can also preserve the original "outer" order, by using OrderedSet instead of set.


text:
Q: IOS Rotation Notification does not work I'm trying NSNotificationCenter with this code:

but does not print anything, never enters in the rotate function, any ideas? thanks a lot

A: Did you confirm that you've enabled the appropriate orientations under App General settings?


text:
Q: Navigation works in browser but not in Ionic View iphone app I have a tabbed application that started out as ionic start myApp tabs. I've been editing it and I added a page called count.html which shared the DashCtrl controller. I link to it in the Dash Tab and it works fine when I'm testing in Chrome on my computer, but when I use the Ionic Viewer, it does not navigate; it just stays on the Dash Tab page as if nothing were supposed to happen.
How do I fix the navigation for the device?
tab-dash.html
<ion-view view-title="Test">

  <ion-content class="padding">

    <button class="button button-full button-positive" ui-sref="tab.count">
        Count
    </button>

  </ion-content>
</ion-view>

count.html
<ion-view view-title="Count">

    <ion-nav-bar class="bar-energized">
        <ion-nav-back-button class="button-clear">
            <i class="ion-arrow-left-c"></i> Back
        </ion-nav-back-button>
    </ion-nav-bar>

  <ion-content class="padding">

  </ion-content>
</ion-view>

app.js
  .state('tab', {
    url: "/tab",
    abstract: true,
    templateUrl: "templates/tabs.html"
  })

  // Each tab has its own nav history stack:

  .state('tab.dash', {
    url: '/dash',
    views: {
      'tab-dash': {
        templateUrl: 'templates/tab-dash.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('tab.count', {
    url: '/count',
    views: {
      'tab-dash': {
        templateUrl: 'templates/count.html',
        controller: 'DashCtrl'
      }
    }
  })

A: This appears to be an Ionic View bug. As soon as I killed the app from Switcher, the routing worked properly. Edit: Confirmed to be a caching bug with UIWebView in the Ionic View application.
https://github.com/driftyco/ionic-view-issues/issues/10

It seems that no matter what cache policy you set, it will only apply to the initial request (in this case index.html) and load all CSS and JS from the cache no matter what.

A: I had a similar issue and was able to resolve it by putting "./" at the beginning of the templateUrl. Try
templateUrl: './templates/count.html',


text:
Q: nginx returning netstring with wrong length? I installed nginx (nginx version: nginx/1.7.9) via macports on my mac running the latest OSX.
I configured a URI to use SCGI:
location /server {
    include /Users/ruipacheco/Projects/Assorted/nginx/conf/scgi_params;
    scgi_pass unix:/var/tmp/rpc.sock;
    #scgi_pass 127.0.0.1:9000;
}

And when I do a GET on 127.0.0.1/server I can see the following on my SCGI server:
633:CONTENT_LENGTH0REQUEST_METHODGETREQUEST_URI/serverQUERY_STRINGCONTENT_TYPEDOCUMENT_URI/serverDOCUMENT_ROOT/opt/local/htmlSCGI1SERVER_PROTOCOLHTTP/1.1REMOTE_ADDR127.0.0.1REMOTE_PORT62088SERVER_PORT80SERVER_NAMElocalhostHTTP_HOST127.0.0.1HTTP_CONNECTIONkeep-aliveHTTP_CACHE_CONTROLmax-age=0HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8HTTP_USER_AGENTMozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36HTTP_DNT1HTTP_ACCEPT_ENCODINGgzip, deflate, sdchHTTP_ACCEPT_LANGUAGEen-US,en;q=0.8,End of file

The problem is that the length of the netstring (633) does not match the interpreation. If I understand the netstrings spec correctly, 633 should be the length of characters between the first : and the last ,:
Any string of 8-bit bytes may be encoded as [len]":"[string]",". Here [string] is the string and [len] is a nonempty sequence of ASCII digits giving the length of [string] in decimal. The ASCII digits are <30> for 0, <31> for 1, and so on up through <39> for 9. Extra zeros at the front of [len] are prohibited: [len] begins with <30> exactly when [string] is empty.

For example, the string "hello world!" is encoded as <31 32 3a 68 65 6c 6c 6f 20 77 6f 72 6c 64 21 2c>, i.e., "12:hello world!,".

So, I'm getting the wrong length. How can this be explained?


text:
Q: how to accumulate 2D array elements in Scala? I have 2D array as:
Array(Array(1,1,0), Array(1,0,1))
and I would like to accumulate values over column so my final output look like
Array(Array(1,1,0), Array(2,1,1))
If this is 1D array, I can simply use 'scan' but I'm having trouble with using scan in 2D array.
can anyone help on this issue?

A: Here's one way to do it:
val t = Array(Array(1,1,0), Array(1,0,1))

val result = t.scanLeft(Array.fill(t(0).length)(0)) ((x,y) =>
  x.zip(y).map(e => e._1 + e._2)).drop(1)

//to see the results
result.foreach(e => println(e.toList))

gives:
List(1, 1, 0)
List(2, 1, 1)

The idea is to create an array filled with zeros (using Array.fill) and then scan the 2D array using that as an accumulator. In the end, drop(1) gets rid of the zero-filled array.
EDIT:
In response to the comment, this solution works for a matrix of any size. The zip function takes care of element-wise addition.
EDIT 2 (Step by step explanation):
You already know about scan or a one-dimensional array. The idea is essentially the same.

*

*We initialize the accumulator with zero. In this case, zero means an array of zeros. Array.fill is used to create an array filled with zeros.

*Instead of a single addition, we need to add arrays element-wise. This is what the combination of zip and map do. There are a lot of examples available on the Internet about how these methods work.

*Finally, we drop the zero element using Scala's drop(1). The result is an array of arrays containing accumulated values.

A: Pretty much the same approach as a 1D array:
a.tail.scan(a.head)((acc, value) =>
  Array(acc(0) + value(0), acc(1) + value(1), acc(2) + value(2))
)

For arbitrary number (as long as they all have the same number):
a.tail.scan(a.head)((acc, value) =>
  acc zip value map {case (a,b) => a+b}
)

A: I would solve it as for given row r, sum all previous rows.
val accumatedMatrix =
 for(row <- array.indices)
  yield array.take(row + 1).foldLeft(Array(0, 0, 0)) {
    case (a, b) => Array(a(0) + b(0), a(1) + b(1), a(2) + b(2))
  }

input:
val array =  Array(
  Array(1,1,0),
  Array(1,0,1)
)

output:
1,1,0
2,1,1

Instead of summing all the previous rows repeatedly you can improve it to memoize as well.


text:
Q: timeago on my guestbook I build a guestbook and i want to add the Timeago-plugin from Yarp (http://timeago.yarp.com/).
I have this javascript on the top of the page:
<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery("abbr.timeago").timeago();
    });
</script>

Then i have an While-loop there i publish the text from the database. And on each text i have a DATETIME stored.
<abbr class="timeago" title="<?php echo $Date; ?>"><?php echo $Date; ?></abbr>

So, How do I get it to update the dates?


text:
Q: CNAME SSL Redirect Setup with Cloudflare I'm hosting two subdomains with two (non-wildcard) Let's Encrypt certificates outside of cloudflare:
name.feed.example.com
name.example.com
I have a CNAME alias on Cloudflare (free plan) pointing
from name.example.com
to name.feed.example.com
I'm getting an Error 526: Invalid SSL certificate
Any ideas? Thank you! :*


text:
Q: ansible-playbook aws provisioning unable to convert to dict: dictionary requested, could not parse JSON i'm a toddler in ansible sea. however, i'm trying to provision an aws provider playbook in macos. default output for aws profile is json
i'm following this step by step guide:
forem.dev/foremteam/forem-aws-setup-on-macos-hom
github.com/forem/selfhost#aws
aws.yml
---
- name: Deploy Forem to AWS
  hosts: all
  become: false

  collections:
    - amazon.aws
    - community.aws
    - community.general

  vars:
    fcos_arch: x86_64
    fcos_platform: aws
    fcos_format: vmdk.xz
    fcos_stream: stable
    fcos_aws_region: us-east-1
    fcos_aws_size: t3a.small
    fcos_aws_ebs_size: 100
    fcos_aws_profile: forem-selfhost
    butane_cleanup: true
    ssh_key: "{{ lookup('file', '~/.ssh/id_ed25519.pub') }}"

  roles:
    - preflight

  tasks:
  - name: Get FCOS facts
    include_role:
      name: fcos
      tasks_from: facts

  - name: Convert butane file to an Ignition file
    include_role:
      name: butane
      tasks_from: butane
    vars:
      butane_input_template: "../templates/forem.yml.j2"
      butane_aws_s3: true
      butane_aws_s3_url: "https://forem-selfhost-{{ app_domain |replace('.', '-') }}-ign.s3.{{ fcos_aws_region }}.amazonaws.com/forem.ign"

  - amazon.aws.ec2_vpc_net_info:
      filters:
        "isDefault": "true"
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
    register: forem_vpc_info

  - name: Set forem_vpc_id fact
    ansible.builtin.set_fact:
      forem_vpc_id: "{{ forem_vpc_info['vpcs'][0]['vpc_id'] }}"

  - name: Gather info about VPC subnets
    amazon.aws.ec2_vpc_subnet_info:
      filters:
        vpc-id: "{{ forem_vpc_id }}"
        availability-zone: "{{ fcos_aws_region }}a"
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
    register: forem_subnet_info

  - name: Gather info about VPC AZs
    amazon.aws.aws_az_info:
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
    register: forem_az_info

  - name: "Get route table facts for {{ forem_vpc_id }}"
    community.aws.ec2_vpc_route_table_info:
      region: "{{ fcos_aws_region }}"
      filters:
        vpc-id: "{{ forem_vpc_id }}"
      profile: "{{ fcos_aws_profile }}"
    register: forem_vpc_route_table

  - name: "Generate list of route tables for {{ forem_vpc_id }}"
    set_fact:
      forem_vpcd_route_table_ids: "{{ forem_vpc_route_table.route_tables|map(attribute='id')|list }}"

  - name: "Create S3 VPC endpoint in {{ forem_vpc_id }}"
    community.aws.ec2_vpc_endpoint:
      state: present
      region: "{{ fcos_aws_region }}"
      vpc_id: "{{ forem_vpc_id }}"
      service: "com.amazonaws.{{ fcos_aws_region }}.s3"
      route_table_ids: "{{ forem_vpcd_route_table_ids }}"
      profile: "{{ fcos_aws_profile }}"
    register: forem_vpc_s3_endpoint

  - name: Set forem_vpc_s3_endpoint_id fact
    set_fact:
      forem_vpc_s3_endpoint_id: "{{ forem_vpc_s3_endpoint.result.vpc_endpoint_id }}"

  - name: Wait for S3 VPC Endpoint
    pause:
      seconds: 30

  - name: Create FCOS ignition bucket
    amazon.aws.s3_bucket:
      name: "forem-selfhost-{{ app_domain |replace('.', '-') }}-ign"
      state: present
      encryption: "AES256"
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
      policy: |
        {
          "Version": "2012-10-17",
          "Id": "VPCEaccesstoignitionbucket",
          "Statement": [
            {
              "Sid": "VPCE-access-to-ign-bucket",
              "Principal": "*",
              "Action": "s3:GetObject",
              "Effect": "Allow",
              "Resource": ["arn:aws:s3:::forem-selfhost-{{ app_domain |replace(".", "-") }}-ign/*"],
              "Condition": {
                "StringEquals": {
                  "aws:sourceVpce": "{{ forem_vpc_s3_endpoint_id }}"
                }
              }
            }
          ]
        }

  - name: "Upload butane_ignition_stdout to forem-selfhost-{{ app_domain |replace('.', '-') }}-ign"
    amazon.aws.aws_s3:
      bucket: "forem-selfhost-{{ app_domain |replace('.', '-') }}-ign"
      object: "/forem.ign"
      content: "{{ butane_ignition_stdout | to_json | string }}"
      mode: put
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
    register: forem_ign_s3

  - name: Create Forem SSH key
    amazon.aws.ec2_key:
      name: "forem-{{ app_domain }}"
      key_material: "{{ ssh_key }}"
      profile: "{{ fcos_aws_profile }}"
      region: "{{ fcos_aws_region }}"

  - name: "Create Forem security group for {{ app_domain }}"
    amazon.aws.ec2_group:
      name: "forem-{{ app_domain }}"
      description: "Forem security group for {{ app_domain }}"
      vpc_id: "{{ forem_vpc_id }}"
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
      tags:
        "Name": "forem-{{ app_domain }}"
      rules:
        - proto: tcp
          ports:
            - 22
          cidr_ip: "{{ local_wan_ip_address }}/32"
          rule_desc: "Allow SSH access from {{ local_wan_ip_address }}"
        - proto: tcp
          ports:
            - 80
            - 443
          rule_desc: "Allow HTTP and HTTPS access from 0.0.0.0/0"
          cidr_ip: 0.0.0.0/0
      rules_egress:
        - proto: "all"
          from_port: 0
          to_port: 65535
          cidr_ip: "0.0.0.0/0"
          rule_desc: "Allow outbound access to 0.0.0.0/0"
    register: forem_security_group

  - name: "Launch Forem instance for {{ app_domain }}"
    amazon.aws.ec2_instance:
      key_name: "forem-{{ app_domain }}"
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"
      group: "forem-{{ app_domain }}"
      instance_type: "{{ fcos_aws_size }}"
      image: "{{ fcos_aws_image }}"
      wait: yes
      wait_timeout: 500
      vpc_subnet_id: "{{ forem_subnet_info.subnets | map(attribute='id') | list | first }}"
      volumes:
        - device_name: /dev/xvda
          volume_type: gp2
          volume_size: "{{ fcos_aws_ebs_size }}"
          encrypted: yes
          delete_on_termination: no
      monitoring: yes
      assign_public_ip: yes
      user_data: "{{ butane_boot_ignition_stdout | to_json | string }}"
      instance_tags:
        App: "forem"
        Domain: "{{ app_domain }}"
        Name: "forem-{{ app_domain }}"
      count_tag:
        App: "forem"
        Domain: "{{ app_domain }}"
        Name: "forem-{{ app_domain }}"
      exact_count: 1
    register: forem_ec2_instance

  - name: Wait 300 seconds for port 22 to become open
    wait_for:
      port: 22
      host: "{{ forem_ec2_instance.tagged_instances | map(attribute='public_ip') | list | first }}"
      delay: 10
    connection: local

  - name: "Delete object forem-selfhost-{{ app_domain |replace('.', '-') }}-ign/forem.ign from S3"
    amazon.aws.aws_s3:
      bucket: "forem-selfhost-{{ app_domain |replace('.', '-') }}-ign"
      object: "/forem.ign"
      mode: delobj
      region: "{{ fcos_aws_region }}"
      profile: "{{ fcos_aws_profile }}"

  - name: Output EC2 setup message
    ansible.builtin.debug:
      msg:
      - "The public IPv4 IP Address for {{ app_domain }} is {{ forem_ec2_instance.tagged_instances | map(attribute='public_ip') | list | first }}"
      - "Please add an A entry for {{ app_domain }} that points to {{ forem_ec2_instance.tagged_instances | map(attribute='public_ip') | list | first }}"
      - "Example:"
      - "    {{ app_domain }} IN A {{ forem_ec2_instance.tagged_instances | map(attribute='public_ip') | list | first }}"
      - "Once you have DNS resolving to this EC2 instance please read the Forem Admin Docs: https://admin.forem.com/"

setup.yml -- i don't know the correct technical term for this file's inner functionality.
---
all:
  hosts:
  vars:
    ssh_key: "{{ lookup('file', '~/.ssh/forem.pub') }}"
    app_protocol: https://
    database_pool_size: 10
    force_ssl_in_rails: "true"
    lang: en_US.UTF-8
    node_env: "{{ forem_environment }}"
    rack_env: "{{ forem_environment }}"
    rack_timeout_service_timeout: 300
    rack_timeout_wait_timeout: 300
    rails_env: "{{ forem_environment }}"
    rails_log_to_stdout: "true"
    rails_serve_static_files: enabled
    redis_sessions_url: redis://localhost:6379
    redis_sidekiq_url: redis://localhost:6379
    redis_url: redis://localhost:6379
    session_expiry_seconds: 1209600
    web_concurrency: 2
    forem_context: selfhost
    forem_container_tag: quay.io/forem/forem:latest
  children:
    forems:
      hosts:
        forem:
          ansible_connection: local
          ansible_python_interpreter: /usr/bin/python3 # on macOS, this may need to be /usr/local/bin/python3
          # CHANGE_REQUIRED — forem_domain_name: example.com
          forem_domain_name: site.com
          # CHANGE_REQUIRED — default_email: your_email@example.com
          default_email: email@gmail.com
          forem_subdomain_name: www # can be subdomain, i.e. "community" in community.mainwebsite.com
          forem_server_hostname: host # You may change to something else if you choose (i.e. server, srv, etc)

          # CHANGE_OPTIONAL - strict-origin-when-cross-origin enables embedded youtube video playback
          referrer_policy: "same-origin"
          # referrer_policy: "strict-origin-when-cross-origin"
          app_domain: "{{ forem_subdomain_name }}.{{ forem_domain_name }}"
          secret_key_base: "{{ vault_secret_key_base }}"
          session_key: _FOREMSELFHOST_Session
          imgproxy_key: "{{ vault_imgproxy_key }}"
          imgproxy_salt: "{{ vault_imgproxy_salt }}"
          forem_version: latest
          forem_environment: production
          dd_api_key: "{{ vault_dd_api_key }}"
          honeybadger_api_key: "{{ vault_honeybadger_api_key }}"
          honeybadger_js_api_key: "{{ vault_honeybadger_js_api_key }}"
          honeycomb_api_key: "{{ vault_honeycomb_api_key }}"
          postgres_user: forem_production
          postgres_password: "{{ vault_forem_postgres_password }}"
          postgres_host: localhost
          pusher_app_id: "{{ vault_pusher_app_id }}"
          pusher_beams_id: "{{ vault_pusher_beams_id }}"
          pusher_beams_key: "{{ vault_pusher_beams_key }}"
          pusher_cluster: us2
          pusher_key: "{{ vault_pusher_key }}"
          pusher_secret: "{{ vault_pusher_secret }}"
          recaptcha_secret: "{{ vault_recaptcha_secret }}"
          recaptcha_site: "{{ vault_recaptcha_site }}"
          sendgrid_api_key: "{{ vault_sendgrid_api_key }}"
          sendgrid_api_key_id: "{{ vault_sendgrid_api_key_id }}"
          slack_channel: "#forem-activity"
          slack_webhook_url: "{{ vault_slack_webhook_url }}"

          # Required Ansible Vault secret variables
          # Use the following example commands below in a terminal to generate the required variables with Ansible Vault encrypt_string
          # These commands should be run in the selfhost directory, since the
          # ansible.cfg identifies the vault password which will be used to decrypt
          # if ansible-vault prompts for a password, something is not right
          # See this URL to learn more about ansible-vault:
          # https://docs.ansible.com/ansible/latest/user_guide/vault.html#encrypting-individual-variables-with-ansible-vault

          vault_secret_key_base: !vault |
            $ANSIBLE_VAULT;1.1;AES256
                        #secret key

          vault_imgproxy_key: !vault |
            $ANSIBLE_VAULT;1.1;AES256
                        #secret key

          vault_imgproxy_salt: !vault |
            $ANSIBLE_VAULT;1.1;AES256
                        #secret key

          vault_forem_postgres_password: !vault |
            $ANSIBLE_VAULT;1.1;AES256
            #secret key
          # Optional Ansible Vault variables
          # echo -n foobarbaz |  ansible-vault encrypt_string --stdin-name vault_my_cool_vaulted_var
          vault_cloudinary_api_key:
          vault_cloudinary_api_secret:
          vault_dd_api_key:
          vault_honeybadger_api_key:
          vault_honeybadger_js_api_key:
          vault_honeycomb_api_key:
          vault_pusher_app_id:
          vault_pusher_beams_id:
          vault_pusher_beams_key:
          vault_pusher_key:
          vault_pusher_secret:
          vault_recaptcha_secret:
          vault_recaptcha_site:
          vault_sendgrid_api_key:
          vault_sendgrid_api_key_id:
          vault_slack_webhook_url:

i'm getting the following error when it reaches the task "Launch Forem instance for {{ app_domain }}" in aws.yml:
fatal: [forem]: FAILED! => changed=false
  msg: 'argument ''image'' is of type <class ''str''> and we were unable to convert to dict: dictionary requested, could not parse JSON or key=value'

PLAY RECAP *************************************************************************************************************************************************************************************************
forem                      : ok=40   changed=20   unreachable=0    failed=1    skipped=1    rescued=0    ignored=0

since it being the last demanding task, you can assume that all required packages are installed correctly.
I do not know how to overpass this error, tried looking for it online to no avail. my first thought is that maybe it is not defined in vars up above. any ideas or guidance as to how to overpass this are
highly welcomed and appreciated.
thanks


text:
Q: Having trouble submitting question with android app When I post a question with the app I get a nice preview with my tags etc visible, but when I press submit, it thinks about something for a while then goes back to the question edit activity. No question submitted, no errors given.
Screnshots:
Editing my question :

After pressing submit, note random title (didn't see that first time round):

After confirming preview, submitting again:

A: Sorry about that, caught that bug this morning. It'll be fixed in the build from tonight.


text:
Q: Invalid number while comparing string to number oracle Hello I am currently involved in a project that is running for over 2 years, and yesterday,  we started to face following issue:
One query that was always used and ran at least 20.000 every single day, yesterday fom nothing started to return invalid number error.
ORA-01722: invalid number
select orq.rt_id, orec.* from orderrec orec
  join order_header oh on (oh.order_code = orec.ordernumber and oh.page = orec.pagenumber)
  left join order_request orq on oh.orq_id = orq.orq_id
       where ordernumber=? and pagenumber=? and state < 100

the problematic part is:
oh.order_code = orec.ordernumber

*

*order_code is a string

*ordernumber is a number

As this is would give a high impact on clients production I've change the equal comparison to a like find query bellow. After this change process started to work again without issue.
select orq.rt_id, orec.* from orderrec orec join order_header oh on (oh.order_code like orec.ordernumber and oh.page = orec.pagenumber) left join order_request orq on oh.orq_id = orq.orq_id
  where ordernumber=? and pagenumber=? and state < 10

This query is a XML file used with a java program.
My doubt is why this would have happend?

A: I would check to see if the ORDER_CODE field, which you say is a string, contains any new values with non-digit characters (0-9) as that would be my guess as to the cause.
Even though your ORDER_CODE field is a string, when you join that field with a number field, Oracle will attempt to convert that string to a number (implicitly). You might as well be using the to_number() function on the ORDER_CODE field, because that is how it's actually being processed.
For instance, this query:
select *
  from tablea a
  join tableb b
    on a.order_code = b.ordernumber

Will not return an error if ORDER_CODE contains values with only digits (0-9) and no letters.
But if it does contain at least one such value, boom, you get the error you describe.
It is true that you can use LIKE to avoid the error, but it will be unable to match rows where the ORDER_CODE has letters. Notice how in this example http://sqlfiddle.com/#!4/f00f91/1/0 '9A' won't match with 9, whereas '8' does match with 8.
The answer in a nutshell is that because you're joining two fields of a different format, one a string, one a number, a conversion from the string to a number is implied. And obviously, when the string contains letters such as A, B, C, etc. it will be unable to do the conversion and so it will give you that error.
You can run this query to find the "problem values", my guess is that whatever rows are returned were recently inserted, causing the error:
Fiddle:
http://sqlfiddle.com/#!4/f5b55/1/0
select *
from order_header
where regexp_like(order_code, '[^0-9]')


text:
Q: How to have two root websites on one IIS server I have a website on the IIS as the default website. It is in "c:\interpub\wwwroot". When I request "www.mysite1.com", I get to this site.
Now I want to add a second website on the same IIS server. I want to store it in "c:\mysecondsite". When I request "www.mysite2.com", I wish to get to this second site.
NOTE: I don't want the second site to become an application inside the first site. In other words, I don't want to access the second site using "www.mysite1.com/mysite2".
How do I do it?


text:
Q: Elliptical orbit: $\theta$ in terms of $t$ Suppose we have an elliptical orbit with the sun at one focus $F_1$ -- See diagram. Let $F_1$ be the origin and let $\theta$ be the the angle between $F_1P$ and $F_1B$. Find $\theta$ as a function of time $t$.

My attempt:
According to Kepler's 2nd law, $$\frac{dA}{dt}=\frac{1}{2}r^2\frac{d\theta}{dt}=k\tag1$$
where $k$ is a constant.
We know that $\displaystyle r=\frac{p}{1-\epsilon\cos\theta}$ where $p$ is the semi-latus rectum and $\epsilon$ is the eccentricity of the ellipse.
Substituting into (1), we get
$$\frac{1}{2}\left(\frac{p}{1-\epsilon\cos\theta}\right)^2\frac{d\theta}{dt}=k$$
We can now integrate to find $\theta$ in terms of $t$.
Is this correct? Is there is a simpler way to do this that I'm missing?


text:
Q: How to create a data.table with one row filled with NA based on another data.table Say I have the following data.table (but think of it as a table with a lot of columns with dynamically changing names)
DT <- data.table(a=rep(1L,3),b=rep(1.32,3),d=rep("qwe",3))
DT
   a    b   d
1: 1 1.32 qwe
2: 1 1.32 qwe
3: 1 1.32 qwe

Say now that I want to create a row with NAs that I could then rbindlist with DT.
First try (it is not working)
DT1 <- DT[1][,colnames(DT):=NA]
DT1
    a  b  d
1: NA NA NA
rbindlist(list(DT1,DT))
      a    b  d
1:   NA   NA NA
2: TRUE TRUE NA
3: TRUE TRUE NA
4: TRUE TRUE NA

This is not working because DT1 is casted when :=NA is called (something called plonking it seems, because if you provide a full column when := RHS type will overwrite LHS...)
The question is then, how can I extract a row of a data.table and fill it with NA or create a data.table, filled with NA that have the same column names and column type that another

A: There are many ways of doing it, here's one:
rbind(DT[NA], DT)
#    a    b   d
#1: NA   NA  NA
#2:  1 1.32 qwe
#3:  1 1.32 qwe
#4:  1 1.32 qwe


text:
Q: Extract mail list addresses from MailGun I want to extract the addresses OUT OF MailGun, into a CSV and delete the MailGun altogether.
The MailGun database is the only copy of the 951 addresses I have absolutely no access to the database in any form other than looking at the list in MailGun.
http://documentation.mailgun.com/api-mailinglists.html#mailing-lists

A: This is my solution to this problem in C# ,and it can get all members of a list(not only 100 limited).In addition, i use Newtonsoft.Json. Update: I found the 'total_count' has a maximum value 10000, so if the members in your mailing list is more than 10000, the request will return the maximum value 10000! In that case, this is not a great solution!
public void ExportMailList(string listName)
    {
        RestClient client = new RestClient();
        List<MemberDetail> totalMember = new List<MemberDetail>();
        client.BaseUrl = new Uri("https://api.mailgun.net/v3");
        client.Authenticator =
                new HttpBasicAuthenticator("api",
                                           "key-yourKey");
        RestRequest reqForTotal = new RestRequest();
        reqForTotal.Resource = "lists/{list}/members";
        reqForTotal.AddParameter("list", listName, ParameterType.UrlSegment);
        int resultTotal= JsonConvert.DeserializeObject<Member>(client.Execute(reqForTotal).Content).total_count;
        int skipTimes = resultTotal / 100;
        for (int i = 0; i <= skipTimes; i++)
        {
            RestRequest request = new RestRequest();
            request.Resource = "lists/{list}/members";
            request.AddParameter("list", listName, ParameterType.UrlSegment);
            request.AddParameter("skip",100*i);
            totalMember.AddRange(JsonConvert.DeserializeObject<Member>(client.Execute(request).Content).items);
        }

        //CreateCSVFromGenericList(...);
    }

public class Member
{
    public List<MemberDetail> items { get; set; }
    public int total_count { get; set; }
}

public class MemberDetail
{
    public string address { get; set; }
    public string name { get; set; }
    public bool subscribed { get; set; }
    public object vars { get; set; }
}

In the method CreateCSVFromGenericList(..), you can refer to this blog, and export the data to .csv file in any format you want.

A: Using curl,php or any other programming language you can achieve this, then simply delete the mailing list through the control panel:
curl -s --user 'api:YOURAPIKEY' -G \
https://api.mailgun.net/v2/lists/Your@MailingListName.com/members

Apikey and mailing list name are available from the control panel!

A: In python :
def get_members():
    return requests.get(
        "https://api.mailgun.net/v3/lists/LIST_NAME/members",
        auth=("api", "key-YOUR_KEY"),
        data={'limit': 100, 'skip': 1380})

Note that limit and skip are useful to paginate through your member list.


text:
Q: Текстовая RPG игра на Ruby Я абсолютный ноль в программировании, и не так давно, я начал изучать язык Ruby. И мне в голову пришли идея сделать (чисто для себя и друзей) игру, которая имеет свой сюжет, диалоги с вариантами ответов и разумеется несколько концовок. Всё будет работать в консоли через обычный текст. На что-то серьёзное я к сожалению пока не способен.
Так вот в чём проблема. Я хочу иметь несколько сюжетных линий. В зависимости от ответа игрока, будет зависеть по какой сюжетной ветке будет идти игрок. Всё это я хотел реализовать с помощью разбивки всего сюжета на файлы, и при выборе ответа с помощью цифр, происходила загрузка следующего файла: к примеру
puts "СЦЕНАРИЙ"

puts "Для выбора действия нажмите 1, 2 или 3"

user_input = nil
user_input = STDIN.gets.chomp

if user_input == "1"
    load "./сюжетная_линия1.rb"

elsif user_input == "2"
    load "./сюжетная_линия2.rb"

else user_input == "3"
    load "./сюжетная_линия3.rb"

end

Или для красоты IF...ELSE...END можно поместить в метод.
Так вот. Этих файлов с сюжетной линией может быть овер 100500. И все они конечно же называться одинаково не могут. В голову приходит мысль всё раскидывать по папкам. Но тогда идея с методом отпадает, потому что в этом случае придётся каждый раз поправлять директорию загрузки файла.
Или можно (или нужно) присваивать файлам уникальное имя, но ведь сама идея загрузки файлов зависет от того, что напишет игрок.
Скорей всего, я просто занимаюсь мазохизмом и есть более лаконичный способ это всё провернуть, просто я о нём ещё не знаю, так как нахожусь в процессе обучения.
Может подскажите какой нибудь алгоритм?


text:
Q: В массиве выводится мусор (Задача на нахождение одинаковых элементов в динамических массивах) Дано два динамических массива одинаковой размерности. Нужно вывести массив с одинаковыми элементами этих массивов. В итоге делает размерность исходных массивов, заносит одинаковое число, а на остальные места мусор. Помогите найти ошибку:
#include <iostream>
using namespace std;

    void Mas(int** mas1, int** mas2, int &n)
{
    cin >> n;
    *mas1 = new int[n];
    *mas2 = new int[n];
    for (int i = 0; i < n; i++) {
        (*mas1)[i] = rand() % 10;

    }
    for (int j = 0; j < n; j++) {
        (*mas2)[j] = rand() % 10;
    }
}

    void PrintMas1(int* mas1, int n) {
        for (int i = 0; i < n; i++) {
            cout << mas1[i] << '\t';
        }
        cout << endl;
    }

        void PrintMas2( int* mas2, int n){
        for (int j = 0; j < n; j++) {
            cout << mas2[j] << '\t';
        }
        cout << endl;
    }

        void Same(int** mas1, int** mas2, int&n) {
            int Sam = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if ((*mas1)[i] == (*mas2)[j]) {
                        Sam++;
                    }
                }
            }
            int *newMas = new int[Sam];
            int Move = 0;
            for (int i = 0; i < n-Sam; i++) {
                for (int j = 0; j < n-Sam; j++)
                    if ((*mas1)[i] == (*mas2)[j]) {
                        newMas[Move] = (*mas1)[i];
                        Move++;
                    }
            }
            for (int i = 0; i < n; i++) {
                cout << newMas[i] << '\t';
            }
            cout << endl;
            delete[](newMas);

        }

    int main () {
        int n = 0;
        int *mas1 = NULL;
        int *mas2 = NULL;
        Mas(&mas1, &mas2, n);
        PrintMas1(mas1, n);
        PrintMas2(mas2, n);
        Same(&mas1, &mas2, n);
        delete[] mas1;
        delete[] mas2;
        system("pause");
        return 0;
    }

A: Ты сначала считаешь кол-во одинаковых элементов, для создание массива, но затем ты зачем-то приходишься только по n-Sam элементам твоих массивов. То есть если у тебя два массива {5 7 8 9 1} и {6 2 1 7 5}, то ты создаешь третий массив размером в 3, а затем приходишься по первым трем элементам первых двух массивов то есть {5 7 8} и {6 2 1}, как видно здесь нет одинаковых элементов, а так как ты не обнулил третий массив том остался мусор.


text:
Q: Saving numbers (sequence of digits) from a string in an array of pointers to a char I am supposed to save every sequence of digits from a string in an array of chars , this is what i tried:
#include<stdio.h>
#include<ctype.h>
#include<string.h>

int check_number(char *s) {

    for (; *s; ++s) {
        if (!isdigit(*s))
            return 0;
    }

    return 1;
}

void int_in_string(char *s, char **ar, int MaxCap) {

    char temp[100];
    int index = 0;
    int i = 0;
    for (; *s; s++) {
        if (index == MaxCap) {
            break;
        }
        if (isdigit(*s)) {
            temp[i++] = *s;
        }
        if (*s == ' ' && check_number(temp)) {
            ar[index++] = temp;
            memset(temp, '\0', i);
            i = 0;
        }
    }
    if (index == 0) {
        printf("no numbers in string");
    }
    for (int i = 0; i < index; i++)
        printf(" %s \n", ar[i]);
}

but this code only prints several newlines , can someone explain me what i do wrong?

A: Some issues:
ar[index++]=temp;

This is just storing the same value (the address of temp) over and over. What you need to do is copy the string into the array.
Also, you need to terminate the string temp with '\0'. You handle this in all but the first string with memset(temp, '\0', i); However, since local variables are not initialized, you need to do it:
char temp[100] = {0}

Or, you can remove the initialization and the memset by just adding the EOS:
temp[i] = '\0';

Lastly, since you declare the original array as
char * ar[10];

You are not allocating any space for the strings. The simplest way to handle that is with strdup.
void int_in_string(char *s, char **ar, int MaxCap)
{
    char temp[100];
    int index = 0;
    int i = 0;
    for (; *s; s++) {
        if (isdigit(*s)) {
            temp[i++] = *s;
            // Need to avoid buffer overflow
            if (i == sizeof(temp)) {
                i = 0;
            }
        }
        if (isspace(*s)) {
            temp[i] = '\0';
            // strdup will allocate memory for the string, then copy it
            ar[index++] = strdup(temp);
            // if (NULL == ar[index-1]) TODO: Handle no memory error
            i = 0;
            if (index == MaxCap) {
                break;
            }
        }
    }
    if (index == 0) {
        printf("no numbers in string");
    }
    for (int i = 0; i < index; i++) {
        printf(" %s \n", ar[i]);
        // free the mem from strdup
        free(ar[i]);
    }
}

I believe some systems may not have strdup(). If not, it can be easily replicated:
char * my_strdup(const char *src)
{
    if (src == NULL) return NULL;
    char *dest = malloc(strlen(src) + 1);
    if (dest == NULL) return NULL;
    strcpy(dest, src);
    return dest;
}


text:
Q: ImageTransformation: polar to cartesian I am working on something that requires the polar transformation of some images. I implemented this transformation with ImageTransformation:
img = Import["http://i.stack.imgur.com/9cV4T.jpg"]

{center, radius} = ComponentMeasurements[MorphologicalComponents[img, 0.2],
    {"Centroid", "EquivalentDiskRadius"}][[1, 2]];
polar = ImageTransformation[img, center + {Cos[#[[1]]], Sin[#[[1]]]}*#[[2]] &,
    {2 Pi radius, radius}, DataRange -> Full,
    PlotRange -> {{0, 360 \[Degree]}, {1, radius}}]

After some processing I would like to transform the image back into the original coordinate system. This step is where I ran into problems. The transformation of the coordinates isn't really the problem but I couldn't figure out how to center the transformation properly and what PlotRange I have to provide.
So the question is how to reverse the transformation:
ImageTransformation[img, center + {Cos[#[[1]]], Sin[#[[1]]]}*#[[2]] &,
    {2 Pi radius, radius}, DataRange -> Full,
    PlotRange -> {{0, 360 \[Degree]}, {1, radius}}]

One of my failed attempts:
ImageTransformation[imgNorm, {0, Pi radius} + {Sqrt[#[[1]]^2 + #[[2]]^2],
    ArcTan[#[[2]]/#[[1]]]} &, {2 radius, 2 radius}, DataRange -> Full]

A: This seems to work:
ImageTransformation[polar,
 {ArcTan @@ (radius - #), Norm[# - radius]} &,
 {2 radius, 2 radius},
 DataRange -> {{-180 \[Degree], 180 \[Degree]}, {1, radius}},
 PlotRange -> {{0, 2 radius}, {0, 2 radius}}]

Notes:

*

*Don't call ArcTan[y/x]. You'd only get an angle between -90°..90°. There's an overload ArcTan[x,y] that returns an angle from -180°..180°

*Somewhat unintuitively, PlotRange->Full isn't the same as PlotRange->(* dimensions of output image*), it uses the input image's dimensions. If in doubt, give explicit ranges.


text:
Q: Site rebuild. Proper TFS process We are doing a new site for one of our companies. While the new one is in development we need to be able to make edits to the old code base.
Is the proper process for this to create a branch of the project and then merge back in once it goes live?  Is there the ability to wipe the old code base when the merge takes place (if that's the correct process)?

A: It depends on how much of the old code and assets you're planning to use. If the answer is "lots", then yes, create a branch for development. If you do this, make sure to frequently reverse-integrate the changes from the mainline back to your development branch.
If you're pretty much tossing out the old codebase and starting from scratch, then don't bother branching, it gets you nothing.


text:
Q: Inaccurate PGF calculation? I'm trying to implement an invoice calculation in LaTeX and using PGF as the method to do calculations. I've run into an odd problem where it seems that PGF calculates things incorrectly and I'm not sure what's causing it. Here's a minimal example:
\documentclass{standalone}

\usepackage{pgf}
\usepgflibrary{fpu}
\pgfkeys{
    /pgf/fpu=true,
    /pgf/number format/.cd,
    precision=2,
    fixed,
    fixed zerofill,
    use comma,
    1000 sep={.}
}

\begin{document}

\pgfmathparse{(1*800050)}\pgfmathprintnumber{\pgfmathresult}

\end{document}

Why does this output 800.050,05 when it should output 800.050,00?

A: I don't think you can count on eight exact digits with the fpu library; quoting the manual, section 54.3,

The FPU has a uniform relative precision of about 4–5 correct digits.

You might use the fp library of expl3 and rely on PGF for the number printing:
\documentclass[margin=2bp,varwidth]{standalone}
\usepackage{expl3}
\ExplSyntaxOn
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff

\usepackage{pgf}
\pgfkeys{
    /pgf/number format/.cd,
    precision=2,
    fixed,
    fixed zerofill,
    use comma,
    1000 sep={.}
}

\begin{document}

\pgfmathprintnumber{\fpeval{1*800050}}

\pgfmathprintnumber{\fpeval{800050/4}}

\pgfmathprintnumber{\fpeval{800050/8}}

\end{document}

A: If you don't mind compiling with lualatex than you can exploit the mathematical capabilities of lua:
\documentclass[border=5]{standalone}
\usepackage{pgf,pgffor}
\def\luamath#1{\edef\luamathresult{\directlua{tex.write("" .. #1)}}}
\pgfkeys{
    /pgf/number format/.cd,
    precision=2,
    fixed,
    fixed zerofill,
    use comma,
    1000 sep={.}
}
\begin{document}
\parbox{.75in}{
  \foreach \i in {1,...,10}{
    \luamath{800050/\i}\pgfmathprintnumber{\luamathresult}\\
  }
}
\end{document}


text:
Q: Sharepoint 2010 Custom WCF Service Application Development What is the advantages and disadvantages of using custom WCF services as a way for developing custom applications(multiple, more than 10) under sharepoint 2010.
Is it recommended to go this way or not?
P.S: I am using Custom WCF Service not Internally SP services as the data is placed in external database.
Thanks in advance.

A: Wcf is a standard and feature-rich way for exposing .net web services supporting SOAP and other standards and different types of hosting. SharePoint portal provide IIS hosting for you app which (probably) depends from SP infrastructure, thus shouldn't be available when SP is not avaliable.
But IIS hosting is for 'passive' services (please refer to Different Types of Hosting WCF application and there advantages).
I had problems with wcf factories recommended officially (for ex. here), so I can only suggest my way of hosting WCF within SharePoint environment


text:
Q: How to check running job on self-hosted Azure DevOps Agent on Linux via bash I have installed the Azure DevOps agent on my Linux Ubuntu (Ubuntu 20.04.3 LTS) machine - https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/v2-linux?view=azure-devops.
Now I want to write a script, which will check if there is some job (pipeline) running on an agent.
Is it possible to somehow check whether there is a job running on the agent via bash on Linux, where is the agent installed? Without API calls to Azure DevOps.

A: I found a solution by reading the status of the agent service:
Go to folder where you installed the agent and run -
./svc.sh status | tail -n1 | grep -c -e "Running"

*

*Get the agent status

*Get the last line

*Check if the last line contains the word Running. If not, the return code will be 0, and you know, that there is not any job currently running on Agent. Otherwise, the return code of the command will be >=1.