text:
Q: ¿Cómo convertir 2 variables de un data frame a un objeto POSIXct con formato "%Y%m%d %H%M%S"? Dado el dataset beaver1 (Body Temperature Series of Two Beavers)
data.frame':    114 obs. of  4 variables:
 $ day  : num  346 346 346 346 346 346 346 346 346 346 ...
 $ time : num  840 850 900 910 920 930 940 950 1000 1010 ...
 $ temp : num  36.3 36.3 36.4 36.4 36.5 ...
 $ activ: num  0 0 0 0 0 0 0 0 0 0 ...

En donde
day.-es el Día de observación (desde principios de 1990)
time.- es la Hora de observación, en la forma 0330 para las 3:30 am
Quiero pasar las variables day y time a un objeto POSIXct para crear
un nuevo data frame "beaver" que contenga
 data.frame':   114 obs. of  3 variables:
 $ time : POSIXct, format "1990-12-12 08:40:00" "1990-12-12 08:50:00" "1990-12-12 09:00:00"   ...
 $ temp : num  36.3 36.3 36.4 36.4 36.5 ...
 $ activ: num  0 0 0 0 0 0 0 0 0 0 ...

He intentado
as.POSIXct(paste(beaver1$day,beaver1$time), format="%Y%m%d %H%M%S", origin="1990-01-01 00:00:00)

pero resulta en:
    [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [27] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [53] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
 [79] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[105] NA NA NA NA NA NA NA NA NA NA

Creo que mi error está en format="%Y%m%d %H%M%S", origin="1990-01-01 00:00:00", pero no sé como corregirlo
El siguiente paso sería unir este nuevo objeto al data frame beaver1 para crear "beaver", sin embargo
estoy atorado en el paso anterior.
Cualquier ayuda es bien recibida , gracias.

A: day según se lee en la ayuda sería el número de día desde principios de 1990, por lo que podemos hacer a partir de un POSIXct ir sumándole los días llevados a segundos:
fecha <- as.POSIXct('1989-12-31', format='%Y-%m-%d') + (beaver1$day * 24*60*60)

Con time podemos simplemente descomponer el número tal cual está documentado en la ayuda, para llegar también a un número de segundos:
fecha <- fecha +
         (beaver1$time %/% 100 + 24*(beaver1$day - beaver1$day[1]) +
         (beaver1$time %% 100)/60)*3600

Finalmente:
> head(fecha)
[1] "1990-12-12 08:40:00 -02" "1990-12-12 08:50:00 -02" "1990-12-12 09:00:00 -02"
[4] "1990-12-12 09:10:00 -02" "1990-12-12 09:20:00 -02" "1990-12-12 09:30:00 -02"


text:
Q: Шипы в профайлере Есть игра в ней довольно таки много объектов, они появляется и исчезают (делал пул но становилось только хуже).
Также все эти объекты движутся с помощью:
void Update()
{
    transform.position -= new Vector3(20 * Time.deltaTime, 0, 0);
}

Tris ~7.5k а Verts ~15k:

Настройки графики:

Также есть данные с профайлера в формате .data
которые можно загрузить в unity и посмотреть (только нужно сначала распаковать из 7z а то без сжатия они много весят)
данные: http://www.mediafire.com/file/pq3ocr5r1c1ix1w/Profiler_lags.7z/file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark Streaming Continuous Job I have a spark streaming job that implements a custom receiver.  This receiver gets records from a queue until the queue is exhausted (or an interval is met)  before returning those records to the host context to be written to a database.
Once these records are written, I want the host process to fire up a new receiver and continue processing,  how do I do this with the API?
The host process looks like this:
def main(args: Array[String]) {
  val config = new SparkConf()
  config.setAppName("Vehicle Data Queue Consumer")
  config.set("spark.driver.allowMultipleContexts", "true")

  val streamContext = new StreamingContext(config, Seconds(1) )

  val rStream = generateReceiverStream(streamContext)

  val sparkContext = new SparkContext(config)

  streamContext.start()

  streamContext.awaitTermination()
}

def generateReceiverStream(aContext: StreamingContext): ReceiverInputDStream[List[String]] = {

  val rmqReceiver = new RMQReceiver("amqp://myQueue")
  val customReceiverStream = aContext.receiverStream(rmqReceiver)

  val handler = (rdd: RDD[List[String]]) => this.handleStreamResult(rdd)

  customReceiverStream.foreachRDD(handler)

  return customReceiverStream
}

def handleStreamResult(rdd: RDD[List[String]]): Unit ={
  rdd.foreach { record =>
    record.foreach { aString =>
      println("****************************")
      println(s"$aString")
      println("****************************")
    }
  }
}

A: Receivers are instantiated once at the start of the streaming context and are expected to be 'alive' while the Spark Streaming job is active. Spark Streaming will use the onStart() and onStop methods on the receiver to manage its lifecycle.
In Spark Streaming, receivers should concurrently produce data while active. That is after the invocation to receiver.start() a custom receiver should create and manage their own threads where calls to store(...) will produce data for the logical DStream created from this receiver.
Spark Streaming will manage the receiver lifecycle to handle failure scenarios and the streamingContext.stop calls. It's therefore not necessary or even possible to 'fire up a new receiver' programmatically after the streaming context has been started.
Design and implement your custom receiver to follow this expected behavior and the job will run continuously without any further effort.


text:
Q: Ajax in Rails 4 not update the content I have the controller: "Likes" with action: "create"
def create
 @micropost = Micropost.find(params[:micropost_id])
 current_user.like(@micropost)
 @micropost.reload

 @likes = @micropost.count_likes

 respond_to do |format|
   format.html { redirect_to root_path }
   format.js
 end
end

This action will request json and update the view using ajax, the view will render correctly if I write:
$("#like_count-<%= @micropost.id %>").html('<%= @likes %>');

But writing:
$("#like_count-<%= @micropost.id %>").html('<%= @micropost.count_likes %>');

causes no effect. I also have checked that after @micropost.reload, the value of @micropost.count_likes has been updated. I don't know the reason why this happen. Hope you guys could help. Here is the source code of Micropost:
class Micropost < ActiveRecord::Base
 # micropost belong to one user
 belongs_to :user

 # many user can like one micropost
 has_many :user_likes, class_name: "Like",
       foreign_key: "micropost_id",
       dependent: :destroy
 has_many :likers, through: :user_likes, source: :user

 default_scope -> { order(created_at: :desc) }
 mount_uploader :picture, PictureUploader

 validates(:content, presence: true, length: {:maximum => 200})
 validates(:user_id, presence: true)
 validate :picture_size

 def count_likes
   user_likes.length > 0 ? "(#{user_likes.length})" : ""
 end

 private
 # Validates the size of an uploaded picture.
 def picture_size
   if picture.size > 1.megabytes
     errors.add(:picture, "should be less than 1MB")
  end
 end
end

Update
The form post request to Likes#create:
<%= form_for(micropost.user_likes.build, remote: true) do |f| %>

<%= hidden_field_tag :micropost_id, micropost.id %>

<%= f.submit "like", class: "btn btn-primary", style: "width: 100px" %>
<% end %>

The User class:
class User < ActiveRecord::Base
...
# user can like many microposts
has_many :pos_likes, class_name: "Like",
       foreign_key: "user_id",
       dependent: :destroy
has_many :fav_posts, through: :pos_likes, source: :micropost
...
# like a post
def like(micropost)
   self.pos_likes.create(user_id: self.id, micropost_id: micropost.id)
end

A: The issue here is in using #length instead of #count method.
Below there is a good explanation of the difference between them:
Difference between size, length and count in complicated ActiveRecord case
So to fix it you need to use user_likes.count instead of user_likes.length at your Micropost#count_likes


text:
Q: PHP strip_tags not allowing less than '<' in string Please let me know how to allow less than character '<' in strip_tags()
Code Snippet
$string ="abc<123";
StringFromUser($string);

function StringFromUser($string)
{

    if (is_string($string))
    {
        return strip_tags($string);

    }

}

Output : abc
Expected output abc<123

A: Encode it properly in the first place.
$string ="abc<123";

Although if you're not sanitizing for HTML output you shouldn't be using strip_tags() anyway.

A: strip_tags is a pretty basic and not very good way to sanitize data (i.e. "punch arbitrary values into shape"). Again, it's not a very good function, as you are seeing. You should only sanitize data if you have a very good reason to, oftentimes there is no good reason. Ask yourself what you are gaining from arbitrarily stripping out parts of a value.
You either want to validate or escape to avoid syntax problems and/or injection attacks. Sanitization is rarely the right thing to do. Read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for more background on the whole topic.

A: You could search for a character in your string, take it out, strip_tags() your string and put the character back in:
$string = "abc<123";
$character = "<";
$pos = strpos($string,$character);
$tag = ">";
$check = strpos($string,$tag);
if ($pos !== false && $check == false) {
    $string_array = explode("<",$string);
    $string = $string_array[0];
    $string .= $string_array[1];
    $string = strip_tags($string);
    $length = strlen($string);
    $substr = substr($string, 0, $pos);
    $substr .= "<";
    $substr .= substr($string, $pos, $length);

    $string = $substr;
} else {
    $string = strip_tags($string);
}

or you could use preg_replace() to replace all the characters you don't want to have in your $string.

A: The problem:
The purpose to use trip_tags is to prevent attacking from HTML or PHP injection. However, trip_tags not only removes HTML and PHP tags, it also removes part of a math expression with a < operator. So, what we see is "abc<123" being replaced to "abc".
The solution:
What we know is a < followed by a space is not identified as HTML or PHP tags by strip_tags. So what I do is to replace "abc<123" to "abc< myUniqueID123". Please note there is a space followed the < sign. And also, only numbers followed the < sign are replaced. Next, strip_tags the string. Finally, replace "abc< myUniqueID123" back to "abc<123".
$string = "abc<123";
echo StringFromUser($string);

function StringFromUser($string)
{
    if (is_string($string)) {
        //change "abc<123" to "abc< myUniqueID123", so math expressions are not stripped.
        //use myQuniqueID to identity what we have changed later.
        $string = preg_replace("/(<)(\d)/", "$1 myUniqueID$2", $string);
        $string = strip_tags($string);
        //change "abc< myUniqueID123" back to "abc<123"
        $string = preg_replace("/(<) myUniqueID(\d)/", "$1$2", $string);
        return $string;
    }
}


text:
Q: Executing a UiPath activity from C# causes null pointer exception For UiPath version 18.2.3 I successfully created a new logging activity. The idea is, while logging everything in Orchestrator, the new activity would in addition log in a file as well. Coming up our organization will upgrade to UiPath 2019.4.3 and my activity did not work, so I needed to upgrade the UiPath references to current dlls. Doing that gives me a compilable code, but the activity causes a null-pointer exception. Why?
This is my code:
using System;
using System.Activities;
using System.Activities.Presentation.Metadata;
using System.ComponentModel;
using System.IO;
using System.Text;
using UiPath.Core.Activities;

namespace CustomCode.Log
{
    /// <summary>
    /// Designer attribute gives a look & feel like UiPaths own LogMessage activity
    /// </summary>
    [Designer(typeof(UiPath.Core.Activities.Design.LogDesigner))]
    public class LogMessage : CodeActivity, IRegisterMetadata
    {
        [Category("Input")]
        public CurentLogLevel Level { get; set; }

        [Category("Input")]
        public InArgument<System.String> Message { get; set; }

        [Category("Input")]
        public InArgument<System.String> LogFilePath { get; set; }

        /// <summary>
        /// UiPath Log Message object reference
        /// </summary>
        private UiPath.Core.Activities.LogMessage _LogMessage { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        public LogMessage()
        {
            DisplayName = "Extended Log Message";
            Level = CurentLogLevel.Trace; // default setting
        }

        /// <summary>
        /// declare dummy register metadata class to force UiPath to load this assembly
        /// </summary>
        public void Register()
        {
            // intentionally empty
        }

        /// <summary>
        /// First log as if done by native UiPath then log to the file specified
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            // first do the usual UiPath logging...
            string message = Message.Get(context);
            //bool isNew = false;

            #region log as UiPath standard
            // it is necessary to create new objects every time.
            // reassigning property values causes errors when logging is frequent...
            _LogMessage = new  UiPath.Core.Activities.LogMessage
            {
                Level = this.Level,
                Message = new InArgument<string>(message),
            };

            // do UiPath log
            try
            {
                WorkflowInvoker.Invoke(_LogMessage); // NULL POINTER EXCEPTION HERE
            }
            catch (Exception ex)
            {
                throw new Exception("Internal UiPath Invoke Exception ", ex);
            }
            #endregion

            string logFilePath = LogFilePath.Get(context);

            // log to file if path is specified...
            if (logFilePath != null)
            {
                LogToFile(logFilePath, message, Level.ToString());
            }
        }

        /// <summary>
        /// Method to write a line in the log file
        /// </summary>
        /// <param name="filename">the file to which to log</param>
        /// <param name="message">the log message</param>
        /// <param name="level">the log level</param>
        private void LogToFile(string filename, string message, string level)
        {
            StringBuilder LogLine = new StringBuilder(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            LogLine.Append("\t");
            LogLine.Append(level);
            LogLine.Append("\t");

            LogLine.Append("\t - ");
            LogLine.Append(message);
            LogLine.Append(Environment.NewLine);

            try
            {
                // append the log line
                File.AppendAllText(filename, LogLine.ToString());
            }
            catch (Exception ex)
            {
                // try to log the exception in UiPath
                _LogMessage.Message = new InArgument<string>(ex.Message + Environment.NewLine + ex.StackTrace);
                throw new Exception("Internal append to log file exception", ex);
            }
        }
    }
}

A: Your error indicates that _LogMessage is empty thus the null pointer error.
You can verify that by simply checking after the part of your code
_LogMessage = new  UiPath.Core.Activities.LogMessage
            {
                Level = this.Level,
                Message = new InArgument<string>(message),
            };

if your variable is empty:
if (_LogMessage.Any())

Hope this will be helpful.


text:
Q: PHP How correctly check row on symbols array? Good day.
$Symbols = array('1','2','3','4','45','100','0');
$row = '120321'; //for example

how check $row on symbol in array?
P.S.: IE. if $row have one or some symbols from $Symbols than print yes.

A: Quite simple, actually:
if (array_intersect($Symbols, str_split($row))) {
    echo 'Yes';
}

Here, we use str_split() split the $row array into an array of characters and then use array_intersect() to check if it has any elements in common with $Symbols array. Note that this would however fail for numbers like 100 though.
Demo

A: This will also work for numbers > 9:
foreach($Symbols as $symbol){
    if(strpos($row,$symbol) !== false){
        echo "Yes";
        break;
    }
}

Example

A: As per you comment I think you want counter of all element in array present in the $row:
<?php
    $counter = 0;
    $Symbols = array('1', '2', '3', '4', '45', '100', '0');
    $row = '120321'; //for example

    foreach ($Symbols as $sym) {
        if (strpos($row, $sym) !== false) {
            $counter++;
        }
    }
    echo $counter; // It will give you the counter of all element in array present in the $row
  ?>

See live DEMO
Hope this will help!


text:
Q: Convert Flightradar24 API into pandas dataframe I've tried to convert flightradar24api, which gives a list of airlines, into a pandas data frame without succeed. So this is what i've done:
    import flightradar24
    import pandas as pd

    fr = flightradar24.Api()
    airlines = fr.get_airlines()
    items = airlines.items()
    list_items = list(items)
    df = pd.DataFrame(list_items)

    print(airlines)
    print(df.head())

And this was the result:
      0                                        1
0  version                                         1594656446
1     rows  [{'Name': '21 Air', 'Code': '2I', 'ICAO': 'CSB...

That being said, could you please help me convert flightradar24 api into a pandas dataframe?
Thanks in advance.

A: This should do it:
fr = flightradar24.Api()
airlines = fr.get_airlines()

df = pd.json_normalize(airlines['rows'])
print(df)

                        Name Code ICAO
0                     21 Air   2I  CSB
1                40-Mile Air   Q5  MLA
2                      9 Air   AQ  JYH
3                    ABX Air   GB  ABX
4     ACE Belgium Freighters   X7  FRH
...                      ...  ...  ...
1337         Zambian Airways   Q3  MBN
1338                  Zanair   B4  TAN
1339          Zimex Aviation   XM  IMX
1340                  ZIPAIR   ZG  TZP
1341                   Zorex       ORZ


text:
Q: What is the computational complexity of presentation problem for finite groups? Let's define presentation problem for finite groups as the following algorithmic problem:

You are given a list of permutations $g_0, ..., g_k$ (written in form of products of independent cycles). Output some presentation of $\langle g_1, ... , g_k \rangle$

What is the computational complexity of this problem?
If $n$ is the length of input, then the problem can be solved for $2^{O(n \log(n))}$ time worst case via breadth-first traversal of Cayley graph of $\langle g_1, ... , g_k \rangle$ (which has $\leq n!$ vertices and $\leq (n+ 1)!$ edges). But maybe there is some way to do it faster?

A: I think this question needs an answer! A presentation of a subgroup of $S_n$ defined by generating permutations  can be computed in polynomial time using the Schreier-Sims algorithm to compute a base and strong generating set of the group $G$. This can be used to write down a presentation.
I don't want to go into details about the algorithm - there are plenty of available descriptions, starting with the Wikipedia page. The idea is to compute a stabilizer chain
$$G = G^{(1)} > G^{(2)} > \cdots G^{(b)} > G^{(b+1)} = 1$$
of $G$, and to extend the initial generating set to a strong generating set, which contains generators of each of the subgroups in the chain. This involves computing (right) transversals $U^{(i)}$ of $G^{(i+1)}$ in $G^{(i)}$.
The relations in the presentation then consist of relations to define the new generators as words in the old, together with those of form $u_{ij}g = w$, for each $u_{ij} \in U^{(i)}$ and each generator $g$ of $G^{(i)}$, where $w$ is a word in the generators of $G^{(i)}$.
There are (at least) two versions, according to whether you store the elements $u_{ij}$ of $U^{(i)}$ explicitly (in which case you would introduce $u_{ij}$ as a new generator, and $w$ would be a single generator $u_{ij'}$), or whether you use words in the strong generators to represent the $u_{ij}$. Both versions are polynomial in $k$ and $n$ (linear in $k$). The first one has better time complexity but may be prohibitive in terms of memory usage for large $n$.
A lot of research in permutation group algorithms has involved the search for nearly linear time algorithms, which means $O(nk\log^c|G|)$ for some $c$. These are most useful for small base groups (where the length $b$ of the stabilizer chain is small), and $|G| \le n^b$. The book Permutation Group Algorithms by Ákos Seress is a good reference.
As Alexander Hulpke mentioned in his now deleted answer, we almost have a nearly linear time algorithm for computing a BSGS, and the principal remaining obstruction to this is the lack of a known short presentation for the simple groups $^2G_2(q)$.
In practice, the presentation computed  using this method is unwieldy and is likely to have huge numbers of redundant relations. There is a variant of Schreier-Sims, know as the Todd-Coxeter Schreier-Sims, which generally produces a much shorter presentation, and is often quicker as well.
The idea is, for each $i$ with $1 \le i \le b$ (where actually we do this in reverse order $i=b,b-1,\ldots,1$), we calculate a small number of the relations $u_{ij}g = w$, and then use coset enumeration to see if they (together with the relations for larger $i$, which have already been computed) suffice to prove that  the index in the associated finitely presented group is equal to the correct index $[G^{(i)}:G^{(i+1)}]$. If so, then we have enough relations, and there is the added advantage that we can abort the calculations in the Schreier-Sims algorithm for that $i$. If the coset enumeration does not complete quickly with the correct answer, then we interrupt it and adjoin a new relation $u_{ij}g = w$ that does not appear to be a consequence of the existing ones.
This works very well in practice, but it is unfortunately difficult (and probably impossible) to estimate its complexity, because the theoretical unsolvability of the word problem implies that the complexity of coset enumeration in general (not necessarily in this specific situation) is not recursive.


text:
Q: zabbix monitoring mysql database I have a server running multiple instances of mysql and also has the zabbix-agent running.
In zabbix_agentd.conf i have specified:
UserParameter=multi.mysql[*],mysqladmin --socket=$1  -uzabbixagent extended-status 2>/dev/null | awk '/ $3 /{print $$4}'

where $1 is the socket instance.
From the zabbix server i can run the test successfully.
zabbix_get -s ip_of_server  -k multi.mysql[/var/lib/mysql/mysql2.sock]

and it returns all the values
However the zabbix item/trigger does not generate the graphs, I have created a MACRO for $1 which is the socket location
{$MYSQL_SOCKET1} = '/var/lib/mysql/mysql2.sock'

and i use this key in items to poll the value
multi.mysql[{$MYSQL_SOCKET1},Bytes_sent]

LOGS:
this is what i get on the logs:
3360:20120214:144716.278 item [multi.mysql['/var/lib/mysql/mysql2.sock',Bytes_received]] error: Special characters '\'"`*?[]{}~$!&;()<>|#@' are not allowed in the parameters
  3360:20120214:144716.372 item [multi.mysql['/var/lib/mysql/mysql2.sock',Bytes_sent]] error: Special characters '\'"`*?[]{}~$!&;()<>|#@' are not allowed in the parameters

Any ideas where the problem could be?
FIXED
{$MYSQL_SOCKET1} = /var/lib/mysql/mysql2.sock

i removed the single quotes from the line and it worked...

A: FIXED
{$MYSQL_SOCKET1} = /var/lib/mysql/mysql2.sock

i removed the single quotes from the line and it worked...


text:
Q: For loop linux script
*

*Ask the user how many papers to grade?

*Create a for loop that will loop the times necessary for each paper's score to be entered.

*Ask the user for each score (1-100).

*count the number of loops

*At the end of the program display the average score of all the papers

ive done one for a while loop but not sure how to do for loop
#!/bin/bash

set -x

count=0
papers=0
score=0
grade=0
average=0

read -p " How many papers would you like to grade? " papers

while [ $count -lt $papers ]
do
    read -p " Please enter a score " grade
    score=`expr $score + $grade`
    count=$((count + 1))
done

average=`expr $score / $papers`
echo $average

A: You have done almost everything I just changed your while loop into for loop.
#!/bin/bash
set -x
declare -i score=0
declare -i grade=0
read -p " How many papers would you like to grade? " papers
for ((count=0; count<$papers; count++)) ;do
 read -p " Please enter a score " grade
 score=$(expr $score + $grade)
 done
average=$(expr $score / $papers)
echo $average

A: I see you already accepted an answer, but I'll provide a slightly different perspective. If you need to iterate over integers in a bash script, you can use seq Type
$ man seq

in a console and read how it works.
Example oneliner:
$ for i in $(seq 1 10); do echo $i; done
1
2
3
4
5
6
7
8
9
10

instead of echo $i you'll just have your the logic for your task

A: Disregarding the instructions and doing it after my own head (the instructions are bogus anyway as there's no need to ask the user for the number of scores (point 1) if they are to be counted anyway (point 4)).
awk 'BEGIN              { printf("Enter scores, one per line, end with Ctrl+D\n") }
     $1 < 1 || $1 > 100 { printf("Invalid score, must be [1,100]\n"); next }
                        { sum += $1; n++ }
     END                { printf("Average: %.2f\n", sum/n) }'

Testing:
Enter scores, one per line, end with Ctrl+D
0
Invalid score, must be [1,100]
2
3
4
5
99
100
1001
Invalid score, must be [1,100]
Average: 35.50

This would make it easy to read in the scores from a file by just using a redirection into the awk script.
Same thing in /bin/sh (but does not handle non-integer input/result):
#!/bin/sh

echo 'Enter scores, one per line, end with Ctrl+D'
while read score; do
    if [ "$score" -lt 1 ] || [ "$score" -gt 100 ]; then
        echo 'Invalid score, must be [1,100]'
    else
        sum=$(( sum + score ))
        n=$(( n + 1 ))
    fi
done

printf 'Average: %d\n' "$(( sum / n ))"

If you insist on asking for the number of scores, then you will have to handle out of range scores differently:
#!/bin/sh

printf 'Enter the number of scores that you will enter: ' >&2
read nscores

while [ "$nscores" -gt 0 ]; do
    while true; do
        read score
        if [ "$score" -lt 1 ] || [ "$score" -gt 100 ]; then
            echo 'Invalid score, must be [1,100]'
        else
            break
        fi
    done

    sum=$(( sum + score ))
    n=$(( n + 1 ))

    nscores=$(( nscores - 1 ))
done

printf 'Average: %d\n' "$(( sum / n ))"

Oops, another while loop.
A for loop, in shell scripting, is only ever used over an explicit list, such as a list of filenames.  Using a for loop in this exercise, if you are writing a shell script to solve it, is not at all necessary.
A reasonable use case where a for loop could be used to solve this exercise:
#!/bin/sh

for score do
    if [ "$score" -lt 1 ] || [ "$score" -gt 100 ]; then
        printf 'Invalid score (%d), must be [1,100]\n' "$score" >&2
    else
        sum=$(( sum + score ))
        n=$(( n + 1 ))
    fi
done

printf 'Average: %d\n' "$(( sum / n ))"

This script would accept the scores on the command line:
$ sh ./script.sh 1 20 10 22 3001 20
Invalid score (3001), must be [1,100]
Average: 14

Since the list of scores is a static list, it's appropriate to loop over it using a for loop.


text:
Q: Accessing list data in multiple site collections I have an requirement of develop an app for sp2013 to read different site collection's list data and show in a one place the items that are created by me on separate list in separate site collections.

A: SharePoint Search Query APIs is a way to go for accessing list data across site collections.
Examples
Assume we need to retrieve Task items, then the following query could be used:
contentclass:STS_ListItem AND ContentType:Task

to return all the task items.
JavaScript REST example
The following example demonstrates how to utilize Search Query API using REST endpoint:
function searchTaskItems(webUrl,success, failure) {
    var url = webUrl + "/_api/search/query?querytext='contentclass:STS_ListItem AND ContentType:Task'";
    $.ajax({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            success(data.d.query);
        },
        error: function (data) {
            failure(data);
        }
    });
}

//print tasks
searchTaskItems(_spPageContextInfo.webAbsoluteUrl,
  function(query){
      var resultsCount = query.PrimaryQueryResult.RelevantResults.RowCount;
      for(var i = 0; i < resultsCount;i++) {
          var row = query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i];
          var taskName = row.Cells.results[3].Value;
          console.log(taskName);
      }
  },
  function(error){
    console.log(JSON.stringify(error));
  }
);

JSOM Example
The same example but using JSOM:
SP.SOD.executeFunc('SP.search.js', 'Microsoft.SharePoint.Client.Search.Query.KeywordQuery', function() {

  var context = SP.ClientContext.get_current();
  var site = context.get_site();
  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
  keywordQuery.set_queryText("contentclass:STS_ListItem AND ContentType:Task");
  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
  var results = searchExecutor.executeQuery(keywordQuery);
  context.executeQueryAsync(
    function(){
        for(var idx in results.get_value().ResultTables[0].ResultRows) {
            var taskTitle = results.get_value().ResultTables[0].ResultRows[idx].Title;
            console.log(taskTitle);
        }
    },
    function(sender,args){
        //error handling goes here...
    });

});

References

*

*Using the SharePoint 2013 search Query APIs

A: SharePoint Search is the best way to do this in 2013.
Here are some walkthroughs:
http://www.sharepointnutsandbolts.com/2012/10/using-content-search-web-part-and.html
http://channel9.msdn.com/Events/SharePoint-Conference/2014/SPC402
http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2013/04/09/how-to-query-sharepoint-2013-using-rest-and-javascript.aspx


text:
Q: Memory exhausted even when there is a lot of memory allocated I realize that there are a lot of similar threads and I checked all of them. I've tried to increase the memory limit in php.ini, wp-config.php, wp-settings.php but nothing help.
Current error is:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 72 bytes) in /home/xxx/public_html/wp-includes/wp-db.php on line 2516

My limits in php.ini are
;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 3600
max_input_time = 3600
max_input_vars = 1000
memory_limit = 8192M
post_max_size = 256M

I don't know what to increase anymore.
edit: phpinfo() shows this

Edit: wp-db.php
Error is here:
 else {
            // ...column name-keyed row arrays
            $new_array[] = get_object_vars( $row );
 }

and this is the full function (sorry for the long code)
    /**
 * Retrieve an entire SQL result set from the database (i.e., many rows)
 *
 * Executes a SQL query and returns the entire SQL result.
 *
 * @since 0.71
 *
 * @param string $query  SQL query.
 * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
 *                       With one of the first three, return an array of rows indexed from 0 by SQL result row number.
 *                       Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
 *                       With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value.
 *                       Duplicate keys are discarded.
 * @return array|object|null Database query results
 */
public function get_results( $query = null, $output = OBJECT ) {
    $this->func_call = "\$db->get_results(\"$query\", $output)";

    if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
        $this->check_current_query = false;
    }

    if ( $query ) {
        $this->query( $query );
    } else {
        return null;
    }

    $new_array = array();
    if ( $output == OBJECT ) {
        // Return an integer-keyed array of row objects
        return $this->last_result;
    } elseif ( $output == OBJECT_K ) {
        // Return an array of row objects with keys from column 1
        // (Duplicates are discarded)
        foreach ( $this->last_result as $row ) {
            $var_by_ref = get_object_vars( $row );
            $key = array_shift( $var_by_ref );
            if ( ! isset( $new_array[ $key ] ) )
                $new_array[ $key ] = $row;
        }
        return $new_array;
    } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
        // Return an integer-keyed array of...
        if ( $this->last_result ) {
            foreach ( (array) $this->last_result as $row ) {
                if ( $output == ARRAY_N ) {
                    // ...integer-keyed row arrays
                    $new_array[] = array_values( get_object_vars( $row ) );
                } else {
                    // ...column name-keyed row arrays
                    $new_array[] = get_object_vars( $row );
                }
            }
        }
        return $new_array;
    } elseif ( strtoupper( $output ) === OBJECT ) {
        // Back compat for OBJECT being previously case insensitive.
        return $this->last_result;
    }
    return null;
}


text:
Q: how to count cells in excel with conditional statement? I want to create a VBA script that can count the number of cells in two columns , for example column A and B, that have values "yes". Moreover, if one of the two cells or both in the same row have value "yes", I want the script to count only 1 time.
For example, if A2 and B2 have value "yes", it is counted 1 time. If A2 or B2 has value "yes", it is also counted 1 time.
Please suggest a solution.

A: Try this formula.
=SUMPRODUCT((--((A:A="yes")+(B:B="yes"))>0)*1)

I would not advise using whole column references with sumproduct, though, since with over a million rows in Excel 2007 and later, calculation might take a while. You may want to build range names that grow and shrink with the populated rows and use these instead of the column references.
Note that whole column references in SumProduct only work in Excel 2007 and later. For earlier versions of Excel you will need to ringfence a range.


text:
Q: Three phase rectification algorithm Let's suppose we have a three phase rectifier like here:
https://www.youtube.com/watch?v=V6ZWYFTELQA
Now lets suppose we change diodes with transistors. Let's also put current probes on each of the three phases. Now we know exactly in which direction the current is flowing in each of the phases. Knowing this, what is the algorithm for opening/closing transistors, to keep the same operation as before with diodes?


text:
Q: Trouble in getting RFID tag value from serial port of computer I am developing a RFID attendance counting system for my classroom. I have interfaced MFRC-522 RFID module with Arduino Uno. The Arduino Uno is connected to a PC via serial port. A C# program reads the serial port to get the RFID tag number and performs matching.
Now, the C# program can successfully read the whole 13-digit number of the card only when it is the first scan. But in the next scans for the same card, the 13-digit number breaks into several parts. The console output of two consecutive tests are shown below:
Press any key to continue...
Data Received:
160975869190
Matched
Data Received:
1
Not Matched
Data Received:
6097
Not Matched
Data Received:
5869
Not Matched
Data Received:
190
Not Matched
I can not figure out why the card number can be read at the first scan but the number breaks into several parts in the next scans? The both Arduino and C# codes are included below:
Arduino Code:
 void setup()
{
  SPI.begin();
  rfid.init();
  Serial.begin(9600);
}

void loop()
{
   if(rfid.isCard())
   {
    RoutineRFID();
   }
}

void RoutineRFID()
{
  if(rfid.readCardSerial())
  {
     Serial.print(rfid.serNum[0]);
     Serial.print(rfid.serNum[1]);
     Serial.print(rfid.serNum[2]);
     Serial.print(rfid.serNum[3]);
     Serial.print(rfid.serNum[4]);
     Serial.flush();
  }

  while(!Serial.available())
  {
  }

  String studentName = Serial.readString();
  lcd.print(studentName);
  delay(3000);
}

C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace Test_Serial
{
    class Program
    {

        static void Main(string[] args)
        {
            try{
            SerialPort myPort = new SerialPort();
            myPort.BaudRate = 9600;
            myPort.PortName = "COM6";
            myPort.Open();

            myPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            Console.WriteLine("Press any key to continue...");
            Console.WriteLine();
            Console.ReadKey();
            myPort.Close();
        }

            catch (Exception ex)
            {
                Console.WriteLine("Com port Disconnected!");
            }
        }

        private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            Console.WriteLine("Data Received:");
            Console.WriteLine(indata);

            if (String.Equals(indata, "160975869190"))
            {
                Console.WriteLine("Matched");
                sp.WriteLine("Matched");

            }
            else
            {
                Console.WriteLine("Not Matched");
                sp.WriteLine("Not Matched");
            }

            Console.WriteLine();

        }

    }
}


text:
Q: Parse CSS style marginLeft using JavaScript I am trying to parse the marginLeft property value of an HTML element using JavaScript, but I am not sure what I am doing wrong.
I have used both these methods (with or without the ,10), but get "Current marginLeft: NaN" with my console.log:
var elementMargin = document.getElementById("main");
var style = elementMargin.currentStyle || window.getComputedStyle(elementMargin);

// tried this

var oldValue = parseInt(document.getElementById("main").style.marginLeft, 10);
console.log("Current marginLeft: " + oldValue);

// or this

var oldValue = parseInt(document.getElementById("main").style.marginLeft);
console.log("Current marginLeft: " + oldValue);

When I do a straightforward read and console.log of the property value, I do not get an error:
var elementMargin = document.getElementById("main");
var style = elementMargin.currentStyle || window.getComputedStyle(elementMargin);

console.log("Current marginLeft: " + style.marginLeft);

I get the output "Current marginLeft: 199px"
This is based on this post: Get a number for a style value WITHOUT the "px;" suffix
What am I doing wrong?

A: In the first example you are getting the computed left margin, which will give you whatever the margin is after the stylesheet has cascaded.
In the second and third examples you are getting the left margin as specified in the style attribute. Since you are getting NaN this is, presumably, not set using the style attribute so is undefined.
Add parseInt to the code you used in the first place.

A: To clarify the answer in case anyone else has the same question (thank you to Quentin):
var elementMargin = document.getElementById("main");
var style = elementMargin.currentStyle || window.getComputedStyle(elementMargin);

var oldValue = parseInt(style.marginLeft, 10);
console.log("Current marginLeft: " + oldValue);

Output: "Current marginLeft: 199px"


text:
Q: Are there any examples or documentation on using the Castalia source parser? While I have written plenty of recursive parsers before, I have recently become interested in the Castalia Delphi Parser (why re-invent the wheel). I know this parser have been used in many projects over the years - but finding any documentation for it seems difficult.
Where exactly can I find the documentation? Or as an alternative, are there any clear cut examples on using it in a real-life parsing scenario?
The idea is to use Castalia for syntax verification of Delphi units, and (if possible) benefit in generating a node-tree of a program (with classes, their methods, parameters, result datatypes, if/then/else -- basically a full map of a unit or program). You could think of it as "half a script runtime" without actually running any code, just breaking it down into it's most fundamental aspects.

A: why don't you use JvInterpreterParser? it has only 2-3 unit dependencies... can be easily modified to fit your needs and you can also improve the speed, in a old test I've parsed a 80 MB file about in 6 Sec. on a Pentium 4 running @ 2.8 Ghz or so...

A: Using the parser is described here:
http://delphiblog.twodesk.com/using-the-castalia-delphi-parser
The post also references some projects that are using the parser.
Here is another one:
https://github.com/LaKraven/MonkeyMixer


text:
Q: How to make fetch in this React class? I know how to make fetch to my backend using functions in my react component, but I needed a dropdown menu so I found an example in react-select page, but that example is made in a class.
Clean example I found in internet is this, for import react-select it is necesary to run command npm install react-select:
import React, { Component, Fragment, useEffect } from "react";
import Select from "react-select";

const options = [
  { value: "red", label: "red" },
  { value: "blue", label: "blue" },
  { value: "green", label: "green" }
];

export default class CrearPost extends Component {
  state = {
    selectedOption: null
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    // Option selected: { value: "red", label: "red" }
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    return (

      <Fragment>
        <Select
          className="basic-single"
          classNamePrefix="select"
          defaultValue={options[0]}
          isDisabled={false}
          isLoading={false}
          isClearable={true}
          isRtl={false}
          isSearchable={true}
          name="color"
          options={options}
          onChange={this.handleChange}
        />
      </Fragment>
      <input
        type="text"
        placeholder="body"
      />
      <button>
        Submit post
      </button>

    );
  }
}

And looks like this:

So I decided to try to make fetch, and what I tried is this:
import React, { Component, Fragment, useEffect, useState } from "react";
import Select from "react-select";
import { useHistory } from "react-router-dom";

const options = [
  { value: "red", label: "red" },
  { value: "blue", label: "blue" },
  { value: "green", label: "green" }
];

export default class CrearPost extends Component {
  state = {
    selectedOption: null
  };
  handleChange = selectedOption => {
    /*I added all this*/
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

    const PostData = () => {
      fetch('/createpost', { /*This route is in my nodejs server*/
        method:'post',
        headers:{
          'Content-Type':'application/json',
          Authorization: "Bearer " + localStorage.getItem("jwt")
        },
        body:JSON.stringify({
          title,
          body
        })
      }).then(res=>res.json())
      .then(data=>{
        console.log(data)
        if(data.error){
          alert(data.error)
        }
        else{
          alert('Post created')
          history.push('/')
        }
      }).catch(err=>{
        console.log(err)
      })
    }
  };
  render() {
    return (

      <Fragment>
        <Select
          className="basic-single"
          classNamePrefix="select"
          defaultValue={options[0]}
          isDisabled={false}
          isLoading={false}
          isClearable={true}
          isRtl={false}
          isSearchable={true}
          name="color"
          options={options}
          value={title}/*I added this*/
          onChange={(e) => setTitle(e.target.value)}/*I added this*/
        />
      </Fragment>
      <input
        type="text"
        placeholder="body"
        value={body}/*I added this*/
        onChange={(e) => setBody(e.target.value)}/*I added this*/
      />
      <button onClick={() => PostData()}/*I added this*/>
        Submit post
      </button>

    );
  }
}

But I just get this fail in my project:

I hope someone could help me, thanks.

A: Class component is a stateful component and has its own state. So you don't need to useState in class component. Just try out change your state to:
this.state = {
    title: "",
    body: ""
  };

And don´t forget to delete your states consts

A: As per your screenshot of error message, it says useState can not be used in class based components. useState is a new React hook to provide state functionality to class-less functional components.
In class based components you can use state = {...} instead as we used to previously.
so instead of these lines ...
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");

change them to ...
  state = {
    selectedOption: null,
    title: "",
    body: ""
  };

and change all setBodyand setTitle calls to state change calls.


text:
Q: When is a participle put before a noun, and when after? What is the difference in meaning when a past participle is used before or after the word? For example, I have put on a torn shirt, and I have put on a shirt torn. What is the meaning of these sentences?

A: From http://grammar.yourdictionary.com/parts-of-speech/adjectives/what-is-a-participial-adjective.html (sic)
When a participle is used as an adjective it can be considered to be an adjective and in English the adjective goes before the noun with a few exceptions (e.g. Surgeon general, sergeant major)
So it would always be 'torn shirt'.
Unless as previously noted, you are elaborating on the tearing event, e.g. 'a shirt (which has been) torn by the washing machine'
in which case it is a participle in an adjectival sub-clause and no longer a simple adjective.

A: It is frequently difficult to know when a participle is being used as an adjective or part of a verb.

The short was torn

Is "torn" an adjective or part of a verbal phrase?
I doubt that there is any objective way to determine which it is and no particular benefit in doing so.

When was the shirt torn?

The problem is the same. We create a problem for ourselves only if we insist on calling it an adjectival use and also insisting that adjective always precede the noun being modified.
The simplest rule seems to be that in questions the passive participle, regardless of whether we label it part of a verbal phrase initiated by a form of the verb "be" or an adjective  modifying the subject, follows the subject. It is part of the rule regarding inversion for questions.
Furthermore, there is no rule in English that precludes post-positional adjectives; it is just not the usual word order..

We can not dedicate, we can not consecrate, we can not hallow, this ground. The brave men, living and dead, have hallowed it ...

Are we saying that this is bad English because it has post-positional adjectives?
Nevertheless, it is far from normal English to end an indicative sentence with one passive participle unless it is part of a passive verb. There may be cases when it is acceptable, but they are very rare.

The shirt was torn

is fine.

It was a torn shirt

is fine.

It was a shirt, torn

is not fine. It is weird.

It was a shirt, torn, begrimed, and bloody

is atypical, but is grammatical. But "torn" here is not alone in apposition. In fact, I think a single adjective in apposition is much rarer than a list of adjectives.


text:
Q: Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object I am a complete noob with respect to angular, just going through a codeschool tutorial and I've hit my first hurdle.
I am getting Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object
Here is my code:
var bulletinApp = angular.module('bulletinApp', ['ngResource']);

bulletinApp.controller('PostsController', ['$scope', 'Post', function($scope, Post) {
    $scope.heading = 'Welcome';
    $scope.posts = Post.query();

    $scope.newPost = {
        title: 'Test Post'
    }

}]);

bulletinApp.factory('Post', ['$resource', function($resource) {
    return $resource('/posts');
}]);

I found an answer here:
Error in resource configuration while using $resource.query() function with AngularJS/Rails
That says I should add this to my resource declaration:
'query': {method: 'GET', isArray: false }

Problem being I have no idea where I am supposed to add this, or even if this is the problem I'm having?
EDIT:
bulletinApp.factory('Post', ['$resource', function($resource) {
  return $resource('/posts', {'query': {method: 'GET', isArray: false}});
}]);

After this I am still receiving the error. Also in the tutorial, there was no need for this and I've followed it pretty much to a tee, why would the get method be getting an object instead of an array?

A: The result of 'Get' is array or just object?  If it's an array, set isArray=true, else set isArray=false, like the guy said above
bulletinApp.factory('Post', ['$resource', function($resource) {
return $resource('/posts', {}, {'query': {method: 'GET', isArray: false/*true*/}});
}]);

And attention IsArray is different with isArray.
Or if you got your data by json, please add *.json as url

A: Add {} after '/posts'.
bulletinApp.factory('Post', ['$resource', function($resource) {
    return $resource('/posts', {}, {'query': {method: 'GET', isArray: false}});
}]);

For details, see this post.

A: The next line of the error message in the console is a url to a fuller description of the error:
Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array
http://errors.angularjs.org/1.2.28/$resource/badcfg?p0=object&p1=array

According to the linked page either your server's not returning what you think it is or you need to tell $resource to expect an array from the server.


text:
Q: Set a value with multiple duplicate index in pandas DataFrame I have a DataFrame with multiple duplicate index, my question is how can I set the value of row A in col2 with value 0 to other value, say 8.
Case 1:
In [82]: df = pd.DataFrame({'col1':[1,2,3], 'col2':[9,9,0]}, index=['A','B','A'])

In [83]: df
Out[83]:
   col1  col2
A     1     9
B     2     9
A     3     0

I know for this small and fixed DataFrame I can just use ix method with the desired position, as follow:
Desired Result (3rd row change from A 3 0 to A 3 8):
In [84]: df.ix[2, 1] = 8

In [85]: df
Out[85]:
   col1  col2
A     1     9
B     2     9
A     3     8

But for some large and changing DataFrame with multiple duplicate index, how can I set value of row A in col2 with value 0 to other value?
Case 2:
In [90]: df2 = pd.DataFrame({'col1':[1,2,3,4], 'col2':[9,9,0,9]}, index=['A','B','A','A'])

In [91]: df2
Out[91]:
   col1  col2
A     1     9
B     2     9
A     3     0
A     4     9

Desired Result (3rd row change from A 3 0 to A 3 8):
In [91]: df2
Out[91]:
   col1  col2
A     1     9
B     2     9
A     3     8
A     4     9

Case 3:
In [94]: df3 = pd.DataFrame({'col1':[1,2,3,4], 'col2':[9,9,0,0]}, index=['A','B','B','A'])

In [95]: df3
Out[95]:
   col1  col2
A     1     9
B     2     9
B     3     0
A     4     0

Desired Result (4th row change from A 4 0 to A 4 8):
In [95]: df3
Out[95]:
   col1  col2
A     1     9
B     2     9
B     3     0
A     4     8

A: df.loc[(df.index == 'A') & (df.col2 == 0), 'col2'] = 8


text:
Q: Event Calendar in codeigniter doesn't get more than 1 content I am facing  problem in getting more than 1 result on event calendar.
I have more than 1 exam on same day ..which i need to display.. but whats going is that, it is showing only the 1 result of same day..
my query is fetching all exams of same day but not displaying it on calendar.
My Code:
<?php
class Mycal_model extends CI_Model {

var $conf;
function Mycal_model(){
    //parent::CI_Model();

    $this->conf = array(
                    'start_day' => 'monday',
                    'show_next_prev' =>true,
                    'next_prev_url' => base_url().'mycal/display',
                    'day_type' =>'short');

    $this->conf['template'] = '

                            {table_open}
{/table_open}

                            {heading_row_start}
{/heading_row_start}

                                {heading_previous_cell}	{/heading_previous_cell}

                                    {heading_title_cell}{heading}	{/heading_title_cell}

                                {heading_next_cell}	{/heading_next_cell}

                            {heading_row_end}
{/heading_row_end}

                            {week_row_start}
{/week_row_start}

                                {week_day_cell}{week_day}	{/week_day_cell}

                            {week_row_end}
{/week_row_end}

                            {cal_row_start}
{/cal_row_start}
                                    {cal_cell_start}{/cal_cell_start}
                                            {cal_cell_start_today}{/cal_cell_start_today}
                                                {cal_cell_start_other}{/cal_cell_start_other}

                                                    {cal_cell_content}

{day}

{content}

                                                    {/cal_cell_content}

                                                    {cal_cell_content_today}

{day}

{content}

                                                    {/cal_cell_content_today}

                                                    {cal_cell_no_content_today}

{day}

                                                    {/cal_cell_no_content_today}

                                                    {cal_cell_no_content_today}

{day}

                                                    {/cal_cell_no_content_today}

                                                    {cal_cell_blank} {/cal_cell_blank}

                                                    {cal_cell_other}{day}{/cal_cell_other}

                                                    {cal_cell_end}	{/cal_cell_end}
                                                {cal_cell_end_today}	{/cal_cell_end_today}
                                    {cal_cell_end_other}	{/cal_cell_end_other}
                            {cal_row_end}
{/cal_row_end}

                            {table_close}
{/table_close}
    ';

}
function get_calendar_data($year, $month){
    $query = $this->db->select('ee_exam_date,ee_sname')->from('vm_entrance_exams')->like('ee_exam_date',"$year-$month",'after')->get();

    $cal_data = array();

     foreach($query->result() as $row){

        $cal_data[substr($row->ee_exam_date,8,2)] = substr($row->ee_sname,0,50);

     }

     return $cal_data;

}

function add_calendar_data($ee_exam_date, $ee_sname){

    if($this->db->select('ee_exam_date')->from('vm_entrance_exams')
        ->where('ee_exam_date',$ee_exam_date)->count_all_results()){

        $this->db->where('ee_exam_date',$ee_exam_date)
        ->update('vm_entrance_exams',array(
        'ee_exam_date' => $ee_exam_date,
        'ee_sname' => $ee_sname
        ));

    }
    else{
    $this->db->insert('vm_entrance_exams',array(
        'ee_exam_date' => $ee_exam_date,
        'ee_sname' => $ee_sname
        ));
        }
}
function generate ($year,$month){

    $this->load->library('calendar',$this->conf);

        $cal_data = $this->get_calendar_data($year, $month);

    return $this->calendar->generate($year,$month,$cal_data);
}
}

My result:

stdClass Object ( [ee_exam_date] => 2017-12-21 [ee_sname] => DNB CET SS ) stdClass Object ( [ee_exam_date] => 2017-12-03 [ee_sname] => IIFT ) stdClass Object ( [ee_exam_date] => 2017-12-17 [ee_sname] => SNAP ) stdClass Object ( [ee_exam_date] => 2017-12-21 [ee_sname] => IBSAT ) stdClass Object ( [ee_exam_date] => 2017-12-21 [ee_sname] => FMGE ) stdClass Object ( [ee_exam_date] => 2017-12-10 [ee_sname] => Maha TAIT ) stdClass Object ( [ee_exam_date] => 2017-12-10 [ee_sname] => C-CAT ) stdClass Object ( [ee_exam_date] => 2017-12-17 [ee_sname] => CPT EXAMINATION )

A: Edit cal_data variable with conditional like this :
...
function get_calendar_data($year, $month){
    $query = $this->db->select('ee_exam_date,ee_sname')->from('vm_entrance_exams')->like('ee_exam_date',"$year-$month",'after')->get();

    $cal_data = array();

     foreach($query->result() as $row){

        if (array_key_exists(substr($row->ee_exam_date,8,2), $cal_data)) {

            $cal_data[substr($row->ee_exam_date,8,2)] = $cal_data[substr($row->ee_exam_date,8,2)] . ' ' . substr($row->ee_sname,0,50); // this will just prepend current event with previous event

        } else {

            $cal_data[substr($row->ee_exam_date,8,2)] = substr($row->ee_sname,0,50);

        }
     }

     return $cal_data;

}
...


text:
Q: Update session array variable in codeigniter I am suck with an issue.
I have a session array which i need to update. Don't know how to update it.
$detailsData    =   $this->session->userdata['detailsData']['tot_amt'];

I need to update the value of 'tot_amt'.How to implement this?
Waiting for response.....

A: If  'detailsData'  is the session variable and has an array in it. Then
$detailsData    =   $this->session->userdata('detailsData');
$detailsData['tot_amt']= "Any Value";
$this->session->set_userdata('detailsData', $detailsData);

A: For update session value like this :
// modify session
$this->session->set_userdata('tot_amt', 'New value');

when you need to replace old data just unset previous data and then set again your new data
Example :
$session_data = array('uid' => 'test user', 'logged_in' => TRUE);
$this->session->set_userdata($session_data);

//remove old data
$this->session->unset_userdata($session_data);

// modify session
$session_data = array('uid' => 'New user', 'logged_in' => TRUE);
$this->session->set_userdata($session_data);


text:
Q: Pandas function pandas.read_sql_table() returns a DataFrame with the values in the wrong order I'm trying to get a DataFrame from a PostgreSQL table using the following code:
import pandas
from sqlalchemy.engine import create_engine

engine = create_engine("postgresql+psycopg2://user:password@server/database")
table = pandas.read_sql_table(con=engine, table_name= "table_name", schema= "schema")

Suppose the database table primary key goes from 1 to 100, the Data Frames first column will go like 50 to 73, then 1 to 49, the 73 to 100. I've tried adding a chunk_size value to see if that made a difference and got the same result.

A: AFAIK databases don't always return values in order by primary key. You can sort in pandas:
table.sort_values(by=['id'])

A: Logically SQL tables have no order and the same applies to queries, unless explicitly defined using ORDER BY. Some DBMS, but not PostgreSQL1, may use a clustered index and store rows physically in order, but that does not guarantee that a SELECT returns rows in that order without using ORDER BY. For example parallel execution plans throw all expectations about query results matching physical order in the bin. Note that DBMS can use for example indexes or other information to fetch rows in order without having to sort, so ordering by a primary key should not add too much of an overhead.
Either sort the data in Python as shown in the other answer, or use read_sql_query() instead and pass a query with a specified order:
table = pandas.read_sql_query(
    "SELECT * FROM schema.table_name ORDER BY some_column",
    con=engine)

1: PostgreSQL has a CLUSTER command that clusters the table based on an index, but it is a one-time operation.


text:
Q: mina deploy throws error - bundle: command not found ! ERROR: Deploy failed Am trying to deploy rails app to digital ocean using mina gem. I did all the configuration and mina setup also is getting executed properly.
mina deploy throws error. Any help would be much appreciated.
Here is the mina deploy --trace
root@ruby-rails-1gb-blr1-01:/home/rails/rails-demo# mina deploy --trace
** Invoke deploy (first_time)
** Execute deploy
** Invoke remote_environment (first_time)
** Execute remote_environment
** Invoke git:clone (first_time)
** Execute git:clone
** Invoke deploy:link_shared_paths (first_time)
** Execute deploy:link_shared_paths
** Invoke bundle:install (first_time)
** Execute bundle:install
** Invoke rails:db_migrate (first_time)
** Execute rails:db_migrate
** Invoke rails:assets_precompile (first_time)
** Execute rails:assets_precompile
** Invoke deploy:cleanup (first_time)
** Execute deploy:cleanup
** Invoke puma:phased_restart (first_time)
** Invoke remote_environment (first_time)
** Execute remote_environment
** Execute puma:phased_restart
root@139.59.72.156's password:
-----> Creating a temporary build path
-----> Deploying rails-demo to 139.59.72.156:/home/rails/rails-demo
-----> Fetching new git commits
       remote: Counting objects: 43, done.
remote: Compressing objects: 100% (33/33), done.
remote: Total 43 (delta 6), reused 43 (delta 6), pack-reused 0
Unpacking objects: 100% (43/43), done.
       From github.com:krishnateja/rails-demo
          739096a..4cf74f8  master     -> master
-----> Using git branch 'master'
       Cloning into '.'...
       done.
-----> Using this git commit
       root (4cf74f8):
       > small config change
-----> Symlinking shared paths
-----> Installing gem dependencies using Bundler
       bash: line 137: bundle: command not found
 !     ERROR: Deploy failed.
-----> Cleaning up build
       Unlinking current
       OK
       Connection to 139.59.72.156 closed.

 !     Run Error

deploy.rb
require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/rvm'
require 'mina/puma'

set :application_name, 'rails-demo'
set :domain, '139.59.72.156'
set :deploy_to, '/home/rails/rails-demo'
set :repository, 'git@github.com:krishnateja/rails-demo.git'

set :shared_dirs, fetch(:shared_dirs, []).push('log', 'tmp/pids', 'tmp/sockets', 'public/uploads')
set :shared_files, fetch(:shared_files, []).push('config/database.yml', 'config/secrets.yml', 'config/puma.rb')
set :user, 'root'

task :environment do
  invoke :'rvm:use', 'ruby-2.2.3'
end

task :setup do
  command %[touch "#{fetch(:shared_path)}/config/database.yml"]
  command %[touch "#{fetch(:shared_path)}/config/secrets.yml"]
  command %[touch "#{fetch(:shared_path)}/config/puma.rb"]
  comment "Be sure to edit '#{fetch(:shared_path)}/config/database.yml', 'secrets.yml' and puma.rb."
end

task :deploy do
  deploy do
    comment "Deploying #{fetch(:application_name)} to #{fetch(:domain)}:#{fetch(:deploy_to)}"
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'

    on :launch do
      invoke :'puma:phased_restart'
    end
  end

end

puma.rb
environment "production"

bind  "unix:///home/rails/rails-demo/shared/tmp/sockets/puma.sock"
pidfile "/home/rails/rails-demo/shared/tmp/pids/puma.pid"
state_path "/home/rails/rails-demo/shared/tmp/sockets/puma.state"
directory "/home/rails/rails-demo/current"

workers 2
threads 1,2

daemonize true

activate_control_app 'unix:///home/rails/rails-demo/shared/tmp/sockets/pumactl.sock'

prune_bundler

I Some how felt its something to do with the path to executable directory, hence did this..
gem environment - gives this.
root@ruby-rails-1gb-blr1-01:/home/rails/rails-demo# gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.14
  - RUBY VERSION: 2.2.3 (2015-08-18 patchlevel 173) [x86_64-linux]
  - INSTALLATION DIRECTORY: /usr/local/rvm/gems/ruby-2.2.3
  - USER INSTALLATION DIRECTORY: /root/.gem/ruby/2.2.0
  - RUBY EXECUTABLE: /usr/local/rvm/rubies/ruby-2.2.3/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/rvm/gems/ruby-2.2.3/bin
  - SPEC CACHE DIRECTORY: /root/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /usr/local/rvm/rubies/ruby-2.2.3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /usr/local/rvm/gems/ruby-2.2.3
     - /usr/local/rvm/gems/ruby-2.2.3@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/rvm/gems/ruby-2.2.3/bin
     - /usr/local/rvm/gems/ruby-2.2.3@global/bin
     - /usr/local/rvm/rubies/ruby-2.2.3/bin
     - /usr/local/rvm/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin

Added EXECUTABLE DIRECTORY to Path.
root@ruby-rails-1gb-blr1-01:/home/rails/rails-demo# export PATH=$PATH:/usr/local/rvm/gems/ruby-2.2.3/bin
root@ruby-rails-1gb-blr1-01:/home/rails/rails-demo# echo $PATH
/usr/local/rvm/gems/ruby-2.2.3/bin:/usr/local/rvm/gems/ruby-2.2.3@global/bin:/usr/local/rvm/rubies/ruby-2.2.3/bin:/usr/local/rvm/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/rvm/gems/ruby-2.2.3/bin

A: Bundler has to be installed on your server machine (the one you trying to deploy to). The easiest way is to login into it by ssh and run gem install bundler once. It's listed as a common question in official mina FAQ

A: I have this issue as well, and workaround it by moving my launch tasks to a separate task. So you could do this by turning
task :deploy do
  deploy do
    comment "Deploying #{fetch(:application_name)} to #{fetch(:domain)}:#{fetch(:deploy_to)}"
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'

    on :launch do
      invoke :'puma:phased_restart'
    end
  end

end

to
task :deploy do
  deploy do
    comment "Deploying #{fetch(:application_name)} to #{fetch(:domain)}:#{fetch(:deploy_to)}"
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'
  end
end

task :launch do
  invoke :'puma:phased_restart'
end

And then execute it separately (which is admittedly suboptimal):
$ mina deploy
$ mina launch

I don't know the particulars of your task, but I configure mine like so:
task :launch => :remote_environment do
  in_path(fetch(:current_path)) do
    invoke :'my:task'
  end
end

I know this isn't a solution or explanation, but hopefully it helps.

A: For me the issue was with rbenv not being loaded.
If you're sure that ruby and bundler are correctly installed on the server as I was then the fix is to make sure the first thing your shell does it to load rbenv.
Open .bashrc
Make sure the following is called before
# If not running interactively, don't do anything
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"


text:
Q: Split Multiple Rasters into multiple rasters of different size in QGIS I am wondering if there is a way to take multiple .tiff or .ecw files of any given size, and divide them up into multiple files of the same type, but of different size, using QGIS.
Also, is it is possible to do it by degrees, rather than "rows" and "columns"?
For example, say I have aerial imagery of a given region in the world. The total imagery is 10 degree by 10 degrees (lat/lon), but is divided into 4 equal quadrant images. Now say I want it to be divided into 1x1 degree (lat/lon) blocks. It would go from 4 image files (2x2) to 100 (10x10).
It seems like I could do this manually by first merging the rasters as explained here, then simply adding that single large raster to the canvas as selecting Save As and using the VRT Tile option as explained here to split it. I tried to use the merge capability to do this, but my PC locked up for hours. I couldn't move anything and ended up just hard powering it off. There was a very small corrupt file that I just trashed, so it didn't seem to get far.
My question is, do you even need to do the merge. Can you split multiple files? If not, I might just write a new plugin that will.


text:
Q: My homework about algebra Please help
Find the fraction of
$$\frac{3^{2^{2555}}+3^{2^{2554}}+3^{2^{2553}}+\cdots+3^{2^{2012}}}{2^{941}}$$
Working method show is really appreciate
Thank you
Poom

A: HINT:
Using Carmichael Function,
$\displaystyle \lambda(2^n)=2^{n-2}$ for $n\ge3$
$\displaystyle \implies 3^{2^{n-2}}\equiv1\pmod{2^n}$
$\displaystyle \implies3^{2^m}\equiv1\pmod{2^n}$ if $m\ge n-2$
Here the number of terms is numerator is $\displaystyle2555-2012+1$  which is $<< 2^{941}$

A: By repeated use of the difference of squares formula, we can see:
$$P=3^{2^{n}}-1=(3-1)\prod_{i=0}^{n-1}(3^{2^{i}}+1)$$
Since there are $n$ even terms in the productorial and one outside, $P$ is divisible by $2^{n+1}$.So
$$N=\frac{(3^{2^{2555}}-1)+(3^{2^{2554}}-1)+(3^{2^{2553}}-1)+\cdots+(3^{2^{2012}}-1)}{2^{941}}$$
Is integer. Conclude.


text:
Q: where is the css styling which captcha creates? I just signed up for captcha. It gave me php code to display the captcha box on the page and code to put on the server. It works fine but the input box is misaligned (it might be based on the rest of the styling of the page.) I want to modify it manually but I can't.
When I do an inspect code in google chrome, it shows me the styling for the input box I needed. I unchecked a particular style
position: absolute!important

and it now looks fine. Now I need to actually modify the code. But it says the location is registration.php:1. Where is this? Registration.php is the file which creates the html code for the page and it does a "require" for a captcha php file. But I don't see the css style in that file either!

A: See these 2 images to see where the CSS could be coming from:
1- In Chrome console under the elements tab

2- In Chrome console under the resources tab


text:
Q: How to download of any file in android? I want a create custom download Manager in which I need to show all downloading file status in another activity.
I Have an Activity in which there is listing of different file and when I tab on the ListView.
Downoading will start in the BACKGROUND and I have a other activity in which all the downloading file status will be visible like as Image what I attach:

I read Downloadmanager Class and AsyncTask for achieving this functionality and could not resolve.
How to achieve more than one downloading in the background and when I open the Downloding.java (Download Activity). All the downloading will appear
Can somebody suggest me How to do this thing or suggest me the other way to start working on it?

A: DownloadManager is the right direction.

*

*You can add a new doanload by using enqueue

*You can update your Gui by querying regularly the DownloadManager to know the status of each of your downloads.

*You can cancel one of the requested downloads with the cancel method (as your GUI seems to provide a button for that)

*You also want to register a broadcast receiver to be informed when a download is finished even if your Activity is not displayed at that time.

The number of thread used by the DownloadManager, and hence the number of parallel downloads, is managed automatically by the framework.


text:
Q: How to pass stateParams to the angular controller? I try to define stateParams in the controller, but it returns me an empty object {}
My app.js:
angular.module('testApp', ['ui.router','ngResource'])
.config(function($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('app', {
            url:'/',
            views: {
                'header': {
                    templateUrl : 'views/header.html'
                },
                'messages': {
                    templateUrl : 'views/messages.html',
                    controller  : 'MessageController'
                },
                'chat': {
                    templateUrl : 'views/chat.html',
                    controller  : 'ChatController'
                },
                'footer': {
                    templateUrl : 'views/footer.html'
                }
            }
        })
        .state('app.chat', {
            url: ':id'
        });
        $urlRouterProvider.otherwise('/');
})

My controller.js:
angular.module('testApp')

.controller('IndexController', ['$scope', '$stateParams', function($scope,$stateParams) {

    $scope.chosenMessage = $stateParams;

}]);

And my template:

I need an id from StateParams to define choosen message and chat content for the message.

A: The solution:
I have defined $state instead of $stateParams, and check for $state.params.id to get current state.


text:
Q: Class referencing codable protocols is not codable If a member of my class AnotherClass is a of a type with codable abstract protocol the compiler fails to synthesize the coding/decoding code for the class. If instead the same member is a concrete class conforming to the same protocol then the compiler will happily synthesize the coding/decoding code. I think the second case should work, the property mp will always be a Codable concrete instance of MyProtocol, which is Codable.
/* This works */

protocol MyProtocol : Codable {

    func a(_ n : Int) -> Int

}

class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}

class AnotherClass : Codable {
    let y = 5
    let mp : MyClass // <---- ACTUAL CLASS
    init() {
        mp = MyClass()
    }
}

/* But this won't work.
  Compiler error:
  Type 'AnotherClass' does not conform to protocol 'Decodable'
  Type 'AnotherClass' does not conform to protocol 'Encodable'
*/

protocol MyProtocol : Codable {
    func a(_ n : Int) -> Int
}

class MyClass : MyProtocol {
    let x = 3
    func a( _ n : Int ) -> Int {
        return n * x
    }
}

class AnotherClass : Codable {
    let y = 5
    let mp : MyProtocol // <-------- PROTOCOL
    init() {
        mp = MyClass()
    }
 }

A: This is how you fix it.
class AnotherClass<T: MyProtocol> : Codable {
    let y = 5
    let mp : T
    init() {
        mp = MyClass() as! T // handle this more gracefully
    }
}

And use it this way
let a = AnotherClass<MyClass>()

But please consider reading this answer here. It explains a lot about why protocols behave the way they do and will help you understand more about them.


text:
Q: How can I use a command line vpn in CRONTAB? I'm trying to use the nordvpn/windscribe/expressvpn command line utility (take your pick, ive tried them all) to schedule a change to my IP address every 5 minutes.
Using these in the interactive bash work fine:
nordvpn connect
windscribe connect best
expressvpn connect usla

However in crontab none work (I'm omitting the disconnects for brevity):
sudo crontab -e
*/5 * * * * nordvpn connect
*/5 * * * * windscribe connect best
*/5 * * * * expressvpn connect usla

Is there a way to schedule a connection to a VPN? Thanks.


text:
Q: How to paginate associated records? Products belongsToMany Categories and Categories hasMany Products, inside my Product view I'm showing a list of all it's categories but I want to paginate or limit these results.
My current code on ProductsController is:
$product = $this->Products
    ->findBySlug($slug_prod)
    ->contain(['Metas', 'Attachments', 'Categories'])
    ->first();

$this->set(compact('product'));

I know I need to set $this->paginate() to paginate something but I can't get it working to paginate the categories inside the product. I hope you guys can understand me.
UPDATE: Currently I have this going on:
$product = $this->Products->findBySlug($slug_prod)->contain([
              'Metas',
              'Attachments',
              'Categories' => [
                'sort' => ['Categories.title' => 'ASC'],
                'queryBuilder' => function ($q) {
                  return $q->order(['Categories.title' => 'ASC'])->limit(6);
                }
              ]
            ])->first();

The limit works but I don't know how to paginate yet

A: The paginator doesn't support paginating associations, you'll have to read the associated records manually in a separate query, and paginate that one, something along the lines of this:
$product = $this->Products
    ->findBySlug($slug_prod)
    ->contain(['Metas', 'Attachments'])
    ->first();

$categoriesQuery = $this->Products->Categories
    ->find()
    ->innerJoinWith('Products', function (\Cake\ORM\Query $query) use ($product) {
        return $query->where([
            'Products.id' => $product->id,
        ]);
    })
    ->group('Categories.id');

$paginationOptions = [
    'limit' => 6,
    'order' => [
        'Categories.title' => 'ASC'
    ]
];

$categories = $this->paginate($categoriesQuery, $paginationOptions);

$this->set(compact('product', 'categories'));

Then in your view template you can display your $product and separately paginate $categories as usual.
See also

*

*Cookbook > Controllers > Components > Pagination

*Cookbook > Views > Helper> Paginator

*Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data


text:
Q: Crystal Reports, calculate sum field I need your help, how can I know the total(sum) in a field that is itself the joining of two formulas:
Main formula:
sum(@weight)

Formula 1:
@open = if ({OrderRel.OurReqQty}
    - (Sum ({ShipDtl.OurInventoryShipQty}, {OrderRel.OrderRelNum}))
    - (Sum({ShipDtl.OurJobShipQty}, {OrderRel.OrderRelNum}))) < 0 then 0
else
    {OrderRel.OurReqQty}
    - (Sum ({ShipDtl.OurInventoryShipQty}, {OrderRel.OrderRelNum}))
    - (Sum({ShipDtl.OurJobShipQty}, {OrderRel.OrderRelNum}))

Formula 2:
@weight = {@open}*{Part.NetWeight}

I can't calculate the sum field by referring the @open and @weight formulas.

A: You can't calculate the sum by just using sum function, Instead you may use running total or write a formula to calculate sum of the weight function like sum one by one for each group and then reset it at start of the group

A: Make a third formula that uses the logic {@open} + {@weight}. This will get the sum of the two values per record.
If you're looking for a grand total of every instance of Open and Weight on the report, use the new formula as the field to summarize a Running Total. Set the Type of Summary to sum, evaluate for each record, and reset never.


text:
Q: Registering a user through Rails API and returning validation errors I'm trying to build a controller action which will create a new user in my application. I want it to attempt to create the user and if it succeeds, return the User model and if it fails show the validation errors. So far I've got this mostly up and running:
# app/controllers/v1/users_controller.rb

def create
  @user = User.create(user_params)
end

private
  def user_params
    params.require(:user).permit(:email, :password) if params[:user]
  end

and I'm using JBuilder in my view like so:
# app/views/v1/users/create.json.jbuilder

if @user.errors
  json.errors @user.errors
else
  json.user @user
end

This looks like it'd work to me, however when I create a new user that doesn't have any validation errors I get this output rather than the User that just got created:
{"errors":{}}

How come it's printing out the empty errors when the user has no validation errors?

A: In Ruby, only nil and false evaluate to false in the if statement. In your example above, @user.errors is an ActiveModel::Errors class and therefore evaluate to true. Try changing the code above to:
if @user.errors.present?
  json.errors @user.errors
else
  json.user @user
end


text:
Q: Can see 100mbps in the lan even though i have cat6 cables and gigabit switch I have a lan setup where i used cat 6 cable and a gigabit switch .. also the systems all have gigabit ports but lan connection speed only shows as 100mbps .. all the systems are running windows xp .. can some one please guide me as to what i need to do to get 1gbps.. ?
All the systems are close by.. nothing more that 10m apart.
Regards,
Prakash

A: Couple things to check...
Are the cables good?
Are all the systems and switch configured for auto-negotiation?
Are all the systems 100 or just some?
If all the systems are running at 100, I would bet you either don't have a gigabit switch or you don't have it configured correctly.


text:
Q: how to copy java application TextArea content to a web page text area using java? I need copy java application TextArea content to a webpage TextArea using the same java application.
where should I start to learn how to do that?
OK here's an example
I want to post a thread in my favorite forum, so I use this URL(http://myfavoriteforum.com/addpost.html)
a page will appear with text areas for thread title and body.
now instead of writing my post into these text areas
I go to my java application which contains a jTextArea1 for thread title, jTextArea2 for thread body and a jButton.
I write the title "new movie" and the body "blah...blah..." into the application's text areas Respectively.
the question is how to copy the texts "new movie" and "blah...blah..." from the application's text areas to that forum page text areas by pressing the jButton?

A: I you mean upoad it to a web site, then you have to learn how to do a web service. You can do that in java using a basic servlet with a doGet method, passing the text as a parameter in the url of the web request from your android device to your web server.
It's like the big picture. What you wanna do is interesting and will teach you the essence of web services and backend computing for android apps but it's not trivial.
Regards,
 Stéphane


text:
Q: ag-grid rendering in Next.js pages Newbie here...need help.  I tried using the sample code for ag-grid on a ReactJS component on NextJS.  I am getting a loading css error (please see further below).
(Before this, I was able to make the code run using 'create-react-app' "https://www.ag-grid.com/react-getting-started/")
Here's the error message:
appropriate loader needed
I have searched and tried out related (searched-out) answers like adding this on webpack.config.js:
webpack config
and also tried adding this on package.json:
package json
I may be missing out on how to correctly load css on the Next JS setup.
Here's the code..taken mostly from the sample code

A: In Next.js you configure webpack inside a next.config.js file. There should be no webpack.config.js (at least to my knowledge).
There's a plugin called next-css which you install with: npm install --save @zeit/next-css.
Then, in your next.config.js file, write:
const withCSS = require('@zeit/next-css')
module.exports = withCSS()

The ag-grid example worked for me after doing that.


text:
Q: Split home partition into 2 (xfs on LVM) I am using centos 7 and I have a /home mounted on an xfs filesystem on a dedicated LVM partition.
/dev/mapper/centos-home        782G   34M  782G   1% /home

I want to split this partition to 2 partitions, one of them to be mounted on /home, is there any way I can do this while the OS is running normaly, like I don't have to boot into livecd.

A: The usual approach to splitting a filesystem would be to shrink the existing filesystem and create a new one in the space which is made free.
However, you cannot shrink an xfs filesystem.  According to the FAQ Is there a way to make a XFS filesystem larger or smaller?:

You can NOT make a XFS partition smaller online. The only way to shrink is to do a complete dump, mkfs and restore.
An XFS filesystem may be enlarged by using xfs_growfs(8).
If using partitions, you need to have free space after this partition to do so. Remove partition, recreate it larger with the exact same starting point. Run xfs_growfs to make the partition larger. Note - editing partition tables is a dangerous pastime, so back up your filesystem before doing so.
Using XFS filesystems on top of a volume manager makes this a lot easier.

The size of your current /home is small (as filesystems go, nowadays), so the approach would be to

*

*backup your /home (on some other filesystem or computer)

*delete the xfs filesystem

*create the new filesystems to your taste

*restore the backup

Further reading:

*

*XFS FAQ

A: You can reduce a logical volume size with lvreduce, for example say you want to create another 10G partition you can first free up the space needed with:
lvreduce -L -10G /dev/mapper/centos-home

and then create a new LV with
lvcreate -L 10G -n share centos

this will create a /dev/mapper/centos-share device of 10G
As mentioned by Thomas Dickey, the resize operation will destroy your filesystem, so you may want to backup anything valuable you have there. Both logical volumes should be formatted afterwards with the desired filesystems.


text:
Q: Select instance/row with max field/column value per with field/column (group by) So, I have these models:
class Computer(models.Model):
    hostname = models.CharField(primary_key=True, max_length=6)
    <other computer info fields>

class ComputerRecord(models.Model):
    id = models.AutoField(primary_key=True)
    pc = models.ForeignKey(Computer, on_delete=models.CASCADE)
    ts = models.DateTimeField(blank=False)
    <other computerrecord info fields>

I want to get the row / computerrecord instance that has the max ts for each pc (Computer model)
In sql would be something like this:
SELECT hub_computerrecord.*
FROM hub_computerrecord
JOIN (
    SELECT pc_id, MAX(ts) AS max_ts
    FROM hub_computerrecord
    GROUP BY pc_id
) AS maxs ON hub_computerrecord.pc_id = maxs.pc_id
WHERE hub_computerrecord.ts = maxs.max_ts;

Note (edit): There are lot of ComputerRecord instances (10000+) so anything too inefficient won't work

A: Try this
from django.db.models import Max, F

qs = ComputerRecord.objects.annotate(
    max=Max('pc__computerrecord__ts')
).filter(
    ts=F('max')
)
Yes, this form expression doesn't build the exact SQL query in the OP, but it produces the same result (there may be some performance issues, not sure about the matrics)
Alternatively, you can execute the raw SQL using the raw() method as
raw_query = """
SELECT hub_computerrecord.*
FROM hub_computerrecord
JOIN (
    SELECT pc_id, MAX(ts) AS max_ts
    FROM hub_computerrecord
    GROUP BY pc_id
) AS maxs ON hub_computerrecord.pc_id = maxs.pc_id
WHERE hub_computerrecord.ts = maxs.max_ts;
"""

qs = ComputerRecord.objects.raw(raw_query)

A: Add a boolean field in ComputerRecord model, for e.g. max_status. Identify the record with max 'ts' value for Computer object and set it to True. so if you have 10000 records for a particular computer model one record will have True and all the rest 9999 records will have False in max_status field. This needs to be done only once for each computer model.
Next time when you are adding a new row in ComputerRecord model just compare 'ts' of the of new record to 'ts' of the existing record with max_status value as True. if new record has higher 'ts' value set max_status as True for this record and change max_status of previous record to False else no change required.
When you need to find out the instance of ComputerRecord with max 'ts' , query only on max_status=True


text:
Q: Mysql - What's the difference between "utf8_unicode_ci" and "utf8_persian_ci"? In the MySQL database i saved Persian sentences as Unicode(utf8_unicode_ci) in a table. Then i change collation to utf8_persian_ci but the results are same. No changes were made.
What's the difference between "utf8_unicode_ci" and "utf8_persian_ci"?

A: (I cannot speak as an authority specifically on Persian collations.)  The general idea behind MySQL collations is

*

*_bin -- just check the bits; this is usually useless for "words".

*_general_ci -- Case and Accent Insensitive, and rather lame when it comes to all other 'rules'.

*_unicode_ci, _unicode_520_ci, _0900_ai_ci -- Case and Accent Insensitive; based on Uniocde standards 4.0.0, 5.2.0, 9.0.0; but unlikely to be "correct" for any particular language (Spanish, Persian, German, etc)

*_persian_ci (etc) -- Similar to one of the Unicode collations, but tuned for the language.

An example of how specific collations may differ:

*

*_spanish_ci -- one treats "ch" as two letters, as with most collations

*_spanish2_ci -- treats "ch" as a single letter:  'cz' < 'ch' < 'da'.  (And other differences.)

*_lithuanian_ci -- "ch" is the same as "c"; that is 'cha' = 'ca'.

I assume there may be differences between _persian_ci and _unicode_ci in the Persian characters.  A glance of http://mysql.rjweb.org/utf8_collations.html and http://mysql.rjweb.org/utf8mb4_collations.html seems to say that Western European characters are collated the same in those collations.

A: *

*utf8_persian_ci has better performance to store Persian texts & characters.

*When you sort Persian text in utf8_persian_ci, the letters "پ","گ","ژ","چ" are in their correct place (order), but in utf8_unicode_ci they become after "ی".


text:
Q: Python/Pandas - count last duplicate rows in succession I have DataFrame like this:
        product_id         dt  products_qty
70063      2964562 2017-11-14         0.000
72719      2964562 2017-11-15         2.000
401533     2964562 2017-11-16         0.000
413201     2964562 2017-11-17         0.000
424227     2964562 2017-11-18         0.000
450345     2964733 2017-11-14         4.000
470446     2964733 2017-11-17         0.000
473233     2964733 2017-11-18         0.000

And I have to group dataframe by product_id column and count last duplicate rows. For example we don't count 70063 row even if it is duplicated with last rows. So the output should be this:
  product_id          count
     2964562          3.000
     2964733          2.000

A: Use:
#create unique consecutives values by products_qty
a = df['products_qty'].ne(df['products_qty'].shift()).cumsum()
#get lens of each group
b = df.groupby([df['product_id'], a]).size()
#filter out unique groups and get last row
df = b[b > 1].groupby(level=0).last().reset_index(name='count')
print (df)
   product_id  count
0     2964562      3
1     2964733      2

Detail:
print (a)
70063     1
72719     2
401533    3
413201    3
424227    3
450345    4
470446    5
473233    5
Name: products_qty, dtype: int32

print (b)
product_id  products_qty
2964562     1               1
            2               1
            3               3
2964733     4               1
            5               2
dtype: int64


text:
Q: Wordpress Ajax insert data to MySQL I am working with Wordpress and I am trying to develop a plugin for my personal purpose (studying).
At the moment I have created a main file (wp-maincat.php) for the plugin activation and deactivation, and it creates the custom table in the Wordpress called categ_tag.
This file creates also a menu and include 3 more pages:

*

*Page.3: (the problem) a clone of the Wordpress "Tag" page.

In that page I want to create the submit section on the left and on the right the table that displays the results with AJAX, so without the page reload.
The problem is that when I press the submit button, nothing happens, or better I receive an alert() with no errors. On the other hand the alert() tells me that the code returns an error. And another problem is that I cannot see if there are already some rows in the database.
If I remove url:ajaxurl, the code works but in the responds div it load the entire wordpress page. Any help would be appreciated!
Here is some code.
UPDATE
This part adds the entry in the database
global $wpdb;
$table_name = $wpdb->prefix."categ_tag";

if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) {
    $contentToSave = $_POST["content_txt"];

    $insert_row = $wpdb->query($wpdb->prepare(" INSERT INTO $table_name ( name_cats ) VALUES ('".$contentToSave."')"));

    if($insert_row) {
          $my_id = $mysqli->id; //Get ID of last inserted row from MySQL
          echo '
';
          echo '
';
          echo '';
          echo '
';
          echo $contentToSave.'
';
    }else{
        header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
        exit();
    }
}

?>

Here is the part of the code that generates the problem (ajaxurl)

The form

Category Tags

Add New Category

        <form id="addcats" method="post">

                Name
                <input id="name_cats" name="name_cats" type="text" style="width: 95%" value="<?php echo esc_attr($item['name_cats'])?>" class="code" required />

                <input type="submit" name="publish" id="publish" class="button" value="Submit"  />

        </form>

Category List

A: I suggest the simplest way to post data through Ajax :
jQuery('#category').on('change', function() {
    var sel_id = this.value; // or $(this).val()
    jQuery.ajax({
            type: "POST",
            url: "<?php echo get_site_url().'/ajaxdataform.php'; ?>",
            data: {sel_id: sel_id },
            success: function(data) {
            if(data != ''){
                jQuery('#sub_category').html(data);
            }else{
                jQuery('#sub_category').attr('disabled', true);
            }
        },
    });
});

And from another end in the "ajaxdataform.php" we get post data like this:
<?php

require( dirname(__FILE__).'/wp-load.php' );

$sel_id = $_POST['sel_id'];

$sql = "SELECT * FROM job_sub_category WHERE cat_id = $sel_id";
$result = mysql_query($sql);

while($row = mysql_fetch_array($result)) {
    echo $row['sub_category'];
}

Like this you can fire insert query.


text:
Q: Code Compilation errors with poco-1.8.1 I have built a windows service using poco "poco-1.8.1".
I am using various features of poco like services, json, httpclientsession, httprequest etc.
While building the code I get errors like:
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(104): error C2059: syntax error: 'string'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(108): note: see reference to class template instantiation 'Poco::TypeWrapper<T>' being compiled
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(104): error C2238: unexpected token(s) preceding ';'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(114): error C2059: syntax error: 'string'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(118): note: see reference to class template instantiation 'Poco::TypeWrapper<const T>' being compiled
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(114): error C2238: unexpected token(s) preceding ';'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(124): error C2059: syntax error: 'string'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(128): note: see reference to class template instantiation 'Poco::TypeWrapper<const T&>' being compiled
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(124): error C2238: unexpected token(s) preceding ';'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(134): error C2059: syntax error: 'string'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(138): note: see reference to class template instantiation 'Poco::TypeWrapper<T&>' being compiled
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(134): error C2238: unexpected token(s) preceding ';'
1>. . . \libs\poco-1.8.1\net\include\poco\net\httpmessage.h(139): error C2059: syntax error: 'string'

1>. . . \libs\poco-1.8.1\net\include\poco\net\httpmessage.h(139): error C2059: syntax error: 'string'
1>. . . \libs\poco-1.8.1\net\include\poco\net\httpmessage.h(139): error C2238: unexpected token(s) preceding ';'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(104): error C2059: syntax error: 'string'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(108): note: see reference to class template instantiation 'Poco::TypeWrapper<T>' being compiled
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(104): error C2238: unexpected token(s) preceding ';'
1>. . . \libs\poco-1.8.1\foundation\include\poco\metaprogramming.h(114): error C2059: syntax error: 'string'

Note ignore the ". . . \" in the path above as I have removed absolute path  before posting here.
I am not using the metaprogramming part of poco directly.
What might be the cause of these errors and how to rectify it?


text:
Q: removing links from posts in wordpress I have few blogs for some clients. I need to remove links to one of my clients in all posts. Just to be clear i need to remove links and my keyword should stay like it is.
I found this plugin http://wordpress.org/plugins/automatically-remove-links-from-posts/installation/
But this one remove all links.
I need to remove all links just for one client, and links for other clients should stay unchanged.
Does anyone know about some good plugin for this solution?
Is there any way using SQL statements? I need solution to recognize link no meter what is keyword and to remove href text leaving keyword unchanged.
Thanks in advance!

A: You could try using regex .. Create a regex pattern and use in this plugin .This will search and replace them with ''
This is the plugin
Try and let know