text:
Q: applying filters in pandas using jupyter, but no records are there only headers are showing This is the table details from where I am looking for the data.

This is what the output I am getting after applying the filter only the headers.

Please help.

A: That would happen if there are no rows matching your criteria.
Try changing the 'isin' list to include something you are certain should return at least one row, so we can test the filtering step.


text:
Q: Applying a function to two specific columns in a dataframe to give two separate columns I've found code which will convert my metres and zone data to lat/long, but does anyone know how I can apply this to two specific columns in the dataframe (bus_stops)? posx should be column 'Location_Easting' and posy should relate to column 'Location Northing'
I've seen similar questions/answers on here but I'm not quite experienced enough to understand what's being said!
I was thinking it should have been something like the following, but it doesn't work
from geopandas import GeoSeries
from shapely.geometry import Point

posx = bus_stops['Location_Easting']
posy = bus_stops['Location_Northing']

# utm 30U is equivalent to epsg:32630
lon, lat = GeoSeries([Point(posx, posy)], crs='EPSG:32630').to_crs('epsg:4326')[0].coords[0]

bus_stops['Location_Easting]'.apply(lon, lat)
bus_stops['Location_Northing'].apply(lon, lat)

bus_stops.head()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play framework 2.5 logs `?` question marks instead of line numbers I have a play framework app with all standard configurations. I modify logback.xml like this:
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%coloredLevel %logger{15} %L - %message%n%xException{10} </pattern>
    </encoder>
</appender>

I tried instead of %L  put there %line, %class, etc. - all to the same result, it outputs ? in the log message, like this:
[info] application ? - Checking cart...

I also tried to follow the accepted answer to this question: Scala Play framework: logger pattern for displaying file and line
and put val logger = Logger(this.getClass) inside my class. Still same result. Is there any way to fix it? Logback version specified in build.sbt is 2.11.

A: I add includeCallerData and work
   <appender  name="ASYNCSTDOUT" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="STDOUT"/>
        <includeCallerData>true</includeCallerData>
    </appender>

A: Using %L as in your question works perfectly for me in both Play 2.4 and Play 2.5 (exact versions: 2.4.6 and 2.5.12).
I note however that I do not explicitly state any desired version of logback in either application's build.sbt.
This results in (for the Play 2.5 app):
+-com.typesafe.play:play-logback_2.11:2.5.12 [S]
| +-ch.qos.logback:logback-classic:1.1.7
| | +-ch.qos.logback:logback-core:1.1.7
| | +-org.slf4j:slf4j-api:1.7.20 (evicted by: 1.7.21)
| | +-org.slf4j:slf4j-api:1.7.21

(dependency tree via the sbt-dependency-graph plugin)
If you're seeing a different logback version, try removing any explicit dependency declaration, so that you see the same library versions in your dependency tree.
Hope it helps.


text:
Q: Python Iterator: reset iterator? Can you reset iterators? Or is there a way to save the next element without iterating through it?

A: You can use itertools.tee to "remember" previous values of an iterator
>>> from itertools import tee, izip
>>> it = iter([0,1,-1,3,8,4,3,5,4,3,8])
>>> it1, it2, it3 = tee(it, 3)
>>> next(it2)
0
>>> next(it3)
0
>>> next(it3)
1
>>> [j for i, j, k in izip(it1, it2, it3) if i < j > k]
[1, 8, 5]

A: It comes up to my mind to keep a small buffer of the last two elements in two separate variables, a tuple, a list, etc and compare with the current element in the iterator.

A: By excluding cases where the element is in the edge (head, tail), we traverse the element by comparing every element to predecessor/successor, if it's verifying the criteria, we add it to the list.
x= [0,1,-1,3,8,4,3,5,4,3,8]

s= [ x[i] for i in xrange(1,len(x)-2) if x[i-1]< x[i] and x[i]> x[i+1] ]

print s  #Output: [1, 8, 5]

UPDATE
In this case, we would use while to loop into iter, and every time we store datat into three variable left, middle, right. Whenever we call the next variable, we shift middle to left, last to middle and store the next new value in last.
l= iter([0,1,-1,3,8,4,3,5,4,3,8])

res= []

left,middle,last= l.next(),l.next(),l.next() #Initialize data, we assume that we have at least 3 items, otherwise, we will get exception

while  True:
    try:
        if left<middle and middle>last: # I made first, to check in case we got that case in the first three items
            res+=[middle]
        left=middle
        middle= last
        last= l.next()
    except StopIteration:
        break

print res #Output: [1, 8, 5]


text:
Q: ColdFusion - How to get only the URL's in this block of text? How can I extract only the URL's from the given block of text?
background(http://w1.sndcdn.com/f15ikDS9X_m.png)
background-image(http://w1.sndcdn.com/5ikDIlS9X_m.png)
background('http://w1.sndcdn.com/m1kDIl9X_m.png')
background-image('http://w1.sndcdn.com/fm15iIlS9X_m.png')
background("http://w1.sndcdn.com/fm15iklS9X_m.png")
background-image("http://w1.sndcdn.com/m5iIlS9X_m.png")

Perhaps Regex would work, but I'm not advanced enough to work it out!
Many thanks!
Mikey

A: You're over-thinking the problem - all you need to do is match the URLs, which is a simple match:
rematch('\bhttps?:[^)''"]+',input)

That'll work based on the input provided - might need tweaking if different input used.
(e.g. You can optionally add a \s into the char class if that might be a factor.)

The regex itself is simple:
\bhttps?:  ## look for http: or https: with no alphanumeric chars beforehand.

[^)'"]+    ## match characters that are NOT ) or ' or "
           ## match as many as possible, at least one required.

If this is matching false positives, you can of course look for a more refined URL regex, such as these.

A: DEMO
background(?:-image)?\((["']?)(?<url>http.*)\1\)
Explanation:

*

*background(?:-image)? -> It matches background or background-image (without grouping)

*\( -> matches a literal parentheses

*(["']?) -> matches if there is a ' or " or VOID before the url

*(?<url>http.*) -> matches the url

*\1\) -> matches the grouped (third line of this explanation) and then a literal parentheses

A: If you want an answer without regular expressions, something like this will work.
YourString = "background(http://w1.sndcdn.com/f15ikDS9X_m.png)";
YourString = ListLast(YourString, "("); // yields http://w1.sndcdn.com/f15ikDS9X_m.png)
YourString = replace(YourString, ")", "");  // http://w1.sndcdn.com/f15ikDS9X_m.png

Since you are doing it more than once, you can make it a function.  Also, you might need some other replace commands to handle the quotes that are in some of your strings.
Having said all that, getting a regex to work would be better.


text:
Q: How to use isin (without merge) for multiple dataframe columns I have two dataframes:
df1
   Company  Symbol     ID         Date    Value
0  AAA Inc       A    123   2019-12-31       10
1  AAA Inc       A    123   2020-03-30       11
2  BBB Inc       B    456   2019-03-31       12
3  FFF Inc       F    653   2019-06-31       22
4  ZZZ Inc       Z    999   2019-03-30       13

df2
   Company  Symbol     ID         Date   Price
0  AAA Inc       A    123   2019-12-31      10
1  AAA Inc       A    123   2019-09-30      20
2  AAA Inc       A    123   2019-06-31      30
3  AAA Inc       A    123   2019-03-30      40
4  BBB Inc       B    456   2019-12-31      50
5  BBB Inc       B    456   2019-09-30      50
6  BBB Inc       B    456   2019-06-31      90
7  BBB Inc       B    456   2019-03-31      10
8  CCC Inc       C    789   2019-12-31      79
9  CCC Inc       C    789   2019-09-31      43

And I want to create a 3rd dataframe which is all the ['Symbol', 'ID', 'Date'] rows that are in df1, but not in df2. So the output would look like this:
   Company  Symbol     ID         Date
0  AAA Inc       A    123   2020-03-30
1  FFF Inc       F    653   2019-06-31
2  ZZZ Inc       Z    999   2019-03-30

I know I can do something like df3 = df1[~df1['Symbol'].isin(df2['Symbol'])], but after doing some research it doesn't seem like there's a good way to use isin with multiple columns.
I have also checked similar questions but haven't found anything that only addresses specific columns.
I would also like to avoid merging the two dataframes if possible.
So how would I achieve this?

A: Because you want avoid merge here is one posible solution is compare MultiIndex by Index.isin:
cols = ['Symbol', 'ID', 'Date']
df3 = df1[~df1.set_index(cols).index.isin(df2.set_index(cols).index)]
print (df3)
  Company Symbol   ID        Date  Value
1     AAA  Inc A  123  2020-03-30     11
3     FFF  Inc F  653  2019-06-31     22
4     ZZZ  Inc Z  999  2019-03-30     13

Or convert columns to tuples:
cols = ['Symbol', 'ID', 'Date']
df3 = df1[~df1[cols].apply(tuple, 1).isin(df2[cols].apply(tuple, 1))]

For compare solution with merge and indicator parameter:
cols = ['Symbol', 'ID', 'Date']
df3 = (df1.merge(df2, on=cols, indicator=True, how='left', suffixes=('','_'))
          .query("_merge == 'left_only'")[df1.columns])
print (df3)
  Company Symbol   ID        Date  Value
1     AAA  Inc A  123  2020-03-30     11
3     FFF  Inc F  653  2019-06-31     22
4     ZZZ  Inc Z  999  2019-03-30     13


text:
Q: Kotlin by viewModels() Всем привет! Вопрос такой: by viewModels() вернёт один и тот же экземпляр в разных fragment, или нет?
Если нет, то прошу подсказать, каким образом можно получить один и тот же экземпляр viewModel в родительском и дочернем фрагментах.

A: Чтобы в получить ViewModel родительского фрагмента, то нужно в дочернем фрагменте этот родительский фрагмент передать в viewModels как ViewModelStoreOwner:
private val viewModel: MyViewModel by viewModels(ownerProducer = ::requireParentFragment)

В противном случае будет использован дочерний фрагмент и будет создан новый экземпляр модели


text:
Q: Using multiple sockets, is non-blocking or blocking with select better? Lets say I have a server program that can accept connections from 10 (or more) different clients.  The clients send data at random which is received by the server, but it is certain that at least one client will be sending data every update.  The server cannot wait for information to arrive because it has other processing to do.  Aside from using asynchronous sockets, I see two options:

*

*Make all sockets non-blocking.  In a loop, call recv() on each socket and allow it to fail with WSAEWOULDBLOCK if there is no data available and if I happen to get some data, then keep it.

*Leave the sockets as blocking.  Add all sockets to a FD_SET and call select().  If the return value is non-zero (which it will be most of the time), loop through all the sockets to find the appropriate number of readable sockets with FD_ISSET() and only call recv() on the readable sockets.
The first option will create a lot more calls to the recv() function.  The second method is a bigger pain from a programming perspective because of all the FD_SET and FD_ISSET looping.
Which method (or another method) is preferred?  Is avoiding the overhead on letting recv() fail on a non-blocking socket worth the hassle of calling select()?
I think I understand both methods and I have tried both with success, but I don't know if one way is considered better or optimal.

A: I would recommend using overlapped IO instead. You can then kick off a WSARecv(), and provide a callback function to be invoked when the operation completes. What's more, since it'll only be invoked when your program is in an alertable wait state, you don't need to worry about locks like you would in a threaded application (assuming you run them on your main thread).
Note, however, that you do need to enter such an alertable wait state frequently. If this is your UI thread, make sure to use MsgWaitForMultipleObjectsEx() in your message loop, with the MWMO_ALERTABLE flag. This will give your callbacks a chance to run. On non-UI threads, call on a regular basis any of the wait functions that put you into an alertable wait state.
Note also that modal dialogs generally will not enter an alertable wait state, as they have their own message loop which doesn't call MsgWaitForMultipleObjectsEx(). If you need to process network IO when showing a dialog box, do all of your network IO on a dedicated thread, which does enter an alertable wait state regularly.
If, for whatever reason, you can't use overlapped IO - definitely use blocking select(). Using non-blocking recv() like that in an infinite loop is an inexcusable waste of CPU time. However, do put the sockets in non-blocking mode - as otherwise, if one byte arrives and you try to read two, you might end up blocking unexpectedly.
You might also want to consider using a library to abstract away the finicky details. For example, libevent or boost::asio.

A: the IO should be either completely blocking with one thread per connection and in this case the event loop is essentially an OS scheduler or the IO should be completely non-blocking, and in this case select/waitformultipleobjects-based event loop will be in your application
All intermediate variants are not very maintainable and error prone
Completely non blocking approach scales much better when the amount of concurrent connections grows and does not have a thread context switch overhead, so it is a preferrable where the number of concurrent connections is not fixed. This approach has higher implementation complexity compared to completely blocking one.
For a completely non-blocking IO the core of the applicaiton is a select/waitformultipleobjects-based event loop, all sockets are in non-blocking mode, all reads/writes are generally done from within event loop thread (for top performance writes can be first attempted directly from the thread requesting the write)


text:
Q: Notation of the gradient I have problems understanding a specific notation of the gradient, more specifically the following question
What is the meaning of the gradient notation grad_x H where H is a function?
My attempt at answering this question is:
Assume that H = H(x,y) then we know that grad_x ( H(x,y) ) = d/dx ( H(x,y) )
Is this correct?


text:
Q: how to restrict user to touch chrome title bar and 3 vertical dots on mobile I have a website where i want to restrict user to touch chrome title bar, tab menu and 3 vertical dots on mobile. I am just wondering using js is it possible!. If it is possible please give some code refrence..Thanx::SohonScreenshot

A: You could create a PWA and set it's display to standalone in it's manifest, which will hide the browser's UI.
This will only hide the UI once the user installs the PWA on their phone though (i.e. they have to 'approve' you to hide the browser UI from them)


text:
Q: php sort array and rank specific field I am trying to output a ranking by lowest number first for a particular field (OurPrice) based on numeric values.
var_dump Result
$myarray = array_filter($rankresult);
natsort($myarray);

array(6) {
    ["Comp7"]=> string(3) "189"
    ["OurPrice"]=> string(3) "189"
    ["Comp9"]=> string(6) "198.99"
    ["Comp6"]=> string(3) "208"
    ["Comp3"]=> string(6) "226.97"
    ["Comp4"]=> string(3) "274"
}

You will notice that there are 6 total in the count and two of which are the same number, therefore it would equal the same rank (ie. Comp7 and OurPrice are both ranked 1 of 6).
Desired Output:
Our Price Rank = 1 of 6

A: try with this code
 $newarray = (array_unique(array_values($myarray)));
 $rank = array_search($myarray['OurPrice'],$newarray)+1;
 $count = count($myarray));
 echo "Our Price Rank" . $rank . " of " . $count"

A: Assuming you have already sorted the values (which it appears you have), you could simply tell them the index at which the "OurProduct" key exists.
$keys = array_keys( $array );
$rank = array_search( "OurPrice", $keys );

printf( "We rank %d of %d", ++$rank, count($keys) );

Try it online: http://codepad.org/qIwTGBzG


text:
Q: attempt to index global 'torch' (a nil value) When I run a simple piece of code a = torch.Tensor(5,3) in ZeroBraneStudio, I receive the following error:
attempt to index global 'torch' (a nil value)
Does this mean that ZeroBraneStudio does not recognize Torch?

A: Make sure you select Torch as the interpreter (Project | Lua Interpreter | Torch-7) and configure the path to your th or luajit executable from torch (as described in this post).


text:
Q: Gridview items don't show up I want to bind a GridView with an ArrayList.This is my adapter:
public class GridAdapter extends BaseAdapter {
    ArrayList<Upload>uploads;
    ImageView preview;

    public GridAdapter (ArrayList<Upload>uploads) {
        this.uploads=uploads;
    }
    @Override
    public int getCount() {
        return uploads.size();
    }

    @Override
    public Object getItem(int position) {
        return uploads.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater layoutInflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView=layoutInflater.inflate(R.layout.row_data,null);

        preview=(ImageView) convertView.findViewById(R.id.gridImageView);
        Picasso.with(getApplicationContext()).load(uploads.get(position).getImageUrl()).into(preview);

        return null;
    }}

And this is how i set the adapter and how i add items to ArrayList
        pb = (ProgressBar) findViewById(R.id.pb);
        uploadList=new ArrayList<>();
        adapter = new GridAdapter(uploadList);
        intent=getIntent();
        directory=intent.getStringExtra("directory");

        gridView= findViewById(R.id.gridView);
        mDatabaseRef=FirebaseDatabase.getInstance().getReference("uploads/"+directory);

        mDatabaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               for(DataSnapshot postSnapshot:dataSnapshot.getChildren()) {
                   Upload upload=postSnapshot.getValue(Upload.class);
                   uploadList.add(upload);

                }
                gridView.setAdapter(adapter);
               pb.setVisibility(View.INVISIBLE);

            }

In the activity,nothing is shown ,nothing is clickable so there was no GridView item created


text:
Q: In Python, I am trying to obtain fusion of two images, but I am getting unexpected result I am trying to fuse two images using Kekres wavelet transform in python.
I have used DFT (size 32*32) as base matrix to generate wavelet matrix (size 1024*1024). Same program is written in MATLAB, it shows fused result correctly.
But this python program is not showing fused image. I am not able to understand the reason. Sample images are here
MR Image

Registered CT Image

Expected Fused Image

import cv2
import numpy as np
from WaveletMatrix import GenerateWaveletMatrix
import matplotlib.pyplot as plt
import scipy as sp

def dftmatrix(N):
    return sp.fft(sp.eye(N))

TranformSize=32
WaveletSize= TranformSize*TranformSize
dftm=dftmatrix(TranformSize);
WaveletMat=GenerateWaveletMatrix(dftm,TranformSize)

FixedImageR = cv2.imread('D:\MyTransforms_HP\DataSet3\MR_LumbarSpineT2Cube00001.jpg',0)
MovingImageR = cv2.imread('D:\MyTransforms_HP\DataSet3\R.jpg',0)
SizeFixedImage=FixedImageR.shape
SizeMovingImage=MovingImageR.shape

if SizeFixedImage!=SizeMovingImage:
    print("Images must be of same size")
    exit()

FixedImageR=FixedImageR.astype(np.double)
MovingImageR=MovingImageR.astype(np.double)
FixedImage = cv2.resize(FixedImageR,(WaveletSize,WaveletSize),0,0)
MovingImage= cv2.resize(MovingImageR,(WaveletSize,WaveletSize),0,0)
FixedImage=np.ceil(FixedImage)
MovingImage=np.ceil(MovingImage)

#WaveletImage1= np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.double)
#WaveletImage2= np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.double)

WaveletT=WaveletMat.T
WaveletImage1=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex)
WaveletImage2=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex)

WaveletImage1=WaveletMat.dot(FixedImage).dot(WaveletT)
WaveletImage2=WaveletMat.dot(MovingImage).dot(WaveletT)

plt.figure(1)
plt.imshow(np.uint8(WaveletImage1),cmap='gray')
plt.show()

plt.figure(2)
plt.imshow(np.uint8(WaveletImage2),cmap='gray')
plt.show()

FusedImage1=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex)

FusedImage1=(WaveletImage1 + WaveletImage2) / 2

newimg=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex)
mainD=np.zeros(shape=(WaveletSize))

mainD[0:TranformSize]=WaveletSize
mainD[TranformSize:WaveletSize]=TranformSize

for i in range(0,WaveletSize):
    for j in range(0,WaveletSize):
        newimg[i,j]=(FusedImage1[i,j]/(mainD[i]*mainD[j]))

inverseMAT=(WaveletMat.T).dot(newimg).dot(WaveletMat)

plt.figure(3)
plt.imshow(np.uint8(inverseMAT),cmap='gray')
plt.show()


text:
Q: Saving a compressed string using Node.js Right now, I'm compressing some data and saving it to a file in PHP using gzcompress. Here is my PHP code. I save this compressed string to a file and then open it from iOS using zlib.
$compressed_text = gzcompress($text, 9);

I'm trying to do the same thing in Javascript with Node.js but I can't get it to work. Here is what I tried to do in Javascript.
var input = new Buffer(text);
zlib.deflate(input, function(error, output) {
   var compressed_text = output.toString('ascii');
});

It doesn't work to decompress this data from iOS using Node.js. It works fine with PHP but I can't get it to work in Node.js. Should I be using a different method instead of deflate?

A: zlib output is binary, so you need some way of preserving the bytes as-is. In node, the easiest way is to just keep it as a Buffer. Since you mentioned saving this to a file, you could just do
fs.writeFile(path, output, (err) => {
  if (err) throw err;
  console.log('Wrote data to disk');
});


text:
Q: How do I get the paintable area in a CFrameWnd with dialog bars? I have a CFrameWnd with a dialog bar, and I'd like to determine the paintable area (excluding the space used by the dialog bar) so I can draw in it without being overlapped by the dialog bar. How can I do this? GetClientRect() seems to cover the client rect area as well, and I don't see any other obvious candiates in the doucumentation.

A: I'm pretty sure the Cwnd::RepositionBars method should provide the information you need. Does the following code work for you?
CRect rcClient;
pFrameWnd->RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, CWnd::reposQuery, &rcClient);

A: I had a similar problem with CDockablePane which I solved with
CRect rc;
GetDockingManager()->GetClientAreaBounds(rc);

but I also ran into the problem of not being able to find a message or callback to know when to trigger it.


text:
Q: Laravel Asset Manager and serving CSS/JS as modules I'm searching for days now for a proper way to serve the static content for my Laravel 4 website in a most optimal speed performance way. What I tend to obtain is serving only the needed JS and CSS, already minified to each requested page.
Example:
page1.html
-> styles.css - for this page it includes bootstrap.css, jquery-ui, selectize.css, google-custom-maps.css
-> scripts.js - for this page it includes boostrap.js, jquery.js, selectize.ks, google-custom-maps.js

page2.html
    -> styles.css - for this page it includes only bootstrap.css
    -> scripts.js - for this page it includes boostrap.js

Currently I have all my plugins installed with bower and using gulp tasks I managed to minify all the less, css and js scripts at once, the only problem is I don't know If it is possible to serve only the needed files for a custom page.
In my opinion an optimal solution would be that in each view.blade.php file i provide all the needed assests using
{{ asset('front/css/bootstrap.css') }}
{{ asset('front/css/jquery.css') }}
{{ asset('front/css/selectize.css') }}

And at first run this is compiled and cached. Is there any package that can do that?

A: I have been always using template system where I include all the needed files in one place and other blade.php files extend this template.


text:
Q: Mounting second internal HDD in Sony Vaio I mounted new internal HDD instead of optical drive in Sony Vaio VPCEH laptop.
Special caddy was used for that purpose. Currently new HDD has power on it (i can see green light on caddy), but I can't see new disk in diskpart utility (list disk). And there is no pop-up window about new disk in disk management program. My OS in Windows 7, new drive in WD Blue 750Gb.
I updated SATA driver from manufacturer site, but nothing changed. Any ideas on how to fix it?


text:
Q: How to make an object to provide altering functionality for only certain users in C#? I am creating an implementation of the half-edge data structure in C#. The details of this structure is not relevant for my question, so I will introduce it only as deep as required, but a brief summary is available on flipcode if someone interested.
My object-oriented representation of the data structure consists 4 classes: Halfedge, Edge, Vertex and Face, which mutually contain some references to each other. (Specifically: every halfedge references a vertex, while every edge, vertex and face reference a halfedge.) Handling and maintaining this low level representation is a hard task, therefore the modification of it should not be exposed to the users of the code, to guarantee the consistency of the data structure.
In order to achieve this, I created a 5th Graph class to provide a higher abstraction level layer above them. The idea is that the users of the code/library only have to communicate with a Graph instance to build or query the topological model, and do not have to deal with the low level relations of halfedges, edges, vertices and faces; therefore they cannot corrupt it.
Now to the problem. The faces, vertices, edges and halfedges are required to be queryable from the Graph. The half-edge data structure contains topological information about the data, so it is a resource-efficient query to ask for e.g. the adjacent faces for the given face or edge. A sample for how these classes are meant to be used:
Graph graph = new Graph();
Face face = graph.AddFace(/* params about the vertexes of the face to create */);
// More data given to the graph ...

// Later:
Face[] faces = face.AdjacentFaces;
Vertex[] vertixes = face.BoundaryVertices;

For obvious purposes a Graph object needs to manipulate the inner state of the contained Halfedge, Edge, Vertex and Face objects, to build up and maintain the data structure from the input given by the user. However, if these 4 classes have public methods (or properties) to alter their state, then the whole idea of hiding the representation from the user is spoiled, since they can be directly called by the user. (It's a pity C# does not have the friend class conception now.)
If I make the Halfedge, Edge, Vertex and Face classed nested inside Graph and do not make them public, then it would be impossible to retrieve these types for the user. E.g.:
public class Graph
{
    private class Halfedge { /* ... */ }

    private class Edge { /* ... */ }

    private class Vertex { /* ... */ }

    private class Face { /* ... */ }

    // Cannot return a Face, since it is not public.
    public Face AddFace(/* params about the vertexes of the face to create */)
    {
        /* Algorithm to create halfegdes, edges, vertices and a face */
    }
}

So basically my question is what design would be best to follow to implement a data structure like this. The Halfedge, Edge, Vertex and Face classes need to expose an interface to modify them for the  Graph class, but not for others. Internal accessibility is not good, since it would expose these functions for the whole assembly.
Shall I create "read-only" wrapper classes for them, as many collections in .NET have a read-only wrapper (like List<T>), and expose only those for the users when returning an object (with e.g. AddFace())?

A: Why not use an interface for every type and expose them to outside world:
public interface IHalfedge
{
}

public interface IEdge
{
}

public interface IVertex
{
}

public interface IFace
{
}

public class Graph
{
    private class Halfedge : IHalfedge
    { /* ... */
    }

    private class Edge : IEdge
    { /* ... */
    }

    private class Vertex : IVertex
    { /* ... */
    }

    private class Face : IFace
    {/* ... */
    }

    // Cannot return a Face, since it is not public.
    public IFace AddFace(/* params about the vertexes of the face to create */)
    {
        /* Algorithm to create halfegdes, edges, vertices and a face */
    }
}

This way you can hide your classes inside of Graph

A: Have you considered keeping your classes private, but providing public interfaces which only expose what you want to? This has the advantage of implicit implementation (you shouldn't have to write lots of extra code, beyond the interface definition itself, if you keep all the member names the same). Also, remember a read-write property in a class can implicitly implement a read-only property in an interface.


text:
Q: Form ideal to Real . Dijkstra in logistic I have a program for transportation company where optimal route computed by Dijkstra .  Cities as vertexes and routes as edges . To find weight of edge  . I connected  cities in map with line and measure it . Then I accept it as weight of edge . But in real life routes aren't straight . So How can I fix it ? enter image description here
In my project I  must solve logistic problem with creating Software .   Can anyone give me idea what to solve ?

A: As you already found out, problem is not so simple as it might seem.
First of all, connecting only major cities is a bad idea, as they're probably not connected directly with a highways (if it's not U.S. or something).
That's your current idea:

What I would propose is to try to get every minor city on every way that makes sense and add it as a vertex to your Dijkstra:

Now, we come to the point where we can see which way actually exists in real world. From just looking on our graph, we might presume that going with bottom path should be more efficient. But what if we found out this:

We can easily come to conclusion now that upper path is actually much better, because you can achieve twice the speed of the bottom one.
Is that very precise classification? No, it's not.
We might want to think of what traffic is on each way and change weights of edges dynamically. But that's probably too much for your basic implementation.
What I would do in the end is think of what data can I gather almost alone or with little help.
So I can definitely:

*

*somehow scrap some data about actual ways of reaching point B from point A; good references are either Google Maps API or Bing Maps API;

*gather minor cities along the way with finding real world ways from point A to B;

*try finding out what speed limit is where (if there is any database for it)

Actually, you might want to go for full into either Google Maps or Bing Maps and just let them provide you with best road possible.
They both have quite actual data of any road you need.
There is no way you can gather as much data as they do.
You have everything on a plate, if you feel that's the way you can do.
If not, I would go hybrid way - get some vital data from any maps API, then use it for my Dijkstra algorithm, then use this data to write a simple algorithm for measuring actual weight of each edge based on possible modifiers (speed limit, traffic if API provides it and so on).


text:
Q: What is the difference between nested array and associative array? There are two links
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/composites.htm#LNPLS99981 and
Purpose of using different types of PL/SQL collections in Oracle
by referring above two links i have two doubt
1.Which one is correct nested table?
2.If the oracle doc is correct what is the difference between nested table and associative array?

A: Here is another difference which is not that commonly known. You can compare two nested tables with = or <> but associative array you cannot.
DECLARE

    TYPE associative_array IS TABLE OF INTEGER INDEX BY PLS_INTEGER;
    a_var_associative_array associative_array;
    b_var_associative_array associative_array;

    TYPE nested_table IS TABLE OF INTEGER;
    a_var_nested_table nested_table := nested_table(1, 2, 3, 4, 5);
    b_var_nested_table nested_table := nested_table(5, 4, 3, 2, 1);

BEGIN

    IF a_var_nested_table = b_var_nested_table THEN
        -- Note, the different order of values!
        DBMS_OUTPUT.PUT_LINE ( 'TRUE' );
    ELSE
        DBMS_OUTPUT.PUT_LINE ( 'FALSE' );
    END IF;

    -- IF a_var_associative_array = b_var_associative_array THEN -> gives you an error!

END;

When you work with nested tables you can also use Multiset Operators, Multiset Conditions and SET which are not available for associative arrays.

A: A nested table is just an array of n elements.
declare
  type nested_table_of_integer is table of integer;
  v_my_nested_table nested_table_of_integer;
begin
  v_my_nested_table := nested_table_of_integer(); -- initialize
  v_my_nested_table.extend(10); -- add 10 elements
  v_my_nested_table(1) := 100;
  v_my_nested_table(11) := 1000; -- ORA-06533: Subscript beyond count
end;

A nested table must be initialized as shown. It has zero elements at first. To add elements we use EXTEND. This nested table has 10 elements. They are indexed 1 to 10. Element 1 has the value 100. The others have value null. An access to a non-existent element, say the 11th element, raises an error.
An associative array on the other hand is an array of name/value pairs. Let's use numbers (pls_integer typically) for the naming:
declare
  type associative_array_of_integer is table of integer index by pls_integer;
  v_my_associative_array associative_array_of_integer;
begin
  v_my_associative_array(1) := 100;
  v_my_associative_array(11) := 1000;
  v_my_associative_array(12) := v_my_associative_array(2); -- ORA-01403: no data found
end;

An associative array needs no initialization. It is empty and gets populated. Here we associate the element called 1 with the value 100 and the element with the name 11 with the value 1000. So there are two elements in the array. We get a no data found exception when we try to access a name that is not in the array.
We can also use strings for the names:
declare
  type associative_array_of_integer is table of integer index by varchar2(100);
  v_my_associative_array associative_array_of_integer;
begin
  v_my_associative_array('age father') := 39;
  v_my_associative_array('age mother') := 32;
  v_my_associative_array('age daughter') := 11;
end;

You can use both collections to get table data, but you use them differently. The nested table has a count and you can just loop from 1 to count to access its elements:
declare
  type nested_table_of_integer is table of integer;
  v_my_nested_table nested_table_of_integer;
begin
  v_my_nested_table := nested_table_of_integer(); -- initialize
  select table_name bulk collect into v_my_nested_table from user_tables;
  for i in 1 .. v_my_nested_table.count loop
    dbms_output.put_line(v_my_nested_table(i));
  end loop;
end;

The associative array however must be read from whatever happens to be the first index to the next and next and next using FIRST and NEXT.
declare
  type associative_array_of_integer is table of integer index by pls_integer;
  v_my_associative_array associative_array_of_integer;
  i integer;
 begin
  select table_name bulk collect into v_my_associative_array from user_tables;
  i := v_my_associative_array.first;
  while i is not null loop
    dbms_output.put_line(v_my_associative_array(i));
    i := v_my_associative_array.next(i);
  end loop;
end;

The "names" happen to be 1, 2, 3, etc. here (given thus by the bulk collection) and you could access v_my_associative_array(1) for instance. Later in your program, however, after some possible delete operations in the array, there may be gaps, so you don't know whether an element named 1 exists and whether the element before element 4 happens to be element 3. As with bulk collect the "names" for the elements have no meaning you would not really use them, but go instead through the chain as shown.


text:
Q: gcc: separate code and data in custom sections I have a software, which is being migrated from another toolchain to gcc (arm-none-eabi toolchain). In the software there are a few custom defined sections in order to structure data / code, use different memory components.
With the gcc toolchain I have a linker script file with the custom sections. With the old toolchain I could just use #pragma section for a block of code and data or for the whole file. The compiler internally separated such #pragma section blocks in the corresponding sections for code, data, rodata and bss using the given section name.
With gcc I have only two options:

*

*add __attribute__((section("")) to each variable / function

*add the whole file into the section using the linker script file

My problem is, that I now have about 300 files that must be processed and mapped to a specific section, while the code / data separation is kept. The files contain both data and code.
So If I map the file using the linker script, then all data and code will be mapped to this particular section, no code and data separation.
If I add the __attribute__ keyword to each variable / function it will take days to accomplish this.
Is there a way to tell the gcc to map the whole file / whole block to a particular section with automatically separation of data and code? Let's say the section name is "mysection", I want to map a whole file to "mysection" and gcc should automatically do the following:

*

*add uninitalized variables to "mysection.bss"

*initialized data to "mysection.data"

*readonly data to "mysection.rodata"

*code to "mysection.text"

gcc is able to do this for the standard sections.

A: You can complement compilation commands in your Makefile with calls to objcopy:
for s in .bss .data .rodata .text; do
  objcopy --rename-section $s=mysection$s file.o
done


text:
Q: Does anybody know why integrate in R breaks for large numbers in a beta? I have this joint beta distribution I am trying to integrate over:
alpha1 = 400
beta1 = 26000
alpha2 = 410
beta2 = 26000

integrate(function(y) {
   sapply(y, function(y) {integrate(function(x) dbeta(x, shape1 = alpha1,
     shape2 = beta1)*dbeta(y, shape1 = alpha2, shape2 = beta2), y,1)$value})
}, 0, 1)

This works for smaller alpha and beta even up to these values. But if I go much larger in beta the integrate function starts breaking.  I've been comparing this to the Monte Carlo integration
n_sim = 1000000   # number of simulations
y = rbeta(n_sim, shape1 = alpha2, shape2 = beta2)
C2 = (1-pbeta(y, shape1 = alpha1, shape2 = beta1))
mean(C2)

which yields approximately the same answers for smaller reasonable alpha and beta.
And yes I need larger beta, I understand questioning why I need such large beta.  It follows from large data sets. Does anybody know why this breaks? Maybe the inner workings of the integrate function? Is there a work around?


text:
Q: EMF in a half-ring shaped conductor around a solenoid A half-ring shaped conductor is being placed around a solenoid. This solenoid has a changing magnetic field.
a) There is a current and EMF (Electromagnetic force) in the half-ring shaped conductor
b) There is a current but no EMF in the half-ring shaped conductor
c) There is no current but there is an EMF in the half-ring shaped conductor
d) There is no current but there is no EMF in the half-ring shaped conductor
My thoughts about this:
First of all the field outside a solenoid isn't very big in contrast to the field inside the solenoid. But I assume that it can't be neglected.
I think there won't be a current as we would need a full ring-shaped conductor for this.
I do think that there will be an EMF in the conductor, and this will generate some eddy currents in the conductor. But there will be no "full-on current" so to speak.
So I would say the answer is C. Is this correct?
A Little side-question;
Is it at all possible for a non-conducting material to have an induced EMF. For example when we move a non-conducting material (ring-shaped) into a magnetic field. The magnetic flux in the ring changes, but will there be an induced EMF? I know that there won't be a current in the loop, but I'm not certain about the EMF.
Thank you very much!

A: Since there is a steadily changing magnetic flux, there are static closed loops of electric field lines circling the solenoid.
If the half-ring shaped conductor is placed around the solenoid, the mobile charge carriers in the conductor will redistribute in such a way that there is zero net E field inside the conductor.
Thus, there is no current (except for the more or less initial near instantaneous current required for the redistribution of charge within the conductor).  So, that rules out answers a) and b).
If you place a voltmeter across the ends of the conductor (make sure that the leads do not form a loop threaded by the the magnetic flux!), you will measure a voltage across the conductor that is numerically equal to the emf.  (In fact, you're measuring the strength of the opposition to the emf due to the charge distribution in the conductor).  So, you are correct, the answer is c).
If you had a half-ring of a non-conductor, no charge redistribution occurs (no free carriers) so you would not measure a voltage across the non-conductor.


text:
Q: Adding leading zeros inbetween mixed strings I have a vector
x <- c("MB1",  "MB11" ,"MB12" ,"MB13", "B1",  "B11", "B12", "B13", "B2")

and would like it to convert to
x
[1]"MB01"  "MB11" "MB12" "MB13" "B01"  "B11" "B12" "B13" "B02"

x only contains either "MB" or "B" as leading string, followed by maximum two digits.
i know how to str_pad, so i would like to perform something like
new.vector < paste0("Any Letter you find in each element of x", str_pad("numerical elements of x", 2, pad="0"))

or any other way, which can achieve this.
Thanks!

A: library(tidyverse)

strcapture('([A-Z]+)([0-9]+)', x,
           proto = list(char = character(), num = numeric())) %>%
  mutate(num = str_pad(num, 2, pad = '0')) %>%
  unite(value, char, num, sep = '') %>%
  pull(value)

#[1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02"

A: 1) gsub Remove the digits and non-digits respectively and combine back using sprintf.  No packages are used.
sprintf("%s%02d", gsub("\\d", "", x), as.numeric(gsub("\\D", "", x)))
## [1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02"

2) trimws This variation using trimws also uses only base R.
sprintf("%s%02d", trimws(x,, "\\d"), as.numeric(trimws(x,, "\\D")))
## [1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02"

3) gsubfn An ever shorter solution involves extracting the digits, converting to numeric, padding and then inserting back in using gsubfn.
library(gsubfn)
gsubfn("\\d+", ~ sprintf("%02d", as.numeric(digits)), x)
## [1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02"

4) sub Shorter yet we can use only sub by looking for one digit suffixes and inserting a zero.  No packages are used.
sub("(\\D)(\\d)$", "\\10\\2", x)
## [1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02"

5) Generalization If we don't know how many digits are involved and we want to use sufficient 0 padding to right justify them all then we can use * format in sprintf in this variation of (1).  The same approach could be used with the others. No packages are used.
digits <- gsub("\\D", "", x)
nondigits <- gsub("\\d", "", x)
sprintf("%s%0*d", nondigits, max(nchar(digits)), as.numeric(digits))
## [1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02"


text:
Q: Define object and pass by reference inside function parameter Lets say we have a function called foo that gets a pointer to some object.
void foo(int *i){
    // Some code
}

We can call this function the following way:
int i;
foo(&i);

Is there a way we can make the above snippet in one line in c++? Something like
foo(&int(4)) // This is invalid.

Two limitations:

*

*Changing foo to receive by-reference is not an option.

*We also want to avoid using something like foo(new int(4)) which can lead to memory leaks.

A: "Doing all in one line" is usually not something desirable, because it does not make code more clean or more readable. If you have to declare an int and take its address, your code better expresses that explicitly.
However, the usual way to encapsulate common tasks is functions:
 void foo_wrapper() {
       int i = 0;
       foo(&i);
 }

Then call foo_wrapper() rather than foo(&i).
PS: The elephant in the room is: foo apparently uses the argument as out-parameter, but you want to ignore it. If this is really how foo is supposed to be used, then it does unnecessary work. Writing the wrapper is hiding a flaw. To fix the actual issue foo would have to be modified. I know you said it is third party library code, but rather than writing workarounds for library code, I would reconsider if (a) it is the right library or (b) perhaps I do misunderstand how it is supposed to be used.
PPS: I assumed that passing nullptr is not an option. If passing a nullptr is an option then simply do that.

A: I have no idea why such behaviour would be required and assume it's some kind of 'Brain Teaser' question.
If it's an exercise in "macro magic" there may be better solutions.
This is valid:
#include <iostream>
#include <memory>

void f(int *x){
    ++(*x);
    std::cout << *x << '\n';
}
int main() {
     f(std::make_unique<int>(4).get());
    return 0;
}

Expected Output: 5
The temporary object (of type std::unique<int>) will be cleaned up after the function call. No memory leaked but there is of course overhead in dynamic allocation.

A: & and std::addressof are explicitly specified to disallow this, but if you want to ignore that safety measure, you can define your own wrapper around std::addressof that will allow it:
template<typename T>
constexpr auto myaddressof(T&& t) noexcept {
    return std::addressof(t);
}

//...

// temporary created from argument to `addressof` lives
// until end of full-expression
foo(myaddressof(4));

That's quite easy to get wrong though. For example if you replace T&& with T, then using it may result in undefined behavior. This relies on rules for temporary lifetime that are probably not intuitive. I don't really think this is better style than declaring a variable and wrapping it with the call in a block.
Full demo here based on a comment by @JasonLiam.
(Note that you probably shouldn't use addressof as name for this function. There are some corner cases where argument-dependent lookup will cause problems with that name if called unqualified.)

A: void foo(int *i) expresses intent that the lifetime of the argument is managed by the caller, outside of foo. Which means allocating some time before foo call and deallocating some time after foo returns. So one liner is out of the question because of your reason #2.
The idiomatic way of handling optional pointer values is to use nullptr or NULL (pre-C++11) argument as an indicator to ignore it: foo(nullptr).

A: You can use wrapper class (which in a way is similar to the other answer with myaddressof function template):
#include <iostream>

template<typename T>
class my_wrapper_class
{
  public:
    my_wrapper_class(T const &v) : value(v)
    {
    }
    T *operator&()
    {
      return(&value);
    }
    T const *operator&() const
    {
      return(&value);
    }
  private:
    T value;
};

void f(int *v)
{
  std::cout << "v: " << *v << std::endl;
  (*v)++;
}

int main()
{
  f(&my_wrapper_class<int>(4));
  return(0);
}

Please note that EVERY book about C++ I've read strongly advises against overloading unary operator & which I've just did. The other option (not shown) is to define conversion operator to appropriate pointer and omission of explicit & at call site which in my opinion is equally confusing.
Putting it here so it is available for those in need with a strong disclaimer - DON'T DO THAT. Consider what others wrote on this topic before heading this way.


text:
Q: The commutator of two "basis" derivations of $GL(n, \mathbb{F})$ Let us define a $G$-invariant derivation of $G=GL(n,\mathbb{F})$ by extending $\frac{\partial}{\partial x_{i,j}}$ (A derivation of $G$ at $e$) into a derivation of the whole space like so:
$$ \delta_{i,j}(f)(g) = \left ( \frac{\partial}{\partial x_{i,j}} f(g-) \right ) (e)$$
Here I have a correspondence between $G$ and $\mathbb{F}^{n^2}$ by taking each matrix into it's flattened vector.
My question is, what is:
$$ [\delta_{a,b}, \delta_{c,d}] $$
This is supposedly a simple (albeit messy) calculation, but my work doesn't make sense to me. I would like to understand where is my mistake (and what is the correct answer). First I calculated $\delta_{i, j}$ like so:
$$ \partial_{i,j}(f)(g)=\left[\frac{\partial}{\partial x_{i,j}}f(g-)\right](e)= $$
$$ =\left[\frac{\partial}{\partial x_{i,j}}f([\sum_{k=0}^{n}[g]_{a,k}[-]_{k,b}]_{a,b})\right](e)= $$
$$ = \left[\frac{\partial}{\partial x_{i,j}}f\right](ge)\cdot(\frac{\partial}{\partial x_{i,j}}[\sum_{k=0}^{n}[g]_{a,k}[-]_{k,b}]_{a,b})(e) = $$
$$ =\left[\frac{\partial}{\partial x_{i,j}}f\right](g)\cdot\sum_{k=0}^{n}g_{k,i} $$
Where here $g_{i, k}$ is the $i,k$ element of $g$ (which is a matrix). Here between the second and the third line I used the chain rule.
Now, using this result I calculated the composition of two of said derivations:
$$ \partial_{a,b}(\partial_{c,d}(f))(g)=  \partial_{a,b}\left(\left[\frac{\partial}{\partial x_{c,d}}f\right](x)\cdot\sum_{k=0}^{n}x_{k,c}\right)(g)=$$
$$ =\left[\frac{\partial}{\partial x_{a,b}}\left(\left[\frac{\partial}{\partial x_{c,d}}f\right](x)\cdot\sum_{k=0}^{n}x_{k,c}\right)\right](g)\cdot\sum_{k=0}^{n}g_{k,a}= $$
$$ =\left(\left[\frac{\partial^{2}}{\partial x_{a,b}\partial x_{c,d}}f\right](g)\cdot\sum_{k=0}^{n}g_{k,c}+\left[\frac{\partial}{\partial x_{c,d}}f\right](g)\cdot[\frac{\partial}{\partial x_{a,b}}\sum_{k=0}^{n}x_{k,c}](g)\right)\sum_{k=0}^{n}g_{k,a}= $$
$$ =\delta_{b,c}\left[\frac{\partial}{\partial x_{c,d}}f\right](g)\cdot\sum_{k=0}^{n}g_{k,a}+\left[\frac{\partial^{2}}{\partial x_{a,b}\partial x_{c,d}}f\right](g)\cdot\sum_{k=0}^{n}g_{k,c}\cdot\sum_{k=0}^{n}g_{k,a} $$
And now by noticing that the second term of the result will also appear when we take the composition the other way around we will get:
$$ [\delta_{a,b}, \delta_{c,d}] = \delta_{b,c}\left[\frac{\partial}{\partial x_{c,d}}f\right](g)\sum_{k=0}^{n}g_{k,a}-\delta_{d,a}\left[\frac{\partial}{\partial x_{a,b}}f\right](g)\sum_{k=0}^{n}g_{k,c} $$
Now, this result doesn't make sense to me. This is because if we restrict the result to a derivation at $e$ it will be the same as $\delta_{b,c}\cdot\partial_{c,d}-\delta_{d,a}\partial_{a,b}$ as a derivation at $e$. Now, because (supposedly) a commutator of $G$-invariant derivations is still a $G$-invariant derivation we should be able to extend the result as a derivation at $e$ to the whole space like I did in the beginning of the question. This will imply:
$$ \delta_{b,c}\left[\frac{\partial}{\partial x_{c,d}}f\right](g)\sum_{k=0}^{n}g_{k,a}-\delta_{d,a}\left[\frac{\partial}{\partial x_{a,b}}f\right](g)\sum_{k=0}^{n}g_{k,c} = (\delta_{b,c}\cdot\partial_{c,d}-\delta_{d,a}\partial_{a,b})(g) $$
Which seems obviously false.


text:
Q: How to update/refresh TextView to show updated Json data every second? I want to create an online queue monitoring application which it will show the new data entered to the database.The UI sample is below

I want the Current Serving Ticket to update every second if there is a new data entered(Json).
Here the MainActivity.java
public class MainActivity extends AppCompatActivity {

public static TextView data;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button input_number = (Button) findViewById(R.id.button2);
    Button reminder = (Button) findViewById(R.id.button);

    final TextView userinputtext = (TextView) findViewById(R.id.textView6);

    data = (TextView)findViewById(R.id.textView10);

Here is the data.java that i created.
public class data extends AsyncTask<Void,Void,Void> {

String data=" ";
String singleParsed = " ";

@Override
protected Void doInBackground(Void... voids) {
    try {

        URL url = new URL("url/SamplePage.php");
        HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line ="";
        while(line!=null){
            line = bufferedReader.readLine();
            data = data + line;
        }

        JSONArray JA = new JSONArray(data);
        for (int i =0; i<JA.length();i++){
            JSONObject JO = (JSONObject) JA.get(i);

            singleParsed = JO.get("ticket_number")+"";

            //dataParsed = dataParsed + singleParsed;

        }

    }catch (MalformedURLException e){
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (JSONException e){
        e.printStackTrace();
    }
    return null;

}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);

    MainActivity.data.setText(this.singleParsed);

}

}

If there is any comment or help I would appreciate. Thanks.

A: The fastest answer would be setting a timer each second to query the database for data, and update the view.
If you're looking for a more optimized, complete, documented and easier solution, I suggest you use firebase,  which offers services like Realtime database : https://youtu.be/U5aeM5dvUpA
Of course there are other alternatives like  RethinkDB.
You should also look up websocket since they are similar approach to this kind of real time update problem.
But firebase is perfect for this in my opinion.

A: You can use SyncAdapter and LiveData. If you use Room, it will be more easier to handle.


text:
Q: Chart js 2 bars with one customize label on top I have few values like A and B now I have pair of them I am showing them on chart-js like this

Now for my use case, I am calculating the third value using A and B. E.g a=100 and b=50, and dividing them will give me c=2.0. Now I want to show this c value on top of A and B bar as a common label like this

"chart.js": "^3.3.0",
react-js
const newChartInstance = new Chart(chartContainer.current, {

  type: "bar",
    options: {
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
            },
          },
        ],
      },
      ...config.options,

      onClick: (e) => {
        const points = newChartInstance.getElementsAtEventForMode(
          e,
          "nearest",
          { intersect: true },
          true
        );

        if (points.length) {
          const firstPoint = points[0];

          var type =
            newChartInstance.data.datasets[firstPoint.datasetIndex].label;
          var label = newChartInstance.data.labels[firstPoint.index];
          var value =
            newChartInstance.data.datasets[firstPoint.datasetIndex].data[
              firstPoint.index
            ];
          // This is the result that you will use to breakdown the chart
          //console.log(label, value, type);
          dispatch(setClickedBar({ label, value, type, tile: props.tile }));
        }
      },
    },
    data: data,
  });

A: You can use a custom plugin for that:

var options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: 'red'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      customValue: {
        name: 'ROI',
      }
    }
  },
  plugins: [{
    id: 'customValue',
    afterDraw: (chart, args, opts) => {
      const {
        ctx,
        data: {
          datasets
        },
        _metasets
      } = chart;

      datasets[0].data.forEach((dp, i) => {
        let barValue = `${(datasets[1].data[i] + dp) / 2}%`;
        const lineHeight = ctx.measureText('M').width;
        const textVal = opts.name || 'fill'

        ctx.textAlign = 'center';

        ctx.fillText(barValue, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 1.5), _metasets[0].data[i].width);
        ctx.fillText(textVal, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 3), _metasets[0].data[i].width);
      });
    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>


text:
Q: PHP Linkify Links In Content I've been working on a little project, and I find myself in a position where I need a php function which can linkify URLs in my data, while enabling me to set some exceptions on links I don't want to linkify. Any idea of how to do this?

A: Well, this is quite ok, but there is still huge problem, existing anchors within the string, I would like to linkify text without transforming those into a senseless piece of sh.t.

A: I have an open source project on GitHub: LinkifyURL which you may want to consider. It has a function: linkify() which plucks URLs from text and converts them to links. Note that this is not a trivial task to do correctly! (See: The Problem With URLs - ands be sure to read the thread of comments to grasp all the things that can go wrong.)
If you really need to NOT linkify specific domains (i.e. vimeo and youtube), here is a modified PHP function linkify_filtered (in the form of a working test script) that does what you need:
<?php // test.php 20110313_1200

function linkify_filtered($text) {
    $url_pattern = '/# Rev:20100913_0900 github.com\/jmrware\/LinkifyURL
    # Match http & ftp URL that is not already linkified.
      # Alternative 1: URL delimited by (parentheses).
      (\()                     # $1  "(" start delimiter.
      ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+)  # $2: URL.
      (\))                     # $3: ")" end delimiter.
    | # Alternative 2: URL delimited by [square brackets].
      (\[)                     # $4: "[" start delimiter.
      ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+)  # $5: URL.
      (\])                     # $6: "]" end delimiter.
    | # Alternative 3: URL delimited by {curly braces}.
      (\{)                     # $7: "{" start delimiter.
      ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+)  # $8: URL.
      (\})                     # $9: "}" end delimiter.
    | # Alternative 4: URL delimited by <angle brackets>.
      (<|&(?:lt|\#60|\#x3c);)  # $10: "<" start delimiter (or HTML entity).
      ((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]+)  # $11: URL.
      (>|&(?:gt|\#62|\#x3e);)  # $12: ">" end delimiter (or HTML entity).
    | # Alternative 5: URL not delimited by (), [], {} or <>.
      (                        # $13: Prefix proving URL not already linked.
        (?: ^                  # Can be a beginning of line or string, or
        | [^=\s\'"\]]          # a non-"=", non-quote, non-"]", followed by
        ) \s*[\'"]?            # optional whitespace and optional quote;
      | [^=\s]\s+              # or... a non-equals sign followed by whitespace.
      )                        # End $13. Non-prelinkified-proof prefix.
      ( \b                     # $14: Other non-delimited URL.
        (?:ht|f)tps?:\/\/      # Required literal http, https, ftp or ftps prefix.
        [a-z0-9\-._~!$\'()*+,;=:\/?#[\]@%]+ # All URI chars except "&" (normal*).
        (?:                    # Either on a "&" or at the end of URI.
          (?!                  # Allow a "&" char only if not start of an...
            &(?:gt|\#0*62|\#x0*3e);                  # HTML ">" entity, or
          | &(?:amp|apos|quot|\#0*3[49]|\#x0*2[27]); # a [&\'"] entity if
            [.!&\',:?;]?        # followed by optional punctuation then
            (?:[^a-z0-9\-._~!$&\'()*+,;=:\/?#[\]@%]|$)  # a non-URI char or EOS.
          ) &                  # If neg-assertion true, match "&" (special).
          [a-z0-9\-._~!$\'()*+,;=:\/?#[\]@%]* # More non-& URI chars (normal*).
        )*                     # Unroll-the-loop (special normal*)*.
        [a-z0-9\-_~$()*+=\/#[\]@%]  # Last char can\'t be [.!&\',;:?]
      )                        # End $14. Other non-delimited URL.
    /imx';
//    $url_replace = '$1$4$7$10$13$2$5$8$11$14$3$6$9$12';
//    return preg_replace($url_pattern, $url_replace, $text);
    $url_replace = '_linkify_filter_callback';
    return preg_replace_callback($url_pattern, $url_replace, $text);
}
function _linkify_filter_callback($m)
{ // Filter out youtube and vimeo domains.
    $pre  = $m[1].$m[4].$m[7].$m[10].$m[13];
    $url  = $m[2].$m[5].$m[8].$m[11].$m[14];
    $post = $m[3].$m[6].$m[9].$m[12];
    if (preg_match('/\b(?:youtube|vimeo)\.com\b/', $url)) {
        return $pre . $url . $post;
    } // else linkify...
    return $pre .'' . $url .'' .$post;
}

// Create some test data.
$data = 'Plain URLs (not delimited):
foo http://example.com bar...
foo http://example.com:80 bar...
foo http://example.com:80/path/ bar...
foo http://example.com:80/path/file.txt bar...
foo http://example.com:80/path/file.txt?query=val&var2=val2 bar...
foo http://example.com:80/path/file.txt?query=val&var2=val2#fragment bar...
foo http://example.com/(file\'s_name.txt) bar... (with \' and (parentheses))
foo http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7348] bar... ([IPv6 literal])
foo http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7348]/file.txt bar... ([IPv6] with path)
foo http://youtube.com bar...
foo http://youtube.com:80 bar...
foo http://youtube.com:80/path/ bar...
foo http://youtube.com:80/path/file.txt bar...
foo http://youtube.com:80/path/file.txt?query=val&var2=val2 bar...
foo http://youtube.com:80/path/file.txt?query=val&var2=val2#fragment bar...
foo http://youtube.com/(file\'s_name.txt) bar... (with \' and (parentheses))
foo http://vimeo.com bar...
foo http://vimeo.com:80 bar...
foo http://vimeo.com:80/path/ bar...
foo http://vimeo.com:80/path/file.txt bar...
foo http://vimeo.com:80/path/file.txt?query=val&var2=val2 bar...
foo http://vimeo.com:80/path/file.txt?query=val&var2=val2#fragment bar...
foo http://vimeo.com/(file\'s_name.txt) bar... (with \' and (parentheses))
';
// Verify it works...
echo(linkify_filtered($data) ."\n");

?>

This employs a callback function to do the filtering. Yes, the regex is complex (but so it the problem as it turns out!). You can see the interactive Javascript version of linkify() in action here: URL Linkification (HTTP/FTP).
Also, John Gruber has a pretty good regex to do linkification. See: An Improved Liberal, Accurate Regex Pattern for Matching URLs. However, his regex suffers catastrophic backtracking under certain circumstances. (I've written to him about this, but he has yet to respond.)
Hope this helps! :)

A: $string = "some text and a link http://www.google.com"
$new_string = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","\\0", $string)

or use:
http://code.iamcal.com/php/lib_autolink/


text:
Q: Using lead-lag relationships for time series prediction I have a large number (hundreds to thousands) of noisy time series that represent contemporaneous observations from different subjects.
I hypothesise that there exist lead-lag relationships between observations for different subjects (or groups of subjects.)
I would like to explore the potential use of such lead-lag relationships for the purposes of predicting the individual series.
What methods might I consider for this?
edit: To be clear, I am not looking at pairwise relationships. What I am looking for is a method that would look at the mountain of data at hand and attempt to discover (potentially non-linear) lead-lag relationships between arbitrary groups of series and the individual series to be predicted.

A: You can choose from about 40 years of research and countless books, dissertations, monographs etc.
Given that your question is not all that focussed yet, maybe an introductory time-series book could help.  In a nutshell, the autocorrelation function gives clues to lead/lag relationships that may be present in a single time-series, or between two series.
Rob has done a lot of research into sensibly automating the process of identifying how many / which leads/lags to use, so please look at his forecast package for R and other research.

A: http://en.wikipedia.org/wiki/Granger_causality
Barrett, Barnett & Seth have a paper which extends the idea of Granger causality to the multivariate case.

A: You should consider the Cross Correlation Function as that is meant to identify the lead/lag relationship.  Dirk had mentioned the Autocorrelation Function, but that is meant for just one single time series and not for multivariate. You should consider looking at the Box-Jenkins textbook Chapter 10 where they introduce the steps do this.
You say your data is noisy, but if it has a pattern where the lead/lag response is strong then you will find significance.


text:
Q: AngularJS - Send $http GET request with associative array params with this code I am trying to send a $http.get request to my rest service:
$http({
    method: 'GET',
    url: '/api/item/all',
    params: {
        query: {
            userid: 7
        },
        fields: 'title'
    }
});

I expected to access this URL:
/api/item/all?query[userid]=7&fields=title

but I am always getting a malformed url...
So, how to proceed?
Or even better: Is it possible to pass the full request url into the url-param of $http?

A: In a GET request, you should pass parameters as part of the query string.
You can use the shortcut get call and pass in the query parameters in the url:
$http.get('api/item/all?userid=" + 7 + "&fields=title");

If you need to access them as scope variables, you can do that too:
$http.get('api/item/all?userid=" + $scope.foo + "&fields=" + $scope.bar);

Also depending on the back end you can send them as a path parameters rather then a query parameter:
$http.get('api/item/all/userid/" + $scope.foo + "/fields/" + $scope.bar);

Hope that helps


text:
Q: GuzzleHttp doesnt show response from a nodejs server I'm using GuzzleHttp. I want to send request from laravel to nodejs.
    try {

        $client = new \GuzzleHttp\Client();
        $url = 'http://localhost:8085/api/test/get';
        $headers = [
            'Accept' => 'application/json',
        ];

        $res = $client->post($url, [
            'headers' => $headers,
            'json' => $data,
        ]);
        dd($res->getBody());
    }
    catch(\Exception $e) {

       echo $e->getMessage();
    }

my request sent as well, but $res->getBody() doesn't show my nodejs result. (I sure nodejs has response)
my nodejs code:
   total_result            = _res.length
    response.total_result   = total_result
    response.result         = _res
    console.log(response)
    res.setHeader('Content-Type', 'application/json')
    res.status(200).json(response);

The result of dd($res->getBody()); is:
Stream {#2694
  -stream: stream resource @1095
    wrapper_type: "PHP"
    stream_type: "TEMP"
    mode: "w+b"
    unread_bytes: 0
    seekable: true
    uri: "php://temp"
    options: []
  }
  -size: null
  -seekable: true
  -readable: true
  -writable: true
  -uri: "php://temp"
  -customMetadata: []
}

A: solved. You should use an asynchronous request:
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

https://github.com/guzzle/guzzle


text:
Q: Return async function in realtime firebase database I'm still starting to program and I'm a little confused with my async function.
I'm trying to fetch the last data from the last day in my firebase realtime database, I get it as you can see in my console.log inside the function
however when I try to return this value from within the function and it comes with all the data for that last day.
in my realtime firebase database is this way:

my function is:
public async findLatestWeatherStationRecord(): Promise<WeatherStation> {
  const RefR = database.ref('Prototipo0/Leitura/');

  const latestWeatherStationRecord = await RefR.limitToLast(1).once(
    'value',
    snapshot => {
      snapshot.forEach(child => {
        database
          .ref(`Prototipo0/Leitura/${child.key}`)
          .limitToLast(1)
          .once('value', snapshot => {
            snapshot.forEach(childSnapshot => {
              const lastMeasurements = childSnapshot.val();
              console.log(lastMeasurements);
              return lastMeasurements;
            });
          });
      });
    },
  );
  // console.log(latestWeatherStationRecord.val());
  return latestWeatherStationRecord;
}

the result of console.log inside the function looks like this:
{
  anemometro: 2.8,
  bh1750Luminosidade: 1185,
  bmp280Altitude: 653.58,
  bmp280Pressao: 94739,
  csmsv12Solo: 40.76,
  dht22Temperatura: 27.9,
  dht22Umidade: 31.7,
  mhrdMolhamento: -0.04,
  pluviometro: 0,
  timestamp: 1598554509834,
  uvm30aIndiceUv: 1
}

I'm breaking my head now, because the return of this function does not give the same result as the return inside the function (console.log). It returns all data for that day and not the last of the function
    ...,
    '-MFlG2p4zMPCC7iQ6Y1D': {
      anemometro: 3.73,
      bh1750Luminosidade: 1187,
      bmp280Altitude: 653.27,
      bmp280Pressao: 94742,
      csmsv12Solo: 40.81,
      dht22Temperatura: 28,
      dht22Umidade: 32.5,
      mhrdMolhamento: -0.04,
      pluviometro: 0,
      timestamp: 1598554389829,
      uvm30aIndiceUv: 1
    },
    '-MFlGHWOxi16Qc2HEPba': {
      anemometro: 2.8,
      bh1750Luminosidade: 1184,
      bmp280Altitude: 653.72,
      bmp280Pressao: 94737,
      csmsv12Solo: 40.79,
      dht22Temperatura: 27.9,
      dht22Umidade: 31.6,
      mhrdMolhamento: -0.04,
      pluviometro: 0,
      timestamp: 1598554450009,
      uvm30aIndiceUv: 1
    },
    '-MFlGW78ZQcHJ8reA0YD': {
      anemometro: 2.8,
      bh1750Luminosidade: 1185,
      bmp280Altitude: 653.58,
      bmp280Pressao: 94739,
      csmsv12Solo: 40.76,
      dht22Temperatura: 27.9,
      dht22Umidade: 31.7,
      mhrdMolhamento: -0.04,
      pluviometro: 0,
      timestamp: 1598554509834,
      uvm30aIndiceUv: 1
    }
  }
}

I wanted to know why the return inside the function is not the same as outside the function.
I would like the end result to be the same from within the function.
Can anyone give me a light?
Edit - Sorry again now my fuction is this way
public async findLatestWeatherStationRecord(): Promise<WeatherStation> {
  const Ref = database.ref('Prototipo0/Leitura/');
  const snapshot = await Ref.limitToLast(1).once('value');

  let latestWeatherStationRecord;

  snapshot.forEach(child => {
    database
      .ref(`Prototipo0/Leitura/${child.key}`)
      .limitToLast(1)
      .once('value', snapshot => {
        snapshot.forEach(childSnapshot => {
          latestWeatherStationRecord = childSnapshot.val();
          // console.log(latestWeatherStationRecord);
          return latestWeatherStationRecord;
        });
      });
  });
  console.log(latestWeatherStationRecord);
// I need to return the snapshot function, but I can't
  return latestWeatherStationRecord;
}

A: You're not using the promise that is returned by once(), but are using the callback to do your processing. This means your return still runs before your processing.
The solution is to separate the await from the rest of your processing:
const snapshot = await RefR.limitToLast(1).once("value");
let latestWeatherStationRecord;
snapshot.forEach((child) => {
  child.forEach(childSnapshot => {
    latestWeatherStationRecord = childSnapshot.val();
  });
});
return latestWeatherStationRecord;


text:
Q: Oracle Bulk Collect - Limit number I read about Bulk Collect and wrote some code using it (not deployed yet). The total amount of rows returned is in the vicinity of 80.000. I limited the amount of rows returned in one batch to 10.000, but there is no basis for using this number, I simply improvised.
What would be a good method for determining how to limit the Bulk Collect?

A: As with anything, the best approach would be to benchmark the different options.
Realistically, though, in the vast majority of cases, there isn't any appreciable benefit to a limit much higher than 100.  With a limit of 100, you're eliminating 99% of the context shifts.  It's relatively unlikely that the remaining 1% of the context shifts account for a meaningful fraction of the execution time of your code.  Reducing the context shifts further probably does nothing for performance and just causes you to use more valuable PGA memory.


text:
Q: How can I blacklist specific rows from being created in my database? In my database, I have constant rows being created for my own purposes. Some of these rows are trash, unneeded spam that I'd like to blacklist from being created. Is there an SQL statement that I can send to blacklist a row from being created if it has a specific field name? For example, creation of any rows WHERE column = 1 will be completely disallowed and the rows will just be denied creation.

A: One way is a check constraint. other, is a BEFORE INSERT trigger


text:
Q: Table1 Left Join Table2 Minus (join Data) TABLE 1) m_conservationsetting
FacilityId   Unit   CategoryId
    1          1        1
    1          1        2
    1          1        3
    1          2        1
    1          2        2
    2          1        1
    2          2        1

Unique Key(FacilityId  Unit CategoryId)
TABLE 2) l_maintelog
FacilityId   Unit  CategoryId  Status
    1          1        1         0
    1          1        2         1
    1          1        3         0
    1          2        1         0
    2          1        1         0
    2          2        1         0

Result :
FacilityId   Unit   CategoryId
    1          2        2

Table1 need to be left Joined  with Table2 and it should ommit the join results and show only table1 data as results.
Table1 LeftJoin Table2 - (join Data) for the below query. The condition for getting result is to check the status=0 for the record in Table2
SELECT cs.FacilityId,Cs.Unit,cs.CategoryId
FROM m_conservationsetting cs
LEFT JOIN l_maintelog ml
ON cs.FacilityId=ml.FacilityId and cs.Unit=ml.Unit
WHERE ml.Status=0
GROUP BY cs.CategoryId

A: If you only want to take those records that are not in result of left join so do like this:
SELECT t.* FROM m_conservationsetting AS t
WHERE NOT EXISTS (
    SELECT cs.FacilityId,Cs.Unit,cs.CategoryId
    FROM m_conservationsetting AS cs
    LEFT JOIN l_maintelog ml on
       (cs.FacilityId=ml.FacilityId and cs.Unit=ml.Unit)
    WHERE ml.Status=0
    group by cs.CategoryId
)

A: Only left join is enough to get the result.
Set Nocount On;

Declare @table1 Table
(
     FacilityId         Int
    ,Unit               Int
    ,CategoryId         Int
)

Declare @table2 Table
(
     FacilityId         Int
    ,Unit               Int
    ,CategoryId         Int
    ,[Status]           Bit
)

Insert Into @table1(FacilityId,Unit,CategoryId) Values
 (1,1,1)
,(1,1,2)
,(1,1,3)
,(1,2,1)
,(1,2,2)
,(2,1,1)
,(2,2,1)

Insert Into @table2(FacilityId,Unit,CategoryId,[Status]) Values
 (1,1,1,0)
,(1,1,2,1)
,(1,1,3,0)
,(1,2,1,0)
,(2,1,1,0)
,(2,2,1,0)

Select  t1.*
From    @table1 As t1
        Left Join @table2 As t2 On t1.FacilityId = t2.FacilityId
            And t1.Unit = t2.Unit
            And t1.CategoryId = t2.CategoryId
Where   t2.FacilityId Is Null

Output:-


text:
Q: How specify a directory to file when downloading it I use this code to download a file from remote server to mine. The file is created and saved but in the home directory. I want it in the plugin directory.
$url ='*.dat';
// Use wp_remote_get to fetch the data
$response = wp_remote_get($url);

// Save the body part to a variable
$fileContent = $response['body'];

// Create the name of the file and the declare the directory and path

$file ='*.dat';

// Now use the standard PHP file functions
$fp = fopen($file, "w");
fwrite($fp, $fileContent);
fclose($fp);

A: You can try this get the plugin directory:
$pluginPath = dirname(_____FILE_____); //plugin path

$pluginUrl = WP_PLUGIN_URL . '/pluginname/'; //plugin URL

good question
you just create one template in your plugin directory. there u use the above code.
you create one page and assign this template like this
add_filter( "template_include", "yourpage" ) ;
function yourpage($single_template) {
        global $post, $pagenow;
    if ($pagenow == 'download-template.php') {

        $single_template = dirname( __FILE__ ) . '/templates/download-template.php';
    }
    return $single_template;
}

A: If you are wanting to write the file to the default plugins directory; then you can use part of what @abalamurugan suggested; in combination with your existing code:
$url ='*.dat';
$response = wp_remote_get($url);
$fileContent = $response['body'];

$pluginUrl = WP_PLUGIN_URL; // Plugins directory url
$file = $pluginUrl.'/*.dat';

$fp = fopen($file, "w");
fwrite($fp, $fileContent);
fclose($fp);


text:
Q: How would you use XSL to transform all elements and all attributes from PascalCase to camelCase? I would like to transform ALL/ANY elements and attributes (not just the explicit elements/attributes in my small sample below) in my XML file from PascalCase to camelCase.
Does anyone have an XSL transform that can do this?
This:
<?xml version="1.0" encoding="utf-8" ?>
<Config Version="2" Name="Test">
    <Process Name="Main">
        X
    </Process>
</Config>

Should become this:
<?xml version="1.0" encoding="utf-8" ?>
<config version="2" name="Test">
    <process name="Main">
        X
    </process>
</config>

A: Try this:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:output method="xml" indent="yes"/>

  <!-- everything not mentioned below (e.g. text, comments, processing instructions) -->
  <xsl:template match="node()">
    <xsl:value-of select="."/>
  </xsl:template>

  <!-- attributes -->
  <xsl:template match="@*">
    <xsl:attribute name="{concat(translate(substring(local-name(), 1, 1),'QWERTYUIOPASDFGHJKLZXCVBNM','qwertyuiopasdfghjklzxcvbnm'), substring(local-name(), 2))}">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>

  <!-- elements -->
  <xsl:template match="*">
    <xsl:element name="{concat(translate(substring(local-name(), 1, 1),'QWERTYUIOPASDFGHJKLZXCVBNM','qwertyuiopasdfghjklzxcvbnm'), substring(local-name(), 2))}">
      <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

NB: if using XSLT 2 you could replace the translate function with the lower-case function.


text:
Q: How to inspect if a element changed there text We need to inspect when the text on a element change, because it is one way to see if the process ended, so we made something like this:
*** Settings ***
Library          Browser
*** Test Case ***
...
Then inspect if the element text is Finished
*** Keywords ***
Then inspect if the element text is Finished
sleep                                                      10
${text} =                                                  Get Text                                                      //*[@id="situacaoUltimaMovimentacaoVariacaoCambial"]
Should Be Equal                                            ${text}                                                      Finished

But I don't think using sleep for this is a good idea, you guys know some solution for doing this in a better way?

A: You can use the below mentioned method:
For Example xpath of the element initially--> //*[@id='anyid' and contains(text(), 'Started')] and finally --> //*[@id='anyid' and contains(text(), 'Finished')]
*** Settings ***
Library          Browser
*** Test Case ***
...
Then inspect if the element text is Finished
*** Keywords ***
Then inspect if the element text is Finished
Wait Until Page Contains Element      //*[@id='anyid' and contains(text(), 'Finished')]    60s

The Keyword Wait Until Page Contains Element will wait until the element with id - 'anyid' and with text - 'Finished' for 60 seconds. If text not changed then testcase will fail.
You can also use Wait Until Element Contains Keyword
Wait Unitl Element Contains    //*[@id='anyid']    Finished    60s

A: Thanks to @senaid I found a good solution.
Because Playwright will always wait until try to do some commands, I used Click on the element with the text that will be find after the process finished. So the code will be:
*** Settings ***
Library          Browser
*** Test Case ***
...
Then inspect if the element text is Finished
*** Keywords ***
Then inspect if the element text is Finished
Click                                                          //*[@id='situacaoUltimaMovimentacaoVariacaoCambial' and contains(text(),'Finished')]


text:
Q: Is $(p^2-1)/2$ never squarefull when $p > 3$ is a Mersenne prime? Let $p\neq 3$ be a Mersenne prime. Is it true that $(p^2-1)/2$ has a prime divisor $r$ such that $r^{2}$ does not divide $n$?

A: Well, maybe I'm missing the point, but the first Mersenne prime is $3=2^2-1$, and $\frac{3^2-1}{2} = 4 = 2^2$, so... no, I guess.

A: Considering there are only 47 known Mersenne primes, and finding the factors of $2^p-1$ is a difficult task, I'm not sure this question is fully tractable.
But we can certainly show that all of the known Mersenne primes satisfy your question. First, take $m=2^p-1$ to be a Mersenne number, and rewrite $n= \frac{m^2 - 1}{2} = 2^{2p-1} - 2^p$. This is powerful when $p=2$, which gives Philip van Reeuwijk's counterexample. For larger $p$, we know $4$ will always divide $n$, so we can ignore powers of $2$ and just consider the odd part $n'= 2^{p-1} - 1$.
We know $p$ is prime, and odd since it is not $2$, so we are looking at $n' = 4^k - 1$, with $k=\frac{p-1}{2}$. Clearly $3$ divides $n'$, and $9$ divides iff $3$ divides $k$. So we require that $p \equiv 1 \mod6$. This is not enough; plenty of known Mersenne primes have this property.
Since $3$ divides $k$, we can write $n'=64^{k'}-1$. Then $7$ divides $n'$, and $7^2$ divides $n'$ iff $7$ divides $k'$. So now we require that $p \equiv 1 \mod42$. Sadly, again this is not enough.
One step further, we see that when $7$ divides $k'$, $43$ divides $64^{k'}-1$, and $43^2$ divides iff $43$ divides $k'$. Now we're happy (for the time being), because no known Mersenne prime has $p\equiv 1 \mod 1806 = 43*7*6$. But it seems there's no reason they can't have this property, so you may have to continue your search once such a Mersenne prime is found. Expect one by the 504th instance: $504 = \phi(1806)$.


text: Q: Plupload check file size with each type before uploading In plupload i can limit file size with this setting "max_file_size : '10mb'". But I want to limit only an image type as 5mb and others are 10mb. How can I do it?


text:
Q: How to input data from keyboard with List in C# I need to write a console application which allows users input list of string as Full Name (First Name and Last Name). After that, write SortName(string[] arr) method to implement following requirements:

*

*You need to sort their Last Name in alphabet.

*If Full Name has only one word, it will be treated as Last Name

Example Input:

Tony Stark, Steve Rogers, Bruce Banner, Thor, Natasha Romanoff, Clint Barton, James Rhodes, Scott
  Lang, Doctor Strange, Carol Danvers, Peter Parker
  Output: Bruce Banner, Clint Barton, Carol Danvers, Scott Lang, Peter Parker, James Rhodes, Steve Rogers,
  Natasha Romanoff, Tony Stark, Doctor Strange, Thor

So how can I do this?

A: As it is a homework assignment, I will not show real code. Instead I will try and explain what you should do. Don't try and tackle this in one go (when everyrhing is new), just take small steps.
Iteration 1
Use Console.ReadLine() to read in one string into a string variable. Then use Console.WriteLine() to print it, maybe with some additional text like "you entered: "
Iteration 2
Now try and fill a List<string>. First create one, then in a loop ask for names and add them to the list. You can start with a simple for-loop to ask for exactly 5 names.
Iteration 3
Change this for-loop to a different type of loop so you can ask for any number of names. Keep going until the user enters a blank name (=just hit enter when asked for a name).
Iteration 4
Loop over the list to print out the names. They will come out in the order you entered - sorting will come next.
Iteration 5
Sort the list in alphabetical order and print it. This will be sorted on first name, not last name, for now.
Iteration 6
You will need to define your own sorting comparison. When you compare two names, you will need to split each name on the space and take (and compare) just the last part.


text:
Q: HttpServletRequest, csrf check for referrer header I need to add a check to see if the domain matches the referrer and completely new to csrf concepts and servlets. I would like to know if there is a way for me to validate if the referrer exists
If the referrer header is not https://[samedomain]/abc/sso?module=console, then fail. Note that the check should be very strict here. Cannot just compare using endswith "/abc/sso?module=console" since it could be bypass with https://attacker.com/abc/sso?module=console or https://[samedomain].attacker.com/abc/sso?module=console
If not fail, proceed
I am looking for the right validation with regards to code like may be need to compare the port and the server name too.  I am not looking for something overly complicated
 i have come this far ,
    String refererHeader = request.getHeader("referer");
    final String PATH = '/abc/sso?module=console',
    String host = request.getServerName();
    int port = request.getServerPort();

    String portstr="";
    if(port!=80 || port!= 443){
      portstr=":"+port;
    }

    if (refererHeader == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (refererHeader != null &&  host!== null) {
     //check if port is not the default ports, in that case construct the url

     //append with PATH and compare if the referrer header and this matches

    }

Any help would be appreciated

A: This was actually a bit harder than I thought so I thought I'd share what I came up with.  The code could be optimized - there are too many if statements but it looks like you are coming from a different language so I tried to make it fairly straight forward.  Additionally, there are probably some error conditions I missed but it should be close.
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter
public class RefererFilter implements Filter {
    private static final String PATH = "/abc/sso?module=console";
    // the domains that you will accept a referrer from
    private static final List<String> acceptableDomains = Arrays.asList("google.com", "mydomain.com");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // unused in this application
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String refererHeader = request.getHeader("referer");
        // no need to continue if the header is missing
        if (refererHeader == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // parse the given referrer
        URL refererURL = new URL(refererHeader);
        // split the host name by the '.' character (but quote that as it is a regex special char)
        String[] hostParts = refererURL.getHost().split(Pattern.quote("."));

        if (hostParts.length == 1) { // then we have something like "localhost"
            if (!acceptableDomains.contains(hostParts[0])) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
        } else if (hostParts.length >= 2) { // handle domain.tld, www.domain.tld, and net1.net2.domain.tld
            if (!acceptableDomains.contains(hostParts[hostParts.length - 2] + "." + hostParts[hostParts.length - 1])) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
        }
        // if we've gotten this far then the domain is ok, how about the path and query?
        if( !(refererURL.getPath() + "?" + refererURL.getQuery()).equals(PATH) ) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        // all tests pass - continue filter chain
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // unused in this implementation
    }
}


text:
Q: Passing values to a Go application on App Engine with Environment variables According to the docs, you just have to include them in the app.yaml file
https://cloud.google.com/appengine/docs/go/config/appconfig#Go_app_yaml_Defining_environment_variables
So I did that like this:
env_variables:
    DEVDOT_OAUTH_CLIENT_ID: 'xxxxx'
    DEVDOT_OAUTH_CLIENT_SECRET: 'xxxxxx'

But when my application runs, it doesn't get these values.  I'm running on a MVM runtime so I removed my init() function and tried calling os.Getenv() from both main() and from a handler I had assigned to the /_ah/start path.
Any ideas?

A: As how to set environment variables on google appengine? explains, "environment variables are not ready until all the init functions are run and I would say same might be applying to the global variable declaration too. It works from a function because by that time environment variables are set".
You appear to be saying otherwise -- can you try the example code at the other Q I pointed to, which was working when that Q was answered, and tell us what you observe instead?


text:
Q: I don't understand the order of methods in python I don't understand why the code uses the print_me method from Class D, and not the method in class A.
I did some testing using print-statements and can see that it reads the print_me-method of class D before initialising class A, but I don't understand why it doesn't do the same for class A.
class A:
    name = "Alfa"

    def __init__(self, foo):
        self.foo = foo
        foo = 100
        self.print_me()

    def print_me(self):
        print(self.name, self.foo)

class B(A):
    name = "Beta"

    def __init__(self, bar = 40):
        self.bar = bar
        print(self.name, bar)

class C:
    name = "Charlie"

class D(A, C):
    name = "Delta"

    def __init__(self, val):
        A.__init__(self, val)

    def print_me(self):
        print(self.name, "says", self.foo)

d = D(60)

The output is: Delta says 60
I thought it would be: Delta 60

A: Because the self you are passing to the __init__ of A is still an instance of D, not A. And the function A.__init__ is calling self.print_me, which belongs to D.
If you do a = A(); a.print_me() you'd get what you expect.
Important note: The __init__ method in python is not the actual constructor, it is just a method that is automatically called after the actual construction of the object. However, when you call it yourself, it works just like any other method.


text:
Q: Integrate $\int \frac{x^2}{(x \sin x + \cos x)^2}dx$ Integrate $$\int^{\pi/4}_{0} \frac{x^2}{(x \sin x + \cos x)^2}dx$$
How can I integrate this ?
Question asks us to re-arrange the numerator

A: If we multiply by $\cos\left(x\right)
 $ the numerator and the denominator and we integrate by parts we have that $$\begin{align}
\int_{0}^{\pi/4}\frac{x^{2}}{\left(x\sin\left(x\right)+\cos\left(x\right)\right)^{2}}dx= & \int_{0}^{\pi/4}\frac{x}{\cos\left(x\right)}\frac{x\cos\left(x\right)}{\left(x\sin\left(x\right)+\cos\left(x\right)\right)^{2}}dx \\
 = & -\frac{2\pi}{4+\pi}+\int_{0}^{\pi/4}\frac{1}{\cos^{2}\left(x\right)}dx \\ = &-\frac{2\pi}{4+\pi}+1 \\
 = & \color{red}{\frac{4-\pi}{4+\pi}.}
\end{align}$$


text:
Q: How can I stop my iMac's remote management connection from defaulting to wifi? I have two Mac computers that I connect to using Screen Sharing and when the Mac Mini's wifi is disabled I get great performance out of it. The problem that occurs is when I enable wifi on the Mac Mini and use screen sharing it appears to bypass the ethernet connection and use wifi instead to connect resulting in a slow connection. Is there any way to force the iMac to connect to my Mac Mini via ethernet instead of wifi when wifi is enabled on the Mac Mini?

A: In System Prefereces > Network set Ethernet above Wifi. That should do the trick.

A: Use the System Preferences > Network > Action (cog) menu > Set Service Order to alter the default network.
You can change the Service Order of your network connections. The order tells Mac OS X to prefer one network connection over another.
Drag your Ethernet connection above your Wi-Fi connection:


text:
Q: Selecting a specific row and column within pandas data array Hopefully this is a quick and simple one. Having looked through the entirity of the pandas.DataFrame documentation I can't quite seem to find exactly what I need. I have a DataFrame as:
           StartDate          End Date
0   10/11/2014 00:00  10/12/2014 12:00
1   12/01/2015 08:00  31/01/2015 07:59
2   15/01/2015 00:00  19/02/2015 15:43

Say, for example, I want to access the value at StartDate column index value 2...i.e, 15/01/2015 00:00 how is this achieved?

A: Use loc:
print (df.loc[2, 'StartDate'])
15/01/2015 00:00

or faster at:
print (df.at[2, 'StartDate'])
15/01/2015 00:00

In [199]: %timeit (df.loc[2, 'StartDate'])
10000 loops, best of 3: 147 µs per loop

In [200]: %timeit (df.at[2, 'StartDate'])
100000 loops, best of 3: 6.3 µs per loop

A: Try this solution:
df.loc[2, 'StartDate']


text:
Q: AutoHotkey: Similar function like ClipWait for "Select All" Does AutoHotkey have anything similar to "ClipWait" for "Ctrl+A" / "Select All".
Or is there a possibility to get such a function somehow ?

A: Would this be sufficient?
^b::
    send ^a
    selectionWait()
    msgbox, All has been selected
return

selectionWait() {
    clipboardSave := clipboardAll
    loop {
        send ^c
        if(clipboard != clipboardSave)
            if(clipboard != "")
                break
    }
    clipboard := clipboardSave
}

ctrl+c IS fired before everything is selected, but this is on purpose. the action will be repeated until the clipboard contents have changed, and the clipboard will be reset to the previous value afterwards

A: I had the same problem when selecting many rows from a network database.
The "Select All" command didn't have time to complete, hence making
Copy & ClipWait useless,
Here's the beautiful fix:
Loop
{
    Send, ^a
    Send, ^c
    ClipWait, 1
    if (!ErrorLevel)
        break
}

Or like this if you want to limit the wait to 5 seconds:
Loop, 5
{
    Send, ^a
    Send, ^c
    ClipWait, 1
    if (!ErrorLevel)
        break
}


text:
Q: I have been trying to deal with this issue for a while now, I am a newbie in shell programming, can anyone help me out? (EDITED)
I have the following code:
#!/bin/bash
exec 3< lista.csv
read -u 3 header
nota1=0
id1=0
nota2=0
id2=0
nota3=0
id3=0
g=1
while [ "$g" -eq 1 ]
do
g=0
while IFS="," read -u 3 -r id nume prenume grupa seria nota
do
if [ "$nota" -gt "$nota1" ]
then
g=1
nota3="$nota2"
id3="$id2"
nota2="$nota1"
id2="$id1"
nota1="$nota"
id1="$id"
fi
done
done
while IFS=, read -u 3 -r id nume prenume grupa seria nota
do
    if [ "$id" -eq "$id1" ]; then
echo "Nume: $nume"
echo "Prenume: $prenume"
echo "Grupa: $grupa"
echo "Seria: $seria"
echo "Nota: $nota"
echo
    fi
done
while IFS=, read -u 3 -r id nume prenume grupa seria nota
do
    if [ "$id" -eq "$id2" ]; then
echo "Nume: $nume"
echo "Prenume: $prenume"
echo "Grupa: $grupa"
echo "Seria: $seria"
echo "Nota: $nota"
echo
    fi
done
while IFS=, read -u 3 -r id nume prenume grupa seria nota
do
    if [ "$id" -eq "$id3" ]; then
echo "Nume: $nume"
echo "Prenume: $prenume"
echo "Grupa: $grupa"
echo "Seria: $seria"
echo "Nota: $nota"
echo
    fi
done

I am supposed to find the top 3 highest values of the operand 'nota' and output the whole line.I know it's not the most space and time effective way, but I don't know how else I could do it.
My csv file looks somewhat like this:
id,nume,prenume,grupa,seria,nota

1,Ion,Andrada,1003,A,8

2,Simion,Raluca,1005,A,7

3,Gheorghita,Mihail,1009,B,5

4,Mihailescu,Georgina,1002,A,6

I have applied the necessary changes proposed, but the program still doesn't seem to work. when I execute it it doesn't let me input values to read. I have seen that some of you have suggested to try it in another programming language, but in this case it is not possible.
Any ideas?

A: Assuming you only need to the 3 highest lines, you can try this head and sort
$ head -3 <(sort -t',' -nrk6 input_file)
1,Ion,Andrada,1003,A,8
2,Simion,Raluca,1005,A,7
4,Mihailescu,Georgina,1002,A,6