text:
Q: Trouble signing out from ASP web app with Federation Services I'm trying to sign out from intranet application, which is also accessible from the internet with signing in using Active Directory Federation Services.
Firstly I just made a href to https://federation.mycompany.com/adfs/ls/?wa=wsignout1.0. The federation page shows and displays a message: "You have been successfully signed out!" But if I go back, I can access the web app again without signing in again. I also tried to append a redirect parameter, so that the user would be prompted to insert credentials again. But the redirect does not happen.
Later on I created a Action in one of my controllers. Here is the code:
public ActionResult Logoff()
{
    string absoluteUrl = HttpContext.Request.Url.AbsoluteUri;
    string replyUrl = absoluteUrl.Substring(0, absoluteUrl.LastIndexOf("/")+1);
    WSFederationAuthenticationModule.FederatedSignOut(new Uri(@"https://federation.mycompany.com/adfs/ls/?wa=wsignout1.0"), new Uri(replyUrl));
    return null;
}

But the problem is the same.
The third thing I tried was to delete cookies before signing out. But it seems that authentication cookie is under domain and not my app, so it is not accessible.
How do I solve this Sign out issue?
Please help.

A: I am only assuming but I suspect that your ADFS is configured for windows authentication while your application has the Login button.
If this is the case then you can't really log out from already authenticated ADFS and it happily reissues the token upon the next request from the application. You can't do anything about it since the authentication is performed with MTML/Kerberos and this is the browser that keeps your credentials until you close it.
The solution would be to change ADFS to Forms mode and see if it helps.


text:
Q: How to concatenate feature maps? I was trying to merge feature maps that I got from two different encoders which have different dimensions in Pytorch
simclr_features: torch.Size([543, 512])
imagenet_features: torch.Size([543, 1024])
so I wanted: torch.Size([543, 1536]). what is a possible solution to do that?

A: You can use torch.cat:
torch.cat((simclr_features, imagenet_features), dim=1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: writing python code to make calls from terminal? I'm trying to write a program that runs the following command in my terminal in ubuntu:
"xselect @ nameofscript"
I am debugging someones code who used this code to perform the feat:
def runXSelect(scriptname):

    '''This function will automatically run any xselect script input.
    It returns the stdout. Since it does not natively overwrite
    existing pha files, in FileHelper, the write script will handle
    this'''

    cmd = "xselect @ " + scriptname
    args = shlex.split(cmd)
    out = ""
    with subprocess.Popen(args, stdout=subprocess.PIPE,
                          universal_newlines=True,shell=True) as proc:

        proc.wait()
        out = proc.stdout.read()

    return out

The error that I am getting from the stdout is:
@: 1: @: xselect: not found

If I simply type the command in on the terminal, it runs fine. But something about the code is causing the execution to fail.
Any suggestions?


text:
Q: Google Cloud SQL: Periodic Read Spikes Associated With Loss of Connectivity I have noticed that my Google Cloud SQL instance is losing connectivity periodically and it seems to be associated with some read spikes on the Cloud SQL instance. See the attached screenshot for examples.
The instance is mostly idle, but my application recycles connections in the connection pool every 60 seconds so this is not a wait_timeout issue. I have verified that the connection are recycled Also, it occurred twice in 30 minutes and the wait_timeout is 8 hours.
I would suspect a backup process but you can see from the screenshot that no backups have run.
The first instance lasted 17 seconds from the time the connection loss was detected until it was reestablished. The second was only 5 seconds, but given that my connections are idle for 60 seconds the actual downtime could be up to 1:17 and 1:05 respectively. They occurred at 2014-06-05 15:29:08 UTC and 2014-06-05 16:05:32 UTC respectively. The read spikes are not initiated by me. My app continued to be idle during the issue so this is some sort of internal GCS process.
This is not a big deal for my idle app, but it will become a big deal when the app is not idle.
Has anyone else run into this issue? Is this a known issue with Google Cloud SQL? Is there a known fix?
Any help would be appreciated.
****Update****
The root cause of the symptoms above has been identified as a restart of the MySQL instance.  I did not restart the instance and the operations section of the web console does not list any events at that time, so now the question becomes, what would cause the instance to restart twice in 30 minutes? Why would a production database instance restart period?

A: Was your instance restarted ? During the restart the spinning down/up of an instance will trigger read/write.
That may be one reason why you are seeing the activity for read/write.

A: That was caused by one of our regular release. Because of the way the update takes place an instance might be restarted more than once during the push to production.


text:
Q: dhtmlx multiple scheduler not working error "Scheduler is not defined" I'm implementing dthmlx schedule in my website. On dashboard I need to show three scheduler in tabs. However scheduler in first tab is working but for second scheduler while initiating an object I'm getting error "Scheduler is not defined". Following is my code.

All require files are included properly. What exactly going wrong ?

A: Be sure that you are using PRO version of dhtmlxscheduler, as only PRO version supports the getSchedulerInstance API.


text:
Q: Variant of principal components analysis where only the variance of a single variable counts Principal components analysis finds the axis(/es) along which the variance of some dataset is maximized. What if I'm in a situation where I have a single dependent variable $v$ that is dependent on $n$ independent variables $v = f(x_1, x_2, \dots, x_n)$ and I would like to know "what principal components of $\mathbf x$ cause the most variance in $v$?" Is this an answered question already? I feel like it would be just a small modification of the PCA algorithm..

A: If I got your question correctly (and I am not sure), the solution is that you have to take the spectral decomposition $VDV^{T}$ where V is the orthonormal matrix of eigenvectors and D is the diagonal matrix of eigenvalues. Then you transform the set of dependent variables by multiplying the original matrix of predictors $X^{*}$  by the eigenvectors $X=X^{*}V$. Then you can regress y against the new transformer predictors X that are now uncorrelated. Since they are uncorrelated, the total explained variance of y will be the sum of variances of $\beta x$ where each x is the vector representing each column of X (so each transformed variable) and $\beta$ denotes its corresponding beta estimated at previous step. The PC variable $x^{max}$ such that $\beta^{2}_{x^{max}} Var(x^{max})$ is maximum among all the pc transformed variables is the one explaining the highest portion of the variance of $y$.


text:
Q: python linear regression predict by date I want to predict a value at a date in the future with simple linear regression, but I can't due to the date format.
This is the dataframe I have:
data_df =
date          value
2016-01-15    1555
2016-01-16    1678
2016-01-17    1789
...

y = np.asarray(data_df['value'])
X = data_df[['date']]
X_train, X_test, y_train, y_test = train_test_split
(X,y,train_size=.7,random_state=42)

model = LinearRegression() #create linear regression object
model.fit(X_train, y_train) #train model on train data
model.score(X_train, y_train) #check score

print ('Coefficient: \n', model.coef_)
print ('Intercept: \n', model.intercept_)
coefs = zip(model.coef_, X.columns)
model.__dict__
print "sl = %.1f + " % model.intercept_ + \
     " + ".join("%.1f %s" % coef for coef in coefs) #linear model

I tried to convert the date unsuccessfully
data_df['conv_date'] = data_df.date.apply(lambda x: x.toordinal())

data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D")

A: convert:
1) date to dataframe index
df = df.set_index('date', append=False)

2) convert datetime object to float64 object
df = df.index.to_julian_date()

run the regression with date being the independent variable.

A: Linear regression doesn't work on date data. Therefore we need to convert it into numerical value.The following code will convert the date into numerical value:
import datetime as dt
data_df['Date'] = pd.to_datetime(data_df['Date'])
data_df['Date']=data_df['Date'].map(dt.datetime.toordinal)

A: Liner regression works on numerical data. Datetime type is not appropriate for this case. You should remove that column after separating it to three separate columns (year, month and day).

A: When using
dt.datetime.toordinal

be careful that it only converts dates values and does not take into account minutes, seconds etc..  For a complete answer on generating ordinals from full datetime objects you can use something like:
df['Datetime column'].apply(lambda x: time.mktime(x.timetuple()))

A: It is really important to differentiate the data types that you want to use for regression/classification.
When you are using time series, that is another case but if you want to use time data as a numerical data type as your input, then you should transform your data type from datetime  to float (if your data_df['conv_date] is a datetime object, if not then you should first transform it by using; data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D") )
I agree with Thomas Vetterli's answer. It is useful to be careful what kind of time data you are using.
If you are only using year and month data then dt.datetime.toordinal would be enough to use;
>>import datetime
>>data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D")
>>data_df['conv_date'] = data_df['conv_date'].map(datetime.datetime.toordinal)
737577

But if you want to use also the hour, minute and second information then time.mktime() suits better;
>>import time
>>data_df['conv_date'] = pd.to_datetime(data_df.date, format="%Y-%M-%D")
>>data_df['conv_date'] = data_df['conv_date'].apply(lambda  var: time.mktime(var.timetuple()))
1591016041.0

Also 1591016044.0 is another exemplary output from my data, it varies with changes in seconds.

A: I'm diving into the different options given here and I just wanted to summarize them. It takes time to write a full answer but this is what I've researched.
Examples reference
I took the same date with different data types following the requirements of each method. Maybe I'm missing other options.
t = pd.Timestamp('2021-09-03 00:00:00')
   # Timestamp('2021-09-03 00:00:00')   pandas._libs.tslibs.timestamps.Timestamp
t2 = dtt.date(2021, 9, 3)
   #  datetime.date(2021, 9, 3)     datetime.date

Pandas methods

*

*pandas.to_numeric
pandas.to_numeric(arg, errors='raise', downcast=None)
# argscalar, list, tuple, 1-d array, or Series

Example
st3 = pd.to_numeric(df_example.index, downcast='integer')
st3[0]
1630627200000000000

Python/Pandas with the same outcome

*

*pandas.Timestamp.toordinal

*Python-date.toordinal

Note: The Proleptic Gregorian ordinal gives the number of days elapsed from the date 01/Jan/0001. And here ordinal is called Proleptic since the Gregorian calendar itself is followed from October 1582.Aug 23, 2021.

# I checked it out and I found a 215 days difference
hoy = dtt.date.today()   # datetime.date(2022, 8, 3)
hoy.toordinal()  # 738370   - (365 * 2022)  =  340
hoy.timetuple()  # tm_yday=215  ---> 340 - 215 = 125

Example
t2.toordinal()
    738036
pd.Timestamp.toordinal(a)
    738036

Python methods

*

*Python-datetime-module-datime

*

*Python-time.mktime

*Python-datetime.date.timetuple
Example
time.mktime(t2.timetuple())
1630638000.0


text:
Q: Task.ContinueWith runs before the task finishes executing In Main method of a console application:
Do().ContinueWith(t => Do())
    .ContinueWith(t => Do())
    .ContinueWith(t => Do());

Do is a method that returns Task:
var source = new CancellationTokenSource();
var token = source.Token;
return Task.Factory.StartNew(() =>
{
    Console.WriteLine("Inside " + _Counter);
    token.WaitHandle.WaitOne(1000);
    Console.WriteLine(_Counter++ + " is done");
}, token);

And _Counter is an integer field:
private static int _Counter = 1;

When I run, the result is this:

Inside 1
  1 is done
  Inside 2
  Inside 2
  Inside 2
  2 is done
  3 is done
  4 is done

So let's assume I have a Task called t and an Action<Task> called a.
If I call t.ContinueWith(a), a should be called after t completes, right? And when a runs, that should mean whatever delegate t calls has ended.
What causes this result? Am I not getting something obvious here?
What I use:

*

*Windows 8 RTM

*.NET Framework 4.5

A:
If I call t.ContinueWith(a), a should be called after t completes, right?

Sure. But since your Do function creates a new task, it completes immediately, thus starting the next Do. Remove the task creation from Do (leaving only the Console.WriteLine stuff) and it should work as expected.
    static void Do()
    {
        Console.WriteLine("Inside " + _Counter);
        Thread.Sleep(1000);
        Console.WriteLine(_Counter + " is done");
    }

    static void Main(string[] args)
    {
        Task.Factory.StartNew(Do)
            .ContinueWith(t => Do())
            .ContinueWith(t => Do())
            .ContinueWith(t => Do());
    }


text:
Q: How to keep return code and log of sub function in bash I want to run a sub function(with some interactive operation like read) and keep it's log.
Original
#!/bin/bash
foo() {
  echo "Error"
  return 1
}
bar() {
  local data
  read -p "data=" data
  echo "OK: $data"
  return 0
}
foo
echo "Return code=$?"
bar
echo "Return code=$?"

After keep the log
#!/bin/bash
foo() {
  echo "Error"
  return 1
}
bar() {
  local data
  read -p "data=" data
  echo "OK: $data"
  return 0
}
LOG=my.log
foo | tee -a $LOG
echo "Return code=$?"
bar | tee -a $LOG
echo "Return code=$?"

A: Use a named pipe to send the return value:
#!/bin/bash
foo() {
  echo "Error"
  return 1
}
bar() {
  echo "OK"
  return 0
}

rm -f retcode
trap 'rm -f retcode' EXIT
mkfifo retcode

LOG=my.log
{
     foo
     echo $? > retcode
} | tee -a $LOG &
read rc < retcode
echo "Return code=$rc"
{
    bar
    echo $? > retcode
} | tee -a $LOG &
read rc < retcode
echo "Return code=$rc"

A: Use process substitution to run tee. This takes advantage of the fact that the return code of the process inside >(...) is lost.
#!/bin/bash
foo() {
  echo "Error"
  return 1
}
bar() {
  echo "OK"
  return 0
}
LOG=my.log
foo > >(tee -a $LOG )
echo "Return code=$?"
bar > >( tee -a $LOG )
echo "Return code=$?"


text:
Q: Displaying data from multiple studies where different analysis methods were used I hope this is an ok place to post this. I am an epidemiologist looking at 14 studies on a particular topic (e.g. chemical exposure on semen parameters). All the studies performed similar semen analysis methods, but their analyses were varied. Some used a continuous outcome (with continuous or categorical exposure), some used a dichotomous outcome (all with categorical exposure).That difference feels manageable to me.
However, they also didn't all report the same effect estimates (betas for continuous, betas for high vs. low quartiles, correlation coefficient, % change, mean difference, means, odds ratios) or use the same transformations of the variables (ln, log10, cubic root, Box-Cox of outcome, ln, log10 of exposure).
Ideally, if all the studies used the same techniques, I would put them all in a forest plot. But this is just a mess. There are hardly any that did things they same. But they are all looking at the same question.
Does anyone have any suggestions for displaying this mess in such a way that the reader can easily see what the findings were across studies and can understand what the general trend is? There is also the additional complication of different studies having different median exposures, so wanting to preferably sort by that.
Currently, I just have a big old table with all the continuous outcome studies first, then all the categorical outcomes, and with information about what the transformation and effect estimate is. I just don't think it is very effective.
Thanks so much (and sorry for the wall of text)!

A: There are ways of converting between standardised mean differences and (log) odds ratios

@ARTICLE{chinn00,
  author = {Chinn, S},
  year = 2000,
  title = {A simple method for converting an odds ratio to effect size for use
          in meta--analysis},
  journal = {Statistics in Medicine},
  volume = 19,
  pages = {3127--3131}
}

which may help to put more of them onto the same footing.
You presumably know that you can convert between logarithms to different bases fairly simply $\log_a{N} = \log_a{b} \times \log_b{N}$.
If you have the correlation and the standard deviations then by calculating from them the covariance you can estimate the $\beta$.
Apart from that you could always try writing to the authors. In my experience there are two sorts of reply: (a) silence, (b) the enormously helpful.


text:
Q: xhtml->docx->xhtml retain div ids? I'm attempting to export some CKEditor created xhtml fields from a database, convert them to a docx, edit the document in Word, then convert it back to xhtml and import those fields back into the database.  I'm currently using docx4j-XHTMLImport, but I'm open to suggestions.
The xhtml structure is like:

    database-field-1

xyz

    database-field-2

xyz

etc...
So when converting between formats I would like to retain the id's from the divs so when I import again, I can parse the xhtml and extract the fields per id to update the database.
Thanks!

A: You can convert the divs to content controls.
See XHTML-docx roundtrip: content tracking (just written).


text:
Q: Jython code stopped working after upgrade from 2.7.1 to 2.7.2 // MyPythonObject.java

import org.python.core.PyObject;
import org.python.expose.ExposedClassMethod;
import org.python.expose.ExposedType;

@ExposedType
public class MyPythonObject extends PyObject {

    @ExposedClassMethod
    public void hello() {
        System.out.println("Hello");
    }
}

// Main.java

import org.python.core.PyStringMap;
import org.python.util.PythonInterpreter;

public class Main {
    public static void main(String[] args) throws Exception {
        PythonInterpreter.initialize(null, null, new String[0]);
        PyStringMap map = new PyStringMap();
        PythonInterpreter pythonInterpreter = new PythonInterpreter(map);
        map.__setitem__("myobj", new MyPythonObject());
        pythonInterpreter.exec("myobj.hello()");
    }
}

The code runs fine on Jython 2.7.1 but fails on Jython 2.7.2:
Exception in thread "main" Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'null' object has no attribute 'hello'

Is this a bug in Jython 2.7.2?
P.S. I asked the same question on GitHub but didn't get any answer yet.

A: david.perez has asked the right question. The exposer annotations are used to create built-in Python objects in the interpreter. They add code to methods when processed during the Jython build, in classes that will act like a Python built-in.
You do not need them simply to use a class defined in Java from a program written in Python. Take them off and your code works.
I don't know what changed from 2.7.1 to move exposer annotations from unnecessary to harmful. (ASM update, maybe.)


text:
Q: Should I use Queue for sending email through 3rd party service Laravel and Lumen provide a Queueing mechanism for queueing tasks that take more processing so that the performance of web-app is not affected during busy times.
But when using 3rd party Emailing service like SendGrid, Gmail.
Should I queue Email Sending through 3rd party? I don't know whether it'd take as much processing on my Laravel Web-App as self-hosted Email Sending does?

A: It totally depends on situation.
Suppose you need to verify a user's email address so the verification email should be send in real time. Now another situation, you have to send a newsletter, so you can send it any time. So it totally depends on the importance of the email.
Here can read about different email types, https://www.mailjet.com/docs/email_types


text:
Q: A simple php script does not return same size answer all the time I have a simple "what's my ip" running. It gets called by ajax every 5 seconds.
The php is simply <?php echo $_SERVER['REMOTE_ADDR'];?>
But, looking in the apache server log at requests from the same client, same browser, a table of the size of the frequencies vs the size of requests, shows the output size is not consistent.
I do not use cookies on that site.
467 417
164 570
140 385
 40 538
 15 4205
  4 4173
  1 600
  1 5834
  1 559
  1 530
  1 2002

How can the size vary? Same question, same answer, I would assume.
...
Edit:
When I do curl -i, I get this; size 330. But the size transferred as shown in log is consistently 3956 bytes?!?
The server is on https; so some certificate exchange is being done, still it should be the same?
HTTP/1.1 200 OK
Date: Thu, 06 Dec 2018 08:46:21 GMT
Server: Apache/2.4.25 (Debian) SVN/1.9.5 PHP/5.6.30-0+deb8u1 mod_python/3.3.1 Python/2.7.13 OpenSSL/1.0.2l mod_perl/2.0.10 Perl/v5.24.1
X-Powered-By: PHP/5.6.30-0+deb8u1
Access-Control-Allow-Origin: *
Content-Length: 10
Content-Type: text/html; charset=UTF-8


text:
Q: Chaining Maven Flyway commands How can Flyway commands be chained into a single command using Maven?
For example, I want to run mvn initialize flyway:clean followed by mvn initialize compile flyway:migrate. However, mvn initialize flyway:clean compile flyway:migrate fails.
Thanks!

A: I just checked
mvn initialize flyway:clean compile flyway:migrate

with both Maven 2.2.1 and Maven 3.0.3 and it works every time.
Could you double check this? In case you think you really found a problem, please file an issue in the Issue Tracker with the necessary steps to reproduce it and I'll do my best to fix it asap.

A: That will give you the ability to chain maven steps, just add the goals you want in there
<profile>
        <id>clean-migrate</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>process-resources1</id>
                            <goals>
                                <goal>resources</goal>
                            </goals>

                            <phase>generate-sources</phase>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.6</source>
                        <target>1.6</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>com.googlecode.flyway</groupId>
                    <artifactId>flyway-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>process-resources2</id>
                            <goals>
                                <goal>clean</goal>
                                <goal>migrate</goal>
                            </goals>
                            <phase>generate-sources</phase>
                        </execution>
                    </executions>
                    <version>1.4.2</version>
                    <configuration>
                        <driver>oracle.jdbc.driver.OracleDriver</driver>
                        <url>jdbc:oracle:thin:@${database-hostname}:${database-port}:${database-sid}</url>
                        <user>${database-username}</user>
                        <password>${database-password}</password>
                        <schemas>${database-schema}</schemas>

schema_history

                        <initialVersion>0.1.00</initialVersion>
                        <initialDescription>Base Migration</initialDescription>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

You will also need the following in your settings.xml
<profile>
  <id>inject-flyway-properties</id>
    <properties>
      <database-hostname>${env.DB_HOSTNAME}</database-hostname>
      <database-port>${env.DB_PORT}</database-port>
      <database-username>${env.DB_USER}</database-username>
      <database-password>${env.DB_PASSWORD}</database-password>
      <database-sid>${env.DB_DEFAULT_SID}</database-sid>
      <database-schema>${env.DB_SCHEMA}</database-schema>
    </properties>
</profile>

A: If i understand the docs correct you have to configure the maven-flyway plugin to do the work and bound it to the correct phases of maven than you can use the default maven calls like mvn clean package or mvn clean verify.

A: You can use profiles in order to bundle "commands" together. Once it's done you just call:
mvn -Pmy-profile


text:
Q: Apache Beam Pipeline - Serialization problem My Beam pipeline seems to work properly, but produces a lot of warnings:
[direct-runner-worker] WARN org.apache.beam.sdk.util.MutationDetectors - Coder of type class org.apache.beam.sdk.coders.SerializableCoder has a #structuralValue method which does not return true when the encoding of the elements is equal. Element com.emarsys.dataflow.templates.MetricBundle@73d85187

The class looks like this:
@AllArgsConstructor
@Data
public class MetricBundle implements Serializable {
    private Long customerId;
    private String query;
    private Map<PrimaryKey, Metric> metrics;
}

The problem is with the Map. PrimaryKey and Metric classes are composed of simple types, and implement the Serializable interface.
The transform producing the PCollection<MetricBundle> is using .setCoder(SerializableCoder.of(MetricBundle.class));
Do I have to implement a custom coder in order to serialize Map properly?
During testing, I found no conflicts in the result, all elements are handled properly.

A: This is warning that due to the use of SerializableCoder it's not able to check certain properties of your pipeline. (SerializableCoder is also very inefficient.) I would recommend using a more specific coder here, but you don't have to necessarily write one of your own. E.g. it looks like you could decorate your class with @DefaultSchema(JavaFieldSchema.class). See https://beam.apache.org/documentation/programming-guide/#schemas


text:
Q: ¿Como puedo cambiar el formato de un DatetimeField en Django? Estoy trabajando en una API en django-rest para migrar una base de datos que tengo en un CSV a una instancia SQL en la nube de google. El problema, me lanza un error 400 porque el formato de algunas columnas no es el mismo que el que esta en la base de datos. Con la ayuda de pandas ya he logrado introducir algunos campos, pero no los relacionados con fechas.
""" MODELS """
class Contrato(models.Model):
    def __init___(self):
        pass
    contrato_numero = models.CharField(primary_key=True, max_length=100)
    acta_inicio = models.DateField()
    hasta = models.DateField()

    objeto_contrato = models.CharField(max_length=500)
    porcentaje_cumplido = models.FloatField()
    fecha_contrato = models.DateField()
    """ son muchos mas campos pero estoy validando estos """

""" serializers """
class Contratos_serializer(serializers.Serializer):

    contrato_numero = serializers.CharField(max_length=100)
    acta_inicio = serializers.DateField()
    hasta = serializers.DateField()

    objeto_contrato = serializers.CharField(max_length=500)
    porcentaje_cumplido = serializers.FloatField()
    fecha_contrato = serializers.DateField()

    def create(self, data):
        return Contrato.objects.create(**data)

""" view """
class Introduce_contrato(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    # POST API
    def post(self,request):
        serializer = Contratos_serializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        contrato = serializer.save()
        return JsonResponse([0], safe=False)

Estoy enviando los request con la libreria request de python.
response = requests.post(url, data={'contrato_numero': '3.500-1234567', 'acta_inicio':        '2021-01-14', 'hasta': '2021-04-30', 'objeto_contrato': 'PRESTAR LOS SERVICIOS PROFESIONALES COMO ABOGADA EN LA ACTIVIDAD:BRINDAR APOYO EN LAS EMERGENCIAS Y DESASTRES, DENTRO DEL PROYECTO IMPLEMENTACIÓN DEL PROCESO DEL MANEJO DEL DESASTRE EN EL DEPARTAMENTO', 'porcentaje_cumplido': 0.25, 'fecha_contrato': '2021-01-07'},
             headers = {'Authorization': token,
             'Content-Type': 'application/json'})

A: yo te podría sugerir lo siguiente, si te llega la fecha en formato de texto mediante strptime convertirlo a un objeto datetime que es el que maneja django y tu indicandole el formato de fecha que estas recibiendo, te pongo un ejemplo:
import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

Con lo anterior estas recibiendo tu str '2018-06-29 08:15:27.243860' y en la parte de: '%Y-%m-%d %H:%M:%S.%f' estas indicando el formato de fecha y tiempo que estas recibiendo para hacerle el cast a un objeto datetime.
Si solo requieres un objeto date solo dejarias  ''%Y-%m-%d' suponiendo que en ese formato lo estes mandando. Aqui puedes encontrar los formatos aceptados por strftime: https://strftime.org/
Esto lo tendrías que aplicar en donde estés recibiendo tu request para formatearlo previamente antes de asignarlo a un campo.
En DRF que es en tu método validate_campo(self) donde tendrias que acceder a tu campo(cambia campo por el nombre del tuyo) y al valor, seria algo asi:
def validate_campo(self, value):
    datetime_str = value
    try:
        date_time_obj = datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S.%f')
        # Retornar el valor como datetimeobj y no como str
        return date_time_obj
    except ValueError:
        raise serializers.ValidationError("Formato o fecha incorrecta.")


text:
Q: How can I log the failed cases of selenium ide and send them to an email using selenium ide commands I need a command that helps me to find a solution for the following problem:
logging the failed cases of selenium ide and send them to an email using selenium ide commands.
Thanks.
Omar

A: Please refer following URL to execute Selenium-IDE HTML Scripts using Selenium RC. Using this you will get HTML result file. To get screenshot you can add captureScreenshot command after failed step.
http://www.softwaretestingdiary.com/2012/02/selenium-core-setup-to-execute-selenium.html


text:
Q: Does VisualSVN Server 3 support HTTP compression? Does anyone know if version 3 of VisualSVN server supports HTTP compression? It was in 2.0 then dropped in 2.0.4 and I thought it was meant to be incorporated back into 3 but now can't find any references (Visual SVN is very light on documentation).

A: No, VisualSVN Server doesn't support HTTP compression and most likely will not support it in future because of memory leaks in mod_dav_svn/mod_deflate (SVN-3084).
But Subversion deltas already self-compressed so there is no big benefit to use HTTP compression for Subversion traffic.
UPDATE: The (SVN-3084) issue has been fixed, so VisualSVN Server will support HTTP compression someday, but currently it doesn't. You may add the following lines to %VISUALSVN_SERVER%\conf\httpd-custom.conf if you really want HTTP compression in VisualSVN Server:
LoadModule deflate_module bin/mod_deflate.so

# Disable builtin Subversion compression
SVNCompressionLevel 0

# Enable HTTP compression
DeflateCompressionLevel 5
SetOutputFilter DEFLATE

IMPORTANT: Make sure that you are using VisualSVN Server 3.5.7 or later, otherwise you may get excessive memory usage in some cases.


text:
Q: Slice indices TypeError and Insert list method weird behavior I have the following code:
a = [[0, 4]]
b = '1','2','3','4','5'
c = '*a3b*'

for f in b:
    if (f in c[a[0][0]:a[0][1]]):
        a[0].insert(0,f)

It returns:
TypeError: slice indices must be integers or None or have an __index__ method

But the slice indices are already integers, aren't they? What's going on? I also did (and worked, don't know why):
a[0].insert(0,int(f))

A: After your loop has performed the insert once (for '3'), a has the value [['3', 0, 4]]. So the next time you try to slice, it's trying to slice c['3':0], where before it was slicing c[0:4].
Changing to a[0].insert(0,int(f)) made it "work" by making a's value [[3, 0, 4]], so the slice became c[3:0], which ends up slicing out nothing, but does it with valid integers. Your code logic looks very strange, but without knowing the goal, I can't provide any more suggestions beyond "You need to be more careful with your types" and "I'm not sure that insert is doing what you expect it to do".


text:
Q: deploy Django site on Netlify I'm trying to upload my full-stack website, done with Django and React on Netlify.
I have tried various ways and searched for different tutorials, but unfortunately I did not find them useful ...
Many recommend using cactus to launch their own applications consisting of python, but I don't think it can work with Django, does anyone know how to do it or give me some advice? Thanks
note: netlify is only for "static" websites, so how can I make my Django application "static"?

A: Netlify is not really the match made in heaven for Django, I think you should give Heroku a go, which supports Django out-of-the-box.
If you do want to use Netflify and are ready to resign from the Django's backend features (built-in database, admin panel etc are not going to work after you make a static export), Cactus does work with Django. You could also try django-distill.


text:
Q: How can I jump to an item of a list view in android? I have an application where I have one edittext. And also I have one listview that is populated with 100 items and can show only 5 items at a time. I enter a number (n) in the Edittext and I want listview to jump to the n th item of the list view and that n th item should come at the top of the viewable area (the one that shows 5 listview items). Can you please tell me how this can be achieved..

A: A call to setSelection(position) should do the trick.


text:
Q: Does anyone know an example of a local homeomorphism from the open unit disc onto itself that is not a homeomorphism? I am interested in an example of a local homeomorphism from the open unit disc D onto itself
which is not a homeomorphism. Or, could one prove that any such map is a homeomorphism?


text:
Q: Redux-form how to update Material-UI v4 textField value? How to update TextField value(from state) by using redux-form?
I am using the version below:
  "@material-ui/core": "^4.11.0"
  "redux-form": "^8.3.6"

Before I use redux-form, I was able to update the TextField value from the onChange event by dispatch to the reducer action such as below:
<TextField
  id="name-id"
  label="Name"
  name="Name"
  value={props.Info.Name || ""}
  onChange={(e) => {
    props.updateTextInput({ //calling reducer
      name: e.currentTarget.name,
      value: e.currentTarget.value,
    });
  }}
/>

Now, I want to use the redux form, but I am not able to typing in the input field. I've tried to add value property but not working.
Below are my redux-form code:
const renderTextField = ({
  label,
  input,
  meta: { touched, invalid, error },
  ...custom
}) => (
    <TextField
      label={label}
      placeholder={label}
      value="test value" //try to set value, but not working
      error={touched && invalid}
      helperText={touched && error}
      {...input}
      {...custom}
    />
  );

<Field
  name="Name"
  component={renderTextField}
  label="Name"
  variant="outlined"
  fullWidth
  value={props.Info.Name || ""} //try to set value, but not working
  onChange={(e) => {
    props.userUpdateTextInput({
      name: e.currentTarget.name,
      value: e.currentTarget.value,
    });
  }}
/>

I found on the {...input} there is an onChange function, it will perform something for redux-form, but at the end, my input text will be removed.

A: What I missed is the formReducer. After adding the code below, everything working as expected.
import { reducer as formReducer } from 'redux-form';
export default combineReducers({
  User: userReducer,
  form: formReducer,
});


text:
Q: Getting java.lang.ClassNotFoundException:MalformedPatternException While trying to marshal the java object to xml i am getting below exception .
java.lang.ClassNotFoundException: org.apache.oro.text.regex.MalformedPatternException
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:186)
    at org.castor.xml.AbstractInternalContext.getRegExpEvaluator(AbstractInternalContext.java:325)
    at org.exolab.castor.xml.validators.PatternValidator.initEvaluator(PatternValidator.java:262)
    at org.exolab.castor.xml.validators.PatternValidator.validate(PatternValidator.java:200)
    at org.exolab.castor.xml.validators.StringValidator.validate(StringValidator.java:302)
    at org.exolab.castor.xml.validators.StringValidator.validate(StringValidator.java:340)
    at org.exolab.castor.xml.FieldValidator.validateInstance(FieldValidator.java:324)
    at org.exolab.castor.xml.FieldValidator.validate(FieldValidator.java:271)
    at org.exolab.castor.xml.util.XMLClassDescriptorImpl.validate(XMLClassDescriptorImpl.java:1072)
    at org.exolab.castor.xml.Validator.validate(Validator.java:135)
    at org.exolab.castor.xml.Marshaller.validate(Marshaller.java:2594)
    at org.exolab.castor.xml.Marshaller.marshal(Marshaller.java:826)
    at in.mywebapp.util.XMLUnmarshaller.getStatusRequestParam(XMLUnmarshaller.java:266)

Not sure which jar is missing  .

A: you are probably missing oro.jar. You can add maven dependency
    <dependency>
        <groupId>oro</groupId>
        <artifactId>oro</artifactId>
        <version>2.0.8</version>
    </dependency>

or download the jar from maven repository

A: Please make sure oro jar file is in classpath. It is not there. So, class loading is failing


text:
Q: Google Direction Service: Estimating U turn at slightest deviation from route I am using Google Direction Service for route drawing by providing it way points (recorded at some specific time interval). While drawing, it, sometimes (may be due to slight error in GPS measurement), it draws like the vehicle took a U turn to reach there. I guess it can be solved only if google ignores road dividers.
For example:
Look at the below picture, my vehicle moves on left road, but due to GPS accuracy issues, it sometimes gives me coordinates on right part of road. And when I give the coordinates to google to draw the the path, it gives me a U - Turn.
Can anybody please tell me how can I solve this issue?


text:
Q: Wrong result for pandas timestamp - dateoffset Strangely enough:
In[]:  import pandas as pd
       pd.Timestamp('2015-10-10') - pd.DateOffset(month=1)
Out[]: Timestamp('2015-01-10 00:00:00')

What am I doing wrong?
PS:
pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 2.7.10.final.0
python-bits: 64
OS: Linux
OS-release: 3.13.0-63-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8

pandas: 0.16.2
nose: 1.3.7
Cython: 0.23.3
numpy: 1.9.2
scipy: 0.16.0
statsmodels: 0.6.1
IPython: 4.0.0
sphinx: 1.3.1
patsy: 0.3.0
dateutil: 2.4.2
pytz: 2015.4
bottleneck: 1.0.0
tables: 3.2.0
numexpr: 2.4.3
matplotlib: 1.4.3
openpyxl: 1.8.5
xlrd: 0.9.3
xlwt: 1.0.0
xlsxwriter: 0.7.3
lxml: 3.4.4
bs4: 4.3.2
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: 1.0.5
pymysql: None
psycopg2: None

A: You probably want this:
>>> pd.Timestamp('2015-10-10') - pd.DateOffset(month=9)
Timestamp('2015-09-10 00:00:00', tz=None)

This may be even better for you though:
>>> pd.Timestamp('2015-10-10') - pd.DateOffset(months=1)
Timestamp('2015-09-10 00:00:00', tz=None)

You're setting month but you want to set months. Minute difference.

A: Thanks so much @rofls for noting that pd.DateOffset(month=X) will SET the month to X.  What I wanted was simply to subtract one month.  This seems to be achieved with ... - pd.DateOffset(months=1).  ("months" plural, even though there is just one to remove).


text:
Q: How to hide PHP file name and extension in url (IIS) How to hide filename.extension in url but not in .htaccess. I'm using IIS server and I need to play with web.config
With code below I can hide only extention which is .php:
<rewrite>
  <rules>
    <rule name="Redirect .php extension" stopProcessing="false">
      <match url="^(.*).php$" ignoreCase="true" />
    <conditions logicalGrouping="MatchAny">
      <add input="{URL}" pattern="(.*).php$" ignoreCase="false" />
    </conditions>
      <action type="Redirect" url="{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="hide .php extension" stopProcessing="true">
      <match url="^(.*)$" ignoreCase="true" />
    <conditions>
      <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
      <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      <add input="{REQUEST_FILENAME}.php" matchType="IsFile" />
    </conditions>
      <action type="Rewrite" url="{R:0}.php" />
    </rule>
  </rules>
</rewrite>

A: First of all, if you already have an .htaccess file, you can import it using URL Rewrite section in IIS Manager.
Secondly, you cannot hide both filename and extension because filename identifies the script. Hiding extension in your example, you make an assumption it is .php, check if file with requested name and .php extension exists, and execute it. E.g. http://some.site/page.php can be requested as http://some.site/page, and http://some.site/home.php can be requested as http://some.site/home.
Hiding both filename and extension will result with http://some.site/ in both cases, which make it impossible to identify which 'page.php' or 'home.php' should be called.
You can redirect everything to a single php script and analyse query string yourself though. The following rule redirects every request to index.php:
<rewrite>
    <rules>
        <rule name="front controller" stopProcessing="true">
            <match url="^(.*)$" ignoreCase="false" />
            <action type="Rewrite" url="index.php" appendQueryString="true" />
        </rule>
    </rules>
</rewrite>

You may need other rules or conditions to exclude static files, directories, etc.


text:
Q: During installation of Django, why do I keep getting ImportError: No module named django? I'm just trying to get a "hello world" using django.  I've downloaded django onto my desktop and i have python with Idle in my applications folder.  I've followed the instructions on https://www.djangoproject.com/download/ but when i try to import django in Idle I get ImportError: No module named django
I've looked around and have tried sys.path which yields ['', '/Users/nicholastzikas/Documents', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages']
I've also seen PYTHONPATH mentioned a few times, but I have no idea how to use this.  Any help is much appreciated.

A: Probably the path where django got installed to is somehow not in any of the paths listed in your sys.path. Normally it should be inside of site-packages. What you could try is the following:
1) Search for the dir where django was installed on your system.
2) once you find it, you can quickly test if that is the problem, adding in IDLE the path with sys.path.append('/path/to/django/dir') and then try import django again.
3.a) If that worked, you can manually move the path to '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages' for example.
3.b) If that doesn't work, well, then maybe the django files are corrupted (try installing again) or maybe the versions of your installed python and django mismatch?

A: Two suggestions.  First, if you haven't restarted IDLE since you installed django, try quitting IDLE (Command-Q) and restarting it.  If that doesn't help, chances are that you inadvertently installed Django to another Python instance, probably one of the Apple-supplied system Pythons.  Just try it again: quit IDLE again then, from a new Terminal shell window, install Django again but make sure you are using /usr/local/bin/python2.7 rather than just python.


text:
Q: What's the difference in content between the Ubuntu and Lubuntu Software Centers? Why aren't winners of the app showdown available in the latter? What's the difference in content between the Ubuntu and Lubuntu Software Centers?
I've seen this Are softwares installable on ubuntu also installable on lubuntu? which indicates that the content should be the same. However, I looked for Ridual, OrthCal, Cuttlefish and MenuLibre. While all four are available in the Ubuntu Software Center, they aren't listed in the Lubuntu Software Center. Will they eventually be listed? Who decides?
I'm asking because one of the criteria in the apps showdown, if I understood correctly, was desktop integration. If by "desktop", Unity is specifically implied then it would make sense not including them in the Lubuntu Software Center. Is that correct?
I'm on 12.04.

A: Both distributions use the same repositories. So, software that can be installed on ubuntu can also be installed on Lubuntu ,which means that they have the same software center.

A: The Lubuntu Software Center will list more apps in future according to Stephen Smally in a response posted here:

That's because Lsc is not currently able to show software from other
  sources (e.g. the paying software or the ubuntu apps showdown). the
  new  Lsc will be hopefully be able to replace Usc in every aspect.

Updated on 20130304:
In a comment to a post on Lubuntu's "Official" Facebook page dated 201300303, Phill Whiteside had this to say:

Lubuntu Software Center is currently stalled as there is no developer
  to take it forward. So... if you know a competent python programmer
  who would like a project, please get them to get in touch.

(I don't know how to link to comments in Facebook.)

A: You can add the Ubuntu software center to Lubuntu by installing "software-center" package from Synaptic.
The Lubuntu software center is a lightweight app written by the Lubuntu team, by design, it doesn't have all the features of the Ubuntu software center.
That said, the app-contest winners don't seem to be in the main Ubuntu repositories.
for example for the "MyAgenda" app I can go to https://myapps.developer.ubuntu.com/dev/apps/1211/
and I have two options to install the app.  I can download the .deb, or I can add the ppa repo, then install the package with
sudo add-apt-repository ppa:piotr-zagawa/ma
sudo apt-get update
sudo apt-get install myagenda


text:
Q: Wicket CheckBox (Model problem) How can I make wicket to call CheckBox setObject every time form is submitted?
new CheckBox("booox", new IModel(){
..
..
..
});
Now it's called only IF value has changed. Please?

A: Why would you need this? If you are calling business logic in setter it's not very good approach. If you just need dynamic model updating, go for (Compound)PropertyModel.

A: What's the use case?
Surely anything that needs to be aware of the checkbox model changing on form submit should look at the model value in the relevant onSubmit()?

A: If you add a CompoundPropertyModel to your panel/page, wicket will update the checkbox automatically if a form submit takes place. No need for manually calling the setObject function.
private IModel<Boolean> boooxModel;
...
public SamplePage(){
 boooxModel = new CompoundPropertyModel(new Boolean());
}
...
new CheckBox("booox", boooxModel);

make sure your booox is added to the form you are submitting.


text:
Q: Can a phase margin become bigger than 180° and is this bad? I have a wrong mental model about phase margin in control theory.
I see that a phase of -180° is bad. If my input is a sine wave and I have negative feedback, which has a -180° phase shift, the feedback will become positive --> oscillation.
But why is positive phase margin good? Would a phase shift of +180° degree not be equally bad? I assume the best would be it is 0 every where. But I don't see why +45° is better then -45°.
When I am thinking about this I always try to imagine a sinusoidal signal, since one can not know how the input signal will actually look like. This is the reason I am treating positive and negative phase margins equally.
EDIT:
I just found one big mistake I have made. @Chu also pointed this out. The phase margin is 180° minus the phase at unity gain. Therefor all negativ phase margins mean an actual phase of smaller then -180°
This means my questions is almost obsolete. The actual questions should be now: Is a positive phase margin bigger than 180° bad and possible to achieve?

A: What really matters is what the gain and phase are for a given frequency, phase margin is how much phase is allowed at a given frequency. If the signal is very attenuated (below 0 or something like -80dB, then most of the time it doesn't matter what the phase is).
A better way to look at it would be not to worry about what phase margin is, but how much phase there is at a given frequency. You find the 0dB point, and then look at the phase, if it is lower than -180deg then you have a problem, it will make the system unstable.
Either find the 0dB point or -180deg point then find out how much phase margin you have.

Source: https://www.sciencedirect.com/topics/engineering/gain-margin


text:
Q: How to display next items from a plist file in a quiz app? Just new to xcode. I'm trying to create a quiz app with several questions and answers stored in a plist file. So far the first question and answers are correctly displayed in a labels on the UIView. There is also a next button that displays when the correct answer is given. When the "Next" button is pressed the next question and answers should be loaded into the labels on the UIView.
Any idea what the code for this might be?

A: I agree with hw731 regarding the broadness of this question, however... I recently have been working with plists and I am happy to share an advice based on what I have done.  Typically, what I have found is that something like:
    path = [[NSBundle mainBundle] pathForResource: @"questions" ofType: @"plist"];

    if ([fileManager fileExistsAtPath: path])
    {
        questionsArray = [[NSMutableArray alloc] initWithContentsOfFile: path];
    }

which will turn your plist into an array will allow you to shift your thinking from 'how to get info from a plist' to 'how to iterate through an array'.  You can easily track which question is currently being displayed by it's array index, and then retrieve the next item by incrementing the index.


text:
Q: Can I install a Laravel project in a subdirectory of my server? I have a website that was built with just good vanilla PHP, no frameworks, etc. I am now needed to add a blog to this website and I am wanting to use Laravel / Statamtic to do so. My question is this:
Can I install a Laravel project in a subdirectory of my server? For example, www.mywebsite.com/blog/. Ideally, everything in the blog directory would operate with my Laravel code. Everything outside of the blog directory would just continue to work as is. Is this possible?
And if it is possible, is there something special I need to do in my Ngnix config file?

A: All you would have to do is take the contents in the /public folder and put it in the desired subdirectory, so "yourwebsite/blog".  Then move the contents from the root laravel folder to outside the root folder on the server, so basically everything that is left in the project after you remove public would then go into say "/var/www/" if your root folder is "/var/www/html".  After that simply update the path to the autoloader and app.php in the index.php file, which was previously in your public folder but is now in your sub directory.  Keep in mind if you do this all routes in the laravel app will have to have the subdirectory as part of any relative url, probably simple to solve this with a group.
If you are simply looking to do a blog and already know PHP why not pick up wordpress and do a basic template for yourself?  It's simple to pick up, a weekend maybe.  If you consider it check out VCCW as a development environment.


text:
Q: How do you work out how long a program will take to run by inspection? I went to a lecture on algorithms the other day, and we were learning about dynamic programming. The lecturer mentioned that to solve fibonacci recursively will take close to exponential time, and doing it in a linear fashion will take quadratic time. How do you work this kind of stuff out just by inspection?

A: If you use only the recursive implementation(with out memoization)
to determine f_n you need to calcualte f_n-1 and f_n-2, similarly
f_n-1 will branch to f_n-2 and f_n-3 and same for f_n-2.
So if there is such branching
and there is no any reuse concept try to count the nodes. It will be >2^n most of the time
this implies exponential running time.
But if you use a linear fashion(as you mentioned) it will be linear O(n) not even quadratic!
But you have to be careful about divide and conquer algorithms like merge sort
although it uses binary division the deepth of the tree will be logn where the number of nodes will become to be 2^logn which is equal to n.


text:
Q: Line breaks in listings Is there a way like wrap the line after at most 60 letters but it should not break inside some commands like listings does?
Example:
    \documentclass[a5paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage[utf8]{inputenc}
    \usepackage{listings}
    \usepackage{xcolor}

    \lstset{%
      language=[LaTeX]TeX,
      backgroundcolor=\color{gray!25},
      basicstyle=\ttfamily,
      breaklines=true,
      columns=fullflexible
    }

    \begin{document}
    \begin{lstlisting}
    The roadrunner is the fastest running bird \remark{Check this again with a zoologist!}.
    \end{lstlisting}
    \end{document}

Output:
    The roadrunner is the fastest running bird         remark{Check this again with a zoologist!}.

That should not happen! In my eyes this problem is not discussed in verbatim environment that can break too long lines.

A: Thanks to Torbjørn T., my question is answered:
One simply has to say:
\lstset{%
  breaklines=true,
  breakatwhitespace=true,
}


text:
Q: discord.py [mp3 @ 000001dc99bec540] Estimating duration from bitrate, this may be inaccurate I have a problem with "[mp3 @ 000001dc99bec540] Estimating duration from bitrate, this may be inaccurate", using discord.py. Everything works (bot is speaking the text, which we tell him), but, at the end, always shows it. How can I solve it?
        if _command == "speak":
            try:
                await message.delete()
                try:
                    error = _message[1]
                except IndexError:
                    message = await _channel.send("Where is my text, which I have to speak?!")
                    await asyncio.sleep(3)
                    await message.delete()
                    return
                channel = message.author.voice.channel
                voice = discord.utils.get(client.voice_clients, guild=_guild)
                if voice and voice.is_connected():
                    await voice.move_to(channel)
                else:
                    voice = await channel.connect()
                tts = gTTS(text=text, lang='en')
                tts.save("pcvoice.mp3")
                voice.play(discord.FFmpegPCMAudio(executable=r"C:\ffmpeg\bin\ffmpeg.exe", source="pcvoice.mp3"))
            except discord.errors.ClientException:
                await _channel.send("Come on! I am already playing something!")

A: This is a perfectly normal FFmpeg debug print
A way to disable this, while probably not the best is doing
discord.FFmpegPCMAudio(options = "-loglevel panic")

or any other loglevel FFmpeg deems acceptable.
This is generally bad because if FFmpeg is failing, you might want to know.


text:
Q: How to change all the text on all my activities (button text, textviews, etc.) with a click event? Can i change all the text in my app to other text, when i click a button or maybe select a menu item?
What I am actually trying to do is make my app to translate to a couple of non-iso languages ("non-iso" means i couldn't find them on wiki's ISO-639 list).
So I want the user to be able to select the language in which they view my app, regardless of whatever their phone language settings might be. And i want them to be able to make the language selection from within the app.
I have all the english button and textview text in strings.xml, and i can make a strings-xx.xml for the new languages.
I will be using a submenu with the language options listed. So the text change will be responding to an onclick event on that menu.
Any pointers will be very welcome.

A: Taken from: How to change language of app when user selects language?
public void setLocale(String lang) {
    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, YOURACTIVITY.class);
    startActivity(refresh);
    finish();
}

You cann pass any valid language string to the setLocale method, like "de" or "it", but you have to restart the Activity.
I don't know how your App will behave if you press the back button. If it starts your "old" Activity try this while restarting your Activity:
public void setLocale(String lang) {
    myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, YOURACTIVITY.class);
    refresh.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(refresh);

}


text:
Q: AWS: Wordpress install I hope you can help.
I'm trying to setup a wordpress blog. In the past I've been using HostGator but now making the switch to AWS. However, I'm having problems with the basics.
I have created an instance and managed to login to the instance via putty.
In S3 I have created 2 buckets. lmof.uk and www.lmof.uk (following one of the AWS guides) and uploaded a php file to lmof.uk
In Route 53, I have added the Domain to the Hosted Zone, created A record and CNAME as well.
Updating my Nameservers from my register and if you visit lmof.uk it downloads the php file.
When I log into my Putty, I can't seem to find the php file anywhere. I followed this guide: https://www.youtube.com/watch?v=PbQSs-_d-yM but when it came to looking at my public ip address, the connection times out.
I'm sure I'm missing something fundamental, but at this stage I'm just looking to install wordpress, see the files, edit them and see the changes on the website.

A: you forgot to open port 80 on security groups.follow the link below
Opening port 80 EC2 Amazon web services


text:
Q: @Scheduled job blocking Quartz job I have managed to configure two jobs in my Spring Boot app as below.

*

*Echo job scheduled for every 3 minutes.

@Service
public class TransactServiceImpl {

@Scheduled(fixedRateString = "${interval}")
  @Override
  public void echo() { /* implementation ommitted*/
  }
}

In the logs, I see "logger":"com.pip.service.impl.TransactServiceImpl", "msg":"Echo", "thread":"scheduling-1" and this keeps coming every 3 mintues.

*I have also configured a Quartz job scheduled every minute which works fine only when I comment out the //@Scheduled of the echo job. When I run it both together, only the echo job gets triggered. I believe this is because of the thread that's supposed to execute Quartz job is getting blocked somehow or something to do with ThreadPool, I suppose.  The quartz job is supposed to run only once at night, but I kept it as 1 minute for testing purposes. I need to get these jobs working together asynchronously. Here are my quartz configurations.

@Configuration
@EnableAsync
@EnableScheduling
public class SchedulerJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

  private AutowireCapableBeanFactory beanFactory;

  @Override
  public void setApplicationContext(final ApplicationContext context) {
    beanFactory = context.getAutowireCapableBeanFactory();
  }

  @Override
  protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    beanFactory.autowireBean(job);
    return job;
  }
}

ShedulerConfig
@Configuration
public class SchedulerConfig {

  @Autowired
  private DataSource dataSource;

  @Autowired
  private ApplicationContext applicationContext;

  @Autowired
  private QuartzProperties quartzProperties;

  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() {

    SchedulerJobFactory jobFactory = new SchedulerJobFactory();
    jobFactory.setApplicationContext(applicationContext);

    Properties properties = new Properties();
    properties.putAll(quartzProperties.getProperties());

    SchedulerFactoryBean factory = new SchedulerFactoryBean();
    factory.setOverwriteExistingJobs(true);
    factory.setDataSource(dataSource);
    factory.setQuartzProperties(properties);
    factory.setJobFactory(jobFactory);
    factory.setTriggers(repoTriggerConfig().getObject());
    return factory;
  }

  @Bean
  public JobDetailFactoryBean repoJobConfig() {
    JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
    jobDetailFactory.setJobClass(RepoJob.class);
    jobDetailFactory.setDurability(true);
    jobDetailFactory.setGroup("pip-scheduler-group");
    return jobDetailFactory;
  }

  @Bean
  public CronTriggerFactoryBean repoTriggerConfig() {
    CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
    cronTriggerFactoryBean.setJobDetail(repoJobConfig().getObject());
    cronTriggerFactoryBean.setCronExpression("0 0/1 0 ? * * *");
    cronTriggerFactoryBean.setGroup("pip-scheduler-group");
    return cronTriggerFactoryBean;
  }
}

RepoJob
@Slf4j
public class RepoJob implements Job {

  @Autowired RepoService repoService;

  @Autowired RepoUtil repoUtil;

  @Override public void execute(JobExecutionContext jobExecutionContext)
      throws JobExecutionException {

    boolean success = repoService.createFile();

    if (success) {
      try {
        boolean isSuccess = repoUtil.sendInfo();
        if (isSuccess) {
          log.info("Info sent success");
        }

      } catch (Exception ex) {
        log.error(ex);
      }
    }
  }
}

quartz properties from application.yml
  quartz:
    properties:
      org.quartz.jobStore.isClustered: true
      org.quartz.scheduler.instanceId: AUTO
      org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
      org.quartz.scheduler.instanceName: pip-clustered-scheduler
      org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
      org.quartz.jobStore.useProperties: true
      org.quartz.jobStore.misfireThreshold: 60000
      org.quartz.jobStore.tablePrefix: qrtz_
      org.quartz.plugin.shutdownHook.class: org.quartz.plugins.management.ShutdownHookPlugin
      org.quartz.plugin.shutdownHook.cleanShutdown: TRUE
  jdbc:
      initialize-schema: never
    job-store-type: jdbc

Uses the same database schema for application & quartz tables. I am not sure if there is anything wrong in the way quartz is configured.
Could anyone please guide me here. This is my first time using Quartz. Thank you.
Start up log:

 INFO [StartupInfoLogger.java:55] Thread:[main] Starting PipDvsApplication using Java 11.0.11 on B720L with PID 22720 (D:\Projects\pip-dvs-app\target\classes started by U55097 in D:\Projects\pip-dvs-app)
 INFO [SpringApplication.java:663] Thread:[main] The following profiles are active: dev
 INFO [DirectJDKLog.java:173] Thread:[main] Initializing ProtocolHandler ["http-nio-9090"]
 INFO [DirectJDKLog.java:173] Thread:[main] Starting service [Tomcat]
 INFO [DirectJDKLog.java:173] Thread:[main] Starting Servlet engine: [Apache Tomcat/9.0.50]
 INFO [DirectJDKLog.java:173] Thread:[main] Initializing Spring embedded WebApplicationContext
 INFO [HikariDataSource.java:110] Thread:[main] HikariPool-1 - Starting...
 INFO [HikariDataSource.java:123] Thread:[main] HikariPool-1 - Start completed.
 INFO [IsoClient.java:77] Thread:[main] Connected with host:216.76.27.250 , post:20500, status:false
 INFO [StdSchedulerFactory.java:1220] Thread:[main] Using default implementation for ThreadExecutor
 INFO [SchedulerSignalerImpl.java:61] Thread:[main] Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
 INFO [QuartzScheduler.java:229] Thread:[main] Quartz Scheduler v.2.3.2 created.
 INFO [ShutdownHookPlugin.java:120] Thread:[main] Registering Quartz shutdown hook.
 INFO [QuartzScheduler.java:294] Thread:[main] Scheduler meta-data: Quartz Scheduler (v2.3.2) 'pip-dvs-clustered-scheduler' with instanceId 'B720L1633520106597'
  Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
  NOT STARTED.
  Currently in standby mode.
  Number of jobs executed: 0
  Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 20 threads.
  Using job-store 'org.springframework.scheduling.quartz.LocalDataSourceJobStore' - which supports persistence. and is clustered.

 INFO [StdSchedulerFactory.java:1374] Thread:[main] Quartz scheduler 'pip-dvs-clustered-scheduler' initialized from an externally provided properties instance.
 INFO [StdSchedulerFactory.java:1378] Thread:[main] Quartz scheduler version: 2.3.2
 INFO [QuartzScheduler.java:2293] Thread:[main] JobFactory set to: com.pip.job.SchedulerJobFactory@b3c7c75
 INFO [DirectJDKLog.java:173] Thread:[main] Starting ProtocolHandler ["http-nio-9090"]
 INFO [QuartzScheduler.java:547] Thread:[main] Scheduler pip-dvs-clustered-scheduler_$_B720L1633520106597 started.
 INFO [StartupInfoLogger.java:61] Thread:[main] Started PipDvsApplication in 58.08 seconds (JVM running for 60.088)
 INFO [DirectJDKLog.java:173] Thread:[RMI TCP Connection(2)-192.168.29.216] Initializing Spring DispatcherServlet 'dispatcherServlet'


text:
Q: Building the min heap using recursion alone This is an attempt to make heapsort building the heap solely with function calls. The problem is that it's taking too long to complete, longer than a simpler bubblesort written in the same project, nearly 100 seconds vs bubble's 42 with 100000 entries in descending order. Mergesort and quicksort never got past a second. Nevermind the fact that it crashes on 100000 if the compiler fails to make a tail-call optimization.
It used to crash, some of the details on the implementations are there to make tail-calls happen. It has been tested on descending, ascending and randomly distributed data. Some of the changes were also made to remedy how slow it was, what gives it it's obfuscated look.
int heap_sort_step(int v[], int len, int i){
    int nextl = 2 * i + 1, nextr = nextl + 1;
    char bfl = (nextl<len)|((nextr<len)<<1);

    switch(bfl)
    {
        case 3:
        case 2:
            while(v[i] > heap_sort_step(v, len, nextr))
                swap(v + i, v + nextr);
        case 1:
            while(v[i] > heap_sort_step(v, len, nextl))
                swap(v + i, v + nextl);
        default:
            return v[i];
    }

}

void heap_sort(int v[], int len){
    return (len > 1)?
                (heap_sort_step(v, len, 0),
                 heap_sort(v + 1, len - 1)):
            NULL;
}

heap_sort(int v[], int len) takes an array and it's size and builds the min heap for every member in the array using heap_sort_step(), ordering it. Tail calls needed here.
heap_sort_step(int v[], int len, int i) takes an array, it's size and an index for building the heap, with equations as seen in nextl and nextr, 2i+1 and 2i+2, starting with i = 0. 'bfl' is an optimization trick(minor improvements over using ifs) to decide which branches to go to or just return the current value by seeing if there are more items ahead. The switch uses fallthrough and is where the heap is built, 3 and 2 means there are things to the right (0b11, and 0b10) and 1 means there are things to the left (0b01), default behaviour is returning the current number. It used to be written as:
int heap_sort_step(int v[], int len, int i){
    int nextl = (((i + 1) * 2) - 1), nextr = nextl + 1;
    if(nextl < len)
        while(v[i] > heap_sort_step(v, len, nextl))
            swap(v + i, v + nextl);

    if(nextr < len)
        while(v[i] > heap_sort_step(v, len, nextr))
            swap(v + i, v + nextr);

    return v[i];
}

As for the recursive step, it compares the current number with the returning value from the next function call, and if it is bigger, it swaps, if it is not, there is a cascade return back to the root.
At this point I'm pretty sure it's just a bad implementation and want to know if this is a complexity problem made by the changes or something else. Can it be made to compete with mergesort and quicksort using the same concept? It should be O n(log(n)), right?

A: Leaving aside the question of the performance impact of recursion, and of how you're relying on tail-call optimization to make the heap_sort() function non-recursive after all, your implementation does not look like heap sort.  Heap sort can be described like this:

*

*Arrange the elements to be sorted into a heap (naively, O(n log n); thoughtfully, O(n))

*As long as there are at least two elements in the heap, (O(n) iterations)

*

*Swap the head element with the last. (O(1))

*Reduce the (logical) heap size by 1. (O(1))

*Restore the heap condition. (O(log n) if done right)

Of course, this applies whether you're sorting in increasing order by using a max-heap or in decreasing order by using a min-heap.
As you clarified in comments, your approach is to arrange the array into a min-heap to obtain the least element, then repeat with the n - 1 element tail of the array.  That's not heap sort -- it's a variation on selection sort.  If well-implemented, it costs O(n2), because each heap-building step must visit at least the n / 2 non-leaf nodes, and therefore costs O(n).

A: After a few changes it works like a charm, here's the solution:
It's incomplete:
The heap is being formed over and over again for each item, therefore, as pointed by John this is working like a weird selection sort.
Two new functions are added to finish:
void sift(int v[], int len, int i){
    int nextl = 2 * i + 1, nextr = nextl + 1;
    int next  = 0;

    if(nextr < len)
        if(v[i] > v[nextr]){
            if(v[nextr] < v[nextl])
                swap(v + i, v + (next = nextr));
            else
                swap(v + i, v + (next = nextl));
        }
    if(nextl < len)
        if(v[i] > v[nextl])
            swap(v + i, v + (next = nextl));

    return (next == 0) ? NULL: sift_min(v, len, next);
}

restores the heap. After switching the first and the last it swaps every smaller number down the tree following a single path.
void reverse(int v[], int len){
    int i;
    for(i = 0; i < len/2; i++)
        swap((v + i), (v + (len - (i + 1))));
}

reverses the array after sorting because without knowing about the second step, using a minheap, the sorting occurs in descending order, so it's just there in to make it ascending.
There's an unnecessary recursion in the main block:
void heap_sort(int v[], int len){
    return (len > 1)?
                (heap_sort_step(v, len, 0),
                 heap_sort(v + 1, len - 1)):
            NULL;
}

Gets replaced with
void heap_sort(int v[], int len){

    heapify(v, len, 0);//this is heap_sort_step with a new name

    int templen = len
    while(templen > 1){
        swap(v, v + --templen);
        sift(v, templen, 0);
    }

    reverse(v, len);
}

The final code is:
void swap(int* ref1, int* ref2){
    int temp = *ref1;
    *ref1 = *ref2;
    *ref2 = temp;
}

int heapify(int v[], int len, int i){
    int nextl = 2 * i + 1, nextr = nextl + 1;

    if(nextr < len)
        while(v[i] > heapify(v, len, nextr))
            swap(v + i, v + nextr);

    if(nextl < len)
        while(v[i] > heapify(v, len, nextl))
            swap(v + i, v + nextl);

    return v[i];
}

void sift(int v[], int len, int i){
    int nextl = 2 * i + 1, nextr = nextl + 1;
    int next  = 0;

    if(nextr < len)
        if(v[i] > v[nextr]){
            if(v[nextr] < v[nextl])
                swap(v + i, v + (next = nextr));
            else
                swap(v + i, v + (next = nextl));
        }
    if(nextl < len)
        if(v[i] > v[nextl])
            swap(v + i, v + (next = nextl));

    return (next == 0) ? NULL: sift(v, len, next);
}

void reverse(int v[], int len){
    int i;
    for(i = 0; i < len/2; i++)
        swap((v + i), (v + (len - (i + 1))));
}

void heap_sort(int v[], int len){

    heapify(v, len, 0);

    int templen = len;

    while(templen > 1){
        swap(v, v + (--templen));
        sift(v, templen, 0);
    }

    reverse(v, len);
}

Lengthy, but it still builds the heap recursively and is fast. Can be made faster using maxheap, and of course, eliminating recursion. A quick test yields an average of less than 0.1 seconds for the same samples that were taking more than a minute.


text:
Q: Repositioning interactive advertisements in Corona SDK I've added advertisements by interactive in my app like so:
local ads = require("ads")
local adNetwork = "inneractive"
ads.init(adNetwork, "test_id")

local function displayAd()
ads.show("banner", {x=0,y=0, interval=30})
end

Then I call displayAd() in local function scene:enterScene(event) method. This works okay. Now, from the current class (game.lua), there are two scenes it can go to: gameover.lua and stage.lua. If the player clears the stage, it goes to the stage clear.
Now, if the stage clear scene appears, I'd like to move the advertisement's y-position to something like y=display.contentCenterY so I tried something like this on displayAd():
if adFlag == true then
     ads.show("banner", {x=0,y=0, interval=30})
elseif adFlag == false then
     ads.show("banner", {x=0,y=display.contentCenterY, interval=30})
end

The problem with this is that the advertisement only moves once game.lua is recalled and it never goes back to it's original position. I can't put it on the stage clear class because it has a time delay and automatically goes to the next stage. So my question is, how can I move my advertisement's position immediately on the next page?

A: You can try to modify your code like this:
if adFlag == true then
     ads.hide()
     ads.show("banner", {x=0,y=0, interval=30})
elseif adFlag == false then
     ads.hide()
     ads.show("banner", {x=0,y=display.contentCenterY, interval=30})
end


text:
Q: What is the semantically correct way to include transcript from a comic? Suppose you have a page that displays a comic image. You already have the full textual contents of the comic (its transcript) in text. What would be the semantically correct way to include it in an HTML5 page so that:

*

*search engines know of the textual contents of the image,

*users can find specific text (e.g. memorable punchline) within the images through search,

*users can optionally click to read the transcript if they have trouble reading it from the image?

Option 1 (figcaption approach):

Sandwich

- Make me a sandwich. - What? Make it yourself. - Sudo make me a sandwich. - Okay.

This is my best creation. I hope you like it.

Also, my cat was especially cute today.

Problems:

*

*figcaption is supposed to be describing content, not transcribing;

*transcript is too close to image UX-wise, this content ideally has to be accessible but not immediately in the way of other information.

Option 2 (enclose everything in figure):

Sandwich

This is my best creation. I hope you like it.

Also, my cat was especially cute today.

- Make me a sandwich. - What? Make it yourself. - Sudo make me a sandwich. - Okay.

Problems:

*

*figcaption is supposed to be describing content, not transcribing;

*content not relevant to image ("Also, my cat was especially cute today.") is semantically connected to it.

Option 3 (alt text approach):

Sandwich

This is my best creation. I hope you like it.

Also, my cat was especially cute today.

Problems:

*

*alt text should be describing content, not transcribing;

*with very long transcripts, alt text will look like spam;

*transcript not available to user on demand (unless it is duplicated as HTML or via a script).

Option 4 (details approach):

Sandwich

This is my best creation. I hope you like it.

Also, my cat was especially cute today.

        Transcript
        - Make me a sandwich. - What? Make it yourself. - Sudo make me a sandwich. - Okay.

Problems:

*

*transcript is not semantically connected to the image.

What would be the best approach to this given the original goals?

A: A caption and a transcript are two semantically different things.
 should be used for captions, which are brief explanations of the figure. As such, it seems inappropriate to use it for the transcript.
Option 4 seems the closest. The transcript can be tied to the comic image using the aria-describedby attribute.
The author's message may be best as an , since it's complementary content indirectly related to the article.
Also, consider adding markup to the transcript itself, including character names.
Something like:

Sandwich

Today's comic.

This is my best creation. I hope you like it.

Also, my cat was especially cute today.

    Transcript

Name1: Make me a sandwich.

Name2: What? Make it yourself.

Name1: Sudo make me a sandwich.

Name2: Okay.


text:
Q: Pyserial, in_waiting gives empty value '0L' currently I am struggling with serial communication to an external device using Python 2.7/ Pyserial. As an alternative I used a terminal software for data logging: Screenshot of fomerly used Software.
One can see the device first gives a header line followed by cyclic updated data strings (separated lines with CR LF each)
Now trying to get the data into Python somehow does not work, cp:
import serial
ser = serial.Serial('COM8', 38400)

Then
ser.inWaiting()

gives
0L

The buffer seems to be empty when accessing from python while the terminal software runs fine.
I tried setting
ser.setDTR(1)
ser.dsrdtr=1

both without success.
Further information: The device runs on a virtual port splitter. The USB cable is connected to COM3. There are two tools accessing the device using COM6 (for device configuration over HMI) and COM8 for data logging as described here.
I really appreciate any help.
Regards,
mulm

A: So, I found a workaround for my problem. Since the terminal software that works with my device runs fine I use its built in http-server and then make a request using Python. Now I have to start an extra software, but in my case this is the best option available.
Used software:
http://www.umonfw.com/ucon/
Code snippet:
import socket

# Closing the connection after a single request prevents the buffer from filling up with outdated data.

try:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('xxx.xx.xx.xxx', 50080))

    val = client.recv(96)

    client.close()

except socket.error:
    print "Unable to connect to server."
    val = None

Not pretty but it does the job.


text:
Q: Catch mousve hover on text and highlight related value
If you look at the attached image, in the second table, when the cursor moves to the cell contains 4, all correspond text in the first table will get highlighted. I managed to acheive this using hover function :
/////////////////////////////////////////////////////////////
function HightLightTable1() {

    // 0
    $(".t1_h_x0").hover(
function () {
    $(this).css("background-color", "yellow");
    $(".t1_t_x0").css("background-color", "yellow");
}, function () {
    $(this).css("background-color", "white");
    $(".t1_t_x0").css("background-color", "white");
}
);

    // 1
    $(".t1_h_x1").hover(
function () {
    $(this).css("background-color", "yellow");
    $(".t1_t_x1").css("background-color", "yellow");
}, function () {
    $(this).css("background-color", "white");
    $(".t1_t_x1").css("background-color", "white");
}
);
// and keep adding code here if there are more tables
}

This will lead to alot of html code also, for example, the first table :

Now I'm re-designing the site, and came to wonder is there any more efficient way to achieve this?
Link to my site if you want to take a look

A: You could simplify your code by giving all the cells to be hovered the same class name and then use the cells text to build a query to adress the right spans like this:
$(".hovercell").hover(
    function () {
        $(this).css("background-color", "yellow");
        $(".t1_t_x"+$(this).text()).css("background-color", "yellow");
    }, function () {
        $(this).css("background-color", "white");
        $(".t1_t_x"+$(this).text()).css("background-color", "white");
    }
);

jsfiddle: http://jsfiddle.net/markai/o3arj251/


text:
Q: Как расположить блоки друг под другом? Нужно расположить блоки друг под другом при разрешении экрана меньше 800px. Размер у всех трех блоков должен быть одинаковый. codepen
В порядке
.block_1
.block_2
.block_3

код
.blocks
  .block_1
    p block_1
  .blocks_left
    .block_2
      p block_2
    .block_3
      p block_3

.blocks,
.blocks_left {
  display: grid;
}

.blocks {
  grid-template-columns: 2fr 1fr;
  @media screen and (max-width: 800px) {
    grid-template-rows: 1fr 2fr;
  }
}

.block_1 {
  background: red;
}
.block_2 {
  background: yellow;
}
.block_3 {
  background: green;
}

Если без медиа запроса, то grid-template-rows: 1fr 2fr; работает, а с ним почему нет?

A: Вариант без медиа запросов:

.blocks,
.blocks_left {

  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));

}

.block_1 {background: red;}
.block_2 {background: yellow;}
.block_3 {background: green;}

block_1

block_2

block_3

A: grid-template-columns: 1fr; тоже надо было добавить)


text:
Q: Why are Linux installs bigger than I've read? Some beginner questions
*

*I've read in different textbooks that say Linux is light-weight(e.g. It could fit on a 1.4MB floppy). So why is the download from the Ubuntu or Fedora CD sized or larger?

*Do the device drivers extend the kernel? For example: if I have new hardware and I have installed the device driver, will my kernel code get extended or is the driver installed as a service for the kernel to use?

*When using a LiveCD such as Ubuntu, when system boots does all 700MB of the OS get loaded to RAM or just parts of it?
I ask these questions because I feel they're common beginner questions and I think it would be good to have them all in one place.

A: It's just barely possible to fit an extremely minimal Linux system on a floppy. (Here are a few examples; beware that many of these span several floppies.) With just 1.44MB, there is no have any room for any application; I think you can get a minimalistic command line with no interesting command to run.
As an example of a more realistic tiny system, my home router runs Linux. The whole disk image (kernel plus programs) fits in 4MB (in fact, I think it's close to 2.8MB). That's a dedicated system, with an old kernel version, only the drivers needed for that particular device, and not many programs — mostly networking administration tools, including a small web server, an SSH client and server, a shell.
A distribution like Ubuntu or Fedora comes with thousands of programs. Some of these programs take tens of MB on their own. Some of these programs' documentation takes tens of MB. Just the device drivers for all the peripherals, network protocols and other parts of the kernel take about 100MB these days — there are so many different devices one can connect to a PC.
For a basic system with a GUI and a web browser, you'll need a couple of hundred MB. For a more complete system with a full desktop environment, a word processor and so on, count on a couple of GB. If you start having multiple alternatives for each program (Gnome and KDE, Firefox and Chrome, …), the sky's the limit.
If you feel like comparing with the size of Windows, keep in mind that a Linux distribution contains much more than the equivalent of Windows: distributions like Ubuntu and Fedora ship a lot of applications that you would need to install separately on Windows.

A: *

*"Linux" is really just a kernel.  You can compile your own to customize it, or use one pre-compiled by a distribution.  A kernel runs the computer and provides an environment for applications and tools.  So you need applications if you want to actually use the kernel for anything.  Distributions such as Ubuntu and Fedora provide not only a kernel but also applications and tools.  Since Linux is an implementation of UNIX, many traditional UNIX utilities are provided.

*Device drivers are distributed with the kernel.  It's possible to include modules as part of the kernel, or let them stand as separate files.  Usually they are compiled as modules - it's roughly similar to how Windows DLLs operate in concept.  This way you don't have a huge kernel in RAM with every device driver built-in, and the kernel can work in a variety of environments.

*The kernel is loaded in RAM on boot and stays there.  Applications are loaded when you use them and release their memory when they terminate.  Modules are loaded when they are inserted, which is usually when hardware is detected or some operating system facility is used.  Modules can also be removed, or unloaded.

A: 1 - The base system may fit. The cd editions(like ubuntu or fedora) have more than the system, like for example some of the programs you should use(Firefox,Gnome,Banshee etc...) and probably some codecs for media.
2 - Most of the drivers come bundled, and run as kernel modules, but non-crucial proprietary drivers are not bundled, only Open Source ones.
If you don't have a custom kernel, then all the drivers needed for a basic usage, should be present, but probably proprietary drivers will get you a better performance.
3 - No, only the required is loaded. The Kernel image/Modules, and the processes that are being used (like xorg/systemd etc...)

A: *

*As Claudiop and ultrasawblade told you, there is a kernel which is small and can be customized to be even smaller, then there are tools, usually present on unix like systems, and the huge applications like office, browser, multimedia software, games and so on, with graphical user interfaces which occupy much more space.
Ten years before now I really had such a Linux on a floppy disk, it is called tomsrtbt and could be installed on a classical floppy for 1.4 MB, but reformated it and contained 1.7 MB with a very restricted kernel, which means very few device drivers, very few tools, a very restricted shell and no GUI and no such. Maybe you'll find it if you're really interested.

*Most drivers are part of the kernel. For new hardware - either your kernel already includes a driver, or a generic driver exists (mice, harddrives, keyboards, ...) which works. Some drivers are client space programs (example printing: CUPS). You don't search the net for new drivers or visit the vendors page. There might be rare exceptions.

*Yes, the whole CD is loaded to RAM which acts as a pseudo HDD.


text:
Q: Qt-Designer's spinbox does show or store data I am new in Qt Designer. I created a user form to show and insert data to a shapefile. Everything works well, except the spinboxes. The fieldtype in the shapefile is integer with fieldlength 10. The shapefile already contains data. In the userform these data in the spinboxes are not shown, the spinbox shows "NULL". When I look in the attribute table data also are missing, even they have been there before. When I insert data the field length is not 10 as it was before, but only 2. The inserted data are not stored.
What's the problem?


text:
Q: Parsing text files containing lists of files I have txt files containing info about catalogs and it files on a server. From each file I need only to get 2 catalogs with it filenames to get them into a massive for further comparison with local files.
I thought about line by line reading but I am stuck. Especially if it finds 'SDU__DACS' in filename in other catalog which I'm not interested it writes it to previous catalog name.
I was trying:
pathSDU = []
pathSCI = []
filesDict = {}
for file in glob.glob('/foo/bar/catalog/*.txt'):
    with open(os.path.join('/foo/bar/catalog', file), 'r') as openFile:
        print('opening file ' + file)
        for line in openFile:
            if '/ACS/SDU_:' in line:
                pathSDU = line
            else:
                if 'SDU__DACS' in line:
                    if 'manifest' not in line:
                        filesDict.update({line: pathSDU})
            if '/ACS/ScienceDataFile:' in line:
                pathSCI = line
            else:
                if 'SCI__DACS' in line:
                    if 'manifest' not in line:
                        filesDict.update({line: pathSCI})

Example of txt files content:
/data/foo/bar/ACS/SDU_:
68421952
17660866 2021-09-06 09:56 SDU__DACS_69DC_0241DB01_2021-246T08-13-26__00001.EXM
17660866 2021-09-06 09:41 SDU__DACS_69DB_0241DB01_2021-246T08-12-37__00001.EXM
17660866 2021-09-06 09:24 SDU__DACS_69DA_0241DB01_2021-246T08-11-46__00001.EXM
17660866 2021-09-06 08:27 SDU__DACS_69D9_0241DB01_2021-246T08-10-56__00001.EXM

/data/foo/bar/TGO/ACS/ScienceDataFile:
69881252
 14759936 2021-09-05 21:51 SCI__DACS__0241DA01_2021-246T04-26-15__00001.EXM
       53 2021-09-05 21:51 SCI__DACS__0241DA01_2021-246T04-26-15__00001.EXM.manifest
318758912 2021-09-05 14:42 SCI__DACS__0241D801_2021-246T00-30-32__00001.EXM

A: Try using the following.
with open('data.txt') as openFile:

    path = None
    files = []
    filesDict = dict()

    for line in openFile:
        line = line.rstrip()

        # empty line; you're done with one folder
        # store the previous data, if it exists and start a new collection
        if not line.strip():
            if files and (path is not None):
                filesDict[path] = files
                path = None; files = []
                continue

        # paths end with colons, don't store specific variables for each path
        if line.endswith(':'):
            # save previous results, if any
            if files and (path is not None):
               filesDict[path] = files

            path = line; files = []
            next(openFile) # skip the line with only a number
            continue

        if path:  # only continue if path is defined
            if 'manifest' not in line:
                files.append(line)

    # last folder read from file but not yet stored
    if path:
        filesDict[path] = files

Sample run
for p, l in filesDict.items():
  print(p)
  for f in l:
    print('\t', f)

Output
/data/foo/bar/ACS/SDU_:
     17660866 2021-09-06 09:56 SDU__DACS_69DC_0241DB01_2021-246T08-13-26__00001.EXM
     17660866 2021-09-06 09:41 SDU__DACS_69DB_0241DB01_2021-246T08-12-37__00001.EXM
     17660866 2021-09-06 09:24 SDU__DACS_69DA_0241DB01_2021-246T08-11-46__00001.EXM
     17660866 2021-09-06 08:27 SDU__DACS_69D9_0241DB01_2021-246T08-10-56__00001.EXM
/data/foo/bar/TGO/ACS/ScienceDataFile:
      14759936 2021-09-05 21:51 SCI__DACS__0241DA01_2021-246T04-26-15__00001.EXM
     318758912 2021-09-05 14:42 SCI__DACS__0241D801_2021-246T00-30-32__00001.EXM


text:
Q: Ajax get hidden form in PHP file with jQuery I have a PHP file that pulls information from a SQL database. I need to refresh this information every few seconds and plot onto a Google map. The map code is contained on another page and is within the header for the location marker etc, is there a way I can pass the PHP data to the map?
Overview:
data.php (contains information from database)
map.php (file that contains map to refresh every 10 seconds)
Really appreciate any help.

A: You need to call 2 different XMLHttpRequest every 10 secondes (thanks to setTimeout method) ;

*

*1 to recover data.php informations ;

*1 to send it to map.php.

In your php files, you will have to code the behavior to adopt when getting those requests.


text:
Q: Adding a click function to a button in Python I am very new to Python. I'm creating a simple 3D world using Vizard 4.0 and I want to add a stopwatch to the screen. I dont want an actual 3D stopwatch, just a simple text box in the corner of the screen which updates as the stopwatch counts. Heres what I ave so far and it doesnt work, any suggestions or help would be very appreciated!
def mytimer(num):
    time = 'Elapsed time:',viz.elapsed(),'seconds'
    print time
    timer_update = viz.addText('Time:', viz.SCREEN)
    timer_update.color(viz.GREEN)
    timer_update.fontSize(42)

    viz.callback(viz.TIMER_EVENT,mytimer)
    viz.starttimer(0,1, viz.FOREVER)

A: Cracked it :)
#Add text fields to a dictionary.
text_dict = {}
for kind in ['score','instructions','time' ]:
    text = viz.addText('', viz.SCREEN )
    text.setScale( .5,.5)
    text.alignment( viz.TEXT_CENTER_BASE )
    text.alpha( 1 )
    text_dict[ kind ] = text
text_dict['score'].setPosition( .1,.9 )
text_dict['instructions'].setPosition( .5,.5 )
text_dict['time'].setPosition( .1,.85 )

def game_timer_task():
    #Grab the text field for
    #time.
    text = text_dict[ 'time' ]
    time = 0
    text.message( 'Time: 0' )
    #Loop through as long as time
    #is under a certain number of
    #seconds.
    while time < 10:
        yield viztask.waitTime( 1 )
        time += 1
        text.message( 'Time: ' + str( time ) )

def game():
    time_passing = viztask.waitTask( game_timer_task() )
    data = viz.Data()

    yield viztask.waitAny( [time_passing], data )

    if data.condition == time_passing:
        game_over = text.message( 'Game Over!' )
        game_over.setPosition( .1,.85 )

def main_sequence():
    yield game()

viztask.schedule( main_sequence() )


text:
Q: Css print style. Different layout for left/right pages? I am trying to create layout for print with css. I was hoping to alternate the position of the sidebar on left/right pages.
So basically what I would like is something like:

* {
  box-sizing: border-box;
}

ul {
  list-style: none;
  padding: 0;
}

aside {
  float: left;
  width: 30%;
  padding: 20px;
}

aside img {
  max-width: 100%;
  height: auto;
}

article {
  float: left;
  padding: 20px;
  width: 70%;
}

@page {
  margin: 2cm;
  size: 150mm 150mm;
}

@page: left {}

@page: right {
  aside {
    float: right;
  }
  article {
    float: right;
  }
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fortitudinis quaedam praecepta sunt ac paene leges, quae effeminari virum vetant in dolore. Hic Speusippus, hic Xenocrates, hic eius auditor Polemo, cuius illa ipsa sessio fuit, quam videmus.
    Sed fortuna fortis; Itaque eos id agere, ut a se dolores, morbos, debilitates repellant. Idem fecisset Epicurus, si sententiam hanc, quae nunc Hieronymi est, coniunxisset cum Aristippi vetere sententia. An dolor longissimus quisque miserrimus, voluptatem
    non optabiliorem diuturnitas facit? Dici enim nihil potest verius. An tu me de L. Primum quid tu dicis breve? Duo Reges: constructio interrete.

Equidem etiam Epicurum, in physicis quidem, Democriteum puto. Videmus in quodam volucrium genere non nulla indicia pietatis, cognitionem, memoriam, in multis etiam desideria videmus. Tubulo putas dicere? Vitae autem degendae ratio maxime quidem illis
    placuit quieta. Si stante, hoc natura videlicet vult, salvam esse se, quod concedimus; Isto modo ne improbos quidem, si essent boni viri.

Non est ista, inquam, Piso, magna dissensio. Si verbum sequimur, primum longius verbum praepositum quam bonum. Ne tum quidem te respicies et cogitabis sibi quemque natum esse et suis voluptatibus? Venit enim mihi Platonis in mentem, quem accepimus primum
    hic disputare solitum; Age sane, inquam. Quamquam tu hanc copiosiorem etiam soles dicere.

Ita est quoddam commune officium sapientis et insipientis, ex quo efficitur versari in iis, quae media dicamus. Eam si varietatem diceres, intellegerem, ut etiam non dicente te intellego; Quid ergo? Potius inflammat, ut coercendi magis quam dedocendi
    esse videantur. Inde igitur, inquit, ordiendum est. Quid enim necesse est, tamquam meretricem in matronarum coetum, sic voluptatem in virtutum concilium adducere? Atque hoc loco similitudines eas, quibus illi uti solent, dissimillimas proferebas.
    Sed quanta sit alias, nunc tantum possitne esse tanta. Mene ergo et Triarium dignos existimas, apud quos turpiter loquare? Iam in altera philosophiae parte.

Idque testamento cavebit is, qui nobis quasi oraculum ediderit nihil post mortem ad nos pertinere? Qua ex cognitione facilior facta est investigatio rerum occultissimarum. Haec dicuntur fortasse ieiunius; Quamquam id quidem licebit iis existimare, qui
    legerint. Deinde prima illa, quae in congressu solemus: Quid tu, inquit, huc? Itaque nostrum est-quod nostrum dico, artis est-ad ea principia, quae accepimus. Apparet statim, quae sint officia, quae actiones. Quae qui non vident, nihil umquam magnum
    ac cognitione dignum amaverunt. Quid est, quod ab ea absolvi et perfici debeat?

I know about the named pages feature of print css, but that only applies to the whole element (article in my case), and the element potentially flows over multiple pages.
Is this possible in CSS?
Hope someone can shed some light on this.