text:
Q: Manipulating Y axis limits does not work (ggplot2 percent bar plot) Following the nice example here:
Create stacked barplot where each stack is scaled to sum to 100%
I generated a barplot for my data in which the results are presented as percent.
My data frame is:
small_df = data.frame(type = c('A','A','B','B'),
                      result = c('good','bad','good','bad'),
                      num_cases = c(21,72,87,2))

And my attempt to draw looks like so:
library(scales)
library(ggplot2)

ggplot(small_df,aes(x = type, y = num_cases, fill = result)) +
  geom_bar(position = "fill",stat = "identity") +
  scale_y_continuous(labels = percent, breaks = seq(0,1.1,by=0.1))

This all works fine and produces the a figure like so:

However, I want to make the limits of the y axis to be 0-110% (I will later want to add a label on top so I need the space). Changing the line to:
scale_y_continuous(labels = percent, breaks = seq(0,1.1,by=0.1), limits = c(0,1.1))

fails with the following error:

Error: missing value where TRUE/FALSE needed

Any idea how to solve this?
Many thanks!!!

A: You can change the out of bounds option via oob or use coord_cartesian to set the limits.  See info here
ggplot(small_df, aes(x = type, y = num_cases, fill = result)) +
    geom_bar(position = "fill", stat = "identity") +
    scale_y_continuous(labels = percent, breaks = seq(0, 1.1, by=0.1),
                    oob = rescale_none, limits = c(0, 1.1))

ggplot(small_df, aes(x = type, y = num_cases, fill = result)) +
    geom_bar(position = "fill", stat = "identity") +
    scale_y_continuous(labels = percent, breaks = seq(0, 1.1, by=0.1)) +
    coord_cartesian(ylim = c(0, 1.1))


text:
Q: How can I make a external phpbb-login without redirecting to another page? It's possible to make an external login with the following code
<form action="./phpBB3/ucp.php?mode=login" method="post">

Login  •   Register

 <fieldset>
    Username:
    <input type="text" name="username" id="username" size="10" title="Username" />
    Password:
    <input type="password" name="password" id="password" size="10" title="Password" />
    <input type="submit" name="login" value="Login" />
 </fieldset>
</form>

but this will end you up at the forum index.
If you add
<input type="hidden" name="redirect" value="./somefile.html" />

you can get it to redirect back to the page you started at, but you will still have needlessly gone to another page only to come back and have lost everything you have done on that page.
Does anyone have an idea how to make a system that lets you login without leaving the page? Maybe something with an iframe?

A: This might be late but here this works:
<?php
define('IN_PHPBB', true);
$phpbb_root_path = './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();

if($user->data['is_registered'])
{
    //User is already logged in
    }
else
{
$result = $auth->login($username, $password, '', 1, 0);

print_r($result);
if ($result['status'] == LOGIN_SUCCESS)
{
    echo '//User was successfully logged into phpBB';
}
else
{
    echo '//Users login failed';
}
}
?>

in the above code , change the $username and $password to ur login stuff , run it and see , I have tested this on the latest phpbb version, and it works.
Don't forget to change the root path and things to ur specifications.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I edit the Bot Code c# after its published in Azure I created a bot in the Azure bot framework.  It's a Qna one.
It works, I can see it in the webchat, I can see it in my bots of bot framework page, I can see the qna data source in qnamaker.
When I go to azure and look at the resources and click on my bot service, it takes me to the Create Page,  well I don't want to create, I want to get to the code of the existing bot, I can't figure out how, some of the props are editable in the bot framework site, but not the code.
I did not configure continuous integration. Or download the code as it was boiler plate, but I want to poke at it now.

A: Develop with Azure Bot Service > Set up continuous integration

*

*Within your Azure bot, click the Settings tab and expand the Continuous integration section.

*Click the link to download the zip file that contains the source code for your bot.

*Extract the contents of the downloaded zip file to the local folder where you are planning to sync your deployment source.

(source: microsoft.com)

A: I have found the answer to this problem.
Once you have closed all your windows and want to return to your bot, if you find that you seeing the Create Application ID screen and not the bot details screen with the code, channels and analytics bit, then you have opened this is IE11,
Ditch the crappy browser and open it in Chrome.


text:
Q: Need help with a complex MySQL query I'm struggling to get a final result set for a 3 table hierarchical set of data. Hopefully, the diagrams will indicate what I have and what I'm trying to do. Briefly, my final result set (below) should easily allow me to define a dynamic number of checkboxes in my web site, while also allowing me to define whether the boxes are checked, all from within a single result set.  I believe that since the data is normalized, I should be able to get a single result set, but I can't get my head wrapped around this on...   Can anyone help??
    TABLE A                    TABLE B                 TABLE C
    MEMBER                     CONTACT                 ALERT
(pk)$member_id  ->         (pk)$contact_id  ->       (pk)$alert_id
                           (fk)$member_id            (fk)$contact_id
                                                         $alert_type ->
                                                             -> 'local', 'state', 'nation'

Example of my filter criteria is member_id = 1 AND alert_type = 'local'
* = results of filter member_id = 1

TABLE MEMBERS A
+----------+----------+
|member_id |   Name   |
+----------+----------+
|     1    |   Alan   | *
|     2    |   Brad   |
|     3    |   Doug   |
|     4    |   Flo    |
+---------------------+

TABLE CONTACTS B
+--------------------------------------------------------------------+
| contact_id |  member_id  |    email      |    phone     |   Name   |
+------------+-------------+---------------+--------------+----------+
|     1      |     1       |  a@gmail.com  |              |   Alex   | *
|     2      |     1       |  b@gmail.com  | 123-456-7890 |   Bob    | *
|     3      |     3       |  c@gmail.com  |              |   Cris   |
|     4      |     1       |  d@gmail.com  |              |   Dan    | *
|     5      |     2       |  e@gmail.com  |              |   Ed     |
|     6      |     1       |  f@gmail.com  |              |   Fran   | *
|     7      |     1       |  g@gmail.com  | 212-323-1111 |   Greg   | *
|     8      |     2       |  h@gmail.com  |              |   Hans   |
|     9      |     3       |  i@gmail.com  |              |   Ida    |
|    10      |     1       |  j@gmail.com  | 945-555-1212 |   Jeff   | *
|    11      |     2       |  k@gmail.com  | 945-555-1212 |   Karl   |
|    12      |     3       |  l@gmail.com  |              |   Leo    |
+--------------------------------------------------------------------+

# = resutls of filter alert_type = 'local'
TABLE CONTACTS_SELECTED C
+-----------------------------------------+
|  alert_id  | contact_id |  alert_type   |
+------------+------------+---------------+
|     1      |     1      |     local     | * #
|     2      |     1      |     state     | *
|     3      |     3      |     state     |
|     4      |     5      |     local     |
|     5      |     5      |     state     |
|     6      |     6      |     nation    | *
|     7      |     7      |     local     | * #
|     8      |     8      |     nation    |
|     9      |    10      |     local     | *
|    10      |    12      |     state     |
+-------------------------+---------------+

REQUIRED OUTPUT
+------------------------------------------------------------------------------------+
|member_id | contract_id  |    email      |    phone     |   Name   |   alert_type   |
+----------+--------------+---------------+--------------+----------+----------------+
|     1    |      1       |  a@gmail.com  |              |   Alex   |    local       |
|     1    |      2       |  b@gmail.com  | 123-456-7890 |   Bob    |     NULL       |
|     1    |      4       |  d@gmail.com  |              |   Dan    |     NULL       |
|     1    |      6       |  f@gmail.com  |              |   Fran   |    nation      |
|     1    |      7       |  g@gmail.com  | 212-323-1111 |   Greg   |    local       |
|     1    |     10       |  j@gmail.com  | 945-555-1212 |   Jeff   |    local       |
+------------------------------------------------------------------------------------+

With this result set, I should be easily able to FOREACH my way through all 6 records and create a checkbox for each record, and flag those records with 'local' as checked. Can anyone help with setting up this complex query?

--
-- Table structure for table `contacts`
--

CREATE TABLE IF NOT EXISTS `contacts` (
  `contact_id` int(12) NOT NULL AUTO_INCREMENT,
  `member_id` int(12) NOT NULL,
  `email` varchar(30) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`contact_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=13 ;

--
-- Dumping data for table `contacts`
--

INSERT INTO `contacts` (`contact_id`, `member_id`, `email`, `phone`, `name`) VALUES
(1, 1, 'a@gmail.com', '', 'Alex'),
(2, 1, 'b@gmail.com', '123-456-7890', 'Bob'),
(3, 3, 'c@gmail.com', '', 'Cris'),
(4, 1, 'd@gmail.com', '987-654-3210', 'Dan'),
(5, 2, 'e@gmail.com', '', 'Ed'),
(6, 1, 'f@gmail.com', '', 'Fran'),
(7, 2, 'h@gmail.com', '234-567-8901', 'Hans'),
(8, 3, 'i@gmail.com', '', 'Ida'),
(9, 1, 'g@gmail.com', '', 'Greg'),
(10, 1, 'j@gmail.com', '456-789-0123', 'Jeff'),
(11, 2, 'k@gmail.com', '945-555-1212 ', 'Karl'),
(12, 3, 'l@gmail.com', '', 'Leo');

CREATE TABLE IF NOT EXISTS `contacts_selected` (
  `alert_id` int(12) NOT NULL AUTO_INCREMENT,
  `contact_id` int(12) NOT NULL,
  `alert_type` varchar(6) NOT NULL,
  PRIMARY KEY (`alert_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;

--
-- Dumping data for table `contacts_selected`
--

INSERT INTO `contacts_selected` (`alert_id`, `contact_id`, `alert_type`) VALUES
(1, 1, 'local'),
(2, 1, 'state'),
(3, 3, 'state'),
(4, 5, 'local'),
(5, 5, 'state'),
(6, 6, 'nation'),
(7, 7, 'local'),
(8, 8, 'nation'),
(9, 10, 'local'),
(10, 12, 'state'),
(11, 1, 'nation');

CREATE TABLE IF NOT EXISTS `alert_types` (
  `alert_type` varchar(6) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `alert_types`
--

INSERT INTO `alert_types` (`alert_type`) VALUES
('local'),
('state'),
('nation');

SOLUTION:
$alert_type = 'local';
// choices are local, state, nation
//
SELECT c.contact_id, c.member_id, c.email, c.phone, c.desc, s.alert_type
FROM contact c
    LEFT JOIN contact_select s
    ON c.contact_id = s.contact_id
WHERE c.member_id = 1 AND c.contact_id NOT IN
(SELECT cs.contact_id FROM contact_select cs WHERE cs.alert_type = '$alert_type')
GROUP BY c.contact_id
UNION
SELECT * FROM
    (SELECT c.contact_id, c.member_id, c.email, c.phone, c.desc, s.alert_type
    FROM contact c
    LEFT JOIN contact_select s
    ON c.contact_id = s.contact_id
    WHERE c.member_id = 1
    AND s.contact_id
    IN (SELECT cs.contact_id FROM contact_select cs WHERE cs.alert_type = '$alert_type')) z
WHERE z.alert_type = '$alert_type'

A: select member_id, cs.contract_id, c.email, c.phone, c.name, cs.alert_type
FROM contact c
LEFT JOIN contact_selected cs on cs.contact_id = c.contact_id
WHERE c.member_id = 1

Not sure i understand well what do you mean but maybe you're looking for thiS?

A: This should give you your desired output.
SELECT C.member_id, C.contact_id, C.email, C.phone, C.name, S.alert_type
FROM CONTACTS C
    LEFT OUTER JOIN CONTACTS_SELECTED S
        ON C.contact_id = S.contact_id
WHERE member_id = 1

A: I would try this:
select `c`.`contact_id`, `member_id`, `email`, `phone`, `name`, `alert_type` from contacts `c`
left join contacts_selected `s` on `c`.`contact_id` = `s`.`contact_id`
where member_id=1
group by `c`.`contact_id`

However, two points: One, it's not clear to me how you want to narrow the result set to select only one of the alert types. Two, your sample data and your insert statments contain slightly different data. That's not a problem, but it is a little confusing at first.


text:
Q: how to handle accessibility issues related with OUTLOOK I've a situation,my software's folder is shared on network and user can execute application on his system as his own.The problem is while he is trying to send mails through OUTLOOK using the application.following exception is thrown
"Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE))."
I searched internet whole day and found it is accessibility issues of processes making the problem.I tried with regedit as suggested by msdn,but unfortunately it is also not helpful.Is there any solution for this can be done programatically.
thanks

A: This usually happens if the security contexts of your app and Outlook are different. Is either one running with elevated privileges (Run As administrator)?


text:
Q: Tinymce wrongly rewriting HTML I have a custom button that insert some HTML in the editor

First block of code is the button action and the second one is how the HTML is inserted
Any idea why it is rewriting it that way and how to stop it?

A: I just managed to fix it, in the init function:

valid_children : 'pre[code]'

A: TinyMCE includes the ability to insert code samples into the editor via its Code Sample plugin:
https://www.tinymce.com/docs/plugins/codesample/
If you want to try to do this yourself you need to do a few things like using the protect configuration option to tell TinyMCE to allow your PHP tags.  See this TinyMCE Fiddle for a basic example:
http://fiddle.tinymce.com/Qdgaab


text:
Q: Suitable graph to compare predicted and actual values across multiple sites I would like to make a graph to compare predictions with actual values.
The graph must be independent of scale and show equal emphasis for over and under prediction.  The purpose is to summarise predictions at a range of sites where the size of predictions and actual values differ.
This is what I've come up with.  Errors are plotted as a correction factor which is
required to make the prediction equal to the actual values. You can see that having to multiple predictions by 2 to get the actual value plots as the same magnitude as having to multiply predictions by 1/2.  This was inspired by this plot.  Are there other graphs with a similar purpose?
(edited to incorporate suggestion by @rvl)

@rvl suggests a plot of log(actual/predicted) as below.

(code includes log(actual/prediction) as suggested by @rvl)
#Example plot (now includes log version)
library(MASS)

prediction <- c(2, 5, 10, 20, 30)
actual <- rep(10, times = length(prediction))

# Factor needed to multiply the prediction by to equal
# the actual value
(ratio.diff <- actual/prediction)
# [1] 5.0000000 2.0000000 1.0000000 0.5000000 0.3333333

# Make the values to plot
DiffFactor <- function(y,yhat){
  out <- (y/yhat)
  out[out < 1] <- -1/out[out < 1] + 2
  out

}

(diff.factor <- DiffFactor(actual, prediction))
# [1]  5  2  1  0 -1

par(oma = c(1,2,0,0))
plot(diff.factor,
     ylab = '',
     yaxt = 'n',
     las = 1,
     ylim = c(-3, 5))
abline(h=1, lty=2)

my.at = c( -3 : 5)
my.labels <- c(as.character(fractions(-1/(my.at[ my.at < 1 ] -2))), my.at[my.at >= 1])

axis(side = 2, at = my.at, labels = my.labels, las = 1)
mtext(side = 2, line = 3, text = 'Correction factor required to make prediction =     actual')

#--------------------------------------------------------

# Log version

par(oma = c(1,2,0,0))
plot(log(actual/prediction, base = 2),
     ylab = '',
     yaxt = 'n',
     ylim = c(-3,3),
     las = 1)

abline(h=0, lty=2)

my.at <-  c( -3 : 3)
my.labels <- as.character(fractions(1/(2^rev(my.at))))

axis(side = 2, at = my.at, labels = my.labels, las = 1)
mtext(side = 2, line = 3, text = 'Correction factor required to make prediction = actual')


text:
Q: Related Object serializer Django restframework My question is somewhat related to this one with some differences. I have a model similar to this one:
class Project(models.Model):
    project_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
    created_by_id = models.ForeignKey('auth.User', related_name='project', on_delete=models.SET_NULL, blank=True, null=True)
    created_by = models.CharField(max_length=255, default="unknown")
    created = models.DateTimeField(auto_now_add=True)

With the following serializer:
class ProjectSerializer(serializers.ModelSerializer):

    created_by = serializers.ReadOnlyField(source='created_by_id.username')

    class Meta:
        model = Project
        fields = ('project_id', 'created_by', 'created')

And corresponding view:
class projectsView(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def perform_create(self, serializer):
        serializer.save(created_by_id=self.request.user)

This code behaves like I want but forces information redundancy and does not leverage the underlying relationnal database. I tried to use the info from the linked question to achieve a "write user id on database but return username on "get"" in a flat json without success:
Removing the "created_by" field in the model. Replacing the serializer with:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

class ProjectSerializer(serializers.ModelSerializer):

    created_by = UserSerializer(read_only=True)
    created_by_id = serializers.PrimaryKeyRelatedField(
    queryset=User.objects.all(), source='created_by', write_only=True)

    class Meta:
        model = Project
        fields = ('project_id', 'created_by', 'created_by_id', 'created')

Which would NOT 100% give me what I want, i.e. replace the user id with the username in a flat json but return something like: {'project_id': <uuid>, 'created_by': <user json object>, 'created': <data>}. But still I get a {'created_by_id': ['This field is required.']} 400 error.
Question: How can I write a user id to a database object from the request.user information to refer to an actual user id but return a simple username in the GET request on the projectsView endpoint without explicitly storing the username in the Model? Or more generally speaking, how can I serialize database objects (Django models) into customer json response by using default serialization DRF features and default DRF views mixins?
Alternate formulation of the question: How can I store an ID reference to another DB record in my model (that can be accessed without it being supplied by the payload) but deserialize a derived information from that object reference at the serializer level such as one specific field of the referenced object?

A: I would recommend you to use Two different serializers for Get and POST operations. Change your serializers.py as
class ProjectGetSerializer(serializers.ModelSerializer):
    created_by_id = serializers.StringRelatedField()

    class Meta:
        model = Project
        fields = '__all__'

class ProjectCreateSerializer(serializers.ModelSerializer):
    created_by_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), default=serializers.CurrentUserDefault())

    def create(self, validated_data):
        return Project.objects.create(**validated_data, created_by=validated_data['created_by_id'].username)

    class Meta:
        model = Project
        fields = '__all__'

Also, I reccomend ModelViewSet for API class if you are looking for CRUD operations. Hence the view will be like this,
class projectsView(viewsets.ModelViewSet):
    queryset = Project.objects.all()

    def get_serializer_class(self):
        if self.action == 'create':
            return ProjectCreateSerializer
        return ProjectGetSerializer

So, the payload to create Project is,
{
}

One thing you should remember, while you trying to create Project user must logged-in
UPDATE - 1
serializer.py
class ProjectCreateSerializer(serializers.ModelSerializer):
    created_by_id = serializers.StringRelatedField()

    class Meta:
        model = Project
        fields = '__all__'

    def create(self, validated_data):
        return Project.objects.create(**validated_data, created_by_id=self.context['request'].user)
views.py
class projectsView(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectCreateSerializer

A: The error is in the write_only field options. The required parameter default value is set to True while the intent is to not make it required if we take a look at the model. Here in the view, I use the perform_create as post processing to save on the Model DB representation. Since required default value is True at the creation level, the first .save() to the DB fails. Since this is purely internal logic, the required is not necessary. So simply adding the required=False option on the PrimaryKeyRelatedField does the job:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

class ProjectSerializer(serializers.ModelSerializer):

    created_by = UserSerializer(read_only=True)
    created_by_id = serializers.PrimaryKeyRelatedField(
    queryset=User.objects.all(), source='created_by', write_only=True, required=False)

    class Meta:
        model = Project
        fields = ('project_id', 'created_by', 'created_by_id', 'created')

Enforcing the required=True at the Model level as well would require to override the .save function of the serializer if I insist on playing with the logic purely at the serializer level for deserialization. There might be a way to get the user ref within the serializer as well to keep the views implementation even more 'default'... This can be done by using the default value from Jerin:
class ProjectSerializer(serializers.ModelSerializer):

    created_by = UserSerializer(read_only=True)
    created_by_id = serializers.PrimaryKeyRelatedField(
    queryset=User.objects.all(), source='created_by',
                           write_only=True,
                           required=False,
                           default=serializers.CurrentUserDefault())

    class Meta:
        model = Project
        fields = ('project_id', 'created_by', 'created_by_id', 'created')

Now to flaten the json with username only, you need to use a slug field instead of the UserSerializer:
class ProjectSerializer(serializers.ModelSerializer):

    created_by = serializers.SlugRelatedField(
      queryset=User.objects.all(), slug_field="username")
    created_by_id = serializers.PrimaryKeyRelatedField(
      queryset=User.objects.all(), source='created_by', write_only=True, required=False)

    class Meta:
        model = Project
        fields = ('project_id', 'created_by', 'created_by_id', 'created')

And then only the username field value of the User Model will show at the create_by json tag on the get payload.
UPDATE - 1
After some more tweaking here is the final version I came up with:
class ProjectSerializer(serializers.ModelSerializer):

    created_by_id = serializers.PrimaryKeyRelatedField(
        queryset=User.objects.all(), write_only=True, required=False, default=serializers.CurrentUserDefault())
    created_by = serializers.SerializerMethodField('creator')

    def creator(self, obj):
        return obj.created_by_id.username

    class Meta:
        model = Project
        fields = ('project_id', 'created_by_id', 'created_by', 'created')


text:
Q: Oracle BI Publisher Report output is not opening in LibreOffice We are using Oracle BI Publisher as repoting tool.
We have designed the template in RTF format and uploaded into bi publisher also using the query to generate report output as Excel format.
But the excel output is not opening in LibreOffice 4.3.
How to open the excel output in LibreOffice 4.3.
any idea's please...
Thanks in Advance.

A: BI Publisher is not certified to export to LibreOffice.
That being said what is happening when you publish the report? Is it opening at all in any program?


text:
Q: How to express a fraction into product of two terms I want to express the following fraction:
$$x^2\left(\frac{y-1}{y+1}\right)^2+x\left(\frac{y-1}{y+1}\right) + 1$$ into
$$K(y-c)(y-d),$$ where $c$ and $d$ are zeroes of the above function. How can I do this decomposition?
The above function is a function of both $x$ and $y$, and $K$ is also a function of both $x$ and $y$. $c$ and $d$ are only function of $x$.

A: Such a decomposition is not possible.
Your first expression is undefined for $y=-1$ whereas your desired form $K(y-c)(y-d)$ is defined for all $y$. Therefore the two expressions cannot be equivalent. Of course, if you limit $x$ in some ways, such as $x=0$, your first expression does have a limit as $y$ approaches $-1$. But that is not the same thing and would only work for those special values of $x$.
The Fundamental Theorem of Algebra implies that any polynomial with complex coefficients can be written as a constant times the product of linear polynomials. But this applies to polynomials, whereas your expression is a rational expression of $y$, quite a different thing.


text:
Q: Utilizar TimeStamps para filtrar información de un DataFrame - Python Tengo este DataFrame que representa datos aproximadamente 200 mil líneas de mediciones de 1 min en 1 min
data                      rad     t_amb  pot       t_mod
2018-01-01 00:00:00 0.305   24.26746    3.0     22.396478
2018-01-01 00:01:00 0.300   23.57200    45.0    21.955995
2018-01-01 00:02:00 0.200   23.52663    28.4    22.239656
2018-01-01 00:03:00 -0.100  23.41020    30.5    21.658972
2018-01-01 00:04:00 -0.198  23.24851    23.1    21.378779

Necesito filtrar y crear 2 nuevos DataFrame en donde solo filtre las informaciones de 15 en 15 min, y de 60 en 60 min
Leí que lo ideal seria utilizar la función TimeStamps, por ejemplo algo así timeStamps = [1, 15, 60]
Pero no entiendo como funciona, me podrían ayudar por favor
Intento que hice
Voy a llamar a mi DataFrame de df_dados por ahora estoy aplicando este código:
df_dados['data'] = pd.to_datetime(df_dados['data'])
df = df_dados.resample('60min', on='data').mean()
df.head(40)

Si bien, el código me filtra las los valores en 60 min pero me promedia los otras variables rad,t_amb,pot,t_mod lo cual necesito que mantengan sus valores de la fila

A: La forma de hacer esto es usando la instrucción .asfreq con los modificadores de tiempo adecuados (en tu caso '15min', y 'H'). Puedes aprender más sobre esta función aquí: función .asfreq
y sobre los modificadores de tiempo en este enlace:
valores válidos de modificadores temporales
Yo he hecho varias pruebas con un dataframe como el de siguiente:
                     time     open     high  ...  tick_volume  spread  real_volume
0     2021-01-04 00:00:00  1.22393  1.22414  ...          136       3            0
1     2021-01-04 00:05:00  1.22311  1.22319  ...           29      37            0
2     2021-01-04 00:10:00  1.22315  1.22315  ...           43      34            0
3     2021-01-04 00:15:00  1.22310  1.22356  ...           29      16            0
4     2021-01-04 00:20:00  1.22343  1.22344  ...           30      17            0
...                   ...      ...      ...  ...          ...     ...          ...
54388 2021-09-23 22:05:00  1.17473  1.17483  ...          114       0            0
54389 2021-09-23 22:10:00  1.17477  1.17478  ...          109       0            0
54390 2021-09-23 22:15:00  1.17468  1.17487  ...           94       0            0
54391 2021-09-23 22:20:00  1.17482  1.17489  ...           68       0            0
54392 2021-09-23 22:25:00  1.17475  1.17475  ...           77       0            0

[54393 rows x 8 columns]

Como se puede apreciar, el índice no es la columna 'time', así que aplicamos
df = df.set_index('time'), y obtenemos como salida un nuevo DataFrame:
                        open     high  ...  spread  real_volume
time                                   ...
2021-01-04 00:00:00  1.22393  1.22414  ...       3            0
2021-01-04 00:05:00  1.22311  1.22319  ...      37            0
2021-01-04 00:10:00  1.22315  1.22315  ...      34            0
2021-01-04 00:15:00  1.22310  1.22356  ...      16            0
2021-01-04 00:20:00  1.22343  1.22344  ...      17            0
...                      ...      ...  ...     ...          ...
2021-09-23 22:05:00  1.17473  1.17483  ...       0            0
2021-09-23 22:10:00  1.17477  1.17478  ...       0            0
2021-09-23 22:15:00  1.17468  1.17487  ...       0            0
2021-09-23 22:20:00  1.17482  1.17489  ...       0            0
2021-09-23 22:25:00  1.17475  1.17475  ...       0            0

A continuación ya puedes filtrar por el tiempo que necesites:
df = df.asfreq('30min') nos dará como resultado:
                        open     high  ...  spread  real_volume
time                                   ...
2021-01-04 00:00:00  1.22393  1.22414  ...     3.0          0.0
2021-01-04 00:30:00  1.22370  1.22399  ...     3.0          0.0
2021-01-04 01:00:00  1.22332  1.22412  ...     0.0          0.0
2021-01-04 01:30:00  1.22401  1.22440  ...     0.0          0.0
2021-01-04 02:00:00  1.22502  1.22502  ...     0.0          0.0
...                      ...      ...  ...     ...          ...
2021-09-23 20:00:00  1.17442  1.17458  ...     0.0          0.0
2021-09-23 20:30:00  1.17453  1.17463  ...     0.0          0.0
2021-09-23 21:00:00  1.17488  1.17488  ...     0.0          0.0
2021-09-23 21:30:00  1.17452  1.17461  ...     0.0          0.0
2021-09-23 22:00:00  1.17468  1.17476  ...     0.0          0.0

Atención, haciendo esto estamos modificando el DataFrame original, por lo que los datos se modifican para siempre, y si ahora quieres recuperar los datos de 15 minutos, habrás perdido información y obtendrás esto:
                        open     high  ...  spread  real_volume
time                                   ...
2021-01-04 00:00:00  1.22393  1.22414  ...     3.0          0.0
2021-01-04 00:15:00      NaN      NaN  ...     NaN          NaN
2021-01-04 00:30:00  1.22370  1.22399  ...     3.0          0.0
2021-01-04 00:45:00      NaN      NaN  ...     NaN          NaN
2021-01-04 01:00:00  1.22332  1.22412  ...     0.0          0.0
...                      ...      ...  ...     ...          ...
2021-09-23 21:00:00  1.17488  1.17488  ...     0.0          0.0
2021-09-23 21:15:00      NaN      NaN  ...     NaN          NaN
2021-09-23 21:30:00  1.17452  1.17461  ...     0.0          0.0
2021-09-23 21:45:00      NaN      NaN  ...     NaN          NaN
2021-09-23 22:00:00  1.17468  1.17476  ...     0.0          0.0

Espero que te sirva para seguir tu proyecto.


text:
Q: use php script to run schedule job I have followed the solution in How to cause a redirect to occur before php script finishes? to make a page will follow schedule to sent email to prevent exceed sending limit of Gmail. The loop works and it can stop after a specific number of emails sent. but the link cannot be redirected until all the code loaded. And is it ok if the code will run for around 6 days?
<?php
//Redirect to messageToUser.php
header("Location: show_message.php");
//Erase the output buffer
ob_end_clean();
//Tell the browser that the connection's closed
header("Connection: close");

//Ignore the user's abort (which we caused with the redirect).
ignore_user_abort(true);

//Extend time limit to 30 minutes
set_time_limit(0);
//Extend memory limit to 10MB
ini_set("memory_limit","10M");
//Start output buffering again
ob_start();

//Tell the browser we're serious... there's really
//nothing else to receive from this page.
header("Content-Length: 0");

//Send the output buffer and turn output buffering off.
ob_end_flush();
//Yes... flush again.
flush();

//Close the session.
session_write_close();

/*---function start---*/

file_put_contents("gate.cfg","Y");
include 'header.php';
$foreword = $footer = "";
$send = $_SESSION['send_template']; //get newsletter information
$news_id = $send['news_id'];
if ($conn){
    $sql = "select * from newsCat as n1, newsletter as n2 left outer join schedule as s on n2.news_id = s.news_id where n1.news_id = n2.news_id and n2.news_id = $news_id"; //check newsletter stage -- P:processing / F: finish / Null: not sent
    $result = mysql_query($sql,$conn);
    if (mysql_num_rows($result) != 0) { //get newsletter information
        $array =  mysql_fetch_array($result);
        $subject = $array['title'];
        $parent_id = $array['cat_id'];
        $filename = "filemanager/file/newsletter/".$array['locat'].".txt";

        $sql = "select c.cat_id,name from category as c, parent as p where p.cat_id = c.cat_id and parent_id=$parent_id"; //get category name
        $result = mysql_query($sql,$conn);
        if (mysql_num_rows($result) != 0) {
            while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
                $category[$row['cat_id']] = $row['name'];
            }

        }
        //get newsletter information
        $file_id = substr($array['locat'],4,10);
        $fp = fopen ($filename,"r"); //get newsletter content
        $contents = fread($fp, filesize($filename));
        $content = explode("", $contents);
        for ($i=0;$i<count($content);$i++){
            $content[$i] = explode("", $content[$i]);
            if ($i ==0 || $i == count($content)-1){
                $code[$content[$i][0]] = $content[$i][1];
            }else if ($content[$i][1] !=''){
                $code[$content[$i][0]] = "
".$category[$content[$i][0]]."
".$content[$i][1];
                $full_content .= $code[$content[$i][0]];
            }

        }
        if ($code['for']!=''){
            $foreword = "
$code[for]
";
        }
        if ($code['fot']!=''){
            $footer = "
$code[fot]
";
        }
        $full_content = $foreword.$full_content.$footer;
        if($array['processing'] == 'F'){
            header("Location: show_message.php?msg=2");
        }else{
            if (empty($array['processing'])){ //new schedule
                $sql = "create view sch_$file_id as select id,email,lname,title,count(*) as total from subscriber as s1, subscription as s2, category as c, parent as p where s1.id = s2.user_id and p.cat_id = c.cat_id and s2.cat_id = c.cat_id and parent_id = $parent_id group by id order by total desc;";
                $result = mysql_query($sql,$conn);
                $sql = "insert into schedule (news_id,processing) values ($news_id,'P')";
                $result = mysql_query($sql,$conn);
            }
            while(file_get_contents("gate.cfg")=="Y"){ //start get subscriber
                $sql = "select * from sch_$file_id as s1 left outer join sentRecord as s2 on s1.id= s2.user_id where news_id is null order by id limit 40";
                $result2 = mysql_query($sql,$conn);
                if (mysql_num_rows($result2) != 0) {
                    while ($row2 = mysql_fetch_array($result2, MYSQL_BOTH)) { //40 different subscribers
                        $body = '';
                        $to = $row2['email'];
                        $headers = "From:Biometrics Alerts <biometrics.alerts@gmail.com>\r\nMIME-Version : 1.0\r\nContent-type : text/html; charset=iso-8859-1\r\nReply-To:biometrics.alerts@gmail.com";
                        if ($row2['title']!='' && $row2['lname'] !=''){
                            $body ="
View this email in your browser

Dear ".ucfirst($row2['title']).". ".ucfirst($row2['lname']).",
";
                        }
                        $sentppl = false;
                        if ($row2['total']==12){ //full subscribe
                            $body .= $full_content;
                            $sentppl = true;
                        }else{
                            $body .= $foreword;
                            $sql = "select cat_id from subscription where user_id = $row2[id]";
                            $result3 = mysql_query($sql,$conn);
                            while ($row3 = mysql_fetch_array($result3, MYSQL_BOTH)) {
                                if($code[$row3['cat_id']] !=''){
                                    $body .= $code[$row3['cat_id']];
                                    $sentppl = true;
                                    $total++;
                                }
                            }
                        }
                        $body .= "$footer
If you wish to unsubscribe to IEEE Biometrics Compendium Alerts. Please click here.";
                        if ($sentppl){
                            /*send code*/
                            if (@mail($to,$subject,$body,$headers)){
                                $sql = "insert into sentRecord values ($news_id,$row2[id],'T')";
                                $result3 = mysql_query($sql,$conn);
                            }else{
                                $error = error_get_last();
                                $sql = "insert into sentRecord values ($news_id,$row2[id],'E')";
                                $result3 = mysql_query($sql,$conn);
                                $sql = "insert into errorRepord values ($news_id,$row2[id],'$error[message]')";
                                $result = mysql_query($sql,$conn);
                            }
                        }else{
                            $sql = "insert into errorRepord values ($news_id,$row2[id],'Subscriber does not subscribe in that category')";
                            $result = mysql_query($sql,$conn);
                        }
                    }
                    $sql = "select count(*) as total from sch_$file_id as s1 left outer join sentRecord as s2 on s1.id= s2.user_id where news_id is null order by id";
                    $result = mysql_query($sql,$conn);
                    $array =  mysql_fetch_array($result);
                    if ($array['total'] < 2900){ //control number
                        file_put_contents("gate.cfg","N");
                        $sql = "drop view sch_$file_id";
                        $result = mysql_query($sql,$conn); //delete view
                        $sql = "delete from sentRecord where news_id = $news_id";
                        $result = mysql_query($sql,$conn); //sent record
                        $sql = "update schedule set processing = 'F' where news_id = $news_id";
                        $result = mysql_query($sql,$conn); //update record
                        $date = date("Y-m-d H:i:s");
                        $sql = "update schedule set sent_date = '$date' where news_id = $news_id";
                        $result = mysql_query($sql,$conn); //update record

                    }
                }
                sleep(3); // set time period
            }
        }
    }else{
        header("Location: show_message.php?msg=1");//newsletter not find
    }
}else{
    // database error
    header("Location: show_message.php?msg=3");
}//end?>


text:
Q: runjags trouble locating JAGS - error "'where' not found" even after setting jagspath Seems that runjags suddenly (after update to version 2.0.3-2) has trouble finding JAGS binary, issuing an error:
[1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in system("where jags", intern = TRUE): 'where' not found

I fixed this by putting this line to my Rprofile:
.runjags.options <- list(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe")

This pretty much fixes the problem (although it is not ideal - previous versions of runjags could find the binary automatically).
However, when the Rgui (in Windows XP) is launched by opening an .Rdata file, which is associated to it, it stops working:
> .runjags.options # it was set in the Rprofile
$jagspath
[1] "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe"

> require(runjags)
Loading required package: runjags
Warning message:
package 'runjags' was built under R version 3.1.3
> runjags.getOption("jagspath")
[1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in system("where jags", intern = TRUE): 'where' not found

Is this a bug? How to fix this?
I am currently calling runjags.options(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe") in my source after require(runjags), but I would like to avoid this as much as possible!

A: The problem is in the findjags() function, more specifically use of the 'where' system command which was added to Windows in 2003 and therefore doesn't exist in Windows XP. There is some code in findjags() that is designed to detect earlier versions of Windows and revert to a different method of finding JAGS, but this hasn't changed since version 1.x so I don't know why this has 'suddenly' stopped working. Perhaps there has been a change in your system, or a change in the way the system() command works in R. I have modified this code to work around where I think the error is coming from, but I don't have access to Windows XP (I'm rather surprised that you do!) so I can't test it. I don't think it will do any harm though so I will include it in the next release anyway, after testing on more recent versions of Windows.
I also don't know exactly why the .runjags.options is not being found when you open a .Rdata file, but it is possible that opening a .Rdata file loads the library before setting objects. I will look into this but it is likely not something I can do anything about. The alternative to using runjags.options() is to set the jags argument in calls to run.jags etc.


text:
Q: Xamarin.iOS strange behavior for webview showing html5 contain video360 I have a webview showing URL containing HTML5 content with video 360
public class HybridWebViewRenderer : WkWebViewRenderer
    {

        WKUserContentController userController;

        public HybridWebViewRenderer() : this(new WKWebViewConfiguration())
        {
        }

        public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
        {
            userController = config.UserContentController;

        }

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                HybridWebView hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup();
            }

            if (e.NewElement != null)
            {
                BackgroundColor = UIColor.Clear;
                Opaque = false;
                Configuration.AllowsInlineMediaPlayback = true;
                Configuration.Preferences.JavaScriptEnabled = true;
                Configuration.Preferences.JavaScriptCanOpenWindowsAutomatically = true;
            }
        }

        public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
        {
            ((HybridWebView)Element).InvokeAction(message.Body.ToString());
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                ((HybridWebView)Element).Cleanup();
            }
            base.Dispose(disposing);
        }
    }

I got the video in the middle and when I double click on it
it shows as a separate window and could be closed

A: sorry I was mistaken of where to change configurations
it should be like that
public class HybridWebViewRenderer : WkWebViewRenderer
    {

        WKUserContentController userController;
        static WKWebViewConfiguration config = new WKWebViewConfiguration()
        {
            AllowsAirPlayForMediaPlayback = false,
            AllowsInlineMediaPlayback = true,
            Preferences = new WKPreferences()
            {
                JavaScriptCanOpenWindowsAutomatically = true,
                JavaScriptEnabled = true
            }
        };

        public HybridWebViewRenderer() : this(config)
        {
        }

        public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
        {
            userController = config.UserContentController;

        }

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                HybridWebView hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup();
            }

            if (e.NewElement != null)
            {
                BackgroundColor = UIColor.Clear;
                Opaque = false;

            }
        }

        public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
        {
            ((HybridWebView)Element).InvokeAction(message.Body.ToString());
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                ((HybridWebView)Element).Cleanup();
            }
            base.Dispose(disposing);
        }


text:
Q: Post method is getting bytes instead of json data I am making a post request from jquery to create an article in my blog.
//Responsible for creating an article
$('#create-article').click(function(e){
    title = $('#input-title').val()
    description = $('#input-desc').val()
    data = {title, description}
    $.post('/blog/create/', data, 'json')
    e.stopPropagation();
    e.preventDefault();
})

The View below is responsible for printing out the POST response. According to my POST submission, it should print out a json response but it is printing out a Python bytes. why is it happening?
@csrf_exempt
def create_article(request):
    if request.POST:
        print(request.body)
        return HttpResponseRedirect(reverse('home'))

Printing: b'title=hello+&description=world+there'
Expecting: {'title': 'hello', 'description': 'world there'}
What should i do to get the expected result?

A: Even though you are specifying that you are expecting the server to return JSON in the AJAX call, you still need to handle the return of JSON on the backend.  Right now request.body just returns whatever Python's default it, which isn't JSON.
import json

@csrf_exempt
def create_article(request):
    if request.POST:
        print 'Content-Type: application/json\n'
        print(json.dumps(request.body))
        return HttpResponseRedirect(reverse('home'))


text:
Q: In System.setProperty , project path is getting added before Chromedriver path in eclipse Exception is thrown as

"Exception in thread "main" java.lang.IllegalStateException: The
  driver executable does not exist:  C:\Users\Prasanna
  venkatesh\workspace2\TryProject1\H:\ExternalJar\chromedriver.exe"

for below line;
System.setProperty("webdriver.chrome.driver","H:\\ExternalJar\\chromedriver.exe");

If I copy the chrome driver into project src package and if i execute the below line, it works.
System.setProperty("webdriver.chrome.driver","chromedriver.exe");

Which means the project path is getting added before chromedriver.exe.
Can anyone please explain me why it is so?


text:
Q: whats the meaning of curl "-s" and "-m" I have found following in crontab
* * * * * sleep 5; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 10; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 15; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 20; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 25; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 30; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 35; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 40; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 45; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 50; curl -s -m 10 http://url > /dev/null 2>&1
* * * * * sleep 55; curl -s -m 10 http://url > /dev/null 2>&1

so whats the meaning of curl -s -m 10 here ?

A: If you take a look at the man page for curl, you'll see the following:
 -s, --silent
          Silent  or  quiet  mode. Don't show progress meter or error mes-
          sages.  Makes Curl mute. It will still output the data  you  ask
          for, potentially even to the terminal/stdout unless you redirect
          it.

And:
-m, --max-time <seconds>
          Maximum time in seconds that you allow the whole operation to take.  This is useful for preventing your batch jobs from hanging for hours due to slow networks or links going  down.   Since  7.32.0,  this
          option accepts decimal values, but the actual timeout will decrease in accuracy as the specified timeout increases in decimal precision.  See also the --connect-timeout option.

          If this option is used several times, the last one will be used.

So, curl -s -m 10 means that curl will not show progress or error messages, and will timeout after 10 seconds.

A: From man curl:
--snip--

-m, --max-time <seconds>

Maximum time in seconds that you allow the whole operation to take.  This is useful for preventing your batch jobs from hanging for hours due to  slow  networks or  links  going down.  Since 7.32.0, this option accepts decimal values, but the actual timeout will decrease in accuracy as the specified timeout increases in decimal precision. See also the --connect-timeout option.
If this option is used several times, the last one will be used.

--snip--

-s, --silent

Silent  or  quiet mode. Don't show progress meter or error messages.  Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.


text:
Q: Chrome Developer Tools add a SINGLE file to workspace not folder I'm doing some clean up work in the stylesheets. But there are some files that I don't want to touch by accident. So I don't want them to be editable. How can I add some files to the workspace but leave the rest of the files in the folder are not added.
Basically I want to achieve below;

A: DevTools technical writer here. It's not possible to choose which files are editable in Workspaces. The intended use of the feature is to persist any changes in a given directory to disk.
Maybe you'd prefer to use Local Overrides?
Also, a potential workaround could be to use chmod to disable write access on the files you don't want to touch...


text:
Q: Print one column of integers into multiple columns I would like to take a data file containing 9 numbers in a single column and print out 3 columns containing 3 numbers.
I have loaded the file but can only print a single column. Not sure what to do.
Integer[] Array = new Integer[9];
         int i = 0;

for (int x = 0; x < i; x++) {
    System.out.printf("%d\n",Array[x]);

A: Try something like this:
for (int x = 0; x < Array.length; x += 3) {
   System.out.printf("%d %d %d\n", Array[x], Array[x+1], Array[x+2]);
}

A: You could traverse through the loop and then number of column you want print them in single line and print newline once you got total column.
final int COLUMN =3; // define total number of column you want.

for (int x = 0; x < arr.length; x++) {
   System.out.print(arr[x] +" ");

   if((x+1)%COLUMN == 0)
      System.out.println();
}


text:
Q: C# Converting mixed JSON into an object Yo Guys,
I'm currently trying to pass some mixed JSON, and was wondering if it was possible to do anything like the following?
struct example_data
{
    public Dictionary<string, List<string>> information {get; set;}
}

class TestClass
{
    static void Main(string[] args)
    {
        string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }"

        example_data deserialized_entry = JsonConvert.DeserializeObject<example_data>(test_string)
    }
}

As you would expect the above code snippet fails, but I was hoping I could avoid wrapping each JSON entry in a JSON array or having to create a custom JSON reader in C#.
Any advice on the matter would be greatly appreciated.

A: Sounds like what you're looking for is to parse a JSON string into a dynamic object, like so:
dynamic myObject = JsonConvert.DeserializeObject(@"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }");

string desc = myObject.EventSpecificInformation.Description;
string longName = myObject.EventSpecificInformation["Long name"];

This is likely your best option if you don't have an explicit static model for your JSON input. For properties without a space in their name you can reference them directly using member access syntax, for those with a space you can reference them using indexer access syntax.

A:
As you would expect the above code snippet fails

string test_string = @"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }"

In the above you're clearly missing an ending ; at test_string assignment, this wont compile, fix this first (I'm sure it's a type-o). Next, this isn't valid json, you see all the ' in that json, it should be quotes: ". So in short, just replace the bad characters...
 string test_string = @"{'EventSpecificInformation':
                               {
                               'measure':''
                               ,'Long name':'test_name'
                               ,'Short name':'test_s_name'
                               ,'Description':''
                               ,'Status':'Real (Imported)'
                               ,'Viewers':['Everyone']
                               ,'Modifiers':['Supervisor only']
                               ,'calculation':''
                               }
                           }".Replace("'", "\"");

Note - As far as deserializing your json, create a new question with what you've tried (after fixing this), what isn't working and expected output; you've multiple issues, let's address one at a time.

A: You can push the results to Dictionary
string test_string = @"{'EventSpecificInformation':
                        {
                        'measure':''
                        ,'Long name':'test_name'
                        ,'Short name':'test_s_name'
                        ,'Description':''
                        ,'Status':'Real (Imported)'
                        ,'Viewers':['Everyone']
                        ,'Modifiers':['Supervisor only']
                        ,'calculation':''
                        }
                    }".Replace("'", "\"");

var results = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(test_string);

A: Assuming that you do not want to use a static model,the problem with the code is that it doesn't match signature of your Json. The Json comprises of a Dictionary<string,Dictionary<string,List<string>>. However, there is another concern.
Some of the values in inner Dictionary is not List<string>. Instead, they are strings. For example,
'Short name':'test_s_name'

For this purpose you need to use a a Custom JsonConverter which if the values is not a array, converts the single string value to list. For example, consider the following Custom JsonConverter.
class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

Now, you could deserialize your Json as
string test_string = @"{'EventSpecificInformation':
                                   {
                                   'measure':''
                                   ,'Long name':'test_name'
                                   ,'Short name':'test_s_name'
                                   ,'Description':''
                                   ,'Status':'Real (Imported)'
                                   ,'Viewers':['Everyone']
                                   ,'Modifiers':['Supervisor only']
                                   ,'calculation':''
                                   }
                               }";

var deserialized_entry = JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string, List<string>>>>(test_string,new SingleOrArrayConverter<string>());

Output


text:
Q: a generic dialog load routine i have alot of dialog in my winform app and i do this for each one of them when i need to load
Dim frm As New Settings
        frm.ShowDialog()
        frm = Nothing

i was thinking if its possible to have a routine like this
sub LoadDialog(byval item as form)
' code to load specific form passd here
end sub

then i call like this loadDialog(customersDialog). where the CustomerDialog is a form
an idea on how to do this?

A: You can make a generic procedure to handle this:
Public Shared Sub LoadAndShowDialog(Of T As {Form, New})()
    Dim frm As New T
    frm.ShowDialog()
End Function

You could then call this as:
LoadAndShowDialog(Of Settings)()

A: All forms inherit from Form right? Below should be fine. And if you need something from that form store it in the tag and you can retrieve it after the form closes.
Public Function LoadForm(MyForm As Form) As Object
    MyForm.ShowDialog()
    Return MyForm.Tag
End Function


text:
Q: Bower package not found - necessary to use npm as well? I'm new to Bower, and I'm setting up a dummy project. I have initialised my project and installed jQuery and gulp just to get things started. This is fine, they have been added to my dependencies list in bower.json and are now present in my bower_modules folder. Great so far.
However, I want to install two plugins: main-bower-files and gulp-filter, but bower doesn't seem to have these libs.
When I run bower install --save main-bower-files, I get:

bower ENOTFOUND     Package main-bower-files not found

So, it seems my only solution is use npm instead. But surely bower is supposed to be an alternative to npm, right?
Or is the only solution just to npm init as well as bower init at the start of the project, and then run two lists of separate dependencies?
Any help appreciated.

A: Actually, Bower and NPM have slightly different aims.
In my experience, Bower focuses mainly on frontend packages (jQuery, CreateJS, ...). See it as an alternative of using an external CDN for certain resources. NPM, however, has most of those packages on Bower, and then a large selection of packages for the backend, as well.
You would indeed need to keep two separate dependency lists, if you need packages from both repositories. Using those two managers in tandem is actually not that uncommon.
Be sure to install gulp and its modules through NPM, since they are definitely not frontend resources.
TLDR: Bower = frontend resources that you could have also hosted on a CDN, NPM = everything from frontend to backend and more.


text:
Q: alternative to dict.update in python So I realized that
dict1.update(dict2)

replaces values of dict2 with dict1 if the key exists in both the dictionaries. Is there any way to add the values of dict2 to dict1 directly if the key is present instead of looping around the key,value pairs

A: You say you want to add the values, but not what type they are. If they are numeric, you may be able to use collections.Counter instead of dict
>>> from collections import Counter
>>> a = Counter({'a':1, 'b':2})
>>> b = Counter({'a':5.4, 'c':6})
>>> a + b
Counter({'a': 6.4, 'c': 6, 'b': 2})


text:
Q: Showing any metric space is a Hausdorff space
This is the question i've been given along with the solution i have written, however, could someone explain why showing $z \notin V$ shows any metric space is a Hausdorff space


text:
Q: How to overcome Ramsey Reset test without failing in R? I have a simple linear model with some independent variables including dummy variables for world regions. Unfortunately, the Ramsey Reset test in R rejects the null hypothesis that the model is correctly specified.
I then transformed all regressors and the independent variables to take a natural logarithm form. Nevertheless, the Ramsey Reset test still rejects the null hypothesis with almost unchanged low p-value. Which alternatives does one have to solve the misspecification of regression models?


text:
Q: multigrid 2-d restriction and interpolation How to build a restriction or interpolation matrices for 2-d problem for V-cycle multigrid. I read a lot of references about it, they only shows the coefficients matrix like following.
$$
        \begin{matrix}
        1/16 & 1/8 & 1/16 \\
        1/8 & 1/4 & 1/8 \\
        1/16 & 1/8 & 1/4 \\
        \end{matrix}
$$
For 1-d cases, I can easily build a interpolation matrix like(3 to 5):
$$
        \begin{matrix}
        1 &  &  \\
        2 &  &  \\
        1 & 1 & \\
 &2  &  \\
 & 1 &  \\
        \end{matrix}
$$
and do the transpose to get the restriction matrix and get the coarser mesh by A2h = RAI. And that only work for 1-D case. Here's the python code I used to do the multigrid example:
https://people.sc.fsu.edu/~jburkardt/py_src/gmgsolve/gmgsolve.py
For the 2-d case, I think I am supposed to use bilinear interpolation. But I don't know what the restriction and interpolation matrix look like. Does any one could show me a example, just like 9 to 5 restriction for 2-d case?


text:
Q: Calculating a non-overlapping moving average I'm trying to calculate a moving average of a timeseries in R, but I'm getting unsuccessful results.
Here is what I have done:
Sample vector:
library(gtools)
test <- sample(1:100, 50)

testrunning <- running(test, width=10, by=10, FUN=mean, trim=0, na.rm=TRUE)

It produces a result, but the result is not the average of the windows in my data; rather, it is an average of the window. Like so:
testrunning

## 1:10 11:20 21:30 31:40 41:50
## 5.5  15.5  25.5  35.5  45.5

A: I think I found the problem. It should be fun and not FUN:
running(test, width = 10, by = 10, fun = mean, trim = 0, na.rm = TRUE)

You could also do:
sapply(split(test, (seq_along(test) - 1) %/% 10), mean)


text:
Q: Public Folders not accessible to Outlook clients I've got a problem at the moment with my Exchange 2010 Server's Public Folders database - we had a VM issue over the weekend during some networking work and the Public Folders have been inaccessible since.

The main Mail Store was also inaccessible, but that was due to the RPC service on the CAS stopping - restarting that service recovered it.
I've tried dismounting the Public Folder database and remounting it, but that has made no difference.
I've also worked through the tutorials like this one - http://blog.bruteforcetech.com/archives/766 - but all the data is correct in ADSIEdit.
I've also worked through this Spiceworks thread and it doesn't fix anything - https://community.spiceworks.com/topic/170165-exchange-2010-public-folder-issue.
The Public Folders open fine in Public Folder Management Console.
Any suggestions?

A: I resolved the problem by restarting the DB server.
I wasn't aware that an Exchange DB server still relied on IIS (a cursory glance in IISAdmin showed just the Default Site, so I guess I assumed it wasn't used) and as I was just restarting the plethora of Microsoft Exchange services, I was missing the problem.


text:
Q: GCD of $N$ numbers is 1 Given two numbers $m$ and $n$.
$\gcd(a_{1},a_{2},\ldots,a_{m})$ is the gcd of number $a_{1},a_{2},\ldots,a_{m}$.
How to find number of ways such that $\gcd(a_{1},a_{2},\ldots,a_{m})$ ($1\le a_{i}\le n$ ) is $1$?

A: Once $m$ is not very small, it will be almost $n \choose m$  The chance that $2$ is a factor of the GCD is roughly $2^{-m}$.  For other primes, it is even smaller.  An inclusion/exclusion argument says it is about $${n \choose m}\left(1- \sum_{p\  prime} p^{-m} + \sum_{p,q\  prime} (pq)^{-m}-\dots\right)$$


text:
Q: GC overhead limit exceeded in Android Studio After some update of Android Studio I can't build signed APK because it fails with "GC overhead limit exceeded". I tried to add

dexOptions {
          javaMaxHeapSize "4g"
  }

but it doesn't help. Any other options to how fix it?

A: did you try adding org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError in gradle.properties?


text:
Q: Pass javascript variable in twig to php controller on button click I have Google maps and a rectangle highlighting some area on top of the map. NorthEast and Southwest latitudes of that rectangle are stored as javascript variables(ne,sw).I want to send those parameters to a php controller on button click, like this:
View
How can I do that? I d'ont have knowledge of AJAX nor JQuery.
{% extends 'base.html.twig' %}

{% block body %}

var ne;
var sw;

View

{% endblock %}

Please excuse my bad syntax. I'm new to PHP and Symfony.

A: Assuming that your code is working you can do this easily with jquery:

So you send your vars ne sw by POST to your controller. In your controller you can get it by your request object: $request->get('data');
If you want you can send back a response data to the AJAX function to inform all was ok, using Symfony\Component\HttpFoundation\JsonResponse;
In your Symfony controller:
use Symfony\Component\HttpFoundation\JsonResponse;

class YourController extends Controller
{
    public function yourAction() {
        $data = $this->getRequest()->get('data');
        var_dump($data); // Here you can see your vars sent by AJAX
        $dataResponse = array("error" => false); //Here data you can send back
        return new JsonResponse($dataResponse);
    }
}

If you do this you must to configure your jquery AJAX function to receive json data:
    $.ajax({
       url: 'Controller/SatelliteImages_Controller.php',
       type: "post",
       data: neSw,
       dataType: 'json'
    })


text:
Q: Find all the user defined public synonyms in a database i want to find all the user defined public synonyms but ALL_SYNONYMS is returning all synonyms created by oracle and users how to filter only user created synonyms from them

A: You may use any of these options.
If you know the names of the users who created the synonyms.
select * from all_synonyms where owner IN ('SCHEMA_USER1','SCHEMA_USER2');

If you are logged in as a particular user, then this will show all the synonymns
private to the user.
select * from user_synonyms;

If you are looking for only public synonyms, this query may be close to what you are looking for.
select * from all_synonyms where owner ='PUBLIC'

This would show synonyms on tables owned by system, sys etc.
You may exclude them using
select * from all_synonyms where owner ='PUBLIC' and
table_owner not IN ( 'SYS','SYSTEM') ;


text:
Q: how to refresh recyclerview after making some change on sqlite database My app has recyclerview in fragment and when I click one of the list inside recyclerview, on the next page, there is check button that I can update a value on sqlite database. With this updating, I can change order of list of recyclerview. Since sqlite database is not like firebase addlistener. It can not refresh database right away.
Is there any way to refresh list of recyclerview right away when I click back button to go to recyclerview page?
I googled and found some similar questions but I couldn't resolve my issue. Any help would be appreciated.
package com.donghyouny.biblecard;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;

import java.util.ArrayList;

public class BibleAdapter extends RecyclerView.Adapter<BibleAdapter.BibleViewHolder> {

    private  ArrayList<Bible> arrayList;
    private  Context context;
    private OnVerseItemClickListener listener;

    public BibleAdapter(ArrayList<Bible> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }

    public void setOnItemClickListener(OnVerseItemClickListener listener){
        this.listener = listener;
    }

    @NonNull
    @Override
    public BibleAdapter.BibleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.verse_item, parent, false);
        BibleViewHolder holder = new BibleViewHolder(view, listener);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull BibleAdapter.BibleViewHolder holder, int position) {

      /* RequestOptions reqOpt = RequestOptions
                .fitCenterTransform()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(140,100);

                   .apply(reqOpt)
*/

        Glide.with(holder.imageView)
                .load(arrayList.get(position).getImage())
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(holder.imageView);

        //Glide.with(PersonInfoActivity.this).load(R.drawable.standard_profile).apply(new RequestOptions().centerCrop()).into(imageView);
       // holder.imageView.setImageResource(R.drawable.church);

        holder.bibleType.setText(arrayList.get(position).getBibleType());
        holder.content.setText(arrayList.get(position).getContent());
        holder.verse.setText(arrayList.get(position).getVerse());

    }

    @Override
    public int getItemCount() {
        return (arrayList!=null? arrayList.size():0);
    }

    public void setList(ArrayList<Bible> list ) { this.arrayList = list; }

    public class BibleViewHolder extends RecyclerView.ViewHolder{

        ImageView imageView;
        TextView bibleType;
        TextView verse;
        TextView content;
        ImageView save;

        public BibleViewHolder(@NonNull View itemView, final OnVerseItemClickListener listener) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.imageView);
            this.bibleType = itemView.findViewById(R.id.bibleType);
            this.content = itemView.findViewById(R.id.content);
            this.verse = itemView.findViewById(R.id.verse);
            this.save = itemView.findViewById(R.id.save);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if(listener != null){
                        listener.onItemClick(BibleViewHolder.this, v, position);
                    }
                }
            });
        }

    }
}

 Cursor readAllData(String value){
        Log.d("readData", "test");
        String query = "select Id,BibleType, Verse, Content, Num, CNum, CheckNum, Image, datetime(TimeStamp) as MyDate  from bible where CNum=" + "(select Id from category where CategoryName='" + value + "') order by TimeStamp asc";
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if(db != null){
            Log.d("readData1","test");
            cursor = db.rawQuery(query, null);
        }
        return cursor;
    }

void updateData(Bible bible){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        String id = String.valueOf(bible.getId());
        cv.put(COLUMN_TIMESTAMP, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        long result = db.update(TABLE_BIBLE, cv, "Id=?", new String[]{id});
        if(result == -1){

        }else {
           Log.d("update", "success")
        }

    }

package com.donghyouny.biblecard;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;

import static com.donghyouny.biblecard.SplashActivity.ROOT_DIR;

public class Fragment1 extends Fragment {

    public static final String VERSE_DATA = "data";
    public static final int REQUEST_CODE = 101;
    private RecyclerView recyclerView;
    private BibleAdapter adapter;
    private LinearLayoutManager mLayoutManager; //for sorting
    private ArrayList<Bible> bList = new ArrayList<>();
    private Connection conn;
    private Statement stmt;
    private ResultSet rs, rs2;
    private Bible bible;
    private String value;
    private InterstitialAd mInterstitialAd;

    public Fragment1(String value) {
        this.value = value;
    }
    public Fragment1(){

    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_1, container, false);

        conn = Utiles.dbConnection();

       MyDatabaseHelper myDB = new MyDatabaseHelper(getActivity());
       Cursor cursor = myDB.readAllData(value);
       while(cursor.moveToNext()){
           bible = new Bible();
           Log.d("cursorid", String.valueOf(cursor.getInt(0)));
           bible.setId(cursor.getInt(0));
           bible.setBibleType(cursor.getString(1));
           bible.setVerse(cursor.getString(2));
           bible.setContent(cursor.getString(3));
           bible.setNum(cursor.getInt(4));
           bible.setCnum(cursor.getInt(5));
           bible.setCheckNum(cursor.getInt(6));
           bible.setImage(cursor.getBlob(7));
           bible.setTimestamp(cursor.getString(8));
           bList.add(bible);
       }

        Log.d("blist", bList.toString());
        recyclerView = rootView.findViewById(R.id.recyclerView);
        //recyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(mLayoutManager);
        adapter = new BibleAdapter(bList, getContext());
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        adapter.setOnItemClickListener(new OnVerseItemClickListener() {

                    @Override
                    public void onItemClick(BibleAdapter.BibleViewHolder holder, View view, final int position) {     //Toast.makeText(getContext(), "num"+adapter.getItemCount(), Toast.LENGTH_LONG).show();

                        if(mInterstitialAd.isLoaded()) {
                            // Step 1: Display the interstitial
                            mInterstitialAd.show();
                            // Step 2: Attach an AdListener
                            mInterstitialAd.setAdListener(new AdListener() {
                                @Override
                                public void onAdClosed() {

                                    Intent intent = new Intent(getContext(), VerseActivity.class);
                                    Log.d("bible33", bList.get(position).toString());
                                    intent.putExtra("bible", bList.get(position));
                                    intent.putExtra("category", value);
                                    Log.d("bibleIntent", bible.toString());

                                    startActivityForResult(intent, 1);
                                }
                            });
                        }else{
                            Intent intent = new Intent(getContext(), VerseActivity.class);
                            Log.d("bible33", bList.get(position).toString());
                            intent.putExtra("bible", bList.get(position));
                            intent.putExtra("category", value);
                            Log.d("bibleIntent", bible.toString());

                            startActivityForResult(intent, 1);
                        }

                    }
        });

        setHasOptionsMenu(true);
        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.actionbar_actions, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.save_folder:

                Intent intent = new Intent(getContext(), SaveActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                return true;

        }
        return super.onOptionsItemSelected(item);
    }

    }
}

package com.donghyouny.biblecard;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.donghyouny.biblecard.SplashActivity.ROOT_DIR;

public class VerseActivity extends AppCompatActivity {

    private ImageView imageView;
    private TextView bibleType;
    private TextView verse;
    private TextView content;
    public Bible bible;

    private ImageView save, check;

    private String category;
    private Toolbar toolbar;

    private Statement stmt;
    private ResultSet rs;
    private SharedPreferences checkDialog;
    private SharedPreferences saveDialog;
    private SharedPreferences shareDialog;
    private AdView mAdView;
    private boolean flag=true;
    private Fragment1 fragment1;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_verse);

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        mAdView = findViewById(R.id.adbanner);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        fragment1 = new Fragment1();
        bibleType = findViewById(R.id.bibleType);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        verse = findViewById(R.id.verse);
        content = findViewById(R.id.content);
        imageView = findViewById(R.id.imageView);
        save = findViewById(R.id.save);
        check = findViewById(R.id.check);
        //   category = findViewById(R.id.category);
        //key = getIntent().getStringExtra("key");

        if((getIntent().getParcelableExtra("bible")!=null)&& (getIntent().getStringExtra("category")!=null)){
            Log.d("nocard", "Test");

            bible = getIntent().getParcelableExtra("bible");
            category = getIntent().getStringExtra("category");
            Log.d("!!!bible", bible.toString());

            display();

        }else if((getIntent().getParcelableExtra("cardBible")!=null)&& (getIntent().getStringExtra("cName")!=null)){
            Log.d("cardop", "test");
            check.setVisibility(View.INVISIBLE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)save.getLayoutParams();
            //lp.rightMargin=0;
            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,0);
            lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
            save.setLayoutParams(lp);
            bible = getIntent().getParcelableExtra("cardBible");
            //Log.d("bible.key", bible.getKey());
            category = getIntent().getStringExtra("cName");
            display();

        }

        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkDialog = getSharedPreferences("checkDialog", MODE_PRIVATE);
                boolean isFirstTime = checkDialog.getBoolean("firstTime", true);
                if (isFirstTime) {
                    checkDialogPopup();
                } else {
                    checkMethod(bible);
                }
            }
        });

    }
    private void checkMethod(Bible bible) {
        MyDatabaseHelper db = new MyDatabaseHelper(VerseActivity.this);
        db.updateData(bible);

        }
    private void checkDialogPopup() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogCustom);
        builder.setTitle("Check button");
        builder.setMessage("You can not undo this button");
        builder.setPositiveButton("예",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"You click 'yes'",Toast.LENGTH_LONG).show();
                        checkMethod(bible);
                    }
                });
        builder.setNegativeButton("Don't show this message",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPreferences.Editor editor = checkDialog.edit();
                        editor.putBoolean("firstTime", false);
                        editor.commit();
                        Toast.makeText(getApplicationContext(),"Don't want to see this message",Toast.LENGTH_LONG).show();
                    }
                });
        builder.show();
    }

    double getScreenInches() {

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        double wi = (double) width / (double) dm.xdpi;
        double hi = (double) height / (double) dm.ydpi;
        double x = Math.pow(wi, 2);
        double y = Math.pow(hi, 2);
        double screenInches = Math.sqrt(x + y);

        return screenInches;
    }
    private void display(){
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
        params.width = metrics.widthPixels;
        params.height = (int)(metrics.heightPixels/2.8);
        Log.d("width", String.valueOf(params.width));
        Log.d("height", String.valueOf(params.height));
        imageView.setLayoutParams(params);

        Glide.with(getApplicationContext()).load(bible.getImage()).apply(new RequestOptions().centerCrop()).into(imageView);
        //imageView.setImageResource(R.drawable.church);
        bibleType.setText(bible.getBibleType().toString());
        verse.setText(bible.getVerse().toString());
        content.setText(bible.getContent().toString());

        Log.d("content", bible.getContent().toString());
        int inch = (int)( getScreenInches()+0.5 );
        Log.d("inch", String.valueOf(3*inch));
        //content.setTextSize(3*inch);
        toolbar.setTitle(category);

   }

    }

A: You can take the data from the database and list process in a separate function. you can call this function in the onResume() method. I think you should research the android life cycle. Reference Link is : https://developer.android.com/guide/components/activities/activity-lifecycle
According to the definition in the documentation
onResume() : When the activity enters the Resumed state, it comes to the foreground, and then the system invokes the onResume() callback. This is the state in which the app interacts with the user. The app stays in this state until something happens to take focus away from the app. Such an event might be, for instance, receiving a phone call, the user's navigating to another activity, or the device screen's turning off.
For example:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_1, container, false);

conn = Utiles.dbConnection();

recyclerView = rootView.findViewById(R.id.recyclerView);
//recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
adapter = new BibleAdapter(bList, getContext());
recyclerView.setAdapter(adapter);

adapter.setOnItemClickListener(new OnVerseItemClickListener() {

            @Override
            public void onItemClick(BibleAdapter.BibleViewHolder holder, View view, final int position) {     //Toast.makeText(getContext(), "num"+adapter.getItemCount(), Toast.LENGTH_LONG).show();

                if(mInterstitialAd.isLoaded()) {
                    // Step 1: Display the interstitial
                    mInterstitialAd.show();
                    // Step 2: Attach an AdListener
                    mInterstitialAd.setAdListener(new AdListener() {
                        @Override
                        public void onAdClosed() {

                            Intent intent = new Intent(getContext(), VerseActivity.class);
                            Log.d("bible33", bList.get(position).toString());
                            intent.putExtra("bible", bList.get(position));
                            intent.putExtra("category", value);
                            Log.d("bibleIntent", bible.toString());

                            startActivityForResult(intent, 1);
                        }
                    });
                }else{
                    Intent intent = new Intent(getContext(), VerseActivity.class);
                    Log.d("bible33", bList.get(position).toString());
                    intent.putExtra("bible", bList.get(position));
                    intent.putExtra("category", value);
                    Log.d("bibleIntent", bible.toString());

                    startActivityForResult(intent, 1);
                }

            }
});

setHasOptionsMenu(true);
return rootView;

}
public void fetchDataFromSqliteDatabase() {
    MyDatabaseHelper myDB = new MyDatabaseHelper(getActivity());
    Cursor cursor = myDB.readAllData(value);
    while(cursor.moveToNext()){
        bible = new Bible();
        Log.d("cursorid", String.valueOf(cursor.getInt(0)));
        bible.setId(cursor.getInt(0));
        bible.setBibleType(cursor.getString(1));
        bible.setVerse(cursor.getString(2));
        bible.setContent(cursor.getString(3));
        bible.setNum(cursor.getInt(4));
        bible.setCnum(cursor.getInt(5));
        bible.setCheckNum(cursor.getInt(6));
        bible.setImage(cursor.getBlob(7));
        bible.setTimestamp(cursor.getString(8));
        bList.add(bible);
    }
    adapter.setList(bList);
    adapter.notifyDataSetChanged();
}

then you can call it from onResume()
@Override
public void onResume() {
    super.onResume();
    fetchDataFromSqliteDatabase();
}

also you should create a new method named setList. you should give this method a list as a parameter.


text:
Q: Different actions for the embedded and the containing element I have an anchor in a table. I would need an action for the click on the anchor, and another for the click on the table ('s cell). But if I click on the anchor, both of the actions will be run off. How can I disable the table's action when I click on the anchor?
Thank you!

A: try this:
$('anchor').bind('click', function(ev) {

  ev.stopPropagation();

  //... your code

  return false;

});


text:
Q: In Rails, how can I pass a logged in user's password in a hidden field in a form? I have a dwelling object that is built on a user.
Dwellings Controller (create action)
# dwellings_controller.rb
def create
  @dwelling = current_user.properties.build(params[:dwelling])

  if @dwelling.save
    current_user.dwelling = @dwelling
    if current_user.save!
      flash[:success] = "Woohoo! Your dwelling has been created. Welcome home!"
    else
      flash[:notice] = "You have successfully created a dwelling, but something prevented us from adding you as a roomie. Please email support so we can try to correct this for you."
    end
      redirect_to current_user
    else
      render 'new'
    end
  end

The dwelling_id is not being saved to the current_user record. To get more information, I added the bang method (as shown above) to the current_user.save! command. Rails complains that the user's password is required to update the record, as shown below.
ActiveRecord::RecordInvalid in DwellingsController#create

Validation failed: Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank

If providing the user's password through a hidden field isn't the correct solution - and it does seem insecure - how can I correct this problem? Relevant sections of the user and dwelling model shown below.
#dwelling.rb
class Dwelling < ActiveRecord::Base
  attr_accessible :street_address, :city, :state, :zip, :nickname

  belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
  has_many :roomies, :class_name => "User"

#user.rb
class User < ActiveRecord::Base
  attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :zip, :dwelling_id
  has_secure_password

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  belongs_to :dwelling
  has_many :properties, :class_name => "Dwelling", :foreign_key => "owner_id"

A: Turns out the problem was stemming from my validations in the User model. The presence and length validations on password and password_confirmation were being imposed on user.save, which was failing as password and password_confirmation were not being provided. My update validations appear below.
User Model
#user.rb
class User < ActiveRecord::Base
  attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :zip, :dwelling_id
  has_secure_password

  before_save { |user| user.email = email.downcase }
  before_create :create_remember_token

  belongs_to :dwelling
  has_many :properties, :class_name => "Dwelling", :foreign_key => "owner_id"

  validates :first_name, presence: true, length: { maximum: 50 }
  validates :last_name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true,
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: { case_sensitive: false }
  validates :password, presence: { :on => :create }, length: { minimum: 6, :on => :create }
  validates :password_confirmation, presence: { :on => :create }

With this updated implementation, the user is successfully saved and the appropriate attributes are updated. This is a secondary issue stemming from this original question: In Rails, how can I automatically update a User to own a newly created object of another class within the new object's Create method?

A: You can't assign the password anywhere in the form, simply because the user's password is saved in the database (via has_secure_password) in an encrypted password digest format which cannot be decrypted. (The password is saved with one way encryption.) So there is no way to get the password out to put in anywhere in a form's hidden field (which would be a bad idea anyway).
Inspect your current_user in the log (logger.debug current_user) to see if current_user has a valid user (with a password) assigned to it.


text:
Q: Flex AdvancedDataGrid HierarchicalData XML results in unwanted rows I guess the best way to explain my issue is to describe it in terms of the hierarchical XML data example on Livedocs.
Here, the XML is of the form
<Region Region="Arizona">
    <Territory_Rep Territory_Rep="Barbara Jennings" Actual="38865" Estimate="40000"/>
    <Territory_Rep Territory_Rep="Dana Binn" Actual="29885" Estimate="30000"/>
</Region>

However, the data I have is more like:
<Region Region="Arizona">
    <Territory_Rep Territory_Rep="Barbara Jennings">
        <Actual>38865</Actual>
        <Estimate>40000</Estimate>
    </Territory_Rep>
    <Territory_Rep Territory_Rep="Dana Binn">
        <Actual>29885</Actual>
        <Estimate>30000</Estimate>
    </Territory_Rep>
</Region>

And I would programmatically create the columns like so:
var cols:Array = [];

var adgColumn:AdvancedDataGridColumn = new AdvancedDataGridColumn();
adgColumn.headerText = "Rep Name";
adgColumn.dataField  = "@Territory_Rep";
cols.push(adgColumn);

adgColumn = new AdvancedDataGridColumn();
adgColumn.headerText = "Actual";
adgColumn.dataField  = "Actual";
cols.push(adgColumn);

adgColumn = new AdvancedDataGridColumn();
adgColumn.headerText = "Estimate";
adgColumn.dataField  = "Estimate";
cols.push(adgColumn);

grid.columns = cols;
grid.validateNow();

However, this would result in the reps appearing as branch nodes (i.e. folders), with some empty leaf nodes underneath.  This is clearly not what I want - I need it to still look as it does in the example.
Obviously I could solve this by writing some code - the simplest ways being to change the XML (be that at source, or with a parser in my Flex app), or to parse it then dump the required data into an ArrayCollection instead, but is there no way to get this to work out of the box?  Given I've instructed the AdvancedDataGrid to use all the child elements on a single row, why can't it then ignore them from a hierarchy point of view?
Since the AdvancedDataGrid seems to have a few other annoying issues (e.g. question 3517769) is my best bet simply to create my own class that does everything I want it to?  Or are there some decent workarounds that I'm not aware of?
Cheers.

A: I think this behaviour makes sense as effectively you have another level of hierarchy by structuring your XML as you do. So the cleanest solution would be to change that, or if you prefer it that way maybe to introduce a property to mark a branch as non-hierachial like this:
<Region Region="Arizona">
    <Territory_Rep Territory_Rep="Barbara Jennings" NonHierarchial="true">
        <Actual>38865</Actual>
        <Estimate>40000</Estimate>
    </Territory_Rep>
    <Territory_Rep Territory_Rep="Dana Binn" NonHierarchial="true">
        <Actual>29885</Actual>
        <Estimate>30000</Estimate>
    </Territory_Rep>
</Region>

and overriding the parsing method of the AdvancedDataGrid to look for this property.
Edit: you might be able to work around this playing with properties like childrenField in HierarchicalData object, dig around in the documentation a bit! See: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/collections/HierarchicalData.html#childrenField