text:
Q: Resampling DataFrame accounting for holidays and weekends I'm just getting started playing around with Python and Pandas, with ~10 hours total invested to far. I have a dataframe of daily stock data and I've resampled it weekly.  The problem lies in weeks where Friday is a holiday, I get NaN in my dataset. Is there a way to accommodate for this scenario? (Same issue as well when I resample monthly, where the final day is a weekend).
sample = 'W-FRI'
for i in range(tickerCount):
    datalist.append(yf.download(stock_list[i], start, end))
    datalist[i]['High'] = datalist[i]['High'].resample(sample).max()
    datalist[i]['Low'] = datalist[i]['Low'].resample(sample).min()
    datalist[i]['Open'] = datalist[i]['Open'].resample(sample).first()
    datalist[i]['Close'] = datalist[i]['Close'].resample(sample).last()
    datalist[i] = datalist[i].asfreq(sample, method='pad')

As you can see the week of Good Friday could not be sampled properly. I know its possible to remove these from the dataframe:
    datalist[i] = datalist[i][datalist[i]['High'].notna()]

But ideally I would like to grab the last day of data for the specified resampled period (In this case, use Thursday's data.  I've looked at this answer
Is there a way to accomplish this?
EDIT:
@ElliottCollins had an idea to use .ffill() to backfill the Friday with the previous data (from Thursday).  This also backfills every Saturday and Sunday with the previous data.  Unfortunately when I do this and then resample W-FRI my Open values are incorrect; They become Previous Friday's open rather than Monday's Open
EDIT 2
I just realized if I set index again after all this, I'm able to resample as desired.  I'll post the solution below

A: Thanks @ElliottCollins tip about backfilling data.
datalist[i] = datalist[i].ffill()

This also backfills weekends, which I don't want.  So I need to create a column from the index
datalist[i] = datalist[i].reset_index()

And then remove weekends
datalist[i] = datalist[i][datalist[i]['Date'].dt.dayofweek < 5]

And I need the Date column to be reset as the index for transformations later on, so
datalist[i] = datalist[i].set_index('Date')

And I was able to effectively get the data I needed


text:
Q: WP_Query by an array or list of post slugs Is this possible, I couldn't find the question asked anywhere on the web.
If you had a list of posts by their slug, example:
$postslugs = array("page-one","page-two","page-three");

And you wanted to create a single query to find all these specific pages:
$args=array(
'post__not_in' => array($post->ID),
'posts_per_page'=> -1,
'post_type' =>      'customtype',
'post_status' =>    'publish',
'pagename' => $postslugs
);

$my_query = new wp_query( $args );

The result should come back with the three pages. This of course would not work the way it's written now. Is this possible?

A: If you take a look at the documentation for the WP_Query() class, specifically the Post & Page Parameters section, you'll see it has a handy parameter called post_name__in which takes an array of post_name (aka slugs). Also, are you sure you need to use post__not_in (and maybe posts_per_page since you're defining an array of slugs to get already?
$names = array( 'page-one', 'page-two', 'page-three' );

$query_args = array(
    'posts_per_page' => -1,
    'post_type'      => 'customtype',
    'post_status'    => 'publish',
    'post_name__in'  => $names
);

$my_query = new WP_Query( $query_args );

A: I would like to notice, that there is some issue with old WordPress versions where post_name it is not = to a post_slug.
For example if you try to create new post with title Customer.io it will create a post with name customer-io but slug will be customerio the same will be for this Pokéapi
The same will be if you change post slug after you have created the post.
So the best way is to check manually inside loop of your WP_Query.
$desired_array_of_slugs = array( 'page-one', 'page-two', 'page-three' );

$query_args = array(
    'posts_per_page' => -1,
    'post_type'      => 'customtype',
    'post_status'    => 'publish'
);

$my_query = new WP_Query( $query_args );

Then
foreach($my_query as $post) {
    if(in_array(sanitize_title($post->name)], $desired_array_of_slugs, true)){
        //do ur staff
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create multiple folders within multiple S3 buckets with Terraform I am looking to create one S3 terraform module which can take list of bucket names and folder names to be created inside all those buckets.
For e.g. in my S3 module main.tf. I have
resource "aws_s3_bucket_object" "folders" {
    count = var.create_folders ? length(var.s3_folder_names) : 0
    bucket  = element(aws_s3_bucket.s3bucket.*.id, count.index)
    acl    = "private"
    key    = format("%s/",var.s3_folder_names[count.index])
    source = "/dev/null"
}

I am calling this module as given below:
variable "s3_bucket_name" {
  type = list
  description = "List of S3 bucket names"
default = ["bucket1","bucket-2"]
}
variable "s3_folder_names" {
  type        = list
  description = "The list of S3 folders to be created inside S3 bucket"
  default=["folder1/dev","folder2/qa"]

}
module "s3" {
  source = "../../../gce-nextgen-cloud-terraform-modules/modules/s3"
  create_folders = true
  s3_folder_names = var.s3_folder_names
  environment = var.environment
  s3_bucket_name = var.s3_bucket_name
  force_destroy = true
  bucket_replication_enabled = true
  tags = local.common_tags
  providers = {
    aws.main_region = aws.main_region
    aws.secondary_region = aws.secondary_region
  }
}

I am facing problem because count variable can only be set once in resource block. Here is the scenario that is cauing problems:

*

*If
var.s3_folder_names < aws_s3_bucket.s3bucket.*.id.
Then I will not be able to access all the elements of S3 bucket list as shown below

resource "aws_s3_bucket_object" "folders" {
    count = var.create_folders ? length(var.s3_folder_names) : 0
    **bucket  = element(aws_s3_bucket.s3bucket.*.id, count.index)**
    acl    = "private"
    key    = format("%s/",var.s3_folder_names[count.index])
    source = "/dev/null"
}

Hence because of this I will not be able to create these folders inside all of the buckets. The only goal is to create same set of folder structure within all of those buckets.
Any help would be truly appreciated. Thanks in advance!

A: You can create a combined data structure, e.g.:
locals {

  buckets_and_folders = merge([
    for bucket in var.s3_bucket_name:
      {
        for folder in var.s3_folder_names:
        "${bucket}-${folder}" => {
          bucket = bucket
          folder = folder
        }
      }
  ]...)

}

Then you would iterate over this structure using for_each:
resource "aws_s3_bucket_object" "folders" {

    for_each = var.create_folders ? local.buckets_and_folders : {}

    bucket  = each.value.bucket
    acl    = "private"
    key    = format("%s/", each.value.folder)
    source = "/dev/null"
}


text:
Q: Running on iOS 7.1 simulator brings errors in the console output I'm using Xamarin Studio 5.9.3 on Mac with Mono 4.0.1, Xcode 6.3.2 and Xamarin.iOS 8.10.1.64. When I try to run my app in the iOS 7.1 simulator I get the following console output:
objc[1102]: Class AXEmojiUtilities is implemented in both /Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/AccessibilityUtilities.framework/AccessibilityUtilities and /Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libAXSpeechManager.dylib. One of the two will be used. Which one is undefined.
2015-06-22 09:25:43.395 SomeApp[1102:70b] Cannot find executable for CFBundle 0x7869e5f0 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/GameKitFramework.axbundle> (not loaded)
2015-06-22 09:25:43.434 SomeApp[1102:70b] Cannot find executable for CFBundle 0x786a4760 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/StoreKitFramework.axbundle> (not loaded)
2015-06-22 09:25:43.435 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78dbe9f0 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/iAdFramework.axbundle> (not loaded)
2015-06-22 09:25:43.438 SomeApp[1102:70b] Cannot find executable for CFBundle 0x786aca20 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/EventKitUIFramework.axbundle> (not loaded)
2015-06-22 09:25:43.439 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78dc2270 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (not loaded)
2015-06-22 09:25:43.441 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78dc7620 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/SocialFramework.axbundle> (not loaded)
2015-06-22 09:25:43.442 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78dc8120 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/PassKitFramework.axbundle> (not loaded)
2015-06-22 09:25:43.443 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78dc8ab0 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/TwitterFramework.axbundle> (not loaded)
2015-06-22 09:25:43.448 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78dca6c0 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/MusicLibrary.axbundle> (not loaded)
2015-06-22 09:25:43.458 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78c134c0 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/GameCenterUIFramework.axbundle> (not loaded)
2015-06-22 09:25:43.459 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78c12a50 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/RemoteUIFramework.axbundle> (not loaded)
2015-06-22 09:25:43.491 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78f64520 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/GeoServices.axbundle> (not loaded)
2015-06-22 09:25:43.500 SomeApp[1102:70b] Cannot find executable for CFBundle 0x78f7c600 </Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/StoreKitUI.axbundle> (not loaded)

What I'm doing wrong? The simulator is running fine, but those error messages are annoying.

A: I found the solution here.

iOS Simulator -> Reset Content and Settings

Now I don't have the error messages anymore. You should be aware that all installed apps are gone after this action!


text:
Q: How to make async task not stall on response I have to upgrade to Sendgrid v3 API... The email send works (I get the email), but it never returns from the task. What am I missing?
Here is the code I am using. The Label1.Text line does not execute, it never executes past var response.
Thank you!
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;

namespace TrainingWebsite
{
public partial class sendgrid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Execute().Wait();
        Label1.Text = "worked?";
    }

    static async Task Execute()
    {
        var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY_SYSTEM");
        var client = new SendGridClient(apiKey);
        var from = new EmailAddress("email@domain.com", "name");
        var subject = "Sending with SendGrid is Fun";
        var to = new EmailAddress("email@domain.com", "name");
        var plainTextContent = "and easy to do anywhere, even with C#";
        var htmlContent = "and easy to do anywhere, even with C#";
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        var response = await client.SendEmailAsync(msg);
    }
}

}


text:
Q: Thymeleaf does not display Charts I integrate Chart.js in my spring boot project . No charts displayed i do not the reason .
I added all the necessary js libraries  jquery, bootstrap also the css files of chart.js but nothing displayed and not error in the console .Any body had an idea about  the problem ?????
I think the problem that thymeleaf does not read the css file of chart.js included in the html page without knowing the reason why because i test this code in a standlone html page web outside of my spring project and it works fine .

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
 xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
 layout:decorator="template">
<head>
<meta charset="utf-8" name="viewport"
 content="width=device-width, initial-scale=1" />
<title>DOT</title>
<link rel="stylesheet" type="text/css"
 href="../static/css/Chart.css" th:href="@{/css/Chart.css}" />
 <link rel="stylesheet" type="text/css"
 href="../static/css/bootstrap.min.css"
 th:href="@{/css/bootstrap.min.css}" />
 <link rel="stylesheet" type="text/css" href="../static/css/myStyle.css"
 th:href="@{/css/myStyle.css}" />

<link rel="stylesheet" type="text/css"
 href="../static/css/font-awesome.min.css"
 th:href="@{/css/font-awesome.min.css}" />

 <script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{js/jquery-3.2.1.min.js}"></script>
<script type="text/javascript" th:src="@{js/html5shiv.min.js}"></script>
<script type="text/javascript" th:src="@{js/respond.min.js}"></script>
<script type="text/javascript" th:src="@{js/Chart.js}"></script>
<script type="text/javascript" th:src="@{js/Chart.bundle.js}"></script>

</head>
<body>

 <div layout:fragment="content">

  <div class="container col-md-6">
   <canvas id="my" height="400" width="400"> </canvas>

  </div>

<script>

var ctx = document.getElementById('my').getContext('2d');
data = {
    datasets: [{
        data: [10, 20, 30],
            backgroundColor:[ 'rgb(255, 99, 132)', 'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderColor: [ 'rgb(255, 99, 132)', 'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ]
    }],

    labels: [
        'Red',
        'Yellow',
        'Blue'
    ]

};

var myPieChart = new Chart(ctx, {
    type: 'pie',
    data: data

});

<script/>

</div>
</body>

 <script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{js/jquery-3.2.1.min.js}"></script>
<script type="text/javascript" th:src="@{js/html5shiv.min.js}"></script>
<script type="text/javascript" th:src="@{js/respond.min.js}"></script>
<script type="text/javascript" th:src="@{js/Chart.js}"></script>
<script type="text/javascript" th:src="@{js/Chart.bundle.js}"></script>
</html>


text:
Q: Splitting a Circular Linked List in to two halves I am dealing with a problem where i am to split a Circular linked list in to two halves. If the list is even then the split would result in to two even lists. If the split is odd the first list would have the extra node.
Following is code for my node class
public class CLLNode {

    private int data;
    private CLLNode next;

    public CLLNode(int d)
    {
        this.data = d;
    }

    public void setData(int d)
    {
        this.data = d;
    }

    public int getData()
    {
        return this.data;
    }

    public void setNext(CLLNode n)
    {
        this.next = n;
    }

    public CLLNode getNext()
    {
        return this.next;
    }

}

Following is code for my Circular linked list class
public class CLinkedList {

    private CLLNode Head;

    public CLinkedList()
    {
        Head = null;
    }

    public CLLNode getHead()
    {
        return this.Head;
    }

    public void insertFirst(int d)
    {
        CLLNode n = new CLLNode(d);
        if(Head == null)
        {
            this.Head = n;
            n.setNext(n);
        }
        else
        {
            CLLNode temp = this.Head;
            while(temp.getNext()!= this.Head)
            {
                temp = temp.getNext();
            }
            n.setNext(this.Head);
            temp.setNext(n);
            this.Head = n;
        }
    }

    public void insertLast(int d)
    {
        CLLNode n = new CLLNode(d);
        if(Head == null)
        {
            this.Head = n;
            n.setNext(n);
        }
        else
        {
            CLLNode temp = this.Head;
            while(temp!= null)
            {
                temp = temp.getNext();
                if(temp.getNext() == this.Head)
                {
                    break;
                }
            }

            n.setNext(temp.getNext());
            temp.setNext(n);
        }

    }

    public void deleteFirst()
    {
        CLLNode temp = this.Head;
        CLLNode temp2 = this.Head;

        while(temp2!=null)
        {
            temp2 = temp2.getNext();
            if(temp2.getNext()== this.Head)
            {
                break;
            }
        }

        temp2.setNext(temp.getNext());
        this.Head = temp.getNext();
        temp.setNext(null);
    }

    public void deleteLast()
    {
        CLLNode temp = this.Head;
        CLLNode temp2 = this.Head;

        while(temp.getNext()!= this.Head)
        {
            temp2 = temp;
            temp = temp.getNext();
        }

        temp2.setNext(temp.getNext());
        temp = null;
    }

    public void displayList(CLLNode n)
    {
        CLLNode temp = n;
        while(temp!= null)
        {
            System.out.println(temp.getData());
            temp = temp.getNext();
            if(temp == this.Head)
            {
                break;
            }
        }
    }

    public int getLength()
    {
        int count  = 0;
        CLLNode temp = this.Head;
        while(temp != null)
        {
            count ++;
            temp = temp.getNext();
            if(temp == this.Head){
                break;
                }
        }

        return count;
    }

    public void splitList(CLLNode head, CLLNode head1, CLLNode head2)
    {
        CLLNode temp1 = head;
        CLLNode temp2 = head;
        CLLNode temp3 = head;

        while(temp2!=null)
        {
            temp1 = temp1.getNext();
            temp2 = temp2.getNext().getNext();

            if(temp2.getNext()== head)
            {
                temp2.setNext(temp1.getNext());
                head2 = temp1.getNext();
                temp1.setNext(temp3);
                head1 = temp3;
                break;
            }

            if(temp2.getNext().getNext()==head)
            {
                temp2.getNext().setNext(temp1.getNext());
                head2 = temp2;
                temp1.setNext(temp3);
                head1 = temp3;
                break;
            }
        }
        this.displayList(Head1); // This one goes in to a infinite loop..
        this.displayList(head2);

    }

}

Following is my main class
public class main {

    public static void main(String[] args) {

        CLinkedList list = new CLinkedList();

        list.insertLast(10);
        list.insertLast(20);
        list.insertLast(30);
        list.insertLast(40);

        CLLNode head = list.getHead();

        CLLNode head1 = null;
        CLLNode head2 = null;

        list.splitList(head,head1,head2);

    }

}

I am able to successfully split the lists i believe but for some reason when i display the newly split list it goes in to a infinite loop. i am not sure why , if someone can please point out my mistake or suggest a fix i would appreciate it.

A: I don't know how your split operation works but there is a really simple way to split a circular list into two circular lists. Let's not worry about the even/odd stuff for now and consider what happens if you swap the next pointers of two distinct nodes in a circular list. You get two circular lists (neat, right?).
Now to split the list, first count the number of items in the list (call it n) and swap the next pointer of node at position 0 (the first node) with the next pointer of node at position n/2 (you have to follow next pointers to find this node). If the count is even, the lists are split into two lists of even length and if the count is odd, the lists are split into two lists of odd/even length respectively. So find these two nodes, swap their next pointers and assign them to head1 and head2.
You might want to handle separately the case where there is a single node or the list is empty.
Try this on a piece of paper to see that it actually works.


text: Q: Wordpress, content editor default type How to set text as default editor type in Wordpress? Now it is visual and some content (like php content in the widgets) will be change if the mode is changed from visual to text.


text:
Q: Setting css class to field in form depending of it's type I want to manually render login and signup forms in Django.
Here is my code:
{% load widget_tweaks %}

{% for field in form.visible_fields %}

        {{ field.label_tag }}

        {% if form.is_bound %}
            {% if field.errors %}
                {% render_field field class="nice-looking-field"%}
                {% for error in field.errors %}
                    {{ error }}
                {% endfor %}
            {% else %}
                {% render_field field %}
            {% endif %}
        {% else %}
            {% render_field field %}
        {% endif %}

        {% if field.help_text %}

{{ field.help_text }}

        {% endif %}

{% endfor %}

{% if form.non_field_errors %}

    {% for error in form.non_field_errors %}
      {{ error }}
    {% endfor %}

{% endif %}

My question: is it possible to check in a loop what type the field has and, depending on the field, assign a specific CSS class?
For example:

*

*Field_1 has type text, so we apply css-class-1 to it

*Field_2 has a checkbox type, so we apply css-class-2 to it

A: you can use the django form that is inherited from modelform to define specific css class to the form fields.
for instance,
models.py file:
class Post(models.Model):
    title=models.CharField(max_length=254)
    text=models.TextField()

forms.py file
from . import models
class PostForm(forms.ModelForms):
    class Meta():
        model=models.Post
        fields='__all__'
        widgets={
               'title':forms.TextInput(attrs={'class':'textinputclass'}), #--->> you can use this textinputclass as the css class in your css file to style the title field of your forms.
                'text':forms.Textarea(attrs={'class':'content'})
                }

now in your static>css>yourcss.css you can access the class that we defined above as normal css class.

.content{
  font-size:15px;
}

That's all.


text:
Q: What is the correct way to handle an accesstoken with react to secure routes? I have an express backend which on login returns an access token as a response and a refresh token as a cookie
      const sendAccessToken = (res , req, accesstoken) => {
        res.send({
            accesstoken,
            email: req.body.email

        })
    }

const sendRefreshToken = (res, refreshtoken) => {
    res.cookie("refreshtoken", refreshtoken, {
        httpOnly: true,
        path: '/refresh_token'
    })
}

Point is I need to have something similar to an Authservice in my react frontend to check if that access token is valid , it should return something like. True if access token is valid, and false if acces token is invalid, and based on that it will allow access the different routes I have in my react frontend. (I want to implement it right into the switch if possible)
HOw should I approach it?
I remember using an auth guard approach in angular, but since im new to react im not sure
I used to do something like this where canActivate had true or false values:
    ...
import { RoleGuard } from '../guards/role-guard.service';
...
children:[
   ...,
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [RoleGuard],
    data: {role: 'Admin'}
  },
  ...
];

SO as pseudocode in my react it should look like this:
<BrowserRouter>
<Switch>
    <Route  exact path="/register" render={(props) => <RegisterPage />} />
    <Route exact path="/login" render={(props) => <LoginPage />} />
    <Route exact path="/" render={(props) => <NewLandingPage {...props} />} />
    <Route path="/protectedRoute" canActivate = [Guard] render={(props) => <Prueba {...props} />} />
</Switch>
</BrowserRouter>

But appart from that. How am I supposed to check that the returned access token is valid using the front end? (I obtain them with refresh tokens) Since isnt it supposed to happen in the back end? Because the secrets to decode the token are in the backend, i dont know how to check it in the frontend.

A: According to your approach you can do something like this :
state = {
  isAuthenticated: false,
}

//in render :

return (
  <div>
    <Router history={history}>
      <Switch>
        <Route exact path="/login" render={(props) => ((this.state.isAuthenticated) ? <Home {...props}/> : <Login {...props}/>)}/>
        <Route exact path="/" render={(props) => ((this.state.isAuthenticated) ? <Home {...props}/> : <Login {...props}/>)}/>
      </Switch>
    </Router>
  </div>
);


text:
Q: SQL Rank while keeping time sorted Given this data
Type    Time    Outcome Wanted Result
1   8:00    1   1
1   9:00    1   1
1   10:00   1   1
0   11:00   2   2
0   12:00   2   2
0   13:00   2   2
1   14:00   1   3
1   15:00   1   3
0   16:00   2   4
1   17:00   1   5
0   18:00   2   6
1   19:00   1   7

The third column is the current result I have using the following sql query:
SELECT Type, Time, DENSE_RANK() OVER (ORDER BY Type) as Outcome
FROM Tbl

I need the dense_rank to keep the time sorted while ranking the data by type. The 4th column is the wanted result.
I am using SQL Server 2008

A: This is tricky.  You can do this with a difference of row numbers.  This method is a little difficult to understand at first, so I recommend that you run the subqueries to understand what is happening.  You'll quickly "get it" when you look at the results:
select t.*,
       dense_rank() over (order by mintime) as desired_column
from (select t.*,
             min(time) over (partition by id, seqnum_t - seqnum_it) as mintime
      from (select t.*,
                   row_number() over (order by time) as seqnum_t,
                   row_number() over (partition by id order by time) as seqnum_it
            from tbl t
           ) t
     ) t;


text:
Q: How to print outputs of a loop horizontally in R? I'm running a code and getting output like this:
  X.0.0189575409702549
1          -0.01895754
2          -0.14051254
3          -0.04389737
4          -0.06815956
5          -0.12350667
6          -0.07588814

whereas the required output should be like this:
[1] -0.01895754 -0.14051254 -0.04389737 -0.06815956 -0.12350667 -0.07588814

My code is as follows:
corr<-function(directory, threshold=0){
  files_list<-list.files(directory, full.names = T)
  dat<-data.frame()
  final<-data.frame()
  rcor<-c()
for (i in 1:332) {
  dat<-read.csv(files_list[i])
  comp<-sum(complete.cases(dat))
   if (comp>threshold){
     x<-dat[complete.cases(dat),"sulfate"]
     y<-dat[complete.cases(dat),"nitrate"]
                       rcor<-cor(x,y)
                      final<-rbind(final,rcor)
                      }
  }
final
}

I have tried cbind() but it gives me a lot of NAs. Im totally lost, really appreciate any help. Thanks!

A: corr<-function(directory, threshold=0){
  files_list<-list.files(directory, full.names = T)
  dat<-data.frame()
  final<-data.frame()
  rcor<-c()
for (i in 1:332) {
  dat<-read.csv(files_list[i])
  comp<-sum(complete.cases(dat))
   if (comp>threshold){
     x<-dat[complete.cases(dat),"sulfate"]
     y<-dat[complete.cases(dat),"nitrate"]
                       rcor<-cor(x,y)
                      final<-rbind(final,rcor)
                      }
  }
as.vector(final)
}


text:
Q: Java Regular Expression with string utf8 I have 2 strings:
String 1 from txt file, open with BufferedReader use encoding "UTF-8":
Tân_Dậu 1921 – Kỉ_Mão 1999

String 2 is my type in:
Tân_Dậu 1921 - Kỉ_Mão 1999

and my string Pattern:
[(]?([A-ZTĐẤ][a-záââậầấẹịỉìíợnọúùửỵýỷ]+[_][A-ZDĐẤ][a-záậãâậầấẹuịìíợọúùửỵýỷ]+)?[ ]?((\\d{4})|([?]))[ ]?[-][ ]?(([A-ZĐKẤ][a-záâỉoậầấẹịỉìíợọúùửỵýỷ]+[_][A-ZĐẤ][a-záãâậầấãẹịìíợọúùửỵýỷ]+))?[ ]?(\\d{4}|\\d{2}[)])[ ]?[)]?

I use:
Matcher m = p.matcher(test.trim());
while(m.find())
{
    System.out.println("-->"+m.group());
}

With 'test' is string 1 and 2 . But only string 2 matched.
What problem and how to slove it ? thanks for help.

A: The problem is the -. You seem to have two versions of them. Changing your expression to this: [(]?([A-ZTĐẤ][a-záââậầấẹịỉìíợnọúùửỵýỷ]+[_][A-ZDĐẤ][a-záậãâậầấẹuịìíợọúùửỵýỷ]+)?[ ]?((\\d{4})|([?]))[ ]?[-–][ ]?(([A-ZĐKẤ][a-záâỉoậầấẹịỉìíợọúùửỵýỷ]+[_][A-ZĐẤ][a-záãâậầấãẹịìíợọúùửỵýỷ]+))?[ ]?(\\d{4}|\\d{2}[)])[ ]?[)]? should do the trick (example available here).
Notice how [-] has been changed to [-–].


text:
Q: How to pass query parameters from form's action attribute in php? I want to pass a query parameter from one page to another in PHP.
I am redirecting using form's action attribute, instead of hyperlink tag.

    <title>Question 1</title>.

      <form method="GET" action="Result.php?question=1">
 Question 1. What is the full form of PHP?

        A)<input type="radio" name="q1" value="a">
           Pre HyperText Processor

        B)<input type="radio" name="q1" value="b">
           Post HylerText Processor

       C)<input type="radio" name="q1" value="c">
           Personal HyperText Pages

        D)<input type="radio" name="q1" value="d">
           HyperText Preprocessor

        <input type="submit" name="g" value="Go">
   </form>

I am getting below error:
Undefined index:question in Result.php on line 2

Result.php
<?php
$score=0;
$q=$_GET["question"];
if($q)
{
   if($_GET['g']!=null)
   {
   switch($q)
    {
       case 1: $answer1='c';
               if($_GET["q1"]==answer1)
                 ++$score;
               break;
       default: print " try again";
     }
   }
}

Why am I not getting the values passed in query parameters?

A: Finally, I found my way out of this problem.
Turns out that to access a value passed using form's action attribute, $_GET is to be used. And as for the other values, $_POST should be used.
Something like this-
<form method=POST" action="Result.php?question=1">

Result.php
$q=$_GET["question"];
...
 if($_POST['g']!=null)
 ...
    if($_POST["q1"]==$answer)
...

A: You are not getting $_GET['question'] back.
You are getting q1 back. So what you have made will have a url like:
Result.php?q1=a&g=Go"

So you have to set your Result.php at
$q=$_GET["q1"];
if($q)
{
switch($q)
{
   case 'a': print "question 1";
           break;
 }
}

If you want your url to have question insted you need to do it like this:
  <form method="GET" action="Result.php">
 Question 1. What is the full form of PHP?

    A)<input type="radio" name="question1" value="a">
       Pre HyperText Processor

    B)<input type="radio" name="question1" value="b">
       Post HylerText Processor

   C)<input type="radio" name="question1" value="c">
       Personal HyperText Pages

    D)<input type="radio" name="question1" value="d">
       HyperText Preprocessor

    <input type="submit" name="g" value="Go">

Keep in mind that this is a quick fix but do not use GET. Use POST insted.
Also use FireBug to see how you get or post forms.
EDIT
It's better to use POST otherwise it will overwrite your url.
Try this and let me know if it's what you want.

<title>Question 1</title>.

<form method="POST" name="form" action="Result.php?question=1">
Question 1. What is the full form of PHP?

        A)<input type="radio" name="q1" value="a">
        Pre HyperText Processor

        B)<input type="radio" name="q1" value="b">
        Post HylerText Processor

        C)<input type="radio" name="q1" value="c">
        Personal HyperText Pages

        D)<input type="radio" name="q1" value="d">
        HyperText Preprocessor

        <input type="submit" name="g" value="Go">
</form>

Result.php
<?php
$q=$_GET["question"];
if($q)
{
$PostedValue = $_POST['q1'];
switch($PostedValue)
{
    case 'a': echo "Pre HyperText Processor";
        break;
    case 'b': echo "Post HylerText Processor";
        break;
    case 'c': echo "Personal HyperText Pages";
        break;
    case 'd': echo "HyperText Preprocessor";
        break;
    }
}
?>

OR if you want to use Method GET you can pass it through a hiddin input:
And you can use your own Result.php code.

<title>Question 1</title>.

<form method="GET" name="form" action="Result.php">
    <input type="hidden" name="question" value="1">
Question 1. What is the full form of PHP?

    A)<input type="radio" name="q1" value="a">
    Pre HyperText Processor

    B)<input type="radio" name="q1" value="b">
    Post HylerText Processor

    C)<input type="radio" name="q1" value="c">
    Personal HyperText Pages

    D)<input type="radio" name="q1" value="d">
    HyperText Preprocessor

    <input type="submit" name="g" value="Go">
</form>


text:
Q: Android data persistence (Room) with different accounts Let's assume I have a project similar to the google sample code:
https://github.com/googlesamples/android-architecture-components
I want to add an account system to the app. How can I persist data and make the following scenario work:

*

*go to persistent-data-fragment and load data from backend

*log out

*log into a different account

*go to that same fragment

As a result, I should not be able to see the first user's data and instead load them from backend for the second user. How to use Room for that?

A: It a generic question, so I can answer with a generic answer :).
1 - on the server side you need to authenticate a user that access to REST services. There are many ways to do this. JWT is a good solution. Start reading this article.
2 - on the client side, probably you need to introduce in your database a user table and link other database's entities to user identity. Using Room you have to declare a user bean and then link them to other room entities.
I hope it helps.


text:
Q: Copy and replace system file and open iso in WinArchiver(iso mounter) using bat file I want to create a batch file to copy and replace system file and open an iso in WinArchiver (iso mounter).
This command is not working for copying:
COPY  RosettaStoneVersion3.exe  C:\Program Files\Rosetta Stone\Rosetta Stone Version 3\RosettaStoneVersion3.exe /y

A: You need to "quote" any path or filename which contains spaces.


text:
Q: android asynctask doesnt work I use AsyncTask to execute time-consuming operations, the operation scans SD-card and adds all valid photo absolute path to ArrayList container. I put the operation into AsyncTask to execute. The time consuming operation Utils.getPhotoList(); was placed under doInbackgroud method. The return value was assigned to the global variable list under onPostExecute method. From the log, I know the method was executed and the list was assigned a value. But why the global variable list under onStartCommand method  is always null, which confused me a lot. see the code below.
 ConcurrentAsyncTask.execute(new PhotoTask());

and the complete code is
public int onStartCommand(Intent intent, int flags, int startId) {
  if (isCameraUpload) {
    // execute time-consuming operation
    ConcurrentAsyncTask.execute(new PhotoTask());
  }
  // list is always null
  if (list != null) {
    notifyUser(photosCount, repoName);
  }
  return START_STICKY;
}

and the customized class ConcurrentAsyncTask is.
public class ConcurrentAsyncTask {
   public static <T> void execute(AsyncTask<T, ?, ?> task, T...args) {
     if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1) {
       task.execute(args);
     } else {
       task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args);
     }
   }

   public static void execute(Runnable runnable) {
     execute(new SimpleAsyncTask(runnable));
   }
   private static class SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
     Runnable runnable;
     public SimpleAsyncTask(Runnable runnable) {
       this.runnable = runnable;
     }
     public Void doInBackground(Void... args) {
     try {
       runnable.run();
     } catch(Exception e) {
       // ignore
     }
     return null;
   }

}
and the PhotoTask class is
private class PhotoTask extends AsyncTask<Void, Void, List<SelectableFile>> {
   @Override
   protected List<SelectableFile> doInBackground(Void... params) {
     Log.d(DEBUG_TAG, "doInBackgroud");
     Log.d(DEBUG_TAG, "doInBackgroud:pathList.size: " + Utils.getPhotoList().size());
     return Utils.getPhotoList();
   }

   @Override
   protected void onPostExecute(List<SelectableFile> result) {
     Log.d(DEBUG_TAG, "onPostExecute");
     list = result;
     Log.d(DEBUG_TAG, "onPostExecute: list.size: " + list.size());
   }
 }

any feedback will be appreciated. Thanks!

A: to solve the problem, just divide the operation into parts. the time-consuming operations placed in doInbackground() method, and the result placed in onPostExecute() method.


text:
Q: Why are computed properties not reactive in my Vue 3 app? Issue
✅ Vue 2:
computed properties are updated after vuex store mutation.
❌ Vue 3:
computed properties are not updated after vuex store mutation.
Vuex 4
Purpose: Get posts from Firestore. Add to "postsArray". Commit mutation.
Note: The function "getNextPosts" is called from a (working) intersection observer which allows infinite-scrolling.
const postsArray: Array<string> = [];
const vuexStore = createStore({
  state: {
    posts: []
  },
  actions: {
    // See https://firebase.google.com/docs/firestore/query-data/query-cursors#paginate_a_query
    getFirstPosts({ commit }) {
      const getFirstPosts = async () => {
        const firstPostsQuery = firestore.collection("posts").limit(3);

        // Get FIRST posts.
        const firstPosts = await firstPostsQuery.get();

        // Add to postsArray.
        for (const doc of firstPosts.docs) {
          postsArray.push(doc.id);
        }

        // Add to vuex store.
        commit("addFirstPostsToVuex", postsArray);

        // Set reference.
        lastPostDownloaded = firstPosts.docs[2]; // 3rd post.
      };
      getFirstPosts();
    },
    getNextPosts({ commit }) {
      const getNextPosts = async () => {
        const nextPostsQuery = firestore
          .collection("posts")
          .startAfter(lastPostDownloaded)
          .limit(2);

        // Get NEXT posts.
        const nextPosts = await nextPostsQuery.get();

        // Add to postsArray.
        for (const doc of nextPosts.docs) {
          postsArray.push(doc.id);
        }

        // Add to vuex store.
        commit("addNextPostsToVuex", postsArray);

        // Update reference.
        lastPostDownloaded = nextPosts.docs[1]; // 2nd post.
      };
      getNextPosts();
    }
  },
  mutations: {
    addFirstPostsToVuex(state, value) {
      state.posts = value;
    },
    addNextPostsToVuex(state, value) {
      state.posts = value;
    }
  }
});

Computed properties
export default ({
  computed: {
    posts() {
      // List rendering.
      return vuexStore.state.posts;
    }
  }
});

v-for
<template>

        {{ post }}

</template>

A: There is a slight difference in defining the state inside Vuex between the old and new version.
**In Vuex3 state was just a prop with an Object while in Vuex4 it has return an Object or a function which returns an Object.**
When migrating from V3 to V4 you might at first not notice the difference because the V3 style kind of works in V4 as well. The difference shows when you've got modules and have multiple instances of them. Then the state has to be a function that returns an object to avoid state pollution (as commented by tony19).
Modules:
// Vuex 3.x Module
const moduleVUEX3 = {
    export const state = { ... }
}

// Vuex 4.x Module
const moduleVUEX4 = {
    export const state = () => ({ ... })
}

Single Store:
// Vuex 3.x
import Vuex from 'vuex'

const store = new Vuex.Store({
  state: { ... }
})

// Vuex 4.x
import { createStore } from 'vuex'

const store = createStore({
  state() {
    return { ... }
  }
})

Solution for this question would be:
const vuexStore = createStore({
  state: return {
    posts: []
  }
})

A: I usually use it like this

When the status in vuex changes, the page will respond in time, hope it can help you

A: This could be fixed if you use mapState function to map store's state to Vue component's state.
In the code above, that would be something like:
import { mapState } from "vuex";
import { defineComponent } from "vue";

export default defineComponent({
     computed: {
        ...mapState(["posts"])
     }
});

The v-for should work just fine now.
Reference: https://vuex.vuejs.org/guide/state.html and https://scrimba.com/scrim/c8Pz7BSK?pl=pnyzgAP

A: You could try to remove the postsArray, I assume it has something to do with reactivity.
try changing the mutation to
addFirstPostsToVuex(state, docId) {
      state.posts.push(docId);
    }

and then in the action you do
for (const doc of firstPosts.docs) {
          commit("addFirstPostsToVuex",doc.id);
        }


text:
Q: How to detect if client is able to BOLD text with execCommand() I am making a WYSIWYG editor from scratch using execCommand().
I want to disable my formatting buttons (alignment, bold, italicize, underline, color, size, family, etc) when the user has no text selected.
I have the document code inside of an IFRAME, and outside of the IFRAME are the buttons/scripts. I made the iframe's document contentEditable and turned designMode on.
What exactly can I do to find out if any text is selected?
If possible, how can I find out if the user has their cursor anywhere inside of a DIV element for text alignment? I am sure I could use this to detect if the cursor is inside of an already-bolded text or similar, too.
<iframe src="/builder/ajax/load?id=1"></iframe>
<script type="text/javascript">
  function init() {
     // editor is defined in another script as the iframe.contentWindow.document
     editor.body.contentEditable = "true";
     editor.body.designMode = "on";
  }
</script>

A: This can be done using queryCommandSupported and queryCommandEnabled as I just now discovered!


text:
Q: What's the difference between useContext and Redux? What's the difference between useContext and Redux?
Redux is like useContext?
When I use Redux on my project, I don't need useContext anymore?

A: Redux is your global state from which your components receive their state through mapStateToProps.
As I said, it is your application-wide single source of trough. While useState is used to manage (parts of) the state in a single component.
You might not want to keep every small piece of component state in your global store, for example, show a loading spinner (loading: true) in a certain component while an operation is running or display certain parts of the component depending on the users' actions.
Data you want in your global store is data you need to use in multiple components and/or you need it available throughout the lifecycle of your application.
I hope this helps a bit.


text:
Q: How to get the contents and versions of ListItem I am very new to shareopoint development. In my project I want to read the contents of the ListItems according to its versions. Here is my pseudo code
                      foreach (ListItem oListItem in listItemCollection)
                            {
                                var item=  wb.GetItemById(oListItem.Id);

                                clientcontext.Load(item,
                                it => it.Id, it => it.DisplayName,
                                it=>it.ContentType,it=>it.File);

                                clientcontext.ExecuteQuery();

                                Console.WriteLine(itm.DisplayName);

                                var strm = item.File.ListItemAllFields;

                                clientcontext.Load(strm);
                                clientcontext.ExecuteQuery();
                            }

How can I read the contents of ListItem according to its version?
Thanks in Advance.

A: You can try below code.
foreach (Microsoft.SharePoint.Client.FileVersion itemVersion in pageItem.File.Versions)
{
      pageVersion = itemVersion.VersionLabel + ";" + pageVersion;
      Console.WriteLine(itemVersion.VersionLabel);
}

Hope this helps to give you some idea to start with.

To get the older version content
You have to checkout the file.
Make previous version as current version.
Get the content of the file
Undo checkout.


text:
Q: How to update Firestore document when data changes when collected from 3rd Party API instead of creating new document The code below is set up to collect data from a 3rd party API for NBA games. At the moment it all works and the data is stored in GCP Firestore but the issue is that it creates a new document for each game every time you make an API call. So say it's called 3 times a day there will be 3 different documents for the same game.
What I would like to happen is that each time the API is called and the game's data has changed it updates the original document instead of creating a new one.
Any help would be appreciated.
import requests
import json
from firebase_admin import firestore

db = firestore.Client(project='xxxx')

def bluebet_nba_odds():
    # MAKE VARIABLES GLOBAL
    global away_team_win_odds, away_team, home_team_win_odds, home_team, start_time, event_title, event_id, competition

    # API CALL

    link = 'https://xxxxxxxxxx.com.au/json/reply/MasterCategoryRequest?EventTypeID=107&WithLevelledMarkets' \
           '=true&WithLevelledMarkets=true '
    # Request data from link as 'str'
    nbadata = requests.get(link).text
    # convert 'str' to Json
    nbadata = json.loads(nbadata)

    # JSON PARSE

    for nba_odds in nbadata['MasterCategories'][2]['Categories'][0]['MasterEvents']:
        competition = nba_odds['CategoryName']
        event_id = nba_odds['MasterEventId']
        event_title = nba_odds['MasterEventName']
        start_time = nba_odds['MaxAdvertisedStartTime']
        home_team = nba_odds['Markets'][0]['OutcomeName']
        home_team_win_odds = nba_odds['Markets'][0]['Price']
        away_team = nba_odds['Markets'][1]['OutcomeName']
        away_team_win_odds = nba_odds['Markets'][1]['Price']

# WRITE TO FIRESTORE

        data = {
            'competition': competition,
            'event_id': event_id,
            'event_title': event_title,
            'start_time': start_time,
            'home_team': home_team,
            'home_team_win_odds': home_team_win_odds,
            'away_team': away_team,
            'away_team_win_odds': away_team_win_odds,
            'timestamp': firestore.SERVER_TIMESTAMP,
            }

        db.collection('bluebet_nba_season_odds').document().set(data), print('Game Data Written to Firestore')

if __name__ == "__main__":
    bluebet_nba_odds()

A: document() with no arguments generats a random document ID every time it's called.  Don't do that.  Give the document a name instead.
db.collection('bluebet_nba_season_odds').document('you-choose-a-name-here')

You might be helped by reviewing the API documentation to understand better how the API works, especially for the document() method that you're calling.


text:
Q: In a Dyson shell, could centripetal force act as gravity? In a pure Dyson shell surrounding a non-moving star, with the shell rotating around the star, could the centripetal force of the shell act in some way similar to gravity toward the interior of the shell. it's not a field force, so i would assume not, as there is no way it would act on an object that is not part of it.

A: Overall, no, not if you're talking about a "classical" Dyson sphere: a rigid spherical shell. At the equator, centrifugal force will act as a pseudo-gravity for anything making contact with it or coupled to its rotation, so atmosphere will behave approximately correctly. Atmosphere is viscously coupled to the rotating surface, so it gets carried along.
The problem is that, as you move toward the poles, the apparent "gravity" will gradually become both weaker (as the radius of rotation becomes less) and tilted away from local vertical. The direction of the centrifugal force will always be in the plane of rotation, and that will always be parallel to the equatorial plane. At the poles there will be no effect at all, since the moment arm of motion will become zero.
As a result, as you move away from the equator the air will get thinner and the local "gravity" will tilt more and more toward the horizontal at the same time as it gets weaker.
Of course, a Dyson Sphere is pretty big, so there's a lot of equator. Presumably a band of several degrees of latitude will be useable, and that will have an area many times that of earth.


text:
Q: Может ли генератор речи, встроенный в Android воспроизвести английские фонетические знаки, транскрипцию? Может ли генератор (синтезатор) речи, встроенный в Android прочитать и воспроизвести фонетические знаки, транскрипцию? Типа:
краткие: ʌ, ə, æ, i, e, o, u
долгие: ɑ:, ə:, i:, ɔ:, u:
дифтонги: ɑɪ, au, eɪ, əu, ɛə, ɪə, ɔɪ, uə
Как озвучить их в приложении Андроид Студии?

A: Пока на дату 21.04.18 - генератор не может!
Проверено!


text:
Q: Is it possible to programatically distinguish between American and Canadian phone numbers? I'm using this bit of code (in Groovy, but it should be pretty clear what it does)
class MobileNumberUtilService {
def getISOCountryCode(rawNumber) {
    def phoneNumberUtil = PhoneNumberUtil.getInstance()
    def number

    try {
        number = phoneNumberUtil.findNumbers(rawNumber, null).iterator().next().number()
    } catch (NoSuchElementException exception) {
        return ''
    }

    CountryCodeToRegionCodeMap.countryCodeToRegionCodeMap[number.countryCode].first()
}
}

Running mobileNumberUtilService.getISOCountryCode('<internationalized American or Canadian number>') returns [US, AG, AI, AS, BB, BM, BS, CA, DM, DO, GD, GU, JM, KN, KY, LC, MP, MS, PR, SX, TC, TT, VC, VG, VI].
Is there any way to distinguish those, short of some sort of web service lookup?

A: Take a look at the geocoder subproject of libphonenumber.  It provides a PhoneNumberOfflineGeocoder that does exactly what you're looking for:
@Grapes([
  @Grab('com.googlecode.libphonenumber:libphonenumber:5.8'),
  @Grab('com.googlecode.libphonenumber:geocoder:2.9')
])

import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder

def phoneNumberUtil = PhoneNumberUtil.instance
def geocoder = PhoneNumberOfflineGeocoder.instance
def usaNum = phoneNumberUtil.parse("1-406-750-9999", "US")
def canNum = phoneNumberUtil.parse("1-416-750-9999", "US")

assert geocoder.getCountryNameForNumber(usaNum, Locale.default) ==
    "United States"
assert geocoder.getCountryNameForNumber(canNum, Locale.default) ==
    "Canada"


text:
Q: RDD transformation and actions While doing transformations on RDD, for example :-
firstRDD=spark.textFile("hdfs://...")

secondRDD=firstRDD.filter(someFunction);

thirdRDD = secondRDD.map(someFunction);

Does first, second and third RDD store the value in RAM or when we perform action on the final thirdRDD like result = thirdRDD.count() then it will store the data?

A: *

*Until count is called there is no processing at all.

*None of the operations stores any data in memory, excluding constant memory allocation required for the count.

*Rows materialized during count can be immediately discarded and garbage collected.

A: In any case, an RDD will load value only when an action is called upon in chain. In this case, it will load values only when count operation is executed and will load only data until condition specified inside function of "filter" is specified.
It will not load data and keep it in ram. It can If you call method persist on one RDD. Otherwise, it will load data from scratch next time any action is operated.
Please let me know if it helps.


text:
Q: PhoneGap/Cordova: How to add PHP support? I just read that it is indeed possible to use PHP. My question is how to add such support? Is there an API's or plug-ins to add PHP support?
In short, I want to use PhoneGap alongside PHP to develop apps. How?
Specifics

*

*I'll use a Linux server & hosting with godaddy, to park my PHP.

*In addition, I'll use MySQL database

*The app will send database requests to that server.

*The server will be sending large amount of data back to the app.

What would be the most efficient "light weight" method to "transfer the data" and requests between the app and server/hosting account?

A: From http://phonegap.com/about/faq/. The last FAQ reads:
Q: Can you use PHP/ASP/JSF/Java/.NET with PhoneGap?

A: A PhoneGap application may only use HTML, CSS, and JavaScript.
  However, you can make use of network protocols (XmlHTTPRequest, Web
  Sockets, etc) to easily communicate with backend services written in
  any language. This allows your PhoneGap app to remotely access
  existing business processes while the device is connected to the
  Internet.

To be a little more clear, If you want to use PHP, it will be on the server, and the server will NOT run on the mobile device (phone/tablet). Again, your PHP server will run in the cloud, NOT on the phone.


text:
Q: Where i can get Binary for Apache http server 2.2.15 for solaris I need to install apache http server 2.2.15 in solaris 9 .But in apache site ,only source is available for solaris.
Please help me to find binary distribution for solaris 9?
If i have to compile the source to binary for solaris,tell me how to compile the source for solaris 9?

A: I'm aware of two sites that distribute prebuilt software for Solaris.
http://sunfreeware.com/
http://www.blastwave.org/
Both of them appear to have Apache 2.2.15 available at the moment.


text:
Q: Parameters for osm2po web service to route for walking I have started the osm2po web service using the jar file. In the configuration file, I could see different parameters related to walking but not sure what each one does.
I am trying to call the web service through Python program and parse the response to get relevant data. So, far I was able to retrieve route between source and target. But I want to hit the web service and change the parameters to walking.
My URL looks like this,
http://localhost:8888/Osm2poService?cmd=fr&source=40.6413,-73.7781&target=40.7589,-73.9851&format=geojson
I have gone through the examples given in osm2po.de website where example URL is for points which can be reached with given time by a car
?cmd=fx&source=53.5,10.0&findShortestPath=false&maxCost=0.2&format=geojson

A: It depends on the data in the graph file. In order to include or exclude road types modify the osm2po.config file.
See this thread. It's a similar question for bike routing
But dont use maxSpeedOverrides anymore, it's deprecated in newer versions of osm2po.


text: Q: Multiple Inputs / Outputs for Dataset class in PyTorch I've created a Dataset class for PyTorch that can read/generate batches for problems with Nin images as inputs and Nout images as outputs. Now I have to pass this class to the DataLoader, but I don't know how to format such inputs / outputs in order to be supported by the DataLoader. For example I don't think it has to be BatchSize x Nin x Channels x Height x Width because it could not support images with different channels (or dimensions in general).


text:
Q: Doubts when changing the SoftMaxWithLoss layer of caffe framework I want to modify the existing softmaxloss in Caffe. The idea is to add a weight factor to the loss. For instance, if we are processing a pixel that belongs to car class, I want to put a factor 2 to the loss, because in my case, the detection of car class is more important than the dog class(for example). This is the original source code:
__global__ void SoftmaxLossForwardGPU(const int nthreads,
          const Dtype* prob_data, const Dtype* label, Dtype* loss,
          const int num, const int dim, const int spatial_dim,
          const bool has_ignore_label_, const int ignore_label_,
          Dtype* counts) {
  CUDA_KERNEL_LOOP(index, nthreads) {
    const int n = index / spatial_dim;
    const int s = index % spatial_dim;
    const int label_value = static_cast<int>(label[n * spatial_dim + s]);
    if (has_ignore_label_ && label_value == ignore_label_) {
      loss[index] = 0;
      counts[index] = 0;
    } else {
      loss[index] = -log(max(prob_data[n * dim + label_value * spatial_dim + s],
                      Dtype(FLT_MIN)));
      counts[index] = 1;
    }
  }
}

You can find this code in https://github.com/BVLC/caffe/blob/master/src/caffe/layers/softmax_loss_layer.cu
In the following code you can find the modifications that I do in order to achieve my objective:
__global__ void SoftmaxLossForwardGPU(const int nthreads,
          const Dtype* prob_data, const Dtype* label, Dtype* loss,
          const int num, const int dim, const int spatial_dim,
          const bool has_ignore_label_, const int ignore_label_,
          Dtype* counts) {
  const float weights[4]={3.0, 1.0, 1.0, 0.5}
  CUDA_KERNEL_LOOP(index, nthreads) {
    const int n = index / spatial_dim;
    const int s = index % spatial_dim;
    const int label_value = static_cast<int>(label[n * spatial_dim + s]);
    if (has_ignore_label_ && label_value == ignore_label_) {
      loss[index] = 0;
      counts[index] = 0;
    } else {
      loss[index] = -log(max(prob_data[n * dim + label_value * spatial_dim + s],
                      Dtype(FLT_MIN))) * weights[label_value];
      counts[index] = 1;
    }
  }
}

I am not sure if this modification is doing what I want to do. For several reasons:

*

*I am not sure what means each values of this function. I am supposing for instance the label_value corresponds to the ground truth value, but
I am not sure.

*I completely do not understand this line: prob_data[n * dim + label_value * spatial_dim + s]. Where is the loss estimated here? I am supposing the loss calculation is happening in this line, and for that reason I'm putting my weights here, but I can't see the calculation here. Here I can see an access to a specific position of the vector prob_dat.
I know my code proposal is not the best one, I would like at some point to convert these weights into an input of the layer, but right now I don't have enough knowledge to do it (if you can also give me some hints in order to achieve it, that would be great).

A: *

*Implementing your own layer in caffe is a very nice skill to have, but you should do this as a "last resort". There are quite a few existing layers and you can usually achieve what you want using existing layer(s).

*You cannot modify the forward_gpu implementation without modifying forward_cpu as well. More importantly, you MUST modify the backward functions as well - otherwise the gradients updating your weights will not reflect your modified loss.

*"SoftmaxWithLoss" layer is a special case of the loss "InfogainLoss" layer. If you want to have different "weight" for each class, you can simply use "InfogainLoss" with weight matrix H according to your weights.
If you want to have spatially varying weight (different weight for different location) you can look at PR #5828, implementing "WeightedSoftmaxWithLoss".


text:
Q: How to use trigger in sql to create a certain attribute I have a question here. If a car that is under service is not available to be rented out. Then how do I create an attribute titled 'availability' that determines whether a car is available to be rented out? By using the trigger effect/or any other conventional method, how can I create an availability attribute that determines whether the car can be rented out based on the service period in this table.
CREATE TABLE VehicleService (
vehicleServiceID    int (16) AUTO_INCREMENT,
vehiclePlateNumber  varchar (8),
serviceStartDate    datetime,
serviceEndDate      datetime,
servicePeriod   int(4)  AS (TIMESTAMPDIFF(DAY, serviceStartDate, serviceEndDate))
location     varchar(255)
CONSTRAINT pkvehicleServiceID PRIMARY KEY (vehicleServiceID),
CONSTRAINT fkvehiclePlateNumber FOREIGN KEY (vehiclePlateNumber) REFERENCES Vehicle
(vehiclePlateNumber));

A: If the client can pick any arbitrary date they want to check for availability, then the attribute you want would have a different value for each client, depending on the date they want to check. Therefore you can't persist the availability as an attribute. You can only calculate it per query.
SELECT ? BETWEEN serviceStartDate AND serviceEndDate AS is_available
WHERE vehicleServiceId = ?

The first ? would be the date the client is interested in checking.

Re your comment:
Okay, let's do an example.

vehicleServiceId
serviceStartDate
serviceEndDate

1234
2022-02-18
2022-02-22

Suppose I search for availability for date 2022-02-20. The car is in service, so it is not available.
Concurrently, you search for availability for date 2022-02-24. The service should be done, so it is available.
Regardless of how we implement it, what value do you think should be stored in the hypothetical availability attribute that you want in the table? True or false?


text:
Q: Substituting and exponential term by another expression I would like to do, in every calculation that I perform, the following substitution:
$e^x -> (1+x)$.
That is, every term with an exponential should become the Taylor series to the first-order evaluated at zero ($e^{f(x)} = 1+f`(0) x$). Surely my attempt was to try:
$e^x = (1+x)$
however it returns me that it is Protected.
I must address that I make several calculations and this term may appear in several different contexts. As examples:
$e^{2(x+y)}$
and this should return
$(1+2x)e^{2y}$;
or
$e^{-x}-1$
which should become
$-x$.
Is it possible to generalize this to any function following a structure, like: every exponential following a $\delta$ will be simplified, but the ones without it will not. As an example:
$e^{2(x+\delta x) + y-3\delta c} = (1+2\delta x) (1-3\delta c) e^{2x+y}$.

A: One way to do it.
erule[a_] = {a -> Log[1 + a]}

expr = Exp[-x] - 1

Series[expr /. erule[x], {x, 0, 1}] // Normal
(*-x*)

expr = Exp[2 (x + y)]

Series[expr /. erule[x], {x, 0, 1}] // Normal // Simplify
(*(2 x + 1) E^(2 y)*)

expr = E^(2 (x + δx) + y - 3 δc)

Series[expr /. erule[δx] /. erule[δc], {δx, 0, 1}, {δc, 0, 1}] // Normal // Simplify
(*(3 δc - 1) (2 δx + 1) (-E^(2 x + y))*)

While this method is not automated, it does work, at least for these examples.


text:
Q: Flutter Gridview button functionality to new screen with Firebase I've made a Gridview using Firebase and Streambuilder and Gridview.builder. This grid displays album titles, the album cover art for each album, and the artists that make each album. I'd like for each grid tile to be able to be pressed and navigate to a separate page with its specific album details. The plan was on press, the app would be able to identify the entire document the grid tile was referring to, move to a new page, and display the document in full to unveil the album details. The thing is, I don't know how to do that. Since snapshot.data.documents[index]['Title'] worked when iterating though all the documents to create the gridview, I thought that typing snapshot.data.documents[index] would work, but it just displays Instance of 'DocumentSnapshot' in the debug console. I'm out of ideas on how to tackle this, so any suggestions are welcome
My code is shown below
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final Services services = Services();
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgcolour,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: Icon(Icons.menu),
        title: Text("Home"),
        actions: <Widget>[
          Padding(padding: EdgeInsets.all(10), child: Icon(Icons.more_vert))
        ],
      ),
      body: StreamBuilder(
          stream: Firestore.instance.collection('music').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const Text("Loading...");
            return GridView.builder(
              itemCount: snapshot.data.documents.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, childAspectRatio: 0.655172413),
              //cacheExtent: 1000.0,
              itemBuilder: (BuildContext context, int index) {
                var url = snapshot.data.documents[index]['Cover Art'];

                return GestureDetector(
                  child: Container(
                    width: 190.0,
                    child: Card(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(32)),
                      color: hexToColor(
                          snapshot.data.documents[index]['Palette'][0]),
                      elevation: 1,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          SizedBox(height: 12),
                          ClipRRect(
                              borderRadius: BorderRadius.circular(21.0),
                              child: Image.network(url,
                                  height: 180.0, width: 180)),
                          SizedBox(height: 10),
                          Text(
                              snapshot.data.documents[index]['Artist']
                                  .join(', '),
                              textAlign: TextAlign.center,
                              style: GoogleFonts.montserrat(
                                  textStyle: TextStyle(color: Colors.white),
                                  fontSize: 14,
                                  fontWeight: FontWeight.w300)),
                          SizedBox(height: 10),
                          Text(snapshot.data.documents[index]['Title'],
                              style: GoogleFonts.montserrat(
                                  textStyle: TextStyle(color: Colors.white),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600),
                              textAlign: TextAlign.center),
                        ],
                      ),
                    ),
                  ),
                  onTap: () {
                    print("Tapped ${snapshot.data.documents[index]}");
                  },
                );
              },
            );
          }
          ),
    );
  }
}

A: Is there an ID for your snapshot.data.documents[index]? If yes, add it to the end.
onTap: () {
     print("Tapped ${snapshot.data.documents[index]['the property you want']}");
},


text:
Q: Cant initiate break points with Xdebug through dbgpProxy on multi-site dev server I manage a setup with multiple developers using a "developer" Apache Server with PHP 7.4.
Since the Ubuntu 20.04 server is running in a private range in AWS, access is only allowed thru a VPN server. The VPN server is also where we have the dbgpProxy running as it can see both the workstations and the Dev Apache Server.
Our AWS instances are set up to allow all 9000-9010 traffic thru bi-directionally from each box.
This is the /etc/php/7.4/apache2/conf.d/20-xdebug.ini
zend_extension=xdebug.so
xdebug.discover_client_host = yes
xdebug.mode = debug
xdebug.client_host = <<IP ADDRESS OF VPN SERVER>>
xdebug.client_port = 9003
xdebug.log = /var/tmp/php74-xdebug.log
xdebug.log_level = 5
xdebug.start_with_request = yes

I have tried the above without the discover_client_host line too, but that did not help.
The execution of the dbgpProxy on the VPN server looks like this:
./dbgpProxy -i 0.0.0.0:9003 -s 0.0.0.0:9001
Once executed, the output looks like this:
Xdebug DBGp proxy (0.4.2-dev)
Copyright 2020 by Derick Rethans
2022-09-14 19:26:53.893 [warn] [SSL] The 'certs/fullchain.pem' file could not be found, not enabling SSL listeners
2022-09-14 19:26:53.894 [info] [dbgpProxy] Proxy started
2022-09-14 19:26:53.894 [info] [server] Started client server on 0.0.0.0:9003
2022-09-14 19:26:53.894 [info] [server] Started server server on 0.0.0.0:9001
2022-09-14 19:26:59.516 [info] [server] Start new client connection from <<VPN IP ADDRESS>>:53841
2022-09-14 19:27:00.020 [info] [proxyinit] [MATT] Added connection for IDE Key '<<DEVIDKEY>>': <<VPN IP ADDRESS>>:9001
2022-09-14 19:27:00.020 [info] [server] Closing client connection from <<VPN IP ADDRESS>>:53841
2022-09-14 19:27:15.480 [info] [server] Start new client connection from <<APACHE BOX IP>>:42144
2022-09-14 19:27:15.480 [warn] [server] Handler response error: Error reading command: Don't understand command '[494]'
2022-09-14 19:27:15.480 [info] [server] Closing client connection from <<APACHE BOX IP>>:42144

I have been testing and testing small changes for a long time now and I am getting no nearer a solution. I have tried checking out those Handler response errors in google too, but have not found any other posts about this with any information. Can anyone help me?
Thanks!


text:
Q: how to get client secret for a service account for google api This page:
https://console.cloud.google.com/iam-admin/serviceaccounts
if you go into an individual project that has a service account, and use the three dots on that row to execute the action "Get Key", it will generate a json that looks like:
{
  "type": "service_account",
  "project_id": "project name",
  "private_key_id": "sdfljsdlfsdljkf",
  "private_key": "-----BEGIN PRIVATE KEY-----\nsldjflsdjfkljsdf\n-----END PRIVATE KEY-----\n",
  "client_email": "user@projectname.iam.gserviceaccount.com",
  "client_id": "9797979797998",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/projectname.iam.gserviceaccount.com"
}

This doesn't match with what is needed for google.auth.OAuth2(client_id, client_secret, redirect_uris[])
What do I do to create a token to use with google spreadsheets api that uses this key information. It seems that the redirect_uris and the client secret are missing.
Update: the goal of this is to send google calendar events as other users under our domain.

A: I believe your goal and situation as follows.

*

*You want to use Sheets API using the service account.

*You want to achieve this using googleapis for Node.js.

*You have already enabled Sheets API at API console.

In this case, google.auth.JWT is used instead of google.auth.OAuth2(). A simple sample script for this is as follows.
Sample script:
Before you use this script, please set the variable for google.auth.JWT(). In this case, as a samplet, client_email and private_key are set. And please set Spreadsheet ID. And, in this case, please share your sample Google Spreadsheet in your Google Drive with the email of the service account. By this, the service account can read the Spreadsheet.
const { google } = require("googleapis");

const spreadsheetId = "###";  // Please set Spreadsheet ID.
const auth = new google.auth.JWT(
  "###", // Please set client_email here.
  null,
  "-----BEGIN PRIVATE KEY-----\n###\n-----END PRIVATE KEY-----\n", // Please set private_key here,
  ["https://www.googleapis.com/auth/spreadsheets.readonly"],
  null
);
const sheets = google.sheets({ version: "v4", auth: auth });
sheets.spreadsheets
  .get({ spreadsheetId: spreadsheetId })
  .then(({ data }) => console.log(data))
  .catch((err) => console.log(err));

Note:

*

*When you run above script and an error like The caller does not have permission occurs, please confirm that whether the Spreadsheet of spreadsheetId is shared with the email of the service account again. If it is not, please share it with the email of the service account.

*Please confirm whether the version of googleapis is the latest one.

References:

*

*googleapis for Node.js

*Method: spreadsheets.get


text:
Q: Posted image is not appearing in Firebase Recycler View I am trying to retrieve all users posts from firebase database and want to display it on Main Activity with the help Recycler View and Firebase Recycler Adapter.
But After Successfully Uploading The Image to Firebase database , i can see the uploaded image in storage section of firebase console but in database section it's showing something like -

com.google.android.gms.tasks.zzu@3c50f45

So I think the problem is with this line of code :
downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
CODE:
private Uri ImageUri;
    private StorageReference PostsImagesRefrence;
    private DatabaseReference UsersRef, PostsRef;
    PostsImagesRefrence = FirebaseStorage.getInstance().getReference();
    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

            filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>()
            {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
                {
                    if(task.isSuccessful())
                    {
                        downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
                        Toast.makeText(PostActivity.this, "image uploaded successfully to Storage...", Toast.LENGTH_SHORT).show();
                        SavingPostInformationToDatabase();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();

                    }

                }
            });

Design View And Actual Output Image:
Design View
View After Running
Please Try To provide me a correct code , help me as i am a newbie and don't know about Android Studio , and want to complete this College Project.

A: Try changing
String userFullName = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();

To
String userFullName = dataSnapshot.child("fullname").getValue(String.class);
String userProfileImage = dataSnapshot.child("profileimage").getValue(String.class);

EDIT: Try this
dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri downloadUrl)
    {
       downloadUrlString = downloadUrl.toString();
    }
});

A: Solved It , I was using old method for storing the image to firebase database.
Following changes has been done to solve it :
final StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

            final UploadTask uploadTask =filePath.putFile(ImageUri);

            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e)
                {
                    String message =e.toString();
                    Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
            {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
            {
                Toast.makeText(PostActivity.this, "Image uploaded successfully to Storage...", Toast.LENGTH_SHORT).show();

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>()
                {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
                    {
                        if (!task.isSuccessful())
                        {
                            throw task.getException();
                        }
                        downloadUrl= filePath.getDownloadUrl().toString();
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>()
                {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task)
                    {
                        if (task.isSuccessful())
                        {
                            downloadUrl = task.getResult().toString();
                            Toast.makeText(PostActivity.this, "Stored Image Successfully to Database", Toast.LENGTH_SHORT).show();
                            SavingPostInformationToDatabase();
                        }

                    }
                });

            }


text:
Q: import text to pandas with multiple delimiters I have some data that looks like this:
c stuff
c more header
c begin data
 1 1:.5
 1 2:6.5
 1 3:5.3

I want to import it into a 3 column data frame, with columns e.g.
a , b, c
1,  1, 0.5
etc

I have been trying to read in the data as 2 columns split on ':', and then to split the first column on ' '. However I'm finding it irksome.
Is there a better way to sort it out on import directly?
currently:
data1 = pd.read_csv(file_loc, skiprows = 3, delimiter = ':', names = ['AB', 'C'])
data2 = pd.DataFrame(data1.AB.str.split(' ',1).tolist(), names = ['A','B'])

However this is further complicated by the fact my data has a leading space...
I feel like this should be a simple task, but currently I'm thinking of reading it line by line and using some find replace to sanitise the data before importing.

A: One way might be to use the regex separators permitted by the python engine.  For example:
>>> !cat castle.dat
c stuff
c more header
c begin data
 1 1:.5
 1 2:6.5
 1 3:5.3
>>> df = pd.read_csv('castle.dat', skiprows=3, names=['a', 'b', 'c'],
                     sep=' |:', engine='python')
>>> df
   a  b    c
0  1  1  0.5
1  1  2  6.5
2  1  3  5.3


text:
Q: Cygwin gcc issue - cannot find Python.h So I downloaded Cygwin to build Matplotlib on Windows. Upon running

python setup.py build

I get a message saying Python.h cannot be found (pastebin).
Looking in /usr/include/python2.7, I can clearly see Python.h exists.
When I do:

gcc -print-search-dirs

I get paths to some Haskell folder outside of the cygwin installation folder. Full output here.

A: in cygwin make sure the python-devel package is installed:

*

*Run the cygwin installer (setup-x86(_64).exe

*Click through until you get to the page to install packages

*install the "python-devel" package from the "python" section. [Update from Comments] It is available as python2-devel or python3-devel under Python section for some.

A: I realize your question is old but I stumbled upon the exact same problem and found the solution so I thought I would share it. You probably have another gcc installed outside of cygwin, in my case it was a mingw-tdm native windows gcc variant. It happened to be in the path before the actual cygwin gcc, and was therefore picked up by the python installer.
To solve the problem, you only need to locate (or install) the cygwin gcc you need (either 32 or 64-bit), and do
export CC=/path/to/correct/gcc/exe

for instance
export CC=/usr/bin/x86_64-pc-cygwin-gcc

A: This looks similar to the following discussion on ubuntu forums:
http://ubuntuforums.org/archive/index.php/t-2136273.html
one of the solutions is to "sudo apt-get build-dep python-matplotlib", while other solution is to check whether you are compiling with correct python. Python 2 uses MPL < 1.2 and python 3 MPL >= 1.2.


text:
Q: JVM parameters for application server Recently, we upgraded CLM 5.0.2 to CLM 6.0.5 (Distributed Topology) and along with that we have WAS 9.0.0.7 and DB2. We are using applicaitons like CCM, RM, QM, DM, Rational Insight and each servers having 128GB of RAM. While configuring WAS JVM properties -Xmx -Xms we configured with 64g in each applications, for effective change we need to Stop and Start the WAS. After stopping the WAS we were not able to Start the WAS again and we checked the log file and it mentioned 64g is too large. As of now we configured JVM properties with 24g in each applications.
My question is, How to utilise that 128GB RAM? What will be the reason for the log message "64g is too large"? Compare to 128GB RAM, -Xmx24g -Xmx24g is very low and also accessing applications will be low.
Any Solution...

A: In a 64-bit system, object references can be 8-byte long if Compressed Oops is turned off. That means that every reference to an object is 8 bytes. However modern JVMs enable Compressed Oops by default, thus reducing object reference size to 4 bytes. It is at the cost of max allowed heap space. Max allowed heap space is 32G when Compressed Oops is enabled.
You can disable this by using -XX:-UseCompressedOops option.


text:
Q: Hidden Markov Model and Viterbi algorithm: Understanding the Casino Problem? I am deeply struggling with understanding how to apply the Viterbi algorithm. From my course notes, I have the following simple(I'm told) example:

If the sequence HH was observed, what is the most likely sequence in
  which Fair and Biased coins were used ?

Following table was generated as part of solution:

and the answer was given as $O-Biased-Fair$ with probability 0.2025. The $O$ stands for original state before any observations.
Can someone explain this answer in much detail and simplest way possible ? Thanks.

A: Viterbi algorithm is a dynamic programming algorithm for finding the most probable sequence of hidden states given a sequence of observations in an HMM.
The table in your solution has one row per hidden state (O, F, B) and one column per observation ($\emptyset$, head, head) where $\emptyset$ denotes the beginning of the observation sequence. So, the first column tells you with what probabilities we start from each state. Since we always start from O and never from the other states, the first columns is 1, 0, 0.
The second column says, given the probabilities in the previous (i.e. the first) column, what is the probability that we end up at each state after observing the first observation. It seems that the probability of going form state O to F and B is the same and equal to $0.5$. So, your first graph should be like this:

1. After the first observation
Keep in mind that we know that in the beginning we were in state O with probability 1.
Probability of staying at O is 0.
Probability of going to F (from O) is $0.5$ and probability of observing a head (the first observation) there is $0.5$, so, probability of ending up at F after the first observation is $1 \times 0.5 \times 0.5 = 0.25$.
Probability of going to B (from O) is $0.5$ and probability of observing a head (the first observation) there is $0.9$, so, probability of ending up at B after the first observation is $1 \times 0.5 \times 0.9 = 0.45$.
2. After the second observation
The probability of ending up at O, F, or B after the second observation (head) is as follows:
2.1. Probability of ending up at O:
... is zero since there is no way we can enter O (see the diagram).
2.2. Probability of ending up at F:
... there are 3 possibilities:

*

*assuming we came from O: has probability 0 (see 2nd column of your table)

*assuming we came from F: has probability $0.25 \times 0.9 \times 0.5 = 0.1125$

*assuming we came from B: has probability $0.45 \times 0.9 \times 0.5 = 0.2025$

The most probable hypothesis is that we have come form state B.
2.3. Probability of ending up at B:
... there are 3 possibilities:

*

*assuming we came from O: has probability 0 (see 2nd column of your table)

*assuming we came from F: has probability $0.25 \times 0.1 \times 0.9 = 0.0225$

*assuming we came from B: has probability $0.45 \times 0.1 \times 0.9 = 0.0405$

The most probable hypothesis is that we have come form state B.
3. The Viterbi solution
According to the 3rd column of your table, the most probably hypothesis is that after observing two heads with this HMM we end up in state F (it has probability $0.2025$ versus $0.0405$ for state B and $0$ for state O). According to section 2.2, most likely, we have come from $B$ and we know that we started form O (these are indicated by arrows in your table). So, the Viterbi state sequence is O, B, S.


text:
Q: How to filter command line output? I need to filter the output of a command executed in network equipment in order to bring only the lines that match a text like '10.13.32.34'.
I created a python code that brings all the output of the command but I need only part of this.
I am using Python 3.7.3 running on a Windows 10 Pro.
The code I used is below and I need the filtering part because I am a network engineer without the basic notion of python programming. (till now...)
from steelscript.steelhead.core import steelhead
from steelscript.common.service import UserAuth
auth = UserAuth(username='admin', password='password')
sh = steelhead.SteelHead(host='em01r001', auth=auth)
from steelscript.cmdline.cli import CLIMode
sh.cli.exec_command("show connections optimized", mode=CLIMode.CONFIG)
output = (sh.cli.exec_command("show connections optimized"))

A: I have no idea what your output looks like, so used the text in your question as example data. Anyway, for a simple pattern such as what's shown in your question, you could do it like this:
output = '''\
I need to filter the output of a command executed
in network equipment in order to bring only the
lines that match a text like '10.13.32.34'. I
created a python code that brings all the output
of the command but I need only part of this.

I am using Python 3.7.3 running on a Windows 10
Pro.

The code I used is below and I need the filtering
part because I am a network engineer without the
basic notion of python programming. (till now...)
'''

# Filter the lines of text in output.
filtered = ''.join(line for line in output.splitlines()
                            if '10.13.32.34' in line)

print(filtered)  # -> lines that match a text like '10.13.32.34'. I

You could do something similar for more complex patterns by using the re.search() function in Python's built-in regular expression re module. Using regular expressions is more complicated, but extremely powerful. There are many tutorials on using them, including one in Python's own documentation titled the Regular Expression HOWTO.


text:
Q: Помогите сделать подобный зум Подскажите, как сделать подобное на js? Есть картинка по наведению на которую появляется окно в увеличенным изображением. Эдакий эффект лупы. Кроме стандартного плагина на jquery ничего не могу найти(

A: Где-то такое решение я уже видел:

$(document).ready(function() {
  var zoomMargin = 15;

  function startZoom(e) {
    $('.zoomer .large').css('left', $(this).width() + zoomMargin).show(); // Контейнер у большим изображением становится видимым.
  }

  function moveZoom(e) {
    var offset = $(this).offset(), // В переменной offset хранятся координаты блока с миниатюрой
      x = (e.pageX - offset.left), // В переменной хранится координата X курсора мыши относительно блока с миниатюрой
      y = (e.pageY - offset.top); // Координата Y курсора мыши.
    w = $(this).width(), // Ширина миниатюры
      h = $(this).height(), // Высота миниатюры
      // Позиционирование фона большого изображения относительно того, куда указывает курсор на миниатюре.
      $('.large').css({
        'background-position': (x / w * 100) + '% ' + (y / h * 100) + '%'
      });
  }

  function endZoom(e) {
    $('.zoomer .large').hide(); // Контейнер с большим изображением скрывается
  }
  $('.small').on({
    'mouseenter': startZoom, // При наведении мыши на миниатюру срабатывает функция startZoom
    'mousemove': moveZoom, // Когда курсор мыши перемещается внутри миниатюры срабатывает функция moveZoom
    'mouseleave': endZoom // Когда мышь уходит из области миниатюры срабатывает функция endZoom
  });
})
.zoomer {
  width: 300px;
  height: 200px;
  position: relative;
}

.zoomer .small {
  width: 300px;
  height: 200px;
  background: url(https://kalushnews.city/upload/test_img/2266/questions/o_1djrf1fdu1mcmvm6ha51qv2vdjel.jpg) no-repeat;
  background-size: cover;
  /* Масштабирует изображение с сохранением пропорций так, чтобы его ширина или высота равнялась ширине или высоте блока. */
  position: absolute;
}

.zoomer .large {
  background: url(https://kalushnews.city/upload/test_img/2266/questions/o_1djrf1fdu1mcmvm6ha51qv2vdjel.jpg) no-repeat;
  position: absolute;
  display: none;
  width: 600px;
  height: 400px;
}

A: Получилось что-то такое:

addEventListener('mousemove', e => {
  let isImg = e.target.nodeName === "IMG";
  if (isImg) {
    let r = e.target.getBoundingClientRect();
    frame.style.top =  e.y - 50 + "px";
    frame.style.left = e.x - 50 + "px";
    preview.style.background = `url(https://picsum.photos/id/85/900/900) no-repeat`;
    preview.style.backgroundPosition = `${150-(e.x-r.x)*3}px ${150-(e.y-r.y)*3}px`
  }
  preview.style.display = frame.style.display = isImg ? 'inline-block' : 'none';
})
#frame {
  width: 100px;
  height: 100px;
  position: fixed;
  background: #0002;
  pointer-events: none;
  display: none;
}

#preview {
  width: 300px;
  height: 300px;
  display: none;
}

A: Можно использовать библиотеку https://github.com/malaman/js-image-zoom
Пример: http://malaman.github.io/js-image-zoom/example/


text:
Q: Drawing a PDF full of formatted text with images on the iPhone Is it possible to create a page with formatted text that is stored in core data. The text would need to be displayed with paragraphs and a few images. I have already written the code to create a PDF with one line of text, but I am unsure of the pattern needed to layout the PDF in a nice document way. One of reasons is I had to write the code in C. The data that will be in the document is of course In core data. And I do not know what the best practice is for what I am trying to do.

A: I am quite sure NSData (your c bytes) could be stored in NSManagedObject.
Even if not. Why don't store only metadata in CoreData? Is much more simpler for example: info needed to render the page wanted, etc.
I am not sure archiving the hole PDF in CoreData is a good approach.

A: Unless you have a particular need for PDF, the best practice is to use HTML and UIWebView. WebView is the primary formatted-text displayer for iPhone. iPhoneOS 3.2 added CoreText, which is another option if you have serious layout needs, but it generally isn't needed for simple formatted text and data.
The Text and Web Programming Guide includes a good discussion of your formatting and layout options. Generally UIWebView is still your best bet.


text:
Q: MAMP Config help, display PHP errors I am running the latest version of MAMP on Snow Leopard.
My php.ini file has been configured to display errors. display_errors = on. The phpinfo(); page displays the status of error reporting, it is on. I have restarted my web server several times.
I've searched through Google, and I cannot find any similar problem. Everyone just says to do exactly what I have done, but it is not working. The pages will just remain blank, (with no reporting), if I intentionally place errors.
Any thoughts as to what the problem may be?

A: In addition to the display_errors directive, which has to be set to On, you might have to configure error_reporting.
For instance, you can use this in your php.ini file :
error_reporting = E_ALL

Another should, useful to test, might be to place this kind of portion of PHP code at the beginning of your script :
error_reporting(E_ALL);
ini_set('display_errors', 'On');

This is useful when you don't have access to php.ini and/or just want to test quickly, without having to restart the webserver.

As a sidenote, when it comes to displaying errors, the Xdebug extension is really great : when it's installed/enabled/configured, instead of just having an error message, you'll get the full stack-trace, which is much more useful ;-)

A: For any future posters who run into this issue...
I was having the same issue and found that I was making changes to the wrong php.ini files.  Run phpinfo and find the path to the active php.ini file to make sure you're editing the correct one.
On my installation of mamp there were multiple instances of the /conf directory with php.ini files. The php.ini files I needed were located in the /bin/php/php[version#]/conf directory and not the MAMP/conf directory.
Exact path to the php.ini file I needed to edit:
Applications/MAMP/bin/php/php5.4.10/conf/php.ini
Change display_errors = Off to display_errors = On

A: I recently experienced the same problem - in my case I had downloaded a client's Wordpress site from their live server that turned out to have been tampered with by malicious script insertion that was overriding the error reporting in order to escape detection.
A little late to help the OP(!), but perhaps of use to future searchers.

A: There might have a .htaccess file in a directory that overrides the display_errors setting set in php.ini. From your post I assume you didn't explicitly add this but a few frameworks do this by default so might be added that way. Look for a line like this in your .htaccess file:
php_value display_errors 0

and change the value to 1.

A: If you have several php sdks with several versions, first make it sure you are editing correct php.ini file. If you were right add this two lines at the beginning of the code.
error_reporting(E_ALL);
ini_set('display_errors', 'On'); // or ini_set('display_errors', 1);

A: Here's a twist to the same answer. I had the same issues, just copied and pasted the ini path from the php info page and still same problems...
turns out I made a syntax mistake when I edited my 'error_reporting' block in the php.ini.
I had E_NOTICE rather than ~E_NOTICE.
:(
So mistakes can happen in the php.ini if you were editing it and totally forgot you edited something.


text:
Q: hashfile for files in define paths using BATCH I am trying to get the MD5 values of all files in sub folders that are in external file PathList.txt.
I can't make the script use the path names as define in %%i.
In the example I used "C:\Temp\example\" in the place of %%i so the script will work.
Also it skips file with whitespaces like C:\folder2\some file.txt
@ECHO off
echo Files MD5 > MD5_log.txt

FOR /F %%i IN (PathList.txt) DO (
    @FOR /R "C:\Temp\example\" %%G in (*) DO (
     for  %%a in (%%G) do certutil -hashfile "%%~a" MD5 | find /i /v "certutil">> MD5_log.txt
     )
)

PathList.txt
C:\folder1\
C:\folder2\

This is for old computer, s I don't have Powershell option.
How can I make it work?
Thanks

A: To have an output more resembling the usual tools md5deep64.exe, MD5SUMS.EXE etc.
And include the full path on the same line as the hash
I suggest to use something along these lines:
:: Q:\Test\2019\03\19\SO_55243349.cmd
@ECHO off
( echo Files MD5
  FOR /F "delims=" %%P IN (.\PathList.txt) DO if exist "%%~fP" (
    PushD %%P
       FOR /R %%R in (*) DO (
          FOR /F %%A in ('certutil -hashfile "%%~R" MD5 ^| find /i /v ":" ') Do Echo %%A  %%~fR
       )
    PopD
  ) else ( Echo %%~fP not found )
) > MD5_log.txt

Sample output:
> Q:\Test\2019\03\19\SO_55243349.cmd
Files MD5
bea07e6d2b8dce396fe21baa61b34956  A:\a\dmc\foo.txt
81051bcc2cf1bedf378224b0a93e2877  A:\a\dmc\C24117\bar.txt
81051bcc2cf1bedf378224b0a93e2877  A:\b\dmc\bar.txt

A: I can't make the script use the path names as defined in %%i
Please find below a working batch file (test.cmd):
@echo off
setlocal EnableDelayedExpansion
echo Files MD5 > MD5_log.txt
for /f "tokens=*" %%i in (PathList.txt) do (
  for /f "tokens=*" %%j in ('dir /b /s "%%i"') do (
    certutil -hashfile "%%j" MD5 | find /i /v "certutil" >> MD5_log.txt
    )
  )
endlocal

Sample output:
> type PathList.txt
f:\test\bar
f:\test\bar - Copy
f:\test\foo

> test
> type MD5_log.txt
Files MD5
MD5 hash of file f:\test\bar\test.cmd:
eb 4f 28 f4 a0 b0 c5 21 0d e8 5f 99 0f d8 fd ab
MD5 hash of file f:\test\bar\test.html:
3a 68 3a f6 4e 88 f1 22 62 d6 46 dc bb 54 59 45
MD5 hash of file f:\test\bar\test.ps1:
07 fd 41 59 6b fa 90 06 49 4f bf e3 dd be 0d 1c
MD5 hash of file f:\test\bar - Copy\test with space.cmd:
eb 4f 28 f4 a0 b0 c5 21 0d e8 5f 99 0f d8 fd ab
MD5 hash of file f:\test\bar - Copy\test.html:
3a 68 3a f6 4e 88 f1 22 62 d6 46 dc bb 54 59 45
MD5 hash of file f:\test\bar - Copy\test.ps1:
07 fd 41 59 6b fa 90 06 49 4f bf e3 dd be 0d 1c
MD5 hash of file f:\test\foo\test.sh:
d2 12 38 76 9d 8e 9f 51 1a 60 0b 15 6c 0c f8 38
MD5 hash of file f:\test\foo\test.xml:
cd 8f d1 c6 66 ac ff 7f 98 d2 e9 4a ad b5 20 1f
MD5 hash of file f:\test\foo\test.yaml:
78 ce a1 f0 97 46 ee 32 c6 7f f6 16 8d 94 04 d2
MD5 hash of file f:\test\foo\test.yml:
78 ce a1 f0 97 46 ee 32 c6 7f f6 16 8d 94 04 d2

Further Reading

*

*An A-Z Index of the Windows CMD command line | SS64.com

*Windows CMD Commands (categorized) - Windows CMD - SS64.com

*CertUtil Certification Authority Utility - Windows CMD - SS64.com

*Dir - list files and folders - Windows CMD - SS64.com

*Findstr - Search for strings - Windows CMD - SS64.com

*For - Loop through files - Windows CMD - SS64.com

*For - Loop through command output - Windows CMD - SS64.com