text:
Q: Install ipykernel in vscode - ipynb (Jupyter) Greetings!
I am not able to install ipykernel and receiving following error. Please advise.
print('Hello')
Running cells with 'Python 3.10.5 64-bit' requires ipykernel package.
Run the following command to install 'ipykernel' into the Python environment.
Command: 'c:/Users/ps98/AppData/Local/Programs/Python/Python310/python.exe -m pip install ipykernel -U --user --force-reinstall'

A:
'c:/Users/ps98/AppData/Local/Programs/Python/Python310/python.exe -m
pip install ipykernel -U --user --force-reinstall'

Error reports tell you what to do.
Run the command in your terminal:
pip install ipykernel

At the same time, of course, make sure that the pylance extension is installed.


text:
Q: Line integral of a vector Let C be the part of the plane curve defined by $$y^2=x^3-x$$ between $$(\frac{-1}{\sqrt3},\sqrt[4]{\frac4{27}})$$ and $$(0,0)$$ oriented from left to right. How would I calculate
$$\int_{C}y^2\vec{i}+(2xy+4y^3e^{y^4})\vec{j}ds$$
I have already found that the vector field is conservative, I'm just not sure how to proceed from there.

A: Since the vector field is conservative it has a potential function. Check that the gradient of
$$f(x,y) = xy^2 + e^{y^4}$$
is indeed the vector field in the problem. Then use the fundamental theorem of line integrals:
$$\int_{\vec{a}}^{\vec{b}}\nabla f \cdot d\vec{r} = f(\vec{b}) - f(\vec{a})$$
to get that the integral equals
$$f(0,0) - f\left(-\frac{1}{\sqrt{3}},\sqrt[4]{\frac{4}{27}}\right) = \frac{11}{9} - e^{\frac{4}{27}} $$

A: ${\bf F}(x,y)=(y^2,2xy+4y^3e^{y^4})$ is the vector field. If ${\bf F}$ is conservative then ${\bf F}=\nabla G$ for some scalar field $G(x,y)$. And,
$$
\int_C {\bf F}\cdot d{\bf r} = \int_a^b {\bf F}({\bf r}(t))\cdot {\bf r}'(t)dt
=G({\bf r}(b))-G({\bf r}(a))
$$
where ${\bf r}(t)$ is any parametrisation of the curve $C$. We have the endpoints ${\bf r}(b)$ and ${\bf r}(a)$ so we only need to find $G$.
${\bf F}=\nabla G$ means that
\begin{eqnarray*}
\frac{\partial G}{\partial x}&=&y^2 \qquad and \qquad \frac{\partial G}{\partial y}=2xy+4y^3e^{y^4}\\
\implies G&=&xy^2+f(y)+C\qquad and \qquad G=xy^2+e^{y^4}+g(x)+C
\end{eqnarray*}
for some functions $f(y)$ and $g(x)$. So, take $f(y)=e^{y^4}$ and $g(x)=0$ and we have $G(x,y)=xy^2+e^{y^4}+C$.
Now,
$$
\int_C {\bf F}\cdot d{\bf r} = G({\bf r}(b))-G({\bf r}(a)) =
G(0,0)-G\left(-\frac{1}{\sqrt{3}},\sqrt{\frac{4}{27}}\right)
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom Google Sheet Frozen Timestamp Formula Prefacing this with the fact that I'm not especially versed in Google Sheet scripting, just fairly decent at Googling and making stuff work for me.
I'm using IFTTT.com to automatically append a Google Sheet if I save an article in my RSS reader.
With how IFTTT works, it adds a row to the bottom of a sheet based on various attributes of the article saved.
I'm getting hung up on adding an automatic non-volatile timestamp to the row.
I've tried using the automatic timestamping function below, which works when I type into a cell, but not when the sheet is appended.
function onEdit(event)
{
  var timezone = "GMT-5";
  var timestamp_format = "MM-dd-yyyy"; // Timestamp Format.
  var updateColName = "Article Title";
  var timeStampColName = "Date Discovered";
  var sheet = event.source.getSheetByName('Sheet1'); //Name of the sheet where you want to run this script.

  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}

IFTTT lets you set what data gets ported into what column, and has specific "ingredients" for data from Feedly you can put into a column.
They also allow for static text, and formulas.
Realizing this, I found the following custom function, which seems to somewhat work.
function timestamp() {
return new Date()
}

This allowed me to add a function to check whether the title of the article had content, and timestamp if true.
=Timestamp(INDIRECT("E"&ROW()))
Oddly, the first row with this formula did not change when I reloaded the sheet today (I entered the formula yesterday), nor did a row further down the sheet.
Source sheet: https://docs.google.com/spreadsheets/d/1ybfgOgBkqHdld9_sexzMfdMV2lT6Qp7WgQ8Di96S-a8/edit?usp=sharing
Many thanks ahead of time.

A: Since you are only interested in the date of discovery and not too worried about the exact time. You can set up a time trigger for a function to run daily after midnight to add timestamps of yesterday's date to row with non-empty "article title" column.
Here is code that does just that, also added a function to setup the daily trigger
// Run this function to setup daily trigger to run at midnight to set the date of discovery.

function IntializeTrig(){

 ScriptApp.newTrigger("addTimeStamp").timeBased().atHour(0).everyDays(1).create()
  // If you have issues with timezone or if you work late at night you can change time to say 2 am by changing to this ".atHour(2)"
}
// This function checks to see if the column Date Discovered is empty and add yesterday date to it, if Article Title column is a Non empty String
function addTimeStamp(){
 var ss = SpreadsheetApp.getActive()
 var sheet = ss.getSheetByName("Sheet1")
 var updateColName = "Article Title";
 var timeStampColName = "Date Discovered";
 var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
 var dateCol = headers[0].indexOf(timeStampColName), dateCol =dateCol + 1;
 var articleCol = headers[0].indexOf(updateColName), articleCol = articleCol + 1;
 var numOfCol
 if (dateCol < articleCol){
     numOfCol = articleCol
 }else {
     numOfCol = dateCol
 }
 var yesterday = new Date(Date.now() - 864e5)
 var yestDate = yesterday.toISOString().slice(0,10)
 var data = sheet.getRange(2, 1,sheet.getLastRow()-1, numOfCol).getValues()
 for (var i = 0 ; i< data.length ; i++){
   if (data[i][articleCol - 1] !== "")
     if (data[i][dateCol - 1] == "")
       data[i][dateCol - 1] = yestDate
 }
  sheet.getRange(2,1,data.length , data[0].length).setValues(data)
}

Hope this helps!


text:
Q: Clock problem when waking from suspend When waking from suspend, time settings changes to manual, and time on my PC is sometimes 5 days from current time. That causes difficulties using time-related programs, such as chats... When I change to automatically after waking, after 10-15 minutes, time gets normal.
How can I fix this issue?
I'm using 16.04, but i had this problem on earlier versions too.

A: Install Network Time Protocol daemon and utility programs (ntp).
sudo apt install ntp fake-hwclock

NTP, the Network Time Protocol, is used to keep computer clocks  accurate by synchronizing them over the internet or a local network.
To set the hardware clock to the current system time by syncing the hardware clock with the system clock:
sudo hwclock -w


text:
Q: not getting the error Token mismatch exception in Verify csrf token in laravel 5.5 I am new in Laravel and  I am using Laravel 5.5.
When I am submitting without {{ csrf_field() }}
not getting the error Token mismatch exception in Verify csrf token
The error is

The page has expired due to inactivity.
      Please refresh and try again

My HTML form is
<form method="POST" action="/post">

        Title
        <input type="text" class="form-control" name="title">

        Body
        <input type="textarea" class="form-control" name="body">

    <button type="submit" class="btn btn-primary">Publish</button>
</form>

My Route web file
Route::post('/post','PostsController@store');

Here is my Controller class function
public function store() {
    dd(request()->all());
}

A: seems a problem inside laravel. it's showing incorrect message. there are some similar posts: 1stlink, 2ndlink
you should just put your csrfField there and problem will be vanished.
additional links about laravel errors:
Larave 5.5: default error views and costomizing them
Laravel 5.5: set error  details via debug option

A: As @Shaz said in https://es.stackoverflow.com/questions/99342/laravel-5-5-the-page-has-expired-due-to-inactivity-please-refresh-and-try-aga
In Laravel 5.5, "TokenMismatch" throws an exception with code 419
Update: .. and an error page with the message "The page has expired due to inactivity. Please refresh and try again"
I would recommend installing https://github.com/barryvdh/laravel-debugbar
so you can see the exceptions.
You will probably see
../vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php#70
 return $this->addCookieToResponse($request, $next($request));
    }

    throw new TokenMismatchException;
}

Update:

When I am submitting without {{ csrf_field() }} not getting the error Token mismatch exception in Verify csrf token

You are getting the mismatch exception but with the new error page and code.
(https://laravel-news.com/laravel-5-5-error-views)
The {{ csrf_field() }} creates an input hidden with the token, so you have to use it in your forms ( also check that the token is not empty in the form )
<input type="hidden" name="_token" value="nReVYpjfvqiVVkE8LpGeNOdJZnskNLGoB57YHFkO">


text:
Q: How to insert from two tables into one at the same time? So, guys...
I have two tables now, one called nobooks with the id of 4 authors that didn't write books and one called noauthors, with with the id of 4 books that don't have an author, and I need to insert them at a third table called authorship, one id_author for one id_title, I've tried something like this:
insert into authorship (ID_Author,ID_Title) select * from nobooks, noauthors

But it didn't worked, it inserted the 4 id_titles for each id_author, and I don't know anymore what to do, so I would appreciate some help.

A: use union to insert id, title from both tables.
insert into authorship (ID_Author,ID_Title)
select t1.id, t1.title from (select id, title from nobooks
union all
select id, title from noauthors) as t1;

A: Use Union Instead Of Normal Query
insert into authorship (ID_Author,ID_Title)
select id,id from nobooks
union
select id,id from noauthors

DB FIDDLE LINK
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=60fe37c15112fccec304ae079b33df2a

A: insert into authorship (ID_Author,ID_Title)
select id,'nobooks' from nobooks
union
select id,'noauthors' from noauthors


text:
Q: Facebook group_id by vanity name This is an old question, but still no answer on the Internet:
how can one retreive the group id of a Facebook group by it's vanity url  (for example,  https://www.facebook.com/groups/startupmonthly/  ?)
I have to use Open Graph API only - the user provides an url, my server script needs to find the id.
I found no relevant information in the FQL and Open Graph API references.
Somehow services like http://whatismyfacebookid.com/index.php  appear to do  exactly what i need - the question is how?


text:
Q: asyncio.gather() is starting first two tasks but not the third one I have a python function that is supposed to send packet asynchronously in a loop.
import asyncio
import logging
import pickle
from time import sleep

from decoder import decode, encode
from socket import *

UDP_PORT_NUMBER = 44006
HOST_ADDRESS = "192.168.204.139"
server_address = (HOST_ADDRESS, UDP_PORT_NUMBER)

def get_data_packet():
    with open('../packets/packet_15', mode='rb') as fpt:
        packet = pickle.load(fpt, encoding='bytes')
    return packet

class GcuUdpClient:

    @staticmethod
    async def send_packets():
        data = get_data_packet()
        client_socket = socket(AF_INET, SOCK_DGRAM)
        client_socket.sendto(data, server_address)
        print('sending data packets')
        await asyncio.sleep(5)

I have another python program that calls this class, along with two other classes.
import asyncio
from http_server import PostServer
from grpc_server import GrpcServer
from gcu_udp_client import GcuUdpClient

async def main():
    await asyncio.gather(GrpcServer.run(), PostServer.run_server(), GcuUdpClient.send_packets())

if __name__ == '__main__':
    asyncio.run(main())

This code starts up the first two meaning
GrpcServer.run()
and
PostServer.run_server()
However I can't get the last one started, to send out the packets. What am I missing.
Adding the code for http_server.py
import threading
import zlib
from http import HTTPStatus
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from socket import *
from time import sleep
#from GCUSimulator.generated.GDataPayload_pb2 import GDataPayload
from generated.GDataPayload_pb2 import GDataPayload

HTTP_PORT_NUMBER = 8085
HTTP_SERVER_IP="192.168.204.1"

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def __init__(self, *args, **kwargs):
        self.subscribed = False
        super(SimpleHTTPRequestHandler, self).__init__(*args, *kwargs)

    def do_GET(self):
        self.send_response(200)
        self.end_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])  # <--- Gets the size of data
        post_data = self.rfile.read(content_length)  # <--- Gets the data itself
        print("POST Path: {0} Headers: {1} Body: {2}".
              format(str(self.path),  str(self.headers), post_data.decode('utf-8')))
        if str(self.path) == '/setSubscriber.php':
            message = "Subscription Result:Subscribed,APIVersion:1.0.0"
            self.send_response(HTTPStatus.OK)
            self.end_headers()
            self.wfile.write(message.encode('utf-8'))
            self.subscribed = True

        elif str(self.path) == '/removeSubscriber.php':
            self.send_response(HTTPStatus.OK)
            self.end_headers()
            self.subscribed = False

    def get_subscription_status(self):
        return self.subscribed

class PostServer:

    @staticmethod
    async def run_server(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, addr=HTTP_SERVER_IP, port=HTTP_PORT_NUMBER):

        server_address = (addr, port)
        print('Http Post server : {0}:{1}'.format(addr, port))
        httpd = server_class(server_address, handler_class)
        await httpd.serve_forever()

Adding the code for grpc_server.py
from concurrent import futures
import grpc
from generated import guidance_grpc_service_definitions_pb2_grpc
from gcu.ops_station_services import OPSStationServices

GRPC_PORT_NUMBER = 12074

class GrpcServer:

    @staticmethod
    async def run():
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        guidance_grpc_service_definitions_pb2_grpc.add_OpRPCServicesServicer_to_server(OServices(), server)
        server.add_insecure_port('[::]:{0}'.format(GRPC_PORT_NUMBER))
        print('Grpc Server : {0}:{1}'.format('localhost', GRPC_PORT_NUMBER))
        server.start()
#        server.wait_for_termination()


text:
Q: Ansible with Packer I am trying to get packers ansible provisioner to use a username and password but the configuration with ansible keeps stalling because the authentication step fails.
Here is my Packer Ansible provisioner script.
    {
  "type": "ansible",
  "user": "pi",
  "playbook_file": "playbook.yml",
  "extra_arguments": [
    "--extra-vars",
    "ansible_python_interpreter=/usr/bin/python3",

    "--extra-vars",
    "ansible_user=pi",

    "--extra-vars",
    "ansible_ssh_pass=raspberry",

    "-vvv"
  ]
}

I'm a t a complete loss why this does not work.
The output where it gets stuck is as follows.
    armpi: ==> arm-image: Executing Ansible: ansible-playbook --extra-vars packer_build_name=arm-image packer_builder_type=arm-image -i /tmp/packer-provisioner-ansible288108417 playbook.yml -e ansible_ssh_private_key_file=/tmp/ansible-key528332842 --extra-vars ansible_python_interpreter=/usr/bin/python3 --extra-vars ansible_ssh_user=pi --extra-vars ansible_ssh_pass=raspberry -vvv

looks like it is trying to use a ansible_ssh_private_key_file=/tmp/ansible-key528332842 but I dont want it to use that I really just want it to log in with username and password.

A: From the top of the ansible provisioner documentation:

The ansible Packer provisioner runs Ansible playbooks. It dynamically
  creates an Ansible inventory file configured to use SSH, runs an SSH
  server, executes ansible-playbook, and marshals Ansible plays through
  the SSH server to the machine being provisioned by Packer.
Note: Any remote_user defined in tasks will be ignored. Packer will
  always connect with the user given in the json config for this
  provisioner.

What you are trying to do is not possible with the ansible provisioner. But you can achieve the thing you try to do by running ansible with the shell-local provisioner.
(To get the IP address of the VM to use in the Ansible inventory you can follow the general patter I sugest in this post.)


text:
Q: How to remove "Add to Source Control" button from the VS2022 status bar? Is there a way to remove the  button from the status bar in VS 2022? All the solutions I could find are for versions prior to VS 2022.
I don't use any kind of source control and having that button linger in the status bar is visually unpleasing/annoying, especially when it's sitting next to information that's useful.

A: I had to install Visual Commander from https://vlasovstudio.com/visual-commander/ and then enable the example extensions which modifies the UI so that the source control button is not displayed anymore


text:
Q: How OR operator works I am new to R. I want to confirm if my understanding of the concept is correct.
While working with logical operator OR I am unable to understand the below output. Case 1 has result "false" when both the second elements as 0 while it is "true" when these are numbers >0. Is this because 0 is always considered as "FAlse" and in this case both these values are "false"?
Case 1
v <- c(3,0,TRUE,2+2i)
t <- c(4,0,FALSE,2+3i)
print(v|t)
#[1]  TRUE FALSE  TRUE  TRUE

Case 2
v <- c(3,0,TRUE,2+2i)
t <- c(3,0,FALSE,2+3i)
print(v|t)
#[1]  TRUE FALSE  TRUE  TRUE

A: You are doing an elementwise logical comparison of both vectors v and t. And since any number > 0 evaluates to TRUE if converted to logical you are getting this output. (please also note the comment below)
You can think of this happenig in the background (for case 1):
   as.logical(3) | as.logical(4)
   as.logical(0) | as.logical(0)
            TRUE | TRUE
as.logical(2+2i) | as.logical(2+2i)

which yields our output:
TRUE FALSE TRUE TRUE

A: R considers TRUE as 1 and FALSE as 0. Your understanding is correct. You have an elementwise checking and in the case where v[2]=0 and t[2]=0, R understands: 0 | 0 thus 0, i.e. FALSE OR FALSE = FALSE.
You can check this by changing one of the 0 inputs (v[2]=0 and t[2]=0) to something !=0.
As a comment though:
you have to take into account that you can not use c() to create variables with different classes in them. R interprets all the inputs that you provide as complex numbers in this case. I mean that the TRUE is converted to 1+0i and the FALSE to 0+0i (check the:
print(v)
>v
[1] -3+0i  0+0i  1+0i  0+2i)


text:
Q: Organizing large c/c++ project in Eclipse I'm trying to set up eclipse cdt (Indigo) for a large development project and need some help on organizing the eclipse workspace. The project is in its startup phase, parts are completed, but much more is to be developed. The project covers several products each consisting of several processes and a common set of libraries. The structure is about as follows:
top/
  Library/
    Math/
    Sys/
    Com/
  Include/
    Math/
    Sys/
    Com/
  Product/
    Prod1/
    Prod2/

I created a top workspace and want to use this for the whole project. I'm currently strugling with the Library and Include part. I need to create a new library called Err and a corresponding Err directory under the Include branch which is outside of the scope of the project created under the Library folder. Should I create this as a separate Err project in Eclipse? I tried this and the folder under Library was fine, but how then do I create the corresponding folder and files under the Include branch?
Is this the best way to organize the project or should I use one common project for all the libraries or divide the whole thing into several workspaces?


text:
Q: Semantic mark for testimonial details I jus got the following PSD design:

(sorry about the grid line in between , that blue line really is not needed.).
Now i was wondering with all there html5 tags , what would be a great and semantic markup to code the above design , iám usually a guy who goes old school and uses div and spans , but this time i used cite , when i read the MDN doc's there seems to still be no clarity weather a name/designation can be used in cite , basically the way look at cite is , it a tag to be used only when you have a definitive resource to be added to you markup. Even though neither name nor designation is a definitive resource, i came up with the following markup.

            Brian-May 2015
            Managing Partner.Tammy Lenski LLC

can anybody tell me what would be a more semantic way to code the testimonial details ? Thank you , i would greatly appreciate any help or guidance, i have always wonder what would be a semantic markup especially for a scenario like above.

A: Using schema.org metadata

    Brian-May 2015
    Managing Partner.Tammy Lenski LLC


text:
Q: How do I calculate the normal vector of a line segment? Suppose I have a line segment going from (x1,y1) to (x2,y2). How do I calculate the normal vector perpendicular to the line?
I can find lots of stuff about doing this for planes in 3D, but no 2D stuff.
Please go easy on the maths (links to worked examples, diagrams or algorithms are welcome), I'm a programmer more than I'm a mathematician ;)

A: m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:
m1*m2 = -1

then
m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line..

b is something if you want to pass it from a point you defined

A: If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx).
Note that no division is required, and so you're not risking dividing by zero.

A: We know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y') is perpendicular to the line connecting (x1,y1) and (x2,y2). This line has direction (x2-x1,y2-y1), or (dx,dy).
So,
(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0

The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx) or (-dy,dx)

A: Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.
The matrix representation of the general 2D transformation looks like this:
x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.
If t = 90 degrees, then cos(90) = 0 and sin(90) = 1.  Substituting and multiplying it out gives:
x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.


text:
Q: Расчет полей формы Django Есть задача добавить в отображаемую форму автоматический расчет полей, чтобы при вводе значений в одно поле формы автоматически рассчитывалось другое. Например, как в гугл переводчике. Сейчас реализую это следующим образом:
class DealForm(forms.ModelForm):
class Meta:
    model = Deal

    fields = ['buy_price','percent','sell_price']

    widgets = {
        'buy_price':  forms.NumberInput(attrs={'class': 'form-control'}),
        'percent':  forms.NumberInput(attrs={'class': 'form-control','onchange':'calcSell()'}),
        'sell_price':  forms.NumberInput(attrs={'class': 'form-control'})
    }

Шаблон
<script>
function calcSell(){
var val1 = document.getElementById('id_buy_price').value
var val2 = document.getElementById('id_percent').value
var val3 = parseFloat(val1)*parseFloat(val2)
document.getElementById('id_sell_price').value = val3.toFixed(8)
}
</script>

Но в связи с тем, что расчетов должно быть значительно больше, то использование скриптов видится не лучшим решением. Однако "на лету" делать это варианта я не нашел пока. Вероятно, есть какой-либо общепринятый и более правильный способ реализации данного функционала.


text:
Q: Hamiltonian in Majorana basis I read (for example here: cond-mat/0010440) very often that if we transform the Hamiltonian from a fermionic basis to the basis of Majorana operators by expanding the fermionic operators in real and imaginary part $c = a + ib$ with $a^{\dagger} = a$ and $b^{\dagger} = b$, then the corresponding Hamiltonian can be written as
$$
H = \frac{i}{4}\sum_{lm}A_{lm}a_{l}b_{m}\text{.}
$$
Now the matrix $A$ is skew-symmetric ($A^{T} = -A$). My question is now, is there a general reason why $A$ is skew-symmetric?


text:
Q: Jackson XML - Deserialize from specific node I'm new to Jackson XML and I would like to do the following:

*

*Here is the XML I'd like to convert to Java DTO:
 <s:Envelope
     xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
     <s:Body>
         <cotacaoTaxaCambioResponse
             xmlns="http://tempuri.org/">
             <cotacaoTaxaCambioResult
                 xmlns:a="http://schemas.datacontract.org/2004/07/Exchange"
                 xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                 <a:TaxasCambio>
                     <a:CotacaoTaxaCambio>
                         <a:CLIENTEC>0</a:CLIENTEC>
                         <a:CLIENTEV>0</a:CLIENTEV>
                         <a:COMERCIALC>0</a:COMERCIALC>
                         <a:COMERCIALV>30</a:COMERCIALV>
                         <a:DATA>2021-12-15T00:00:00</a:DATA>
                         <a:HORARIO>1027</a:HORARIO>
                         <a:MOEDA>978</a:MOEDA>
                         <a:PARIDADEC>1</a:PARIDADEC>
                         <a:PARIDADEV>1</a:PARIDADEV>
                         <a:TURISMOC>0</a:TURISMOC>
                         <a:TURISMOV>30</a:TURISMOV>
                     </a:CotacaoTaxaCambio>
                 </a:TaxasCambio>
                 <a:serviceStatus>
                     <a:CODRETORNO>0</a:CODRETORNO>
                     <a:MENSAGEM>Sucesso</a:MENSAGEM>
                     <a:MENSAGEMEN>OK</a:MENSAGEMEN>
                     <a:NRREFERENCE>0</a:NRREFERENCE>
                 </a:serviceStatus>
             </cotacaoTaxaCambioResult>
         </cotacaoTaxaCambioResponse>
     </s:Body>
 </s:Envelope>

*Info I need is attributes of a:CotacaoTaxaCambio node.

*Created this DTO
     @JacksonXmlRootElement(localName = "a:CotacaoTaxaCambio")
     public class CotacaoResDTO {

         @JacksonXmlProperty(localName = "a:DATA")
         private String data;

         @JacksonXmlProperty(localName = "a:HORARIO")
         private String hora;

         @JacksonXmlProperty(localName = "a:MOEDA")
         private String codMoeda;

         @JacksonXmlProperty(localName = "a:COMERCIALV")
         private Double valorComercial;

         @JacksonXmlProperty(localName = "a:TURISMOV")
         private Double valorTurismo;
     }

*If I set this subset as input, it does work:
             <a:CotacaoTaxaCambio>
                 <a:CLIENTEC>0</a:CLIENTEC>
                 <a:CLIENTEV>0</a:CLIENTEV>
                 <a:COMERCIALC>0</a:COMERCIALC>
                 <a:COMERCIALV>30</a:COMERCIALV>
                 <a:DATA>2021-12-15T00:00:00</a:DATA>
                 <a:HORARIO>1027</a:HORARIO>
                 <a:MOEDA>978</a:MOEDA>
                 <a:PARIDADEC>1</a:PARIDADEC>
                 <a:PARIDADEV>1</a:PARIDADEV>
                 <a:TURISMOC>0</a:TURISMOC>
                 <a:TURISMOV>30</a:TURISMOV>
             </a:CotacaoTaxaCambio>

But it doesn't deserialize if I set full xml as input.
Is there any configuration or anotation that I can use to archieve this?
Thanks in advance,

A: Unfortunately at the moment the jackson library does not support directly the SOAP protocol, but you can read the part you are interested with the XMLStreamReader class directly pointing the involved tag:
XMLInputFactory f = XMLInputFactory.newFactory();
XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(xml));
XmlMapper mapper = new XmlMapper();
sr.nextTag();
while (!sr.getLocalName().equals("CotacaoTaxaCambio")) {
   sr.nextTag();
}
CotacaoResDTO value = mapper.readValue(sr, CotacaoResDTO.class);
sr.close();

You have to modify also your CotacaoResDTO class ignoring the unknown properties :
@JsonIgnoreProperties(ignoreUnknown = true)
public class CotacaoResDTO {

    @JacksonXmlProperty(localName = "DATA")
    private String data;

    @JacksonXmlProperty(localName = "HORARIO")
    private String hora;

    @JacksonXmlProperty(localName = "MOEDA")
    private String codMoeda;

    @JacksonXmlProperty(localName = "COMERCIALV")
    private Double valorComercial;

    @JacksonXmlProperty(localName = "TURISMOV")
    private Double valorTurismo;
}


text:
Q: Extracting URL for each city in a list using Rvest I have been exploring the rvest package and have a question regarding extracting urls from a list. My goal is to generate a df with the following headers: Country, City and the URL for the city. I already have a df with each of the countries and a list with the cities for each country.
My question is, how can I reference each city so that I can obtain its respective URL link? I am trying to reference the href inside the td class within "wikitable sortable jquery-tablesorter" but when I run links = webpage %>% html_node("href") %>% html_text() I only get the main URL.
Thanks for the suggestions!
# Get URL
url = "https://en.wikipedia.org/wiki/List_of_towns_and_cities_with_100,000_or_more_inhabitants/country:_A-B"

# Read the HTML code from the website
page = read_html(url)

# Get name of the countries
countries = page %>% html_nodes(".mw-headline") %>% html_text()

#Remove the last two items which are not countries
countries = as.tibble(countries) %>%
  slice(1:(n()-2))

#Add row number to each Country to left_join later
countries = rowid_to_column(countries, "column_label")

# Get cities for that country
# Still working on this since it includes the first table and I get blanks when I filter the html_nodes(".jquery-tablesorter td")
tables = html_nodes(page, "table")
tables = lapply(tables, html_table)

#Remove fist element which is not a city, only on the first page
tables = tables[-1]

#---WIP
# Get links for the cities, currently picks the main domain instead of the city
# Can I add a clause before the html node to indicate I want the href from "wikitable sortable jquery-tablesorter"?
links = page %>% html_attr("href") %>% html_text()
#---

#Remove the Providence and Population columns and keeps City and URL
tables = lapply(tables, "[", -c(2, 3))

#Standardize City as the column
tables = map(tables, set_names, "City")

# Flatten List
all <- bind_rows(tables, .id = "column_label") %>%
  mutate(column_label = as.integer(column_label)) %>%
  left_join(countries, by = "column_label")

A: Here's a fully reproducible example that gets you a table of the cities with their full url:
library(tidyverse)
library(rvest)

"https://en.wikipedia.org/wiki/" %>%
  paste0('List_of_towns_and_cities_with_100,000_or_more_inhabitants/') %>%
  paste0('country:_A-B') %>%
  read_html() %>%
  html_nodes(xpath = "//table/tbody/tr") %>%
  lapply(function(x) {
    node <- xml2::xml_find_first(x, 'td/a')
    data.frame(city = html_attr(node, 'title'),
               url = paste0("https://en.wikipedia.org/wiki",
                            html_attr(node, 'href')))}) %>%
  bind_rows() %>%
  remove_missing(na.rm = TRUE) %>%
  as_tibble()
#> # A tibble: 534 x 2
#>    city           url
#>    <chr>          <chr>
#>  1 Ghazni         https://en.wikipedia.org/wiki/wiki/Ghazni
#>  2 Herat          https://en.wikipedia.org/wiki/wiki/Herat
#>  3 Jalalabad      https://en.wikipedia.org/wiki/wiki/Jalalabad
#>  4 Kabul          https://en.wikipedia.org/wiki/wiki/Kabul
#>  5 Kandahar       https://en.wikipedia.org/wiki/wiki/Kandahar
#>  6 Khost          https://en.wikipedia.org/wiki/wiki/Khost
#>  7 Kunduz         https://en.wikipedia.org/wiki/wiki/Kunduz
#>  8 Lashkargah     https://en.wikipedia.org/wiki/wiki/Lashkargah
#>  9 Mazar-i-Sharif https://en.wikipedia.org/wiki/wiki/Mazar-i-Sharif
#> 10 Mihtarlam      https://en.wikipedia.org/wiki/wiki/Mihtarlam
#> # ... with 524 more rows

Created on 2023-01-06 with reprex v2.0.2

A: One approach to achieve your desired result may look like so. I took a different appraoch and use a small custom function to get your desired content by scraping the table rows:
library(tidyverse)
library(rvest)

# Get a dataframe of city names and urls for one table
get_cities <- function(x) {
  x %>%
    html_nodes("tr") %>%
    .[-1] %>%
    # Get first column/cell containing city
    html_node("td a") %>%
    map_dfr(function(x) {
      data.frame(
        city = html_text(x),
        url = paste0("https://en.wikipedia.org",
                     html_attr(x, 'href'))
      )
    })
}

url <- "https://en.wikipedia.org/wiki/List_of_towns_and_cities_with_100,000_or_more_inhabitants/country:_A-B"

# Read the HTML code from the website
webpage <- read_html(url)

# Get name of the countries
countries <- webpage %>%
  html_nodes(".mw-headline") %>%
  html_text()
countries <- countries[!grepl("(See also|References)", countries)]
# Get table nodes
tables <- webpage %>%
  html_nodes("table.wikitable.sortable")
names(tables) <- countries

res <- map_dfr(tables, get_cities, .id = "country")

head(res)
#>       country      city             url
#> 1 Afghanistan    Ghazni    /wiki/Ghazni
#> 2 Afghanistan     Herat     /wiki/Herat
#> 3 Afghanistan Jalalabad /wiki/Jalalabad
#> 4 Afghanistan     Kabul     /wiki/Kabul
#> 5 Afghanistan  Kandahar  /wiki/Kandahar
#> 6 Afghanistan     Khost     /wiki/Khost


text:
Q: How to use one function variable to another function in abstract class abstract class Dropboxapi {
    protected $webAuth;

    protected function abi() {
        require __DIR__.'/app/Dropbox/autoload.php';
        self::start();
        self::dropbox_auth();
    }

    public function start() {
        $webAuth = new Dropbox\WebAuth($appInfo,$appName,'path',$csrfTokenStore);
    }

    public function dropbox_auth() {
        $authUrl = $webAuth->start();
    }
}
    Dropboxapi::abi();

Here i have $webAuth object in start function. When I use this in dropbox_auth it shows Undefined variable: webAuth.
When i use $this->webAuth i'm getting Using $this when not in object context
i tried like self::webAuth also. This is showing  Access to undeclared static property:. So I don't understand how to use that.

A: You are defining things wrong. Abstract class, similar with interface, are tend to be used as "blueprint" class. It means they need to be extended by another classes to be used, and cannot be used by itself as is. Using $this in abstract class is fine, as in documentation of abstract by php.net: http://php.net/manual/en/language.oop5.abstract.php.
What you need to do, is to have another class that inherit / extends that DropBoxApi class of yours, ex:
class DropBoxApi2 extends DropBoxApi
{

}

As class DropBoxApi2 is inherited, then it already has functions and property of it's parent (DropBoxApi). And you can use it like (example):
$api = new DropBoxApi2();
$api->start();

Additionally, the double colon that you use is static operator. Which is far far different concept than abstract.

A: if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Many example are there for abstract class.Just check how you can or not.As you asked without abstract just define the class and function like below.Here all the variable and methods are $this context.
class Dropboxapi {
    public $this->webAuth='';
    public function abi() {
        require __DIR__.'/app/Dropbox/autoload.php';
        $this->webAuth = new
        Dropbox\WebAuth($appInfo,$appName,'path',$csrfTokenStore);
    }
    public function dropbox_auth() {
        $authUrl = $this->webAuth->start();
    }
}
    $dropbox = new Dropboxapi();
    $dropbox->dropbox_auth();

A: Sample Code. Replace with your requirement.
you have to make everything as static
abstract class Dropboxapi {
    protected static $webAuth;

    public static function abi() {
       self::start();
       self::dropbox_auth();
    }

    public static function start() {
        self::$webAuth = new Stdclass();
    }

    public static function dropbox_auth() {
       var_dump(self::$webAuth);
    }
}

Dropboxapi::abi();


text:
Q: how to change shared object path when I save data in it how to change sharedObject save location,I want to save shared object on server for particular user, what I do for this?

A: You can look at SharedObject.getRemote() if you have a Flash Media server. Alternatively you can encode the data associated with your SharedObject as JSON and store it in a database.

A: Bad way, but it works
var src:ByteArray = your byteArray;

var arr:Array = new Array();
for (var i:int = 0; i < src.length; i++)
{
    arr.push(src.readByte());
}
var jsonStr:String = arr.join("|");

and conversely...
var retArr:Array = jsonStr.split("|");
var ba:ByteArray = new ByteArray();
for (var j:int = 0; j < retArr.length; j++)
{
    ba.writeByte(retArr[j]);
}

var ldr:Loader = new Loader();
ldr.loadBytes(ba);
addChild(ldr);


text:
Q: Properties File Java I want to use a pre-configured properties File, load it, and after that, add  a line under the already present line from the default config.properties.
I have a read() function that will read/load my default Properties file and I have a write() function that will add String key = "hey"; String value = "ho";
But when I launch read() and write() and when i look in the new config.properties I only see
hey=ho

In my default config.properties i got
 ha=hi

 hu=hu

But I want in my new config :
ha=hi

hu=hu

hey=ho

My code:
Properties prop = new Properties();
public static PropertiesIParse instance;

public PropertiesIParse() {
    instance = this;
}

public PropertiesIParse getInstance() {
    return instance;
}

public Properties getProp() {
    return prop;
}

public void read() {

    InputStream input = null;

    try {
        String filename = "/config.properties";
        input = PropertiesIParse.class.getResourceAsStream(filename);
        if (input == null) {
            System.out.println("Sorry, unable to find " + filename);
            return;
        }

        getProp().load(input);
        Enumeration<?> e = getProp().propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = getProp().getProperty(key);
            System.out.println("KeyKey : " + key + ", Value : " + value);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public void write() {

    String filename = "config.properties";
    FileOutputStream out;
    //prop = new Properties();

    String key = "hey";
    String value = "ho";

    try {

        out = new FileOutputStream(filename, true);
        getProp().setProperty(key, value);
        getProp().store(out, "--type--"); // <---- variable pour dire YYYY MM DD etc.
        out.close();

    } catch (IOException i) {
        System.out.println("Probleme avec l'écriture dans le fichier Property." + i.getMessage());
        i.printStackTrace();
    }
}

So, in my Main method:
new PropertiesIParse().getInstance().read();
new PropertiesIParse().getInstance().write();

EDIT
i change what you say but i got the same thing ... a new config.properties with only my prop.store(key,value) in it
Properties prop = new Properties();
static PropertiesIParse instance;

private PropertiesIParse() {
    instance = this;
}

public static PropertiesIParse getInstance() {
      if (instance== null) {
            instance = new PropertiesIParse();
        }
        return instance;
}

public void read() {

    InputStream input = null;
    Properties prop = new Properties();

    try {
        String filename = "config.properties";
        input = PropertiesIParse.class.getResourceAsStream(filename);

        if (input == null) {
            System.out.println("Sorry, unable to find " + filename);
            return;
        }
        prop.load(input);
        Enumeration<?> e = prop.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value =prop.getProperty(key);
            System.out.println("Key : " + key + ", Value : " + value);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public void write(String key, String value) {

    Properties prop = new Properties();
    String filename = "./config.properties";
    String comment="";
    FileOutputStream out;

    try {
        out = new FileOutputStream(filename, true);
        prop.setProperty(key, value);
        prop.store(out, "-"+key+"-"+comment);
        out.close();
    } catch (IOException i) {
        System.out.println("Probleme avec l'écriture dans le fichier Property." + i.getMessage());
        i.printStackTrace();
    }
}

My Main
PropertiesIParse.getInstance().read();
PropertiesIParse.getInstance().write(new String("ok"),new String("iiiii"));

And i only got ok=iiiii in it ... i surely miss something there, thanks for your help

A: Your singleton is broken as you use a public constructor. Each time you call -
new PropertiesIParse()

there a new instance of Properties will be created which will be empty.
Make the constructor private and change the getInstance() as follows
public PropertiesIParse getInstance() {
    if (instance== null) {
        instance = new PropertiesIParse();
    }
    return instance;
}

Then use it without using new:
PropertiesIParse.getInstance().read();
PropertiesIParse.getInstance().write();


text:
Q: Clean permutation composition in Haskell What is a clean way to compose two permutations given as integer lists in Haskell?
I know  A !! i is the infix array access operator like the C++ equivalent A[i], but I am stuck as to how to map it. In C++ you would loop over i letting C[i] = A[B[i]].

A: If you choose instead to store them in Data.Vector or Data.Vector.Unboxed from the vector package, you can use the backpermute  combinator directly.
Then what you want is just backpermute a b, and your permutations can be stored unboxed and packed together in memory, reducing your memory footprint as well.

A: The Haskell equivalent of that loop in C++ would be something like this:
c = map (a !!) b

So you could say
compose = map . (!!)

and write
c = compose a b

But !! is for lists, not arrays, and indexing is not particularly efficient. You may want to consider using a Vector.


text:
Q: How to calculate the derivative of a random variable to one of the parameters? So, I have a function: $f(x) = a\cdot x + b\cdot x + \varepsilon$, where $\varepsilon \sim \mathcal{N}(0, a+2b)$
I want to derive this function to one of the parameters (for example $a$) when performing a sensitivity analysis, but I get stuck with the epsilon part. Somebody has an idea?


text:
Q: How to make_pair or make_tuple with one of the elements being a union? I have a union declaration, It is simple:
union VariableType
{
    bool Bool;
    int64_t Int;
    double Double;
    std::string* String;
};

In my header file I use this union inside some complex data types like this:
extern std::map<std::string, std::tuple<uint8_t, VariableType, VariableType>> PredefinedVariables;
extern std::map<std::string, std::pair<uint8_t, VariableType>> UserVariables;

in a cpp file I try to initialize the maps with brace initialization as follows:
std::map<std::string, std::tuple<uint8_t, VariableType, VariableType>> PredefinedVariables
{
    {"num_threads", std::make_tuple(1, {.Int = 1}, {.Int = 1})},
    {"commands_logging", std::make_tuple(0, {.Bool = false}, {.Bool = false})}
};

I get the following error:
error: too many arguments to function 'constexpr std::tuple<typename std::__decay_and_strip<_Elements>::__type ...> std::make_tuple(_Elements&& ...)
[with _Elements = {}]'
         {"num_threads", std::make_tuple(1, {.Int = 1}, {.Int = 1})},

I tried to narrow it down, so I tested initializing a map of simpler types std::map<std::string, std::tuple<uint8_t, uint64_t, uint64_t>> with brace initialization and it works fine. I also tried initializing just a tuple or pair of the union type and it didn't work:
std::pair<uint8_t, VariableType> Tmp = std::make_pair(5, {.Int = 4});

error: no matching function for call to 'make_pair(int, <brace-enclosed initializer list>)'
         std::pair<uint8_t, VariableType> Tmp = std::make_pair(5, {.Int = 4});

I have also tried initializing the union on its own using the same way, no complaints!
So why is the union initialization illegal inside std::make_pair or std::make_tuple but legal elsewhere? and how do I work around this?
I'm using g++ version 6.2.0 with Ubuntu GLIBC 2.24-3ubuntu2.

A: I followed the comment of of @PasserBy. I just added union constructors and used them to assign values instead of the brace initialization.
Worked like a charm.


text:
Q: How can I establish a TCP connection between several computers behind two firewalls? I'd like to establish several TCP connections between computers behind a firewall.
The follow picture illustrates a simple network:
Firewalled Network http://img35.imageshack.us/img35/1545/firewallgf.png
From the picture I'd like to establish 3 TCP connections:
A => 2
B => 2
C => 2

What are my options for establishing these TCP connections?
and
Can I do this without port forwarding?

A: You could have some server in the cloud acting as a proxy for your connections. For instance, think about how a service like LogMeIn or GoToMyPC manages connections between a client and the controlled host. This is one idea.

A: This should be an interesting read.
How does Skype work without port forwarding?


text:
Q: GraphQL] The type of [...] must be Output Type but got: undefined I'm having troubles with referencing to other GraphQLObjectTypes inside a GraphQLObjectType.
I keep getting the following error:

"message": "The type of getBooks.stores must be Output Type but got:
  undefined."

I thought that using a resolve inside books.stores would help fixing the issue, but it doesn't. Can someone help me out?
Code
var express = require('express');
var graphqlHTTP = require('express-graphql');
var graphql = require('graphql');

var { buildSchema, GraphQLSchema, GraphQLObjectType,GraphQLString,GraphQLList } = require('graphql');

var books = new GraphQLObjectType({
  name:'getBooks',
  fields: {
    isbn: { type: GraphQLString},
    stores: {
      type: stores,
      resolve: function(){
        var store = [];
        store.storeName = "this will contain the name of a shop";
        return store;
      }
    }
  }
});

var stores = new GraphQLObjectType({
  name:'storeList',
  fields: {
    storeName: { type: GraphQLString}
  }
});

var queryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    books: {
      type: books,
      // `args` describes the arguments that the `user` query accepts
      args: {
        id: { type: new GraphQLList(GraphQLString) }// graphql.GraphQLStringj
      },
      resolve: function (_, {id}) {
        var data = [];
        data.isbn = '32131231';
        return data;
      }
    }
  }
});

var schema = new GraphQLSchema({query: queryType});

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

A: Or you can just make the field a function type so that it can wrap type relations
For example
fields: () => ({

  //Enter Your Code

})

A: It couldn't find stores because it was defined after books.
So I placed the stores code before books.


text:
Q: using .swipe action on Navigation link not working Xcode Hello I am trying to simply add a swipe action to a list of subviews In the parent view. Each subview is its own navigation link and putting the swipe action is not working. How can I fix this. I don't get any errors though in the code.
struct Tip: Identifiable, Codable, Hashable{
    var id: String
    var caption: String
    var link: String
}
                    ForEach(viewModel.ThreeTips) { tip in
                        TipRowView(tip: tip)
                            .swipeActions {
                                Button {

                                } label: {
                                    Text("delete")
                                }
                            }
                            .tint(.red)
                    }

A: I believe swipeActions is meant for List (and it works there):
List(viewModel.ThreeTips, id: \.self) { tip in
  TipRowView(tip: tip)
    .swipeActions {
      Button {
      } label: {
        Text("delete")
      }
    }
    .tint(.red)
}


text:
Q: Good GTD/todo/tasks app I am looking for a free task management application that has the following:
- Reminders for tasks that can be snoozed (like native reminders app)
- Grouping tasks/Adding subtasks
- UI showing tasks per day/week
- Prioritize task
I tried Wunderlist and Todoist. Wunderlist has a very nice interface but can not snooze tasks. Todoist also is missing time setting per task.
Anydo seems not working properly. Sometimes I get a popup others not.
What can you recommend?
Update:
I have checked the apps in the linked post. They are not meeting my requirement. None offers snooze

A: I like Clear.
It has reminders that can be snoozed. The snooze time is not optional (unlike the default Reminders app). When you snooze, it simply snoozes for 15 minutes.
You can create any number of categories under which to put tasks.
You can very easily prioritize tasks.
It doesn't really have a "today" or "this week" view except as a widget in Notification Center.
The UI is unbelievably easy and efficient to use.


text:
Q: How to dynamically update my drivers/etc/hosts file using PHP script for windows? For windows, I am trying to dynamically edit and update my 'drivers/etc/hosts' using the below PHP code. By this code, I can easily update any file which does not need administrative rights. But in windows, I need administrative rights to open/update host file from this ('Windows/System32/drivers/etc/') directory. Which syntax should I use to open host file with administrative rights in PHP scripts?
<?php

 echo "Hi this Host Testing";

 $currentdir=getcwd();  // it will save your current directory location

 chdir('../../../../Windows/System32/drivers/etc/');  // it will change my
 web to etc directory (/etc/)

 $file='hosts';
 $current=file_get_contents($file);
 $string_Data = 'Any Data';

 $current.=$string_Data."\r\n";;
 if(file_put_contents($file, $current))
 {
   echo "success in writing";
 }
 else
 {
   echo "fail in writing";
 }

 chdir("$currentdir");

 ?>

I am using " chdir " to change directory but without administrative rights it is not working also.

A: $currentdir=getcwd();  // it will save your current directory location

chdir('../../../../etc/');  // it will change your web directory( /var/www/html/website/)  to etc directory (/etc/)

$file='hosts';
$current=file_get_contents($file);
$string_Data = 'It works success!!';
$current.=$string_Data;
if(file_put_contents($file, $current))
{
echo "success in writing";
}
else
{
echo "fail in writing";
}

chdir("$currentdir"); // it will change directory (/etc/) to your web directory( /var/www/html/website/ )

//change permission before run php page because if your user don't have permission this code can't do writing


text:
Q: Ignoring the return value from an async Task method Here's the scenario: In my WPF app I'd like to keep a loop running at all times that does various things. This pattern came to mind:
    void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        SomeProcessAsync(); //throw away task
    }

    async Task SomeProcessAsync()
    {
        while (true)
        {
            DoSomething();

            await Task.Delay(1000);
        }
    }

The call triggers a warning since the return value is unused. What is the cleanest way to silence that warning?
#pragma warning disable 4014
            AddItemsAsync(); //throw away task
#pragma warning restore 4014

This works but it looks so nasty!
Btw, I also could have used a timer but I liked the simplicity of this loop.

A: You can make the event handler async:
async void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
    await SomeProcessAsync(); //throw away task
}

Normally, async void is bad, but it's necessary when an event handler is async and exceptions should be handled here instead of in whatever calls this. You can (and should) use the normal ConfigureAwait(false) if SomeProcessAsync doesn't need the UI context.

A: As already mentioned in chris' answer, the right solution here is to turn the event handler into an async void method and then use await, so that exceptions are propagated correctly.
But if you really want to ignore the Task, then you can assign it to a variable:
var ignored = SomeProcessAsync();

Or in C# 7.0, you can use discard:
_ = SomeProcessAsync();

A: My solution is to silence the compiler warning with a little helper method that is reusable:
static class TaskHelpers
{
    /// <summary>Signifies that the argument is intentionally ignored.</summary>
    public static void DiscardTask(this Task ignored)
    {
    }
}

And the call looks like this:
AddItemsAsync().DiscardTask();

That's clean and self-documenting. Still looking for a better name for the helper.

A: Better to create a task with your delegate code
Task.Factory.StartNew( () => {} );

A: Async-await uses threads from the thread pool. Although the number of threads in the thread pool is fairly large, and possibly adjustable, it is still a limited number of threads.
The threads in the thread pool are optimized for short living tasks. They start and finish fast, the results from these thread can be accessed fairly easily. But these advantages come with a cost. If not, all threads would be threads from the thread pool.
If you want to let your thread do something for a fairly long time, it is best to use a regular System.Threading.Thread, possibly wrapped in a System.ComponentModel.BackgroundWorker.


text:
Q: Make Xorg recognize libevdev virtual device I've been trying to create a simple program using libevdev to make a virtual device that will simply move the mouse by 50 points on the X axis every second. The program runs just fine, however Xorg won't recognize the newly created virtual device.
I suppose it's going to be something trivial, but I cannot figure out what.
Xorgs' logs say:
[  5860.310] (II) config/udev: Adding input device test device Mouse (/dev/input/event18)
[  5860.310] (II) No input driver specified, ignoring this device.
[  5860.310] (II) This device may have been added with another device file.

The program:
#include <libevdev/libevdev.h>
#include <libevdev/libevdev-uinput.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static void check(int i) {
    if (i < 0) {
        printf("%s\n", strerror(-i));
        exit(1);
    }
}

int main() {
    struct libevdev* evdev = libevdev_new();
    libevdev_set_name(evdev, "test device Mouse");
    libevdev_set_id_vendor(evdev, 0x1);
    libevdev_set_id_product(evdev, 0x1);
    libevdev_set_id_version(evdev, 0x1);
    libevdev_set_id_bustype(evdev, BUS_USB);

    check(libevdev_enable_event_type(evdev, EV_REL));
    check(libevdev_enable_event_code(evdev, EV_REL, REL_X, NULL));
    check(libevdev_enable_event_code(evdev, EV_REL, REL_Y, NULL));
    check(libevdev_enable_event_code(evdev, EV_SYN, SYN_REPORT, NULL));

    struct libevdev_uinput* uinput;
    check(libevdev_uinput_create_from_device(evdev, LIBEVDEV_UINPUT_OPEN_MANAGED, &uinput));

    for (int i = 0; i < 1000; i++) {
        check(libevdev_uinput_write_event(uinput, EV_REL, REL_X, 50));
        check(libevdev_uinput_write_event(uinput, EV_SYN, SYN_REPORT, 0));

        sleep(1);
    }
}

What am I doing wrong?

A: The issue was that mouse buttons need to be enabled for mouse movements to work.
Adding these lines fixes the issue:
check(libevdev_enable_event_type(evdev, EV_KEY));
check(libevdev_enable_event_code(evdev, EV_KEY, BTN_LEFT, NULL));
check(libevdev_enable_event_code(evdev, EV_KEY, BTN_RIGHT, NULL));


text:
Q: Why does not archetype:generate with parameters work for me? If i run mvn archetype:generate it works but if i try
mvn archetype:generate -DarchetypeGroupId org.codehaus.mojo -DarchetypeArtifactId gwt-maven-plugin  -DarchetypeVersion=2.5.0

The message is  from my last attempt with backslashes but it''s the same message for without slashes command
E:\mavenplay\a>mvn archetype:generate \ -DarchetypeGroupId org.codehaus.mojo \ -
DarchetypeArtifactId gwt-maven-plugin \ -DarchetypeVersion=2.5.0 -X
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 15:51:
28+0200)
Maven home: E:\apache-maven-3.0.5\bin\..
Java version: 1.6.0_25, vendor: Sun Microsystems Inc.
Java home: E:\Program Files\Java\jdk1.6.0_25\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from E:\apache-maven-3.0.5\bin\..\conf\settings.
xml
[DEBUG] Reading user settings from C:\Users\henkel\.m2\settings.xml
[DEBUG] Using local repository at C:\Users\henkel\.m2\repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for C:\Use
rs\henkel\.m2\repository
[INFO] Scanning for projects...
[DEBUG] Extension realms for project org.apache.maven:standalone-pom:pom:1: (non
e)
[DEBUG] Looking up lifecyle mappings for packaging pom from ClassRealm[plexus.co
re, parent: null]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.247s
[INFO] Finished at: Sun Jun 30 03:00:22 EEST 2013
[INFO] Final Memory: 1M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] The goal you specified requires a project to execute but there is no POM
 in this directory (E:\mavenplay\a). Please verify you invoked Maven from the co
rrect directory. -> [Help 1]
org.apache.maven.lifecycle.MissingProjectException: The goal you specified requi
res a project to execute but there is no POM in this directory (E:\mavenplay\a).
 Please verify you invoked Maven from the correct directory.
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(Lifecycl
eStarter.java:89)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Laun
cher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.jav
a:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(La
uncher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:
352)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MissingProject
Exception
E:\mavenplay\a>

I have tried with / \ and no slashing. Please
 let me  know what other details to give.
LE: As a sidenote i did manage to create the archetype in interactive mode of course but i'm just curious why it does not work directly

A: If you are using a Windows shell you need to put quotes around the arguments like this:
mvn archetype:generate "-DarchetypeGroupId=org.codehaus.mojo" "-DarchetypeArtifactId=gwt-maven-plugin" "-DarchetypeVersion=2.5.0"

Thanks to the poster here for pointing this out.

A: The = signs are missing on some parameters, try:
 mvn archetype:generate -DarchetypeGroupId=org.codehaus.mojo -DarchetypeArtifactId=gwt-maven-plugin -DarchetypeVersion=2.5.0

You may as well specify -DgroupId=<group-id> and -DartifactId=<artifact-id> so Maven won't ask.

A: I encountered this identical problem, on Windows 7. The solution for me was to make sure that the path to the Maven bin subdirectory was explicitly the first thing on the path. I think that Maven is deriving the path to its configuration directory from the path to its executable, and that something on my path was pointing to another version of Maven (I'm not certain what or where) which has an invalid configuration.
So try modifying your PATH to put the correct path to the mvn executable as the first item, and see if this fixes things for you.

A: I was facing the same issue on linux. It happened that I had blank space on either side of = symbol. Removing these blank spaces made it work.

A: When you are writing it in the CMD try writing it without any space before or after ':' colon
write it like this - mvn archetype:generate


text:
Q: Check if editText of decimal number type is empty I am confused for a long time about an issue. In an if statement I want to check that an editText with decimal input IS NOT empty. I found many answers to check if it IS empty but I want the opposite.
Here is my code:
if(r>20 && r<25){
    startActivity(new Intent(Knees.this, HandJoints.class));
} else {
    Toast fail=Toast.makeText(Knees.this, "Erased temperature/s not accepted\nTry again", Toast.LENGTH_SHORT);
    fail.show();
    elbow_r.setText("");
}
break;

So in the first input statement I want to add an AND so as to prevent proceeding to the next activity in case that r field is empty. Besides this my application is running except the case I have no entry to that field.
Thank you in advance for reviewing my problem.

A: You can use this to check if a string is not empty:
if(!TextUtils.isEmpty(eblow_r.getText())){
    //do something
}

I'm guessing elbow_r is the name of your EditText.
Simply adding a ! in front of anything will make it not that, that's some Java basics.

A: This is my whole override method
 next1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            double r = Double.parseDouble(elbow_r.getText().toString());
            //startActivity(new Intent(Knees.this, HandJoints.class));
            switch (v.getId()) {
            case R.id.button2HandJoints:
                if(r>20 && r<25 && !TextUtils.isEmpty(elbow_r.getText())){
                    startActivity(new Intent(Knees.this, HandJoints.class));
                }else {
                    Toast fail=Toast.makeText(Knees.this, "Erased temperature/s not accepted\n                     Try again", Toast.LENGTH_SHORT);
                    fail.show();
                    elbow_r.setText("");}

                break;
            default:
                break;

        }
        }
    });

A: Try something like this:
if(!TextUtils.isEmpty(elbow_r.getText().toString())){
    double r = Double.parseDouble(elbow_r.getText().toString());
    if(r>20 && r<25){
        startActivity(new Intent(Knees.this, HandJoints.class)
    } else {
   Toast fail=Toast.makeText(Knees.this, "Erased temperature/s not accepted\n Try again", Toast.LENGTH_SHORT);
   fail.show();
   elbow_r.setText("");
   }
}

and don't forget to add android:inputType="number|numberDecimal" in your edittext xml


text:
Q: Getting process description with given process-id I've got a program that enumerates all processes with the Toolhelp API. With my Sysinternals Process Explorer I also can see a description of all processes. Is this description coming from the executable ? How do I get its name ?
That's my current code to enumerate the processes:
#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <vector>
#include <system_error>
#include <memory>

using namespace std;

vector<PROCESSENTRY32W> getAllProcesses();

int main()
{
    for( PROCESSENTRY32W &pe : getAllProcesses() )
        wcout << pe.szExeFile << endl;
}

using XHANDLE = unique_ptr<void, decltype([]( HANDLE h ) { h && h != INVALID_HANDLE_VALUE && CloseHandle( h ); })>;

vector<PROCESSENTRY32W> getAllProcesses()
{
    auto throwSysErr = []() { throw system_error( (int)GetLastError(), system_category(), "error enumerating processes" ); };
    vector<PROCESSENTRY32W> processes;
    XHANDLE xhSnapshot( CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) );
    if( xhSnapshot.get() == INVALID_HANDLE_VALUE )
        throwSysErr();;
    PROCESSENTRY32W pe;
    pe.dwSize = sizeof pe;
    if( !Process32FirstW( xhSnapshot.get(), &pe ) )
        throwSysErr();
    for( ; ; )
    {
        processes.emplace_back( pe );
        pe.dwSize = sizeof pe;
        if( !Process32NextW( xhSnapshot.get(), &pe ) )
            if( GetLastError() == ERROR_NO_MORE_FILES )
                break;
            else
                throwSysErr();
    }
    return processes;
}

A: @RemyLebeau 's way with code implement which is adapted from VerQueryValueA document sample. And as OpenProcess states,

If the specified process is the System Idle Process (0x00000000), the
function fails and the last error code is ERROR_INVALID_PARAMETER. If
the specified process is the System process or one of the Client
Server Run-Time Subsystem (CSRSS) processes, this function fails and
the last error code is ERROR_ACCESS_DENIED because their access
restrictions prevent user-level code from opening them.

int main()
{
    TCHAR szFile[MAX_PATH] = {};
    DWORD dwSize = MAX_PATH;

    for (PROCESSENTRY32W& pe : getAllProcesses())
    {
        wcout << pe.szExeFile << endl;

        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION,
            FALSE, pe.th32ProcessID);
        if (hProcess == NULL)
        {
            //ErrorExit(TEXT("OpenProcess"));
        }
        else
        {
            memset(szFile, 0, MAX_PATH);
            dwSize = MAX_PATH;
            QueryFullProcessImageName(hProcess,0, szFile,&dwSize);
            DWORD s = GetFileVersionInfoSize(szFile,NULL);
            if (s != 0)
            {
                LPVOID lpData = HeapAlloc(GetProcessHeap(), 0, s);
                GetFileVersionInfo(szFile,0,s, lpData);

                HRESULT hr;
                UINT cbTranslate;
                struct LANGANDCODEPAGE {
                    WORD wLanguage;
                    WORD wCodePage;
                } *lpTranslate;

                // Read the list of languages and code pages.

                VerQueryValue(lpData,
                    TEXT("\\VarFileInfo\\Translation"),
                    (LPVOID*)&lpTranslate,
                    &cbTranslate);

                // Read the file description for each language and code page.
                LPVOID lpBuffer;
                UINT dwBytes;
                for (int i = 0; i < (cbTranslate / sizeof(struct LANGANDCODEPAGE)); i++)
                {
                    TCHAR SubBlock[255] = {};
                    hr = StringCchPrintf(SubBlock, 50,
                        TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
                        lpTranslate[i].wLanguage,
                        lpTranslate[i].wCodePage);
                    if (FAILED(hr))
                    {
                        // TODO: write error handler.
                    }

                    // Retrieve file description for language and code page "i".
                    VerQueryValue(lpData,
                        SubBlock,
                        &lpBuffer,
                        &dwBytes);

                    wcout << (TCHAR*)(lpBuffer) << endl;
                }
                HeapFree(GetProcessHeap(), 0, lpData);
            }
            //GetProcessImageFileName(hProcess, szFile, dwSize);
        }

    }
}


text:
Q: Analysing Chrome's 'Aw, snap' on android device Can any kind soul give me any tips on how to go about finding the source of an 'Aw, snap' Chrome browser crash on an Android device (Samsung Galaxy Tab 2)?
I am developing an HTML5 / Javascript based game and I have managed to get the ADB plugin working but am not getting much useful info out of it.  It's not crashing at the same point in the code so it's possibly a memory / cpu issue but I am unsure on how to get any more useful info regarding the crash. My interweb searches have not turned up anything particularly useful so it would be great if anyone could point me in the right direction, give me some tips.
Can I get a stack trace?  Can I see the device's RAM / CPU usage when the game is being played without jumping back and forward to the task manager?
Any help appreciated.

A: chrome://crashes should give you the information, and it should also let you file a bug report to if they are caught in there.


text:
Q: Excel 2010: Nested IF statement I have been working on created a nested IF for a document I am working on, however I have maneged to make two diffrent IF statemnets that both work but they need to be merged.
The infomation its in relation to is:
      J           K          L          M        N
23  Start        End                           Cloud
24  01/04/2014             cloud                Yes
25  03/03/2014             Overdue
26  22/05/1992             cloud                Yes
27  03/03/2014             Overdue
28  01/07/2014             cloud                Yes
29  29/06/2014             On Time
30  03/03/2014  10/03/2014 Complete              Yes

The two IF's i current have are:
This If statement firstly looks to see if the End column is filled if it is filled then the project is completed and that can be Displayed in column L. Then it takes the start(date) in ciolumn J and adds 10 workdays it then compares this to todays date to see if the project is Overdue or ontime.
=IF(NOT(ISBLANK(K25)),"Complete",IF(WORKDAY(J25,10)<TODAY(),"Overdue","On Time"))

This IF statement looks to see if there is a Yes in the Cloud collumn(N) if there is it then adds 20 working days to the start date then compares that to todays date to see if the project is overdue or on time.
=IF(AND(N26 = "Yes", (WORKDAY(J26,20)<TODAY())),"Overdue", "On Time")

So what I am looking for is these two combined but i always get an error or a emssage saying to many arguments.
What it needs to do is:
1) look to see if their is and end date if there is set column L to complete
2) see if there is a Yes in the cloud collumn if so add 20 workdays to the start date the compare to todays date and set column L to either overdue or on time
3) if the cloud column is empty add 10 workdays to the start date then compare to todays date and set column L to either overdue or ontime.
Any help would be awesome!!!

A: The problem with your combined formula is simple. When doing complex IF statements in Excel, I find that it can help to nest them with tabs
=IF(NOT(ISBLANK(K26)),
  "Complete",
IF(AND(N26 = "Yes", (WORKDAY(J26,20)<TODAY())),
  "Overdue",
"On Time",
IF(WORKDAY(J26,10)<TODAY(),"Overdue","On Time")))

With Excel IF statements, in order to nest them successfully, they have to be in a pattern of IF(Condition,Value,Else IF). You'll notice that your second IF statement goes IF(Condition,Value1,Value2,Else IF). Obviously this does not work because IF can only take 2 arguments. It appears that you have two scenarios to handle if Cloud = Yes, so we need to take more care in our nesting. One way to do this would be to not use the conditional AND and nest an IF statement in our first value position.
=IF(NOT(ISBLANK(K26)),
   "Complete",
 IF(N26 = "Yes",
   IF(WORKDAY(J26,20)<TODAY(),
     "Overdue",
     "On Time"),
 IF(WORKDAY(J26,10)<TODAY(),
     "Overdue",
     "On Time")))

In the second major IF, we've grouped all of the logic for Cloud = "YES under on IF statement. Then if that's not true, we perform the basic 10 day check. Here is the completed formula in non-nested form. Let me know if I misunderstood anything.
=IF(NOT(ISBLANK(K26)),"Complete",IF(N26 = "Yes",IF(WORKDAY(J26,20)<TODAY(),"Overdue","On Time"),IF(WORKDAY(J26,10)<TODAY(),"Overdue","On Time")))

I switched the dates around to M/D/Y for my own clarity and these were my results with the formula based on today's date (July 11, 2014).
4/1/2014                Overdue         Yes
3/3/2014                Overdue
5/22/1992               Overdue         Yes
3/3/2014                Overdue
7/1/2014                On Time         Yes
6/29/2014               On Time
3/3/2014    10/3/2014   Complete        Yes

EDIT: Table Formulas
Here is the formula above in Table format with the following headers/columns
Start       End         Status      Cloud
4/1/2014                Overdue     Yes
3/3/2014                Overdue
5/22/1992               Overdue     Yes
3/3/2014                Overdue
7/1/2014                On Time     Yes
6/29/2014               On Time
3/3/2014    10/3/2014   Complete    Yes

Formula
=IF(NOT(ISBLANK([@End])),"Complete",IF([@Cloud] = "Yes",IF(WORKDAY([@Start],20)<TODAY(),"Overdue","On Time"),IF(WORKDAY([@Start],10)<TODAY(),"Overdue","On Time")))


text:
Q: Can't get the value of a function inside an object using socketIO I'm trying to pass an object from my socket file to my html file and print out a function value thats located inside it. but I keep getting this error
Uncaught TypeError: Cannot read property 'confirmed' of undefined
socket.js
function querys() {
                var queryString1 = 'SELECT contacts.id, userId, contactId, confirmed, username FROM contacts LEFT JOIN users on contacts.contactId = users.id WHERE userId = ?';
                var buddy = new Object();

                connection.query(queryString1,[id], function(err, rows, fields) {//look for all requests started by another user
                    if (err) throw err;
                    for (var i in rows) {
                        buddy[i] = (
                            {
                                id : rows[i].contactId,
                                username : rows[i].username,
                                sender : false,
                                connectionId : rows[i].id,
                                confirmed : function() {
                                    if(rows[i].confirmed == 0)
                                        return false;
                                    else
                                        return true;
                                }
                            }
                        );
                    }
                    socket.emit('print', buddy);
                });
            }

function in html file
socket.on('print', function(buddy) {
                    alert(buddy[0].confirmed());
                }

Strange thing is that it does print the other values of the object if you ask it to but I cant seem to print out the function inside the object.

A: You can't transmit functions over socket.io, only json data. I'd recommend just sending confirmed as a boolean.


text:
Q: C# and Reflection don't work twice in a row I've a problem and I can't figured it out how to solve it.
I've a class for fetching data from a Database, in this class I've a method for a simple select * this method is called
List<T> All<T>(string tableName)

and you have to specify which resource you want to fetch, for example
All<User>("users")

And, aside from the classic SQL Reader and SQL Command, the core of the method is this
public override List<T> All<T>(string resource)
    {
        List<T> result = new List<T>();
        using (MySqlConnection sqlConnection = new MySqlConnection(connectionString))
        {
            sqlConnection.Open();
            try
            {
                string query = "SELECT * FROM " + resource + " WHERE 1=1";
                using (MySqlCommand sqlCommand = new MySqlCommand(query, sqlConnection))
                {
                    lock (locker)
                    {
                        MySqlDataReader reader = sqlCommand.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                T model = Activator.CreateInstance<T>();
                                Dictionary<string, object> _properties = new Dictionary<string, object>();
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    string property = reader.GetName(i);
                                    object value = reader.GetValue(i);
                                    _properties.Add(property, value);
                                }
                                var type = model.GetType();
                                var method = type.GetMethod("SetProperties");
                                var invoked = method.Invoke(model, new object[] { _properties });

                                result.Add(model);
                            }
                        }
                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Program.eventLogger.Add(new Event(EventType.Error, "SQL Data Providers", "Exception catched on All", ex));
            }
            finally
            {
                sqlConnection.Close();
            }
        }
        return result;
    }

Basically, based on the Type from the method header, the method will try to create an new instance of the specific type, later for each field from the query, it will fills all the attributes of the class on a temporaneous list. Once it's done it will try to call the method "SetProperties" which basically set every attributes of the class using reflection.
This is the core of SetProperties, equal for each entity:
    public virtual bool SetProperties(Dictionary<string,object> properties)
    {
        if(this.ValidateData(properties))
        {
            FillNullableAttributes(properties);
            // Iterate trough every key : value pairs in properties
            foreach (KeyValuePair<string, object> kvp in properties)
            {
                if (this.data.Contains(kvp.Key))
                {
                    var property = this.GetType().GetProperty(kvp.Key);
                    PropertyInfo propertyInfo = this.GetType().GetProperty(kvp.Key);
                    // Set the current fetched key with the given value if !null
                    if (kvp.Value != null)
                    {
                        Type fetchedType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                        object safeConversion = (kvp.Value == null || kvp.Value == DBNull.Value) ? null : Convert.ChangeType(kvp.Value, fetchedType);
                        if (propertyInfo.CanWrite)
                        {
                            propertyInfo.SetValue(this, safeConversion, null);
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

In conclusion the result, which is a list, will be returned and the specific Entity will have its own BindingList filled. The binding list, for each entity is described as follow:
public static BindingList<Seller> items = new BindingList<Seller>();

This code works fine, even if there's a lot of space for improvements I know, but if I called it twice like this:
User.items = new BindingList<User>(provider.All<User>("users"));
User.items = new BindingList<User>(provider.All<User>("users"));

The second list will be filled by empty entities, the counting of the will be correct but they will be empties... and that shouldn't occurs.
The only thing that I figured it out, from the debugging, is that on the second call
var invoked = method.Invoke(model, new object[] { _properties });

invoked is set to false.

A: The result of:
var invoked = method.Invoke(model, new object[] { _properties });

Is the return value from your SetProperties method, not whether the method was invoked as your question indicates.  Your SetProperties method is telling you that it was unable to do its work, debug that and you will find your answer.


text:
Q: Setting values of a tensor at the indices given by tf.where() I am attempting to add noise to a tensor that holds the greyscale pixel values of an image. I want to set a random number of the pixels values to 255.
I was thinking something along the lines of:
random = tf.random_normal(tf.shape(input))
mask = tf.where(tf.greater(random, 1))

and am then trying to figure out how to set the pixel values of input to 255 for every index of mask.

A: tf.where() can be used for this too, assigning the noise value where mask elements are True, else the original input value:
import tensorflow as tf

input = tf.zeros((4, 4))
noise_value = 255.
random = tf.random_normal(tf.shape(input))
mask = tf.greater(random, 1.)
input_noisy = tf.where(mask, tf.ones_like(input) * noise_value, input)

with tf.Session() as sess:
    print(sess.run(input_noisy))
    # [[   0.  255.    0.    0.]
    #  [   0.    0.    0.    0.]
    #  [   0.    0.    0.  255.]
    #  [   0.  255.  255.  255.]]


text:
Q: Join Server to Worfkgroup Without Creds? I am imaging servers from stock AMI's in amazon. For business purposes I have to briefly join these servers to the domain so that I can install some agents before I shut them down, sysprep them, and image them as our golden images.
When I try to remove these servers from the domain by joining them to a arbitrary workgroup, I am getting an Access Denied error. I am trying to do so by running the following powershell:
Add-Computer -WorkgroupName 'AWS' -Force
I have tried doing this by passing random credentials to it as well. It is making me feel like I need credentials for my current domain, to join it to a workgroup.
However... When I go through the Gui to add it to a workgroup, I receive a credential prompt where I can literally give it Username: 'A' - Password:'A' and it will join just fine. After a reboot, my server is completely off the domain. I am not even logged in with a domain joined account, it is the local administrator.
Any ideas? Thanks!

A: Might try Remove-Computer

Remove-Computer  -LocalCredential $cred -WorkgroupName "Workgroup" -Force

Could throw in a -Restart if you want
Remove-Computer docs


text:
Q: SAS to count excel observations I have to carry out a reconciliation of accounts for a number of excel files approximately 500 excel files.
I don't need to match accounts numbers just the volume by file.
Example file 1: \\directory\Loaded\Jan2014\excel1

Example file 2: \\directory\Loaded\Feb2014\excel2

Example file 3: \\directory\Loaded\Feb2014\excel3

(account number is always populated in column  B with rows 1 to 5 as the titles)
Required output using above example:
Main Folder (File) | Sub Folder (Jan2014) | File Name (excel1) | count of account numbers
Is this possible using SAS?
So if this is not enough information, i have searched the net and found ways using batch files to bring back a list of files but nothing that counts the observations.

A: The SAS solution is something like this.  You could make this a bit more efficient if you did all of the libnames and then set all of the datasets, but this code is a bit easier, and for 500 I think it's reasonable.  Unfortunately excel libnames don't seem to do rowcounts for you, so you can't just use dictionary.tables to do this.
If the sheet names vary, you will need to modify this to take that into account, either by setting up a macro variable that holds what the sheet name should be if it's linked to the filename in some way, or by having the macro do a query to dictionary.tables to see what tables are present in the libname.
%let basedir=c:\temp;  *whatever the base directory is that all of your excel files are upstream from;
filename dirl pipe "dir /b/s &basedir.\*.xlsx";

data libnames;
infile dirl lrecl=1024 pad;
input
@1 filename $1024.;
run;

%macro get_rowcount(file=);
  libname _temp excel "&file.";
  data _rowcount;
  set _temp."Sheet1$"n end=eof;
  length file_name $1024;
  retain file_name "&file.";
  if eof then do;
    rowcount=_n_;
    output;
  end;
  keep rowcount file_name;
  run;

  proc append base=rowcounts data=_rowcount force;
  run;
%mend get_rowcount;

proc sql;
select cats('%get_rowcount(file=',filename,')') into :sheetlist separated by ' '
  from libnames;
quit;
&sheetlist.;

A: I'd use Powershell for this, unless you really need to do it in SAS.
To get the result to SAS, if needed, you can save data from powershell to excel file and import it to SAS.
Have a look at e.g. Get the Number of Rows in Column of a worksheet as a starter.


text:
Q: POWER BI - Show/hide charts depending value Is it possible to decide whether to show or hide a chart depending of some value ?
For example, if a row of my column A is greater or equal to 10, we display chart C1 and hide chart C2.
Conversely, if the value in colum A is less than 10, we display chart C2 and hide chart C1.
My research on internet didn't pay.

A: Not without severe DAX trickery and formatting black magic.
You could have a DAX measure that switches the output based on a value, something like..
If([DaxToFindAMaxMoreThan10] >= 10, [ChartValues], BLANK())

OR
Switch([DaxToFindAValue], "X", [Dax1], 999, [Dax2], BLANK())

And then the Charts those formulas are in would need minimal Axis features so as to blend in to the background canvas..
Your best bet is a/set of button(s) hooked up to Bookmarks that un/hide your visuals.


text:
Q: How can i access child component method in parent component using ref in Vue3? I am trying to access the child method in the parent component using vue3 and ref method. But it returns an error.

Uncaught TypeError: addNewPaper.value?.savePaper is not a function

Below is my code. Please guide me where i am wrong.
Child component
<script setup lang="ts">
import { useWindowScroll } from '@vueuse/core'
import { Notyf } from 'notyf'
import { computed, defineProps, reactive, ref } from 'vue'
import { papers } from '/@src/firebase/connections'

const companySize = ref('')
const businessType = ref('')
const productToDemo = ref('')
const date = ref(new Date())

const { y } = useWindowScroll()

const isStuck = computed(() => {
  return y.value > 30
})

const initialState = reactive({
  subject: '',
  paper: '',
  marks: '',
})

const notyf = new Notyf()

const props = defineProps({
  subjects: { required: true },
})

const savePaper = () => {
  papers
    .add(initialState)
    .then(() => {
      notyf.success('Paper saved successfully')
    })
    .catch((err) => {
      notyf.error('Something went wrong')
    })
}
</script>

Parent component

const addNewPaper = ref()

const successSave = () => {
  addNewPaper.value?.savePaper()
  notyf.success('Your paper has been successfully created!')
}

 <template #content>
   <FormAddNewTopical ref="addNewPaper" :subjects="_subjects"></FormAddNewTopical>
 </template>

Any solution appreciated!

A: Public members are supposed to be defined with defineExpose with script setup syntax:
defineExpose({ savePaper })

Or with ctx.expose in setup function:
setup(props, ctx) {
  ...
  ctx.expose({ savePaper })
  ...


text:
Q: Decrypt Values In a String I have the following connectionString string:
"DataSource=R7gIrRzkARUJsQBUYXKCPpH8MdqtQ5Sd+lt4kyBEZBY=; userid=weRGgY7PERBTg2WPPzVerIlMP93kmQbTSuKsJKyDHFU=; password=qcMxEGU75lJ1VD5OaaujnLzleR/7ZQDco3kddfwTOvI=;"

After I pass the string to a decrypt function, I will use it in the following:
iDB2Connection.ConnectionString = connectionString;

My question is, what's the best way to decrypt the values in the connectionString string?
One possibility was to convert the string to a DataSet and call the following code:
String connection = dsConnection.Tables[0].Rows[0]["connectionstring"].ToString();
SqlConnectionStringBuilder DBConfig = new SqlConnectionStringBuilder(connection);
string ConnectionString =
                "Data Source=" + Decrypt(DBConfig.DataSource)
                + ";Initial Catalog=" + Decrypt(DBConfig.InitialCatalog)
                + ";User ID=" + Decrypt(DBConfig.UserID)
                + ";Password=" + Decrypt(DBConfig.Password);

but I haven't figured out how to do that successfully.
Any help is appreciated.

A: The problem is your source is an OleDb connection sting, not a SQL Server connection string.  I would recommend using an OleDbConnectionStringBuilder instead:
var connectionString = "DataSource=R7gIrRzkARUJsQBUYXKCPpH8MdqtQ5Sd+lt4kyBEZBY=; userid=weRGgY7PERBTg2WPPzVerIlMP93kmQbTSuKsJKyDHFU=; password=qcMxEGU75lJ1VD5OaaujnLzleR/7ZQDco3kddfwTOvI=;";

var DBConfig = new OleDbConnectionStringBuilder(connectionString);

string ConnectionString =
            "DataSource=" + Decrypt(DBConfig["datasource"].ToString())
            //+ ";Initial Catalog=" + Decrypt(DBConfig.InitialCatalog)
            + ";UserID=" + Decrypt(DBConfig["userid"].ToString())
            + ";Password=" + Decrypt(DBConfig["password"].ToString());

You could try to map the decrypted values from the source string to a Sql Server connection string, but I don't see a database key that would normally be present if you were connecting to a SQL server through OleDb.


text:
Q: append dictionary in html using jQuery i have a dictionary with key and list value and i want to create a card using jQuery append function.
dict = {
  "Meizu X8": [
    ["4GB 64GB Global", "8 months ago", "8.6", "\u20b9 12,509"],
    ["4GB 128GB Global", "8 months ago", "8.6", "\u20b9 13,992"]
  ],
  "Xiaomi Mi8 Lite": [
    ["Global 128GB", "8 months ago", "8.6", "\u20b9 16,315"]
  ],
  "UMIDIGI F1": [
    ["4GB 128GB", "5 months ago", "8.6", "\u20b9 10,884"]
  ]
}

i want to create a card for every key and if key value having 2 or more list value then function will also create a card with the same key name
for eg-

Meizu X8

4GB 64GB Global

8 months

8.6

12,509

Meizu X8

4GB 128GB Global

8 months

8.6

13,992

Xiaomi Mi8 Lite

"Global 128GB

8 months

8.6

16,315

UMIDIGI F1

4GB 128GB

5 months

8.6

10,884

A: You can do this by nesting a for loop inside another for loop, like I've done in the following snippet

var dict = {
  "Meizu X8": [
    ["4GB 64GB Global", "8 months ago", "8.6", "\u20b9 12,509"],
    ["4GB 128GB Global", "8 months ago", "8.6", "\u20b9 13,992"]
  ],
  "Xiaomi Mi8 Lite": [
    ["Global 128GB", "8 months ago", "8.6", "\u20b9 16,315"]
  ],
  "UMIDIGI F1": [
    ["4GB 128GB", "5 months ago", "8.6", "\u20b9 10,884"]
  ]
}

for (var name in dict) {

  for (var entry of dict[name]) {
    var card = `

${name}

${entry[0]}

${entry[1]}

${entry[2]}

${entry[3]}

`
    $("#container").append(card)
  }
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

A: Here is one more solution. It will work even if sometime you will want to expand an array of phone features:

var dict = {
         "Meizu X8": [
             ["4GB 64GB Global", "8 months ago", "8.6", "\u20b9 12,509"],
             ["4GB 128GB Global", "8 months ago", "8.6", "\u20b9 13,992"]
         ],
         "Xiaomi Mi8 Lite": [
             ["Global 128GB", "8 months ago", "8.6", "\u20b9 16,315"]
         ],
         "UMIDIGI F1": [
             ["4GB 128GB", "5 months ago", "8.6", "\u20b9 10,884"]
         ]
     }
Object.keys(dict).forEach((model) => {
        dict[model].forEach((entry) => {
            var card = `

${model}

`+
                entry.map((feature) => `<h5>${feature}</h5>`).join("") +
                `</div></div>`;
            $("#container").append(card);
        });
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">


text:
Q: ListServ not accepting email posting So I'm having trouble with technology that's 25 years old and has no substantial tech support, so this post is really just a last-resort shot in the dark in case someone has some enlightenment.
I'm a member of a ListServ mailing list. I'm receiving emails from the list just fine, but I can't appear to send any emails to the list. The worst part is... I never get any error messages. The emails that I try to send just never show up. The site has an online form for posting to the list, and if I use that form, it says "Your message has been successfully posted to the (LISTNAME) list.", but still, the message never actually shows up.
I don't suppose anyone has any idea what could be causing this?
(In case it matters, the list is being hosted at http://oracle.wizards.com/archives/index.html, though it's not a public list, so it doesn't actually show up on that page, and I can't disclose what it is. They appear to be running ListServ 14.4).


text:
Q: How do we convert price per kVA to price per kW? I have been told that since kVA is a smaller "unit", price per kW is higher than price per kVA. I'm not entirely sure kVA and kW are not simply units as Power Factor is not really a conversion factor. But I could be wrong in my interpretation. Can someone please confirm this logic? Thank you.

A: kW = kVA X Power Factor. Power factor is a number between zero and one because is is the cosine of the phase difference between voltage and current. Therefore kW is always equal to or less than kVA for a given situation.
Price/kW = Price/(kVAxpf)

A:
How do we convert price per kVA to price per kW?

You pay for energy by kWh (not kW) and reactive power by the kVArh (not kVA).
For an industrial supply or large business supply you may also pay for

*

*MIC (maximum import capacity) which is your contracted supply capability.

*Max demand (maximum kWh used in a 15 or 30 minute interval during the billing period). The idea here is to discourage high peak loads.

*Reactive power or wattless units. Generally the utility company should be happy enough if you keep your power factor above 0.95. If it drops below this then expect to pay a surcharge for wattless units.

I have been told that since kVA is a smaller "unit",

No. Since kWh = kVArh x power factor, and power factor is always <= 1, then kVArh is larger than kWh.

price per kW is higher than price per kVA.

True.

I'm not entirely sure kVA and kW are not simply units as Power Factor is not really a conversion factor.

*

*The kWh measures real energy used.

*The kVArh is effectively energy lost by the utility company in their transmission network feeding into a reactive (inductive or capacitive) load at the customer. If they don't charge for it the problem tends not to get fixed.


text:
Q: volume resistivity I know what resistivity of materials are like, and is given by the formula:
$$R = \frac{\rho L}{A}$$
However what is the volume resistivity of materials like copper and aluminium for instance? How do we calculate the volume resistivity of materials, because this was confusing when I read the site:
Method of calculating eddy currents of a conductor, is this correct?
Where there is the answer given by Floris states the equation:
$$F = \frac{v\cdot B^2\cdot A}{\rho/t}$$
Where $\rho$ is given to be the volume resisitivity.
My question:

*

*how do we measure the volume resistivity of a material for example aluminium?

*what happens if the thickness of the material changes?

A: The volume resistivity is an intrinsic quantity of materials, just like masss density; meaning it doesn't depend on the amount of matter in materials. In other words, since $\rho$ is an intrinsic property, its value doesn't depends on the material size (to answer your second question).
(To answer your first question) Practically, you can measure it for a given material by sampling the material in question with different sizes and average the results. $\rho$ is calculated with rearranging the equation you mentioned:
$$ \rho = \frac{RA}{L}$$
You can certainly measure $R$ with multimeter/Ohmmeter, and A & L with your ruler.


text:
Q: kafka stream doesn't work in bean in spring boot I'm a beginner with kafka stream,
when I create two sample modules one for "Order" and other is "Payment"
In the "Order" Project I use kafka to send to message to "oder-topic"
then in "Payment" I use Kafka listener to received value then send value to other topic( ex: payment-topic).
I want to use kafka Stream in "Order" module to read value from "payment-topic" I define it Order application java class in a "Order" module like this:
@SpringBootApplication

@EnableKafka

@EnableKafkaStreams

public class OrderServiceApplication {
     // this topic will received all value that were processed

    public static final String OUTPUT_TOPIC_NAME = "ordered";

    // this topic is a places received value from payment and stock send value
    public static final String INPUT_ORDER_TOPIC_NAME = "order-topic-result";

    public static final String INPUT_STOCK_TOPIC_NAME = "stock-topic-result";

    public static void main(String[] args) {
        SpringApplication.run (OrderServiceApplication.class, args);
    }

    @Bean
    public KStream <String, String> readStream (StreamsBuilder kStreamBuilder) {

        KStream <String, String> input = kStreamBuilder.stream(INPUT_ORDER_TOPIC_NAME);

        KStream<String, String> output = input.filter((key, value) -> value.length() > 2);

        output.to(OUTPUT_TOPIC_NAME);

        return output;
    }

but the readStream does not work. Please help me
How will I execute the method is automatically after the value was send to this topic