text:
Q: Workflow rule formula help - Two picklist values cannot be populated together I'm trying to create a workflow rule that fires when:

*

*Status = New

*Type = Incident

*Origin is not Production Monitoring or Proactive outreach
AND

*Does not have BOTH of these picklist values
A. Origin = Web Inquiry
B. Category = Change Form

The way it is written right now, if it has either of #4's picklist values it is not firing. Any help would be greatly appreciated.
AND(
    ISPICKVAL( Status, "New"),
    ISPICKVAL(Type, "Incident"),
    NOT(ISPICKVAL (Origin, "Production Monitoring")),
    NOT(ISPICKVAL (Origin, "Proactive Outreach")),
    AND(
        NOT(ISPICKVAL(Origin, "Web Inquiry")),
        NOT(ISPICKVAL(Category__c, "Change Form"))
    )
)

A: You just need to invert your NOT and AND in the final clause:
NOT(
    AND(
        ISPICKVAL(Origin, "Web Inquiry"),
        ISPICKVAL(Category__c, "Change Form")
    )
)


text:
Q: How to Redirect URL Page to another URL Good Day, When a user enters http://test.com on the browser I would like him redirected to my site published on our server. I already knew that I can change it in the hosts file of devices connected to the network but it will takes a lot of time so I'm thinking if I can change it on the router.
Can you give me a link or instructions that could help me regarding the scenario / how to do this on my router? Thanks in advance.

A: The old school way to do this is via HTML meta refresh.
# Redirect to http://example.com/ immediately:
<meta http-equiv="refresh" content="0; url=http://example.com/">

Have a look at these docs for further reading :
http://en.wikipedia.org/wiki/Meta_refresh

A: Its worth noting you have redirect methods available in almost every web programming language. For example php.
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
More info here: https://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run Delegate Method in viewcontroller directly from Custom Cell I have setup a delegate method on Custom cell. let's say,
@protocol CheckDelegate <NSObject>
@required
- (void)checkForUpdate;
@end
@property (nonatomic, weak) id<CheckDelegate> delegateForChecker;

-- I will call above function somewhere in my cell ---
and I want to listen for any change in Custom Cell at Viewcontroller. How can I implement this using the delegate in Viewcontroller without using tableviewcontroller.
In ViewController I though about doing,
-(void) viewDidLoad{
  CustomCell * cll = [[Customcell alloc]init]
  cll.delegateForChecker = self;
}

-(void) checkDelegate{
  NSLog(@"Something changed");
}

P.S. I do not want use NSNotification

A: I came up with different approach to pass the data from cell to another viewcontroller (not the tableviewcontroller where the cell is instantiated) using block. This may help someone who may find themselves stuck with this issue.
In custom cell, I created a block property called that would pass the property to the tableviewcontroller where the cell is instantied.
@property  (copy, nonatomic) void (^didTouchButtonOnCell) (BOOL selectedButton);

In button touched in customCell I set the boolean property with Boolean Value.
 self.didTouchButtOnCell(YES/NO);

In the tableViewcontroller I created another block that would pass data to the viewcontroller where I intended to pass the Boolean value.
 In the TableViewController,
 @property (copy, nonatomic) void (^passBooleanToViewController) (BOOL selectionFromButton)

In cellForRowAtIndexPath in TableViewController, I get the boolean property and pass it to ^passBooleanToViewController.
    cell.didTouchButtonCell = ^(BOOL selection)
   {
      passBooleanToViewController(selection)
    }

Finally, in ViewController I again get the Block property of TableViewcontroller that contained the Boolean value that was passed over to TableViewController from CustomCell
Viewcontroller.passBooleanToViewController = ^(Bool sel){
    NSLog(@"%I here is the boolean value",sel);
}

** This is one of the ways I was able to fix the issue of passing value from custom cell to viewcontroller. It would be great if some other approaches can be shared too.


text:
Q: vue - datatable - item-expanded - load from server I'm using the component datatable from Vuetify library. There is a problem on item-expanded, the code
<v-data-table
  :headers="headers"
  :items="records"
  :options.sync="options"
  :server-items-length="totalRecords"
  :loading="loading"
  :search="search"
  disable-pagination
  :hide-default-footer="true"
  class="elevation-1"
  show-expand
@item-expanded="loadDetails">
<template v-slot:expanded-item="{ headers, item }">

                    id
                    league_id
                    Start
                    End
                    Current

                {{ rec.id }}
                {{ rec.league_id }}
                {{ rec.start }}
                {{ rec.end }}
                {{ rec.current }}

</template>
</v-data-table>

  loadDetails: function({item}) {

    if (item.details)
        return;

    this.ChildApiCall(item).then((data) => {
        item.details = data.response;
    })

//     var self = this;
// return new Promise(function (resolve) {
//     self.ChildApiCall(item).then((data) => {
//         item.details = data.response;
//         resolve(item);
//     })
//      });
},
  async ChildApiCall(item) {
      let formData = new FormData();
      formData.append("action", "GetRecordDetailsLeaguesJS");
      formData.append("recID", item.id);

      const items = await general.GetData("/api/03leagues.php", formData);
      return items;
    }

if I add to server call (03leagues.php) 1 second delay on response, the row expanded but showing only the table header row. When collapse and expand again, showing the table as should be.


text:
Q: Container-bound script is suddenly saying "app is blocked" when attempting to run anything at all Up until today, I've been able to test functions in a container-bound script without issue. However, once I pulled in a standalone script as a library, things have gone awry. (Note that the library uses OAuth2 for read/write access to a GCP resource.)
Now, after going through the permissioning and consent flow, I get a "this app is blocked" message (screenshot below) any time I try to run anything in the bound script. I removed the library to see if that would help but it did not.
The bound script's scopes are displayed as follows:
OAuth Scope required by script:
https://www.googleapis.com/auth/spreadsheets

Where am I going wrong here?


text:
Q: Functions in C Error So I'm not very familiar with functions since I just started to learn the C language. So far I have a program that reverses a string. How do you call the function in main properly? I am getting an error stated below.
#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    printf("\nEnter the string :");
    scanf("%s", str);
    reverse(str);
    return 0;
}

void reverse(char *st) {
    int i, j;
    char temp;
    i = 0;
    j = strlen(st) - 1;

    while (i < j) {
        temp = st[i];
        st[i] = st[j];
        st[j] = temp;
        i++;
        j--;
    }
    printf("\nReverse string is :%s\n", st);
}

Error Message
reverse.c:12:6: warning: conflicting types for 'reverse' [enabled by default]
 void reverse(char* st) {
      ^
reverse.c:8:4: note: previous implicit declaration of 'reverse' was here
    reverse(str);


text:
Q: EventGrid vs EventHub I am working on a service fabric application and want to publish few events from this application and subscribe or process those publish events in another application.
I have tried EventGrid concept and observed that there is a delay while publishing and processing the events. So, now I am looking for other alternatives like EventHub or Queues, etc..
If anyone had already used EventGrid, EventHud or Queues, etc.. , Please do suggest which one will give more performance when we deal with more events.
Design Approach
We have migrated the tables from SQL service to Service Fabric. There is a view in SQL Service, and we are planning to implement that as a service in service fabric.
The implementation logic follows below.

*

*Table 1 implemented service and we publish an event for each CRUD operation to EventGrid/ EventHud.

*Table 2 implemented service and we publish an event for each CRUD operation to EventGrid/ EventHud.

*We have created a view service where it listens to the events when any event sent to EventGrid/ EventHud, it will perform required calculations and store in the ViewService( It is a background job)

We are looking for a messaging service which gives more performance.

A: Have you seen this comparison and this one?
Anyway, can you clarify your requirements in terms of throughput and performance? It depends on a lot of factors including, but not limited to, the message size and the amount of messages.
Having used both Event Grid and Event Hub I'd say Event Hub works very well for many messages per second, say data streams from iot devices, but the performance of the downstream processing can be a bottleneck. You have to process them very fast in order to receive new events. Then there are partitions and consumer groups that can be of help to balance the load and have different processors for the same data but with different view of the data stream. (A fast processor for live displaying of sensor data and a slower one for storing the data for later analysis)
If you're talking about a few events generated by an application that triggers other apps to start doing some work based on those events Event Grid is a good fit. I haven't experienced much delay in receiving those events.
But bottom line, I think all services (Event Grid, Event Hub, Service Bus etc) support different use cases and that should be your first decision point.

A: Can you describe your publisher, subscriber, etc. and show your metrics of the Azure Event Grid usage?
You can use the portal screen snippets on the topic (publisher) and subscription (subscriber).
The following screen snippets are from my tester when manually have been fired few events.
Publisher side:

Subscriber side:

Metrics on the portal:

As you can see, the delivery destination processing time is ~1ms. The latency time on the publisher side (custom topic) is between 2-4ms.
Note, that the AEG is a PUSH->PUSH-ACK or PUSH->PULL-ACK eventing loosely decupled Pub/Sub model instead of the Event Hub model which is based on the PUSH->PULL mechanism, in other words, the Event Hub needs to host a listener and receiver for pulling an event from the partition.


text:
Q: Python connection with Exasol - export to pandas I have problem with export data to pandas from Exasol v.6.0.4. I can connect with Exasol but when I want to transport data to pandas DataFrame then I have error. I'm using library pyexasol. My code is following:
from pyexasol import ExaConnection
con = ExaConnection(dsn=dns, user=user, password=password)
con.execute('OPEN SCHEMA SCHEMATEST1') #to this moment everything works correct
data = con.export_to_pandas('select * from TABLETEST1') # pandas data frame per default

Error:
TypeError: cannot serialize '_io.FileIO' object

What I've done bad? How I can export data from Exasol query to Pandas DataFrame?
My libraries and version of tools:
Exasol 6.0.4
Python 3.6.4

Libraries:
backcall (0.1.0)
bleach (2.1.3)
colorama (0.3.9)
decorator (4.3.0)
entrypoints (0.2.3)
html5lib (1.0.1)
ipykernel (4.8.2)
ipython (6.4.0)
ipython-genutils (0.2.0)
ipywidgets (7.2.1)
jedi (0.12.0)
Jinja2 (2.10)
jsonschema (2.6.0)
jupyter (1.0.0)
jupyter-client (5.2.3)
jupyter-console (5.2.0)
jupyter-core (4.4.0)
MarkupSafe (1.0)
mistune (0.8.3)
nbconvert (5.3.1)
nbformat (4.4.0)
notebook (5.5.0)
numpy (1.14.3)
pandas (0.23.0)
pandocfilters (1.4.2)
parso (0.2.1)
pickleshare (0.7.4)
pip (9.0.1)
prompt-toolkit (1.0.15)
pyasn1 (0.4.2)
pyexasol (0.3.17)
Pygments (2.2.0)
pyodbc (4.0.23)
python-dateutil (2.7.3)
pytz (2018.4)
pywinpty (0.5.1)
pyzmq (17.0.0)
qtconsole (4.3.1)
rsa (3.4.2)
scikit-learn (0.19.1)
scipy (1.1.0)
Send2Trash (1.5.0)
setuptools (28.8.0)
simplegeneric (0.8.1)
six (1.11.0)
sklearn (0.0)
terminado (0.8.1)
testpath (0.3.1)
tornado (5.0.2)
traitlets (4.3.2)
wcwidth (0.1.7)
webencodings (0.5.1)
websocket-client (0.47.0)
widgetsnbextension (3.2.1)

Please help! :)

A: PyEXASOL creator is here! Your code is correct.
This problem was related to Windows "multiprocessing" module implementation lacking fork() and trying to serialize pipe handles created in http_transport.py.
This problem was FIXED starting from version 0.3.23. Please update the package.
pip install --upgrade pyexasol


text:
Q: Heroku and RubyMine Has anyone managed to integrate Heroku with RubyMine? I have Heroku installed and integrated with Git (which is integrated with RubyMine) but I see no way to push to Heroku without dropping to the Terminal.

A: You don't need to do anything special to use Rubymine with Heroku, Heroku is just another git remote location.
From Version Control > Git > Push Changes
there's a 'Remote' drop down, set that to your Heroku remote and it should deploy to Heroku


text:
Q: How to keep focus on an element after recompose? I have a custom component in my Compose Desktop app, which can have the focus:
val focusRequester = remember { FocusRequester() }
var focused by remember { mutableStateOf(false) }
Row(modifier.fillMaxWidth()
    .focusRequester(focusRequester)
    .onFocusChanged { state -> focused = state.isFocused }

This works as you'd expect. However, when I add a border based on focused state, it breaks:
val focusRequester = remember { FocusRequester() }
var focused by remember { mutableStateOf(false) }
Row(Modifier.fillMaxWidth()
    .focusRequester(focusRequester)
    .onFocusChanged { state -> focused = state.isFocused }
    .border(if (focused) 1.dp else 0.dp, MaterialTheme.colors.primary)

From what I can tell, the recompose actually causes the onFocusedChanged to fire again with isFocused = false. So that's the problem, not the remembering of the focused property itself.
How can my component keep the focus after recomposing to draw the border?

A: You can use interactionSource.collectIsFocusedAsState() instead of the
onFocusChanged modifier.
Something like:
val focusRequester = remember { FocusRequester() }
val interactionSource = remember { MutableInteractionSource() }
val focused by interactionSource.collectIsFocusedAsState()

    Row(Modifier
         // add focusRequester modifier before the focusable (or even in the parent)
        .focusRequester(focusRequester)
        .focusable(interactionSource = interactionSource)
        .border(if (focused) 1.dp else 0.dp, MaterialTheme.colors.primary)


text:
Q: How to sum of two different table with two different groupby I have two tables called work and stuff both tables have same fields -
 company, quality, quantity
I need the sum of all the quantity of work with group by company and quality and join the table with sum of all the quantity of stuff with group by company and quality
I didn't get the expected result.
SQLfiddel
 http://sqlfiddle.com/#!9/eea577/6

A: working query
select st.company,st.quality,st.quantitys - ct.quantitys as balance from
(select company,quality,sum(quantity) as quantitys from stuff
 group by quality,company) as st join (select company,quality,
 sum(quantity) as quantitys from work group by quality,company)
 as ct on `ct`.`company` = `st`.`company` and ct.quality = st.quality group by quality,company

u have missed the quality condition in the join

A: Try the following:
SELECT tableA.ID, tableA.`Year`, tableA.`Month`,
       tableA.`Type`, tableA.instrument,
       tableA.totalAmount, tableB.totalInstrument
FROM
(
    SELECT  a.ID, a.`Year`, a.`Month`,
            b.`Type`, b.instrument,
            SUM(b.`amount`) totalAmount
    FROM    `date` a
                INNER JOIN `transactions` b
                    ON a.ID = b.id
    GROUP BY b.`Type
) tableA
INNER JOIN
(
    SELECT  a.ID, a.`Year`, a.`Month`,
            b.`Type`, b.instrument,
            SUM(b.`instrument`) totalInstrument
    FROM    `date` a
                INNER JOIN `transactions` b
                    ON a.ID = b.id
    GROUP BY a.`Year`, a.`Month`
) tableB ON tableA.ID = tableB.ID AND
            tableA.`Year` = tableB.`Year` AND
            tableA.`Month` = tableB.`Month`


text:
Q: __init__ cannot import name from separate .py file I am trying to pass two arrays from one python file (agent.py) to a new module (moea.py).  The MOEA file utilizes PyGMO, if anyone also has any expertise on that.
In short, I am building two arrays, A and B, which will control the mechanics of the MOEA search.
In agent.py, I have:
self.A = []
self.B = []
*code that fills A and B*
problem = R()

In moea.py, I have:
import agent

class R(base):
    def __init__(self):
        super(R,self).__init__(len(self.A),0,4)
        self.set_bound(0,len(self.B))

This is giving an error that moea.py cannot find object A or B.  The purpose of the __init__ is to create a population of entries containing len(self.A) different variables ranging between 0 and len(self.B).
EDIT:
The purpose of this edit is hopefully to clarify the question at hand.  I believe this question can be simplified down to "Is it possible to import data from other .py files into a separate __init__ without changing the number of input variables."  I have changed some of the other code while testing some other ideas.
agent.py:
import moea

class Agent:
    def __init__(self, ...)
        self.A = []
        self.test = 2
        *other attribute statements*
    def function(...)
        self.A = [] #To clear the array on subsequent uses
        *code to fill A*
        problem = moea.R()

In moea.py I have:
import agent

class R(base) #using the _base definition from the link below
    def __init__(self):
        print agent.Agent.test
        super(R,self).__init__(len(agent.Agent.A),0,4)
        ...

My issue is that the test statement says that the Agent attribute test does not exist.  Why is it able to find the agent.py file, and the Agent class in that file, if it cannot also find the attributes attached to that class?  If I could get class R's __init__ to read some of agent's attributes the code would be complete.
Information on the base class can be found here:  PyGMO documentation

A: In agent.py:
import moea

self.A = []
self.B = []
*code that fills A and B*
problem = moea.R(self.A, self.B)

In moea.py:
class R(base):
    def __init__(self, A, B):
        super(R,self).__init__(len(A),0,4)
        self.set_bound(0,len(B))

In short "It's better to be explicit than implicit" and in your situation there would be no other way to do it without circular imports which (IMO) creates even more of a mess. Also, I changed the import to the other file (I didn't see how R would be available without that import)


text:
Q: Oracle JOIN output optimization Using below query I fetch some details scattered across three different tables of a particular oracle database schema...
SELECT USERNAME, FULLNAME, DEPARTMENT, TASKNAME
FROM USERDB t1
JOIN USERDB_TASKS t3 ON t1.USERID = t3.USERID
JOIN TASKS t2 ON t3.TASKSID = t2.TASKSID;

Current output:
USERNAME FULLNAME     DEPARTMENT TASKNAME
duryo    dur yogeli   IT         Domain admin
rected   rec tedenson SALES      Process manager

Here table USERDB contains four columns USERID, USERNAME, FULLNAME, DEPARTMENT. Table USERDB_TASKS contains two columns USERID, TASKSID. Table TASKS contains two columns TASKSID, TASKNAME.
For a particular user, USERID will be same in all tables. Similarly TASKSID for a particular task will be same in all tables.
But actually there are few USERID in table USERDB which are not there in table USERDB_TASKS i.e. few users do not have any tasks assigned so obviuosly their ids are not there in USERDB_TASKS table.
Using above query I am getting details of only those users whose USERID are present in both USERDB as well as USERDB_TASKS tables. My question is how can I modify my query in such a way that for all those few USERID which are only present in USERDB table and not in USERDB_TASKS table, the value for TASKNAME column should come as NONE, for example like below...
USERNAME FULLNAME     DEPARTMENT TASKNAME
duryo    dur yogeli   IT         Domain admin
rected   rec tedenson SALES      Process manager
Ueswit   Ues witer    Market     NONE

Thanks in advance for your help!

A: Use LEFT JOIN.  I also strongly recommend that you qualify all column names, so the query would look like:
SELECT u.USERNAME, u.FULLNAME, u.DEPARTMENT, t.TASKNAME
FROM USERDB u LEFT JOIN
     USERDB_TASKS ut
     ON ut.USERID = u.USERID LEFT JOIN
     TASKS t
     ON t.TASKSID = ut.TASKSID;

This returns t.TASKNAME as a NULL value -- which makes a lot of sense to me.  However, if you want 'NONE', then use COALESCE():
SELECT u.USERNAME, u.FULLNAME, u.DEPARTMENT,
       COALESCE(t.TASKNAME, 'NONE') as TASKNAME
. . .

A: Use Left outer join and NVL
SELECT USERNAME, FULLNAME, DEPARTMENT, NVL(TASKNAME, 'NONE')
  FROM USERDB t1
  JOIN INNER JOIN USERDB_TASKS t3 ON t1.USERID=t3.USERID
  LEFT OUTER TASKS t2 ON t3.TASKSID=t2.TASKSID;


text:
Q: Find the area of the region $ABCD$. In the Figure $\square PQRS$ is a square with side $2\sqrt6$.
By joining the midpoints another square $\square WXYZ$ is formed .
Circles are drawn with $4$ vertices as the center and
radius equal to the side of the square $\square WXYZ$.
Find the area common to all the $4$ circles .
$a.)6\pi\left(\dfrac{\sqrt3-1}{2}\right)\\
b.)4\pi-3\sqrt3\\
c.)\dfrac12\left(\pi -3\sqrt3\right)\\
d.)4\pi-12\left(\sqrt3 -1\right)\quad \LARGE \color{green}{\checkmark}\\$
So i have to find the area of region $ABCD$.

I have found that $WX=WY=YZ=XZ=2\sqrt3.$
Let Region $WBA$=Region $XAD$=Region $ZCD$=Region $YBC=a$
and
Region $WAX$=Region $XDZ$=Region $ZCY$=Region $YBW=b$
and
Region $ABCD=m$
$Area(\square WXYZ)=12\\
m+4a+4b=12$.
Area of sectors.
$Area$(sector $WZY$)=$Area$(sector $XYZ$)=$Area$(sector $WXY$)=$Area$(sector $WZX$)=$m+3a+2b=3\pi$.
Now i m stucked.
I m looking for simple short way.
I have studied maths upto $12th$ grade.

A: Let $[F]$ be the area of a figure $F$.
Since $\angle{WYA}=30^\circ,\angle{AYZ}=60^\circ$, one has
$$\begin{align}a+b&=[YWA]\\&=[\text{sector}\ YWA]-\left([\text{sector}\ ZYA]-[\triangle{ZYA}]\right)\\&=(2\sqrt 3)^2\pi\times\frac{30}{360}-\left((2\sqrt 3)^2\pi\times\frac{60}{360}-\frac{\sqrt 3}{4}\times(2\sqrt 3)^2\right)\\&=3\sqrt 3-\pi\end{align}$$
Hence, one has$$m=12-4(a+b)=12-4(3\sqrt 3-\pi)=4\pi+12-12\sqrt 3.$$

A: Each side of smaller square WXZY is calculated as $$WX=\sqrt{(WQ)^2+(QX)^2}=\sqrt{(\sqrt{6})^2+(\sqrt{6})^2}=2\sqrt{3}$$
The area common to four circles each having a radius $a$ & center at the vertice of a cube with side $a$ is given by the general expression (obtained by using integration) $$\bbox[4pt, border:1px solid blue;]{A_{common}=a^2\left(\frac{\pi-3(\sqrt{3}-1)}{3}\right)}$$ Hence, by setting $a=2\sqrt{3}$ in the above formula, we get the requited common area ABCD $$=(2\sqrt{3})^2\left(\frac{\pi-3(\sqrt{3}-1)}{3}\right)=4\left(\pi-3(\sqrt{3}-1)\right)=4\pi-12(\sqrt{3}-1)$$

A: Base on the following simple principle:-
$n(A \cap B) = n(A) + n(B) – n(A \cup B)$,
the said region can be found by a series a additions and subtrations of regions whose areas can easily be found. Example:-

For further example, see my answer in Find the area of the region which is the union of three circles


text:
Q: How to count the number of occurence of paired variables per sample in dplyr I have a list of samples in a .txt file. Each sample has multiple rows, which are observations from that sample. The columns show a start and end position. I want to count the number of identical pairs of observations per sample.
sample start end
sampleA D C
sampleA D D
sampleB A A
sampleA D D
sampleB A A
sampleB B A
sampleB B A
sampleA A A

expected output (where columns 1 and 2 are the paired observations and column 3 is the count of that observation:
sampleA
D D 2
D C 1
A A 1

sampleB
A A 2
B A 2

I know how to use count() and arrange(desc()) to do this for single observations but how do you do it when I need to be consider two columns simultaneously?
Thanks in advance.

A: Using dplyr, group by your 3 columns and count the number of rows:
library(dplyr)
df %>%
group_by(sample,start,end) %>%
summarise(n=n())

This returns:
 sample start   end     n
        <chr> <chr> <chr> <int>
    1 sampleA     A     A     1
    2 sampleA     D     C     1
    3 sampleA     D     D     2
    4 sampleB     A     A     2
    5 sampleB     B     A     2

A: Or another option is data.table
library(data.table)
setDT(df1)[, .(n = .N), .(sample, start, end)]
#    sample start end n
#1: sampleA     D   C 1
#2: sampleA     D   D 2
#3: sampleB     A   A 2
#4: sampleB     B   A 2
#5: sampleA     A   A 1


text:
Q: How to create Raw socket in Android? Has anybody tried creating RawSocket in Android and have succeeded ?

A: I havent actually created any raw sockets in Android but the java.net and javax.net packages shold do what you need,
java.net package overview
javax.net package overview

A: So far as I'm aware access to raw sockets is not availables in any pure Java library.
In part this is because on most O/S access to raw sockets is a privileged operation, only available to processes running as root / administrator.
The Socket and DatagramSocket classes available in the java.net package are implicitly IP sockets (for TCP, and UDP, respectively).
See for more detail at Apple Lists - Java raw sockets.

A: Raw sockets are not supported in any Java or Android libraries
Use 3rd party libraries:
RockSaw
JSocket


text:
Q: After restarting Chromium, fonts are malformed Everything works great until I restart Chromium. Then the fonts appear as in the screenshot. The weird part is that only the tab title and the link is malformed. And it won't fix till a system restart. Arch Linux, fully updated, with KDE.

A: It is most likely a bug with pixman. It has also been filed upstream.
There are several threads on the Arch boards about this issue, with various suggested workrounds—depending on your driver.


text:
Q: Ubuntu 14.04 - How to Fix the Ubuntu Appearance I have played with XFCE and KDE and after uninstalling them I was left with some problems with my default Ubuntu desktop. I have attached some photos here to show you what I mean.
I would like to reset Ubuntu desktop so that everything looks as it should again.
Thanks!

A: You have to uninstall all of the plasma packages to get rid of the KDE themes.
sudo apt-get purge oxygen-cursor-theme oxygen-cursor-theme-extra oxygen-icon-theme oxygen-icon-theme-complete gtk2-engines-oxygen gtk3-engines-oxygen kde-style-oxyge

be sure to review the list of uninstalled applications before accepting the changes so you don't uninstall something you want or need to keep


text:
Q: Is $E = \{ (x,y) \in \mathbb{R}^2 \mid xy \leq1 \}$ connected? I'm trying to solve this point set topology problem.
I need to prove whether or not $E_1 = \{ (x,y) \in \mathbb{R}^2 \mid xy \leq 1 \}$ is connected. We are using the euclidean topology, as usual. I feel like this set is connected, hence I tried to prove it by contradiction, but I struggled to find one.
Moreover, I need to find the connected components of $E_2 = \{(x,y) \in \mathbb{R}^2 \mid xy \geq 1\}$. Here, I think that $E_2$ is not connected itself, so I cannot find its connected components. Am I right?

A: Hint 1. Note that if $(x,y)\in E_1$ then $(tx,ty)\in E_1$ for all $t\in [0,1]$, that is the segment with endpoints $(x,y)$ and $(0,0)$ is in $E_1$.
Hence $E_1$ is a star domain.
Hint 2. $E_2$ is not connected: show that $(1,1)\in E_2$ and $(-1,-1)\in E_2$ are in different  connected components.

A: There are three obvious ways to prove a set is connected:

*

*Write the set as the continuous image of a connected set and apply the intermediate value theorem.

*Show that the set is path connected. You can do this by:
i. showing the set is convex, or
ii. finding a path between any two points in the set, or
iii. finding a path between any point and some fixed point (such as the origin).

*Try to apply the definition.
In this case, method 2.iii works.
For the second question, note that connected component means a maximal connected subset, not that the original set is connected. In this case, $E_2$ has two connected components:
$$ \{(x,y) : x \ge 0, xy \ge 1\} \text{ and } \{(x,y) : x \le 0, xy \ge 1\}. $$
Hopefully the picture makes this clear.


text:
Q: Ripple effect does not work correctly on Android 9 (Api 28, Pie) Such issue. Set the ripple effect on the button. On all versions of Android works correctly: when I press the button, it is slightly illuminated, then when I release the button, there is a small ripple. On Android 9 works half: the button is highlighted, but when the button is released, there is no ripple. Has anyone come across this? How can I fix it?
Background button - https://ru.stackoverflow.com/questions/935547/%D0%AD%D1%84%D1%84%D0%B5%D0%BA%D1%82-ripple-%D0%BD%D0%B5%D0%BA%D0%BE%D1%80%D1%80%D0%B5%D0%BA%D1%82%D0%BD%D0%BE-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82-%D0%BD%D0%B0-android-9-api-28-pie

A: I ran into this problem and it was due to me setting the background colour to white for the preferenceTheme
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="preferenceTheme">@style/SettingsTheme</item>
</style>
<style name="SettingsTheme" parent="PreferenceThemeOverlay">
    <item name="android:background">@color/white</item>
</style>

To fix this, I removed the preferenceTheme and set the background colour as white in my preference fragment:
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));
}

Also update your preference code to the latest AndroidX way of doing things, eg in your prefs.xml use this:
<androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">


text:
Q: OSX Mavericks cycle through active buttons I have moved to OSX from a while now and something that really bugs me is that I can't cycle through the buttons of an app.
For instance when I try to close an application and it asks me wether I want to save the file or not I cant just hit tab and select don't save.
Does someone know how I can add a shortcut like that or is there a pre-built functionality I can use?

A: *

*Launch System Preferences from the  Apple menu

*Click on the "Keyboards" preference panel

*Select the "Shortcuts" tab (sometimes called "Keyboard Shortcuts" in older versions of OS X)

*Look near the bottom of the window for a mention of "Full Keyboard Access: In windows and dialogs, press Tab to move keyboard focus between:" and click to select the radio button next to "All controls"*

*Close System Preferences

See also:
http://lmgtfy.com/?q=select+button+with+tab+key+mac+osx


text:
Q: Complex residue of $\int_{0}^{\infty} \frac{\log z}{z^2 + a^2} dz $ $\int_{0}^{\infty} \frac{\log z}{z^2 + a^2}  dz $
How to calculate the residue at $\ z = ai$ ? Is Res = $\frac{\log(ai)}{2ai}$
Also, when I do contour integral, I used two semi circles, how do you decide to use one or two semicircles?
Thanks

A: We assume that $a\in \mathbb{R}$.  Then, without loss of generality we take $a>0$.
We present two methodologies, which use distinct closed contours.

METHODOLOGY $1$:  Integration around a semicircle in the upper-half plane
First, we analyze the integral
$$\begin{align}
\oint_{C_1}\frac{\log(z)}{z^2+a^2}\,dz&=\int_0^R\frac{\log(-x)}{x^2+a^2}\,dx+\int_0^R \frac{\log(-x)}{x^2+a^2}\,dx+\int_0^\pi \frac{\log(Re^{i\phi})}{(Re^{i\phi})^2+a^2}\,iRe^{i\phi}\,d\phi\tag1\\\\
&=2\pi i \text{Res}\left(\frac{\log(z)}{z^2+a^2},z=ia\right)\tag2
\end{align}$$
for $R>a$.
We choose to cut the plane from $z=0$ to $z=-\infty$ with $\pi<\arg(z)\le \pi$.  Then, we have
$$\int_0^R\frac{\log(-x)}{x^2+a^2}\,dx=\int_0^R\frac{\log(x)}{x^2+a^2}\,dx+i\pi\int_0^R \frac{1}{x^2+a^2}\,dx\tag3$$
and
$$\begin{align}
\text{Res}\left(\frac{\log(z)}{z^2+a^2},z=ia\right)&=\frac{\log(ia)}{i2a}\\\\
&=\frac{\pi}{4}-i\frac{\log(a)}{2a}
\end{align}\tag 4$$
As $R\to \infty$, the third integral on the right-hand side of $(1)$ approaches $0$.  Thus, using $(3)-(4)$ into $(1)-(2)$ and letting $R\to \infty$ reveals
$$2\int_0^\infty \frac{\log(x)}{x^2+a^2}\,dx+i\frac{\pi^2}2 =\frac{\pi \log(a)}{a}+i\frac{\pi^2}2\tag 5$$
Solving $(5)$ for the integral of interest yields
$$\bbox[5px,border:2px solid #C0A000]{\int_0^\infty \frac{\log(x)}{x^2+a^2}\,dx=\frac{\pi \log(a)}{2a}}$$

METHODOLOGY $2$: Integration around the classical keyhole contour
Second, we cut the plane along the positive real axis and analyze the integral
$$\begin{align}
\oint_{C_2}\frac{\log^2(z)}{z^2+a^2}\,dz&=\int_0^R\frac{\log^2(x)}{x^2+a^2}\,dx+\int_R^0 \frac{(\log(x)+i2\pi)^2}{x^2+a^2}\,dx+\int_0^{2\pi} \frac{\log(Re^{i\phi})}{(Re^{i\phi})^2+a^2}\,iRe^{i\phi}\,d\phi\tag6\\\\
&=2\pi i \text{Res}\left(\frac{\log^2(z)}{z^2+a^2},z=\pm ia\right)\tag7
\end{align}$$
for $R>a$.
Then, we have
$$\int_R^0 \frac{(\log(x)+i2\pi)^2}{x^2+a^2}\,dx=\int_R^0\frac{\log^2(x)}{x^2+a^2}\,dx+i4\pi\int_R^0 \frac{\log(x)}{x^2+a^2}\,dx-4\pi^2 \int_R^0 \frac{1}{x^2+a^2}\,dx\tag8$$
and
$$\begin{align}
\text{Res}\left(\frac{\log^2(z)}{z^2+a^2},z=\pm ia\right)&=\frac{\log^2(e^{i\pi/2}a)}{i2a}+\frac{\log^2(e^{i3\pi/2}a)}{-i2a}\\\\
&=\frac{\log^2(a)+i\pi \log(a)-\pi^2/4}{i2a}-\frac{\log^2(a)+i3\pi \log(a)-9\pi^2/4}{i2a}\\\\
&=-\frac{\log(a)}{a}-i\frac{\pi^2}{a}\tag 9
\end{align}$$
As $R\to \infty$, the third integral on the right-hand side of $(6)$ approaches $0$.  Thus, using $(8)-(9)$ into $(6)-(7)$ and letting $R\to \infty$ reveals
$$\bbox[5px,border:2px solid #C0A000]{\int_0^\infty \frac{\log(x)}{x^2+a^2}\,dx=\frac{\pi \log(a)}{2a}}$$
as expected!

A: Residue at $ai$ is
$a_{-1}=\lim_{z\to i a} \, \dfrac{(z-i a) \log (z)}{a^2+z^2}=\lim_{z\to i a} \, \dfrac{ i\log (z)}{i z-a}=-\dfrac{i \log (i a)}{2 a}=\dfrac{\log (i a)}{2 i a}$


text:
Q: Java -- Error cannot find symbol I don't understand why I get the "Error cannot find symbol" in several spots. Can somebody please shed some light on this simple problem.

*

*PriceCalculator.java:18: error: cannot find symbol  --- private JTextFeild priceFeild1;

*PriceCalculator.java:19: error: cannot find symbol --- private JTextFeild priceFeild2;

*PriceCalculator.java:41: error: cannot find symbol --- setDefaultCloseOpperation(JFrame.EXIT_ON_CLOSE);

*PriceCalculator.java:44: error: cannot find symbol --- buildPanel();
import javax.swing.*;
public class PriceCalculator extends JFrame
{
private JPanel panel;                               // References the panel

private JLabel messageLabel1;                       // References the whole sale label
private JLabel messageLabel2;                       // References the markup label percentage

private JTextFeild priceFeild1;                 // References the whole sale price
private JTextFeild priceFeild2;                 // Referencts the markup label percentage

private JButton calcButton;                     // References the calculator button

private final int WINDOW_WIDTH = 550;           // References the window width
private final int WINDOW_HEIGHT = 550;          // Referenecs the window height

/**

Constructor below

*/

public PriceCalculator()
{
// Set the window title
setTitle("Retail Price Calculator");

// Set the size of the window
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

// Set the [x] exit button to close the program for the user
setDefaultCloseOpperation(JFrame.EXIT_ON_CLOSE);

// Build the panel and add it to the JFrame
buildPanel();

// Add the contents to the panels frame
add(panel);

// Display the window here
setVisible(true);
}

/**

Main Method Below

*/

public static void main(String[] args)
{
new PriceCalculator();
}

}

A: It is because you spell it wrong (JTextFeild). It should be JTextField.
Also, setDefaultCloseOperation instead of setDefaultCloseOpperation

A: Your spelling mistake :
JTextFeild instead of JTextField
and setDefaultCloseOpperation(JFrame.EXIT_ON_CLOSE);
instead of setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); you have used 2 p in Operation.


text:
Q: Perl kill(0, $pid) in Windows always returning 1 I'm trying to make a Perl script that will run a set of other programs in Windows. I need to be able to capture the stdout, stderr, and exit code of the process, and I need to be able to see if a process exceeds it's allotted execution time.
Right now, the pertinent part of my code looks like:
...
        $pid = open3($wtr, $stdout, $stderr, $command);
        if($time < 0){
            waitpid($pid, 0);
            $return = $? >> 8;
            $death_sig = $? & 127;
            $core_dump = $? & 128;
        }
        else{
            # Do timeout stuff, currently not working as planned
            print "pid: $pid\n";
            my $elapsed = 0;
            #THIS LOOP ONLY TERMINATES WHEN $time > $elapsed ...?
            while(kill 0, $pid and $time > $elapsed){
                Time::HiRes::usleep(1000);  # sleep for milliseconds
                $elapsed += 1;
                $return = $? >> 8;
                $death_sig = $? & 127;
                $core_dump = $? & 128;
            }
            if($elapsed >= $time){
                $status = "FAIL";
                print $log "TIME LIMIT EXCEEDED\n";
            }
        }
        #these lines are needed to grab the stdout and stderr in arrays so
        #  I may reuse them in multiple logs
        if(fileno $stdout){
            @stdout = <$stdout>;
        }
        if(fileno $stderr){
            @stderr = <$stderr>;
        }
...

Everything is working correctly if $time = -1 (no timeout is needed), but the system thinks that kill 0, $pid is always 1. This makes my loop run for the entirety of the time allowed.
Some extra details just for clarity:

*

*This is being run on Windows.

*I know my process does terminate because I have get all the expected output.

*Perl version: This is perl, v5.10.1 built for MSWin32-x86-multi-thread
(with 2 registered patches, see perl -V for more detail) Copyright 1987-2009, Larry Wall
Binary build 1007 [291969] provided by ActiveState http://www.ActiveState.com
Built Jan 26 2010 23:15:11

*I appreciate your help :D

For that future person who may have a similar issue
I got the code to work, here is the modified code sections:
        $pid = open3($wtr, $stdout, $stderr, $command);
        close($wtr);
        if($time < 0){
            waitpid($pid, 0);
        }
        else{
            print "pid: $pid\n";
            my $elapsed = 0;
            while(waitpid($pid, WNOHANG) <= 0 and $time > $elapsed){
                Time::HiRes::usleep(1000);  # sleep for milliseconds
                $elapsed += 1;
            }

            if($elapsed >= $time){
                $status = "FAIL";
                print $log "TIME LIMIT EXCEEDED\n";
            }
        }
        $return = $? >> 8;
        $death_sig = $? & 127;
        $core_dump = $? & 128;
        if(fileno $stdout){
            @stdout = <$stdout>;
        }
        if(fileno $stderr){
            @stderr = <$stderr>;
        }
        close($stdout);
        close($stderr);

A: Instead of kill 0, use waitpid $pid, WNOHANG:
use POSIX qw( WHOHANG );

if (waitpid($pid, WNOHANG) > 0) {
   # Process has ended. $? is set.
   ...
}


text:
Q: The name 'Password' does not exist in the current context I do not think my question is new, but I tried many solutions on this website and nothing worked. So, here is my problem:
I have this code that giving me 2 errors about "password" and "username". I created the project as a website, so I do not have a design file to fix. How can I fix this?
Here is the code from aspx file:

        <asp:Login runat="server" ViewStateMode="Disabled" RenderOuterTable="false">
            <LayoutTemplate>

                <fieldset>
                    <legend>Log in Form</legend>

                            <asp:Label runat="server" AssociatedControlID="UserName">User name</asp:Label>
                            <asp:TextBox runat="server" ID="UserName" />
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="UserName" CssClass="field-validation-error" ErrorMessage="The user name field is required." />

                            <asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
                            <asp:TextBox runat="server" ID="Password" TextMode="Password" />
                            <asp:RequiredFieldValidator runat="server" ControlToValidate="Password" CssClass="field-validation-error" ErrorMessage="The password field is required." />

                    <asp:Button runat="server" CommandName="Login" Text="Log in" ID="Login" OnClick="Login_Click" Width="300px" />
                </fieldset>
            </LayoutTemplate>
        </asp:Login>

Here is the code in aspx.cs file:
 string UN = UserName.Text; //Request.QueryString["UserName"];
      string PW = Password.Text;//Request.QueryString["Password"];

A: First you need a way to reference your Login control from code - so give it an ID:
 <asp:Login ID="MyLogin" runat="server" ViewStateMode="Disabled" RenderOuterTable="false">

Then, you access the username and password as properties of the control instance:
MyLogin.UserName
MyLogin.Password

Not as just regular text boxes like you are trying to do.
You can access these values in the LoggedIn event.
protected void MyLogin_LoggedIn(object sender, EventArgs e)
{
    string name = MyLogin.UserName;
}

A: I haven't used anytime the login control, however since i see a ViewTemplate, i assume you need to find the controls within the login container, like the way you do in a Gridview.
control myControl=Login.findControl("id");
textbox password= (textbox) myControl;

that way it should be accesible, and by the way dont forget to use the runat="server" tag on the controls, if dont, they wont be accesible in code behind.


text: Q: Не устанавливается MonoDevelop. Что делать? Захожу я на сайт MonoDevelop, нажимаю download, и открывается страница, где нет ссылки на скачивание самого MonoDevelop. GTK# и Net Framework установлены. Что делать?


text:
Q: empty cells in appending data one by one into the google sheet via api v4 When i append the list of data in a column the data appended leaves the rows equivalent to the maximum rows used in the previous column and then starts appending from the last cell. The picture would explain the problem quite well. I am using flutter and gsheets dependency to connect to the sheet. Date is the column key and data is the data being appended.
if (column != null) {
  if (!column.contains(data)) {
    await sheet.values.map.appendRow({date: data});
  }
  return true;
} else {
  await sheet.values.insertColumnByKey(date, [data]);
  return true;
}

Current output
Required output

A: You should find the last cell that contains a value in the target column and insert values starting in the cell just below that cell, instead of appending after the last row of the occupied data range in the sheet.
One way to do that is to use my appendRows_() utility function.


text:
Q: Could someone help to explain this strange behaviour when Java Socket OutpurStream's send buffer is full and write operation supposed to be blocked? I'm reading the book Tcp Ip Sockets in Java. It says that when the sending buffer is full, a call to the Socket's OutputSream.write() will block until space becomes available. I wrote a test which shows strange behaviour.
Here is the server side code.
public class SocketServer {
public static final Logger LOGGER = LoggerFactory.getLogger(SocketServer.class);
public static final int PORT = 8081;

public static void main(String[] args) throws IOException, InterruptedException {
    ServerSocket serverSocket = new ServerSocket(PORT);
    Socket clientSocket = serverSocket.accept();
    InputStream in = clientSocket.getInputStream();
    System.out.println(in.read());
    System.out.println("getReceiveBufferSize " + clientSocket.getReceiveBufferSize());

    while (true) {
    Thread.sleep(12000);
    }
}
}

And here is the client side code.
public class SocketClient {
public static final Logger LOGGER = LoggerFactory.getLogger(SocketClient.class);

public static void main(String[] args) throws IOException {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress("127.0.0.1", SocketServer.PORT));
    OutputStream out = socket.getOutputStream();
    System.out.println("SendBufferSize " + socket.getSendBufferSize());
    int count = Integer.MAX_VALUE;

    for (int i = 0; i < count; i++) {
    out.write(1);
    LOGGER.info("{} bytes", i + 1);
    }
    LOGGER.info("send over!");
}
}

I run the server and the client. The client keeps sending a single byte to the server and prints the counter fastly. When the counter goes to 195224, it slows down. It write a byte, stops for some seconds and keepd going, but doesn't stop.
I think if the writing client blocks, the thread would hold, logs would stop printing. What is going on and why it does not seem to be blocked? Though I know  I can not say it is not blocked by my test, I just can't explain the test.
Here is a piece of the output of the Client.
2017-03-07 20:28:45,455 [main] INFO  tcpip.socket.underhood.deadlock.SocketClient - 195224 bytes
2017-03-07 20:28:46,655 [main] INFO  tcpip.socket.underhood.deadlock.SocketClient - 195225 bytes
2017-03-07 20:28:49,056 [main] INFO  tcpip.socket.underhood.deadlock.SocketClient - 195226 bytes
2017-03-07 20:28:53,856 [main] INFO  tcpip.socket.underhood.deadlock.SocketClient - 195227 bytes

I run it with Java 8 on windows 10.


text:
Q: Webhelpers with Python Bottle I've got a Python Bottle application up and running use Mako templating. I'd like to use the webhelpers module (used in Pylons web applications) but I'm not sure how to go about doing this. I'd like to be able to do this in my mako templates:
${h.stylesheet_link("some_link_url_text")}

and have it produce the correct link HTML. But when I run this, h is undefined, as you might imagine.
Any ideas or pointers about how to do this?
Thanks in advance,
Doug

A: Webhelpers is a seperate module which can be installed easily.
pip install webhelpers

Then you can create a python moduler called helpers.py.  In the module then import all the functions you want available like below
"""
helpers.py
Import all webhelpers that you want to have access to
"""
from webhelpers.html.tags import stylesheet_link

Then in your bottle app import the helpers module and then pass it to your template as h.
import helpers

@route('/')
def index():
    return Template("template_name").render(h=helpers)

Then in your templete use it like you have above
${h.stylesheet_link("some_link_url_text")}


text:
Q: get_option() is not working even db contains the corresponding option_name and option_value First of all, this is not a plugin specific problem. I wonder why this might happen? I am using @bainternet's Tax Meta Class for saving Taxonomy Meta using the options table. I uploaded my contents from localhost (XAMPP Windows 5.5.19 environment ), I found my data in options table. Everything was working fine.
Now I uploaded my site to the server (Linux | PHP 5.2.17) and it's failing retrieving the data from the options table.
$type_icon_array = get_tax_meta( $type->term_id, 'offer_type_icon' );
var_dump( $type->term_id ); //showing the id nicely
var_dump( $type_icon_array ); //showing null

The function failed retrieving data. How the function is:
//get term meta field
  public function get_tax_meta($term_id,$key,$multi = false){
    $t_id = (is_object($term_id))? $term_id->term_id: $term_id;
    $m = get_option( 'tax_meta_'.$t_id);
    if (isset($m[$key])){
      return $m[$key];
    }else{
      return '';
    }
  }

I bypass the Tax Meta functions, and tried the WP rudimentary:
$tst1 = get_option( 'tax_meta_6' );
var_dump($tst1); //showing null

As you can see the database has the value in options table:

But you can see what happened:

I then uploaded one image (while I'm on the remote server) in Taxonomy ID #2, and you can see the image is showing there.
What could happen here, that the value is in db, but get_option() is not having that value? (But it's working while I'm updating the field in that particular environment) I even tried:
get_option( 'tax_meta_6', array() );

with no luck! :(
I know WordPress' minimum requirement is PHP 5.2.4, but can that missing dev. version cause such a massacre?

Edit
I found a reason why this COULD/MIGHT happen: I checked both the local and server serialized data and found one little mismatch there, suppose my local data is:
a: 1: {
    s: 15: "offer_type_icon";
    a: 2: {
        s: 2: "id";
        s: 3: "428";
        s: 3: "url";
        s: 61: "http://localhost/example/wp-content/uploads/2015/04/image.png";
    }
}

When I'm uploading to the server replacing all the base URL, the sever data becomes:
a: 1: {
    s: 15: "offer_type_icon";
    a: 2: {
        s: 2: "id";
        s: 3: "428";
        s: 3: "url";
        s: 61: "http://example.com/wp-content/uploads/2015/04/image.png";
    }
}

The URL is changing but the string count for the changed URL remains same as of localhost. But it should be 44 because the new base URL is 17 character less.
If this is the cause, how can I solve such WP migration while the db has serialized data with site URL?
EDIT 2
YES, this IS the reason.
The serialized URL data is being changed but their string count isn't.

A: Okay, at last found that, the serialized data, where there is a site_url exists, are causing the problem while I'm migrating the data from localhost to server replacing the local URL to server URL.
I found two solution, both are not tested yet:

*

*PHP Serialization Fix for WordPress Migrations (& other applications like Expression Engine) by David Coveney

*Fix-Serialization (Script to fix length attributes in serialized strings) - by Pau Iglesias
Need not to say that, try them with your own risk.
EDIT

BEFORE EVERYTHING
BACK UP YOUR DATABASE FIRST

Okay, I found the first one only specific to options table and not much flexible and not reliable too (WTFLicensed :p ). So I went with the second one by Pau Iglesias.
I found it working just fine. But as I'm a Windows user, couldn't use shell script, so I forked his repo and made my own way using the same script:

*

*serialization-fixer - Raw PHP way - github

Using my one is a bit sever-specific. You will need to put your exported string-replaced .sql file into the same folder where the serialization-fixer.php is. Then you need to open the file and change line#21 with your .sql file's filename. After then you can simply run the file from your browser.
Thanks to Pau Iglesias for his nice scripts.


text:
Q: Could not find the declaration for module('react-native-imei') I am trying to make a project that can give me the IMEI number of my Mobile, using this package https://github.com/SimenCodes/react-native-imei, the problem is in my code there is a statement as, const IMEI = require('react-native-imei'); here in my code it is showing kind of three dots below 'r' of 'react-native-imei' on hovering over it, it says "could not find the declaration file for module ('react-native-imei')" although I have installed and linked then package in my project so what could be the reason? below is my code:
import React from 'react'
import { StyleSheet,TouchableOpacity ,Text,View} from 'react-native'

export default class Demo extends React.Component {

  constructor () {
    super()
    this.state = {
      deviceIMEI: '',
    }
  }

  getIMEI = () => {
    const IMEI = require('react-native-imei')
    this.setState({
      deviceIMEI: IMEI.getImei(),
    })
  }

  render () {
    return (
      <View style={styles.container}>
        <Text>{this.state.deviceIMEI}</Text>
        <TouchableOpacity onPress={this.getIMEI}>
          <Text>Get Current Device IMEI</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
  },
})

here is the image for that:


text:
Q: Unity: Game Over screen - show stats w/ restart and leaderboards For the last three days I've been fiddling about with a game over screen for my game (which is sooo close to finished!), but haven't been able to come up with the result I want. So far I have a screen that says game over and  shows the total score and how many kills the player got. But I also want two buttons, one for restarting the game and one for showing the leaderboards (once that's implemented).
I want something simple, for example like Jetpack Joyride or Flappy Bird;
Can someone please show me an example code of how to do this? I want it to appear when the game is over (my code for this is if ( gameOver == true ); ). Every one of my attempts so far have either crashed the game or messed with the rest of my code...
I'm creating a game for android and coding in Unityscript.

A: You would need to implement a GUI system that handles what is being viewed. For example, in one of my games I have a game over screen and it will only show if I set my gamestate to game over:
public enum CameraState
{
    CS_PreGame, CS_NodeSelect, CS_Player, CS_Ball, CS_EndGame
}

public enum GameState
{
    GS_MenuSelect, GS_NodeSelect, GS_Swing, GS_BallInAir, GS_BallLanded, GS_EndGame
}

Here you're initializing 2 enums that will represent a State Machine for your game...
You then make instances of those...
public CameraState cam_State;
public GameState game_State;

Then in the start you would probably want to set the state to the first state you want, as so:
cam_State = CameraState.CS_PreGame;

And then you would have a Coroutine that handles whatever behavior you want in that state, as so:
IEnumerator CS_PreGame()
{
    DisableOtherCams (PreGameCam);

    yield return 0;
}

This is in C#, but none of it is syntax-special so you can do this exact thing in Javascript.
If you're still confused then a simple way to look at it is whenever you want the game to go in game over, just set the state to game over there, make your coroutine, and add the behaviors in there. Set a bool, and in an ONGui() function have it display a menu ONLY if the bool is true (set bool to true when the game state is game over)
void OnGUI()
    {
        if (showGUI) {
            // Main Menu Options
            if (currentMenu == "main")
                MainMenu();
            else if (currentMenu == "credits")
                Credits();
            else if (currentMenu == "exit")
                Exit();
    }

Restarting game is simple, Just load the first level (Application.LoadLevel(0)), leaderboards you will have to do yourself but you would have some type of GUI that displays information from a database, or if you hardcode it then that.


text:
Q: Pandas / Python = Function that replaces NaN value in column X by matching Column Y with another row that has a value in X I'm trying to write a function that solves the below problem. I tried solving it by mapping dataframes but this seems like a much better solution, I just can't get the syntax right.

X
Y

Company 1
Parent 1

NaN
Parent 1

NaN
Parent 1

I want to say "if row[X] is np.NaN, then take the value in Y, see if there are matches and return the value in X from another row if it does, otherwise just take the Y value so that:

X
Y

Company 1
Parent 1

Company 1
Parent 1

Company 1
Parent 1

EDIT: Just clarifying that my dataframe is more like this, so using the ffill/bfill doesn't seem to work (unless I can put a condition into this line).
The data looks more like this

X
Y

Company 1
Parent 1

NaN
Parent 2

NaN
Parent 3

Company 2
Parent 2

Company 3
Parent 3

NaN
Parent 1

A: For reference, I managed to find a solution to this problem using lambda.
#Specify which entries in the Name column are NaN
missing_name = df.X.isnull()

#Set index of new dataframe to Borrower
df_name = df_X.set_index('Y')

#impute the Name from the new dataframe at the null positions in the old dataframe
df.loc[miss_name, 'X'] = df.loc[miss_name, 'Y'].apply(lambda x: df_name.X[x])

A: df
            X          Y
0   Company 1   Parent 1
1   NaN         Parent 2
2   NaN         Parent 3
3   Company 2   Parent 2
4   Company 3   Parent 3
5   NaN         Parent 1

Firstly, you can create map of Y to X. So, you can drop NaNs from the table and convert to dictionary.
temp = df.dropna(axis=0, how='any')
temp
            X          Y
0   Company 1   Parent 1
3   Company 2   Parent 2
4   Company 3   Parent 3

map1 = pd.Series(temp['X'].values, index=temp['Y']).to_dict()
map1
{'Parent 1': 'Company 1', 'Parent 2': 'Company 2', 'Parent 3': 'Company 3'}

Then, you can fillna with the map of Y. It'll only affect the values where it is NaNs.
df['X'] = df['X'].fillna(df['Y'].map(map1))
df

            X          Y
0   Company 1   Parent 1
1   Company 2   Parent 2
2   Company 3   Parent 3
3   Company 2   Parent 2
4   Company 3   Parent 3
5   Company 1   Parent 1

A: You can use transform with first:
df['X'] = df.groupby('Y')['X'].transform('first')
df

Output:
           X         Y
0  Company 1  Parent 1
1  Company 2  Parent 2
2  Company 3  Parent 3
3  Company 2  Parent 2
4  Company 3  Parent 3
5  Company 1  Parent 1


text:
Q: Joomla site URL rewriting not working after migration to new host Just moved this Joomla 1.6 install over from iPower to Network Solutions. Moved a 1.5 install previously and it was okay. This one not so much. So when I turn on SEF Friendly URLs it's okay. When I turn on URL Rewriting to get rid of that annoying index.php in the URL, it says page not found. So...
http://hostname/a-z/index.php/about-a-and-z - WORKS!
http://hostname/a-z/about-a-and-z - DOESN'T WORK
Note: everything was working fine on the old site...
Anyone have any thoughts?
My HTACCESS FILE is as follows:
    ##
    # @version      $Id: htaccess.txt 21101 2011-04-07 15:47:33Z dextercowley $
    # @package      Joomla
    # @copyright    Copyright (C) 2005 - 2011 Open Source Matters. All rights reserved.
    # @license      GNU General Public License version 2 or later; see LICENSE.txt
    ##

    ##
    # READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!
    #
    # The line just below this section: 'Options +FollowSymLinks' may cause problems
    # with some server configurations.  It is required for use of mod_rewrite, but may already
    # be set by your server administrator in a way that dissallows changing it in
    # your .htaccess file.  If using it causes your server to error out, comment it out (add # to
    # beginning of line), reload your site in your browser and test your sef url's.  If they work,
    # it has been set by your server administrator and you do not need it set here.
    ##

    ## Can be commented out if causes errors, see notes above.
    Options +FollowSymLinks

    ## Mod_rewrite in use.

    RewriteEngine On

    ## Begin - Rewrite rules to block out some common exploits.
    # If you experience problems on your site block out the operations listed below
    # This attempts to block the most common type of exploit `attempts` to Joomla!
    #
    # Block out any script trying to base64_encode data within the URL.
    RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
    # Block out any script that includes a <script> tag in URL.
    RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
    # Block out any script trying to set a PHP GLOBALS variable via URL.
    RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
    # Block out any script trying to modify a _REQUEST variable via URL.
    RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
    # Return 403 Forbidden header and show the content of the root homepage
    RewriteRule .* index.php [F]
    #
    ## End - Rewrite rules to block out some common exploits.

    ## Begin - Custom redirects
    #
    # If you need to redirect some pages, or set a canonical non-www to
    # www redirect (or vice versa), place that code here. Ensure those
    # redirects use the correct RewriteRule syntax and the [R=301,L] flags.
    #
    ## End - Custom redirects

    ##
    # Uncomment following line if your webserver's URL
    # is not directly related to physical file paths.
    # Update Your Joomla! Directory (just / for root).
    ##

    # RewriteBase /

    ## Begin - Joomla! core SEF Section.
    #
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    #
    # If the requested path and file is not /index.php and the request
    # has not already been internally rewritten to the index.php script
    RewriteCond %{REQUEST_URI} !^/index\.php
    # and the request is for something within the component folder,
    # or for the site root, or for an extensionless URL, or the
    # requested URL ends with one of the listed extensions
    RewriteCond %{REQUEST_URI} /component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC]
    # and the requested path and file doesn't directly match a physical file
    RewriteCond %{REQUEST_FILENAME} !-f
    # and the requested path and file doesn't directly match a physical folder
    RewriteCond %{REQUEST_FILENAME} !-d
    # internally rewrite the request to the index.php script
    RewriteRule .* index.php [L]
    #
    ## End - Joomla! core SEF Section.

A: I got it to work with using: RewriteBase /a-z Forgot it was in a subdirectory.

A: Are you sure that mod_rewrite is turned on?

A: In my case, I made two things in order to enable the links without the index.php in the URL:

*

*Install the rewrite mod in your Apache: sudo a2enmod rewrite

*Check the configuration in you apache2.conf in /etc/apache2
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted

It's very critical to have AllowOverride All if you want to use the rewrite with your links.
This formula works for me


text:
Q: Why is math.factorial much slower in Python 2.x than 3.x? I get the following results on my machine:
Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100)
1.9785256226699202
>>>

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.timeit('factorial(10000)', 'from math import factorial', number=100)
9.403801111593792
>>>

I thought this might have something to do with int/long conversion, but factorial(10000L) isn't any faster in 2.7.

A: Python 2 uses the naive factorial algorithm:
1121 for (i=1 ; i<=x ; i++) {
1122     iobj = (PyObject *)PyInt_FromLong(i);
1123     if (iobj == NULL)
1124         goto error;
1125     newresult = PyNumber_Multiply(result, iobj);
1126     Py_DECREF(iobj);
1127     if (newresult == NULL)
1128         goto error;
1129     Py_DECREF(result);
1130     result = newresult;
1131 }

Python 3 uses the divide-and-conquer factorial algorithm:

1229 * factorial(n) is written in the form 2**k * m, with m odd. k and m are
1230 * computed separately, and then combined using a left shift.

See the Python Bugtracker issue for the discussion. Thanks DSM for pointing that out.


text:
Q: Concurrent unsigned users creating reviews, then sign up and retrieve the review record created by the right user I have a form where user can submit a review to a product without having to log in first. When user clicks the submit button, ReviewsController calls auth_user method which creates a new Review object with the review content updated. But, I want to associate this Review object with the user who is going to sign up. Right now, I'm simply retrieving the last Review object like this, Review.last. However, I know that this is vulnerable to multiple users creating reviews and signing up at the same time. Suppose that User A submits a review, User B submits a review, and User A signs up. In this scenario, it will retrieve the Review object created by the User B instead of the one created by the User A and associate the record with the User A. But, I want the one created by the User A and associate it with the User A regardless of how many users are creating the records simultaneously. Does anybody have an idea of how to go about doing this?

A: You could store the IP of the request when storing the reviews and then when the user logs in, match the IP's and associate the user. You can get the IP as below
remote_ip = request.env["HTTP_X_FORWARDED_FOR"]

Also you could use user agents and cookies apart from IP address. Also check this question


text:
Q: How do I fix W3Schools default Navigation Bar with drop bar working? What I'm trying to do is create a nav bar. I've gotten these codes from W3Schools except the CSS part.

@font-face {
  font-family: "Yeezy";
  src: url("../static/yeezy.ttf");
}

* {
  font-family: "Yeezy";
  font-weight: bold;
  color: #dbdbdb !important;
}

html,
body {
  height: 900px;
  background-size: cover;
  background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 100%), url("https://i.imgur.com/pxYxnOn.jpg");
}

/* Extra Background Links
    Owens Default SSV7.4:       https://i.imgur.com/cwkWLJa.png
    Macs Default Multicolor:    https://i.imgur.com/pxYxnOn.jpg
    "Gen5" BG Lookalike:        https://i.imgur.com/UvTCiL8.jpg
    Dark Purple/Blue Triangle:  https://i.imgur.com/pd7cgsq.jpg
    Lava Pink Tree:             https://i.imgur.com/ZN3rikQ.jpg
    */

/* Start Of Navigation Bar */

/* Navbar container */

.navbar {
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.2);
}

/* Links inside the navbar */

.navbar a {
  float: left;
  font-size: 15px;
  color: rgba(0, 0, 0, 0.4);
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* The dropdown container */

.dropdown {
  float: left;
  overflow: hidden;
}

/* Dropdown button */

.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: rgba(0, 0, 0, 0.2);
  padding: 17px 13px;
  background-color: inherit;
  font-family: inherit;
  /* Important for vertical align on mobile phones */
  margin: 0;
  /* Important for vertical align on mobile phones */
}

/* Add a red background color to navbar links on hover */

.navbar a:hover,
.dropdown:hover .dropbtn {
  background-color: rgba(0, 0, 0, 0.3);
}

/* Dropdown content (hidden by default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.1);
  min-width: 160px;
  box-shadow: 0px 0px 16px -20px rgba(0, 0, 0, 0.1);
  z-index: 1;
}

/* Links inside the dropdown */

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a grey background color to dropdown links on hover */

.dropdown-content a:hover {
  background-color: rgba(0, 0, 0, 0.2);
  ;
}

/* Show the dropdown menu on hover */

.dropdown:hover .dropdown-content {
  display: block;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="icon" href="../static/s_logo.png">
  <title>Sudo Splash</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css" />
  <link rel="stylesheet" href="../static/styles.css">

    Home

      <button class="dropbtn">Splash Mode</button>

        Splash Tasks
        How to use Product Mode

      <button class="dropbtn">Product Mode</button>

        Product Tasks
        How to use Product Mode

The issue is whenever I go on the dropdown part, the links do not go down or show but overlap on the navigation bar.

When I change the .dropdown-content position to "relative" this just happens:

A: as you have mentioned above code is working fine
enter code here https://jsfiddle.net/Gauravkakkar25/o3ybzdtf/

A: Got it to work. Removed the
HTML line:
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css" />

A: The problem is caused by the external stylesheet you're using:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css" />
If you don't need it, just remove it.


text:
Q: variable not incrementing var ro = 0;

function updatePR(sel){
    if(sel.value==1){
        $(".holder").append("

");
        $("#simulador-"+ro).load("inv-imo.php .IM");
        ro=ro++;
    }else if(sel.value==2){
        $(".holder").append("

");
        $("#simulador-"+ro).load("poupanca.php .SP");
        ro=ro++;
    }else if(sel.value==3){
        $(".holder").append();
    }
}

I have this code and I'm having trouble with the variable ro, which doesn't increment.
Everytime that I run the function, ro is always 0.
Anyone knows why?

A: Replace this ro=ro++; with this ro++; or this ro=ro+1.


text:
Q: How long does it take for AWS Amazon Inspector to complete a full EC2 Scan? I enabled AWS Amazon Inspector (2) for a single EC2 instance that I have. It's an ubuntu with php and apache, nothing special, and the status shows Scanning for the last 3 hours.
I look at the htop of this machine, and I see that the /snap/amazon-ssm-agent/####/amazon-ssm-agent is running and that several /snap/amazon-ssm-agent/####/ssm-agent-worker are running. Still.... 3 hours passed, and I have no results.
Is it working? isn't it working? is there a more verbose status?
Also, if someone have experience with this, can you share the avarage time you waited for results?

A: I've been in a similar situation - do inspector scans on EC2 as well as ECR. ECR was pretty quick for scans but for EC2 - it took about 4.5hrs to get to INITIAL_SCAN_COMPLETE state. Very concerning it takes this amount of time but noticed it was doing about 470 vulnerability checks.

A: here's are the document contains the status information.
https://docs.aws.amazon.com/inspector/latest/user/assessing-coverage.html
Scanning – Amazon Inspector is continuously monitoring and scanning the instance.
It won't just scan and leave it but instead continuously monitor the instance for future vulnerabilities too. Hence the status shows Scanning.
You need to get into findings tab to look into what's going on with the vulnerabilities. Findings -> By instance -> Select your instance to see findings related to your instance. Hope that helps.


text:
Q: session forget in laravel 8 not working with cookie issue I'm using Laravel 8.35.1 and in that I'm not able to destroy session in my Laravel project. There I also have issue with the cookie setting and removing.
There I have 3 main functions
index() which returns the basic view which provide basic login form.
logincheck(Request $request) this function check the credentials provided from index() function form
sessionout(Request $request) it logout the current user.
please help Thanks in advance.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;

class CommonController extends Controller
{
  public function index()
 {
    return view('index');
 }
 public function sessionout(Request $request)
 {
  $request->session()->forget('adm');
  Redirect::route('homepage')->send();
 }
 public function logincheck(Request $request)
 {
   $responce=array('status'=>false,'message'=>'Request not valid');
   if(!empty($request->username)&&!empty($request->password))
   {
    $admin=DB::table('admin')->where('username',$request->username)->first();
  //return response()->json($admin);
    if(empty($admin))
    {
      $responce['message']="User Not Found";
      return response()->json($responce);
    }
    if(!Hash::check($request->password, $admin->password))
    {
      $responce['message']="invalid Password";
      return response()->json($responce);
    }
    $responce['status']=true;
    $responce['message']='Login Successfull';
    $request->session()->put('adm', $admin);
    cookie('admid', $admin->id, 120); //can't set cookies
    return response($request->cookie('admid')); //checking if cookie is set and trying to get it's value if we will comment this then it will run the logincheck(Request $request) code and login will be successfull.
   }
  return response()->json($responce);
 }
}

A: You can use like this to set cookies ...
    use Illuminate\Http\Response;
    $response = new Response('Set Cookie');

    $response->withCookie(cookie('admin', $admin->id, 1200));

    echo $response->cookie('admin');//to display cookie...

A: First, the important thing is to understand how cookies work. Cookies cant be accessed in same request they are created. So if you make $request->cookie('adminid') in same method, the result will be always not set cookie or its old value.
Second cookie('admid', $admin->id, 120); just creates cookie, but does not save it. You have to attach cookie to response.
$cookie = cookie('name', 'value', $minutes);
return response('Hello World')->cookie($cookie);

or
use Illuminate\Support\Facades\Cookie;

Cookie::queue('name', 'value', $minutes);

More here: Laravel Docs


text:
Q: Is there any thing hashmap can do but map cannot? I only know  that the difference between hashmap and map is that hashmap is implemented with hash function but map is implemented with tree. Could any body add anything more?
Based on this, is there any thing hashmap can do but map cannot?

A: A map requires the key has a strict weak ordering, which perhaps may not exist. A hashmap only needs a hash function. So in this way a hashmap can be used with keys that have no strict weak ordering.

A: *

*Hashmaps have average case better performance for access (O(1)), but worse worst case performance (O(n)). Maps are always O(lg(n)).

*Maps are ordered by their key, hashmaps are not.

*Hashmaps generally use more memory than maps.

*Maps typically allow for faster iteration.

*Good hash functions are harder to write than good ordering functions (and more difficult to analyse).
I don't believe there's anything that a hashmap can do that a map can't.

A: One advantage that hashmaps have over trees is that, in a multi-threading environment, you don't have to lock the whole container to add or remove a single key - locking the single relevant entry in the hash table is (almost) enough.
Almost because there may be metadata (number of items in the hashtable, for instance) to update. And you probably need to lock the whole table to grow or shrink it, of course.


text:
Q: Reference is not allowed in prolog Please help me to find the reason for this exception ,am using following jars,
core-renderer.jar
itext-paulo-155.jar

firstdoc.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>My First Document</title>

            Greetings Earthlings!
            We've come for your Java.

JAVA :
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;

public class Sample1 {
    public static void main(String[] args)  throws IOException, DocumentException {
                String inputFile = "C:/Users/Joseph.M/WorkPlace_Struts2/Fly-Sauccer/src/test/pdf/firstdoc.xhtml";
                String url = new File(inputFile).toURI().toURL().toString();
                String outputFile = "C:/Users/Joseph.M/WorkPlace_Struts2/Fly-Sauccer/src/test/pdf/firstdoc.pdf";
                OutputStream os = new FileOutputStream(outputFile);
                ITextRenderer renderer = new ITextRenderer();
                renderer.setDocument(url);
                renderer.layout();
                renderer.createPDF(os);
                os.close();
    }
}

Exception  :
plumbing.render INFO:: Using CSS implementation from: org.xhtmlrenderer.context.StyleReference
plumbing.load INFO:: SAX XMLReader in use (parser): com.sun.org.apache.xerces.internal.parsers.SAXParser
plumbing.load INFO:: SAX XMLReader in use (parser): com.sun.org.apache.xerces.internal.parsers.SAXParser
plumbing.load INFO:: SAX XMLReader in use (parser): com.sun.org.apache.xerces.internal.parsers.SAXParser
plumbing.load INFO:: SAX XMLReader in use (parser): com.sun.org.apache.xerces.internal.parsers.SAXParser
plumbing.load INFO:: SAX XMLReader in use (parser): com.sun.org.apache.xerces.internal.parsers.SAXParser
plumbing.load INFO:: SAX XMLReader in use (parser): com.sun.org.apache.xerces.internal.parsers.SAXParser
plumbing.load INFO:: Reference is not allowed in prolog.
ERROR:  'Reference is not allowed in prolog.'
plumbing.exception WARNING:: Unhandled exception. Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 2; Reference is not allowed in prolog.
Exception in thread "main" org.xhtmlrenderer.util.XRRuntimeException: Can't load the XML resource (using TRaX transformer). org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 2; Reference is not allowed in prolog.
    at org.xhtmlrenderer.resource.XMLResource$XMLResourceBuilder.createXMLResource(XMLResource.java:191)
    at org.xhtmlrenderer.resource.XMLResource.load(XMLResource.java:71)
    at org.xhtmlrenderer.swing.NaiveUserAgent.getXMLResource(NaiveUserAgent.java:118)
    at org.xhtmlrenderer.pdf.ITextRenderer.loadDocument(ITextRenderer.java:98)
    at org.xhtmlrenderer.pdf.ITextRenderer.setDocument(ITextRenderer.java:102)
    at test.pdf.Sample1.main(Sample1.java:23)
Caused by: javax.xml.transform.TransformerException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 2; Reference is not allowed in prolog.
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
    at org.xhtmlrenderer.resource.XMLResource$XMLResourceBuilder.createXMLResource(XMLResource.java:189)
    ... 5 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 2; Reference is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(Unknown Source)

A: Use < and > instead of
< and >

You do not have to escape XML special characters here.


text:
Q: Spring Boot and Hibernate creates schema but not tables I'm using hibernate to auto generate the database schema and tables.
Schema gets generated but not the tables.
How the tables can be generated ?
application.properties file:
#jdbc
spring.jpa.hibernate.ddl-auto=create
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/tutor?createDatabaseIfNotExist=true&useUnicode=yes&characterEncoding=UTF-8
jdbc.user= root
jdbc.password =

# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5DBDialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=validate
#hibernate.hbm2ddl.auto=create-drop
pool.size=2

Account.java file:
@Entity
@Table
public class Account implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    private Integer id;

    @Column
    private String username;

    @Column
    private String password;

    public Integer getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

Thanks in advance.

A: This property worked for me:
spring.jpa.hibernate.ddl-auto=create

With the following, I generated the schema to a file under project root:
spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql

And SQL server monitoring shown that there's no queries from the app, so there had to be a configuration error or some switch. For me, root cause was a wrong property name in yaml.


text:
Q: In a PHP webpage, reading text from an external PHP to make updating content across pages easy I'm writing a small website that has multiple pages. I'd like to have the same footers on each page, but I don't want to manually update 10 pages of HTML everyday. I'd like to put a PHP call to an external file in each HTML page (now .php pages, thanks to @br14np) so that when I update the PHP file, all the pages - when loaded - will show the same footer text.

<?php footertext.php ?>

is my wild guess at loading the content in the file of the afformentioned name but to no avail. (In footertext.php the code is: <?php print("Test numba one") ?>).
How can I go about doing this? I'd prefer an answer involving PHP.
UPDATE:
This is the exact code I'm using. Everything is in the same directory.
Main File:

 Content: <?php include "footertext.php ?>

Footer Content:
echo 'Test numba TWO!';

A: Use the include function. Just give it the path to your file. Example:
<?php include "footertext.php"; ?>

There are a few other functions that do similar things, such as require_once(). You can read more about that here.
Response to update
You're missing closing quotation marks after "footertext.php. Another tip that may help this situation is to turn on php error reporting. This will display any syntax or other errors on your page. Just insert the following code at the very top of your pages:
<?php
  error_reporting(E_ALL);
  ini_set("display_errors", 1);
?>

Also make sure you have opening and closing php tags (<?php ... ?>) in your footertext.php file.

A: The best fit solution for your query is include or require functions of php. now you need to identify which one out of those are your choices based on their functional behavior.
PHP include and require Statements
In PHP, you can insert the content of one PHP file into another PHP file before the server executes it.
The include and require statements are used to insert useful codes written in other files, in the flow of execution.
Include and require are identical, except upon failure:

*

*require will produce a fatal error (E_COMPILE_ERROR) and stop the

*include will only produce a warning (E_WARNING) and the script will continue

So, if you want the execution to go on and show users the output, even if the include file is missing, use include. Otherwise, in case of FrameWork, CMS or a complex PHP application coding, always use require to include a key file to the flow of execution. This will help avoid compromising your application's security and integrity, just in-case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. Then, when the header needs to be updated, you can only update the header include file.
Syntax

include 'filename.ext';
  or
require 'filename';

You may like to go through the details of
Include,
Require,
Require_once &
Include_once.
Enjoy!
Anand Chavan


text:
Q: Get variable name from object array Can't find out how to get element variable name from array.
Need something like that:
var test = 1;
var test2 = "2";

var array = new object[]{test, test2};
foreach (var v in array)
{
 Debug.Log($"{v.ToString()} {v}")
}

// test 1
// test2 2

I need that in one method, lets call it "void CombineWithName(params object[] msg){}

A: This is impossible.  The names test1 and test2 are not stored in the variable array but pointers to the location of the data.  Using .net6 on .NETFiddle and the nameof method, the compiler tells you that the expression does not have a name.

A: The nameof operator allows you to get the name of a variable, type or member in string form without hard-coding it as a literal.
 var myVar = "ABC";
 Console.WriteLine(nameof(myVar));

Source: https://riptutorial.com/csharp/example/363/basic-usage--printing-a-variable-name
Edited:
In your above approach, since you are directly mapping variables to an object, There is no way to figure out the variable that was used to set a element, unless you save that information in a separate array or collection (For debug purpose)
var test = 1;
var test2 = "2";

var array = new object[]{test, test2};

var arrayOfArrays = {
    new {Name = nameof(test), Array=test}
,   new {Name = nameof(test2), Array=test2}
};
foreach (var p in arrayOfArrays) {
    Console.WriteLine(p.Name);
    ...
}


text:
Q: Why did Data call the French language "obscure"? In the video below, Data refers to the French language as "obscure". Picard objects to this and Data is about to make a remark as to why the French language was indeed obscure.  Is there any indication given in any other materials as to why Data considered French to be an obscure language?
Jean-Luc Picard insulted by Data - YouTube

A: While Picard states that French was the dominate international language, it has been in decline as English has become the defacto standard since World War 2. Wikipedia

Once the key international language in Europe, being the language of diplomacy from the 17th to mid-20th centuries, French lost most of its international significance to English in the 20th century, especially after World War II, with the rise of the United States as a dominant global superpower. A watershed was when the Treaty of Versailles, ending World War I, was written in both French and English. A small but increasing number of large multinational firms headquartered in France are using English as their working language even in their French operations, and to gain international recognition, French scientists often publish their work in English.

With the center of Starfleet being located in San Francisco, you can imagine it has an English-centric influence on the planet. Additionally, which Africa has been growing in use of French in the last few decades, we don't know what affect World War 3 and the forming of the African Confederation (or the United States of Africa) had on their continued use of French.
Based on Data's statement, we can assume that by the 24th century, French has become a niche language.

A: I keep going back to the Writers Guide again and again, as well as in this case.  The description of Jean-Luc Picard states among other things:

Born in Paris, France, Picard betrays a gallic accent only when deep emotions are triggered. Otherwise, since ethnic accents are no longer common, he carries only a touch of French phrasing in his speech. In discussions with friends, he pretends to believe that France represents "the only true civilization" to appear on Earth -- and that it delights him when a witty companion wants to prove the same for England, Italy or China. He is definitely a 'romantic' and sincerely believes in concepts like honor and duty although on issues that affect the safety if his crew and starship he can be completely pragmatic and tough as hell.

"Federation Standard" is the common tongue for Starfleet and Data, who not only know this and French but also a huge range of other languages, presumably classify languages with fewer then N users to be obscure. If we take the first definition of obscure from Merriam Webster:

*

*not well-known : not known to most people

it is fair to assume this is a direct cold fact way of presenting it from Data's fact-ridden way of thinking.

When it comes to the particular clip it is clear that they intended it to be a humorous awkward moment precisely because of Picards love of France. This is further underlined by the reaction of the crew. A situation we all know; when someone unknowingly is stepping on someone else's toes ;)

A: Data frequently "gets it wrong" when repeating quotes and imitating human behaviour.
Throughout The Next Generation TV series and movies, Data imitates examples of human behaviour that he has observed.  He often misunderstands the original context of these behaviours, making his reenactments misguided and inappropriate.
Examples:

*

*Growing a beard similar to Riker's, to project authority and thoughtfulness ("The Schizoid Man", TNG 2x06).

*Learning to tap dance (at times very robotically) in preparation for ballroom dancing at a wedding ("Data's Day", TNG 4x11).

*Provoking a lovers' quarrel with his girlfriend Jenna D'Sora, in an attempt to strengthen their romantic relationship ("In Theory", TNG 4x25).

*Talking about the weather to Picard, because humans use small talk to fill awkward moments ("Starship Mine", TNG 6x18).

*Pushing Dr. Crusher off of a sailing ship, because the crew laughed when Riker made Worf fall into the ocean (Star Trek Generations).

*Engaging in "girl talk" with Worf, in imitation of a conversation Troi and Dr. Crusher had regarding a rejuvenating effect of the Ba'ku planet (Star Trek: Insurrection).
Data's quote about "an obscure language known as French" is from "Code of Honor" (TNG 1x04):

DATA: It is a highly structured society in which people live by strict codes of honour. For example, what Lutan did is similar to what certain American Indians once did called counting coup. That's from an obscure language called French.
— Transcript

As one of the earliest stories involving Data, this episode is set during a time when his social skills are least developed and when such gaffes are all the more likely.  Data may simply be repeating something he heard or read,(1)(2) without understanding that the quote is inappropriate for the new context.
Another possibility, again based on Data's social inexperience, is that this is his attempt at allowing his crewmates to save face.  The pause in Data's speech after he mentions "counting coup" suggests that he intends to end the description there.  Then, when Picard and the others do not react, Data's reference to the obscurity of French could be his attempt at giving them an excuse for not recognizing the term.
French is apparently a living language on 24th Century Earth.  French accents still exist, as spoken by Picard's mother ("Where No One Has Gone Before", TNG 1x06) and the people in the Café des Artistes ("We'll Always Have Paris", TNG 1x24).  The degree to which these recreations match the in-universe reality is unknown(3), but Picard doesn't think that these speech patterns are out-of-place, so it does not seem that French is "obscure" according to the common conversational use of the word.

(1) Chekov made several exaggerated claims about his Russian heritage, and Scotty wore a kilt as part of his formal uniform.  In some situations, cultural pride and good-natured rivalry is still an acceptable part of life in 23rd (and presumably 24th) Century human society.  Data would have trouble understanding, for example, that a taunt he overheard at an international sports match doesn't necessarily have any basis in science, or that the use of a word in conversation carries different connotations than its use in a scientific journal.
(2) Data's creator Dr. Noonian Soong, proud and highly opinionated, has little care for polite niceties, so he is a possible source for socially blunt quotes.
(3) The French-accented English dialogue that the audience hears could be meant as French in-universe, the way the Klingon language is translated for the audience during the trial of Kirk and McCoy in Star Trek VI.  Conversely, both scenes are based on Picard's memories, and they may sound French only because they are tinged by his nostalgia for the French language.

A: This isn't a great answer, but it's fairly heavily hinted throughout the "modern" series (TNG, DS9, Voyager) that the official language of the Earth is standardized English, and that other languages are basically of hobbyist and research type use only, the way Latin is today. There is also more than one reference of inferior cultures that don't have a common language, and that is one indicator of them being inferior.
As for why French was used specifically, it may be for a light comedic moment with Picard. Or for the reasons of being one of the most widely spoken languages (geographically) in the world, mainly competing with English for geographic spread.
French is also the language other than English that business is conducted in at the UN. Other languages were added as additional working languages later. Some committees and offices in the UN only use English and French to this day (Per Wikipedia). Also CERN requires most staff to speak, write, and read both.

A: Data is a graduate of Star Fleet Academy.  There is a good chance he is quoting a professor, and thus the opinion of Star Fleet in general.

A: Star Trek is written in English, targeting its main audience; the English-speaking population. That's all! It was a nice light jab at the Franco expense and it was humorous. I'm French and I thought it was cute.


text:
Q: Sorting a complex records in MySQL table I'm working on a personal project and I'm stuck in phase of cleaning a particular dataset. The dataset consists of records of an agent(having a unique AgentID) who visits different parking sites (having unique ParkingID). He is using an app to enter his records in the database. When agent enters into the parking site he presses the button for login and when he leaves he presses logout in the app (the agent can press the button multiple times, so there can be possibility of duplicate login and logout records). When the person visits a parking site, he/she can raise some tickets when he meets certain people at that place, thus marking Tickets Finished in the app.
The problem is data that comes into the database is only sorted to minute stage. Thus, the records having same time can appear differently in the database. One such dummy dataset is shown below.

I want to sort it together the event which finishes first should appear at top and the event that finishes later should come at the end. My desired output is shown below.

I'm having no idea how to sort this in MySQL, if anyone of you can help me in figuring out how to solve this problem then it would be really helpful from your side.

A: Sorting by a CASE WHEN to break the tie.
SELECT *
FROM parking_agent_logs
ORDER BY `Date`, `Time`, ParkingID, AgentID
, CASE Event_Type
  WHEN 'Log In' THEN 1
  WHEN 'Ticket Finished' THEN 2
  WHEN 'Log Out' THEN 3
  ELSE 9
  END

Test on db<>fiddle here


text:
Q: Populate form fields with Django forms after raise validation error i need help, im new with django forms o how its work.Have a html form and i encrypted the values with javascript when the form is submited like this
$("#form").submit(function(){
    //remplace the original value and send to the server the encrypted data
    $("#field1").val(encrypted_data);
    $("#field2").val(encrypted_data);
return true
});

I have this class in my django project
class SomeForm(forms.Form):

field1 = forms.CharField(label="field 1")
field2 = forms.CharField(label="field 1")

clean_field1(self):
 data = decrypt_text(self.cleaned_data['field1'])
 p = re.compile(r'[\d]{8}')
 #validate decrypt data is a number and his lengt is more than 8
 if p.match(data) is None:
    raise forms.ValidationError("Error")

 return data

this work fine, the problem is when the data es invalid, i need pass to the field the original value, and currently returns the field with de encrypted value.
thanks in advance!!

A: This is how you do it:
In your post() method in the class based view, you will have this condition
if form.is_valid():
# you do whatever you want with this form
else:
# when your form raises a validation error, this snippet gets executed
#so you need to write the following lines in the else condition to
#repopulate your form:
context['form'] = self.form_class(self.request.POST)
return render(request, self.template_name, context)

Now when you have a validation error, you can see it there in the template as well.
Hope you found this useful


text:
Q: Convert a string (Last\tFirst\tAge) to an array with elements {Last, First, Age} I'm new to Java and I want to convert a string such as Apple\tJohn\t23(note \t are tabs) into an array with 3 elements {Apple, John, 23}. I know that I need to some import some string manipulation method but I'm only beginning Java so is there one that fits my situation?

A: It sounds like you want:
String[] bits = text.split("\t");

Note that split takes a regular expression - so if you ever want to split on a dot, you'd need split("\\.") for example. Personally I prefer the Guava library Splitter class instead, but it's your choice :)
EDIT: From a comment:

Also do you recommend I use an String array to store a mix of integer and character values? Say for futureproofing I might want to do a comparison on say if (age > 21) then John can drink.

No. Once you've split the data into a string array, it would be good to convert that into an object specifically for this data. For example:
String[] bits = text.split("\t");
// Assuming a suitable constructor...
Person person = new Person(bits[1], bits[0], Integer.parseInt(bits[2]));
System.out.println(person.getFavouriteFruit()); // Apple

A: Use String.split()
String str = "Apple\tJohn\t23";
    String[] parts = str.split("\t");
    System.out.println(Arrays.toString(parts));

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex   Result
:   { "boo", "and", "foo" }
o   { "b", "", ":and:f" }