text:
Q: How to stop immediately a task which is started using an ExecutorService? I have tried many different ways to immediately stop a task which is started using an ExecutorService, with no luck.
Future<Void> future = executorService.submit(new Callable<Void>(
    public Void call () {
        ... do many other things here..
        if(Thread.currentThread.isInterrupted()) {
            return null;
        }
        ... do many other things here..
        if(Thread.currentThread.isInterrupted()) {
            return null;
        }
    }
));

if(flag) { // may be true and directly cancel the task
    future.cancel(true);
}

Sometimes I need to cancel the task immediately after it is started, you may be curious why I want to do this, well you may imagine a senario that a user accidentally hits the "Download" button to start a "Download Task" and he immediately wants to cancel the action because it was just an accidental click.
The problem is that after calling future.cancel(true), the task is not stopped and Thread.currentThread.isInterrupted() still returns false and I have no way to know the task was stopped from inside the call() method.
I am thinking of setting a flag like cancelled=true after calling future.cancel(true) and checking that flag constantly in the call() method, I think this is a hack and the code could be very ugly because the user can start many tasks at the same moment.
Is there a more elegant way of achieving what I want?
EDIT:
This really drives me mad. I have spent almost a day on this problem now. I will try to explain a little bit more for the problem I am facing.
I do the following to start 5 tasks, each task will start 5 threads to download a file. and then I stop all 5 tasks immediately. For all of the method calls below, i start a thread(ExecutorService.submit(task)) to make it asynchronous as you can tell from the suffixes of the methods.
int t1 = startTaskAysnc(task1);
int t2 = startTaskAysnc(task2);
int t3 = startTaskAysnc(task3);
int t4 = startTaskAysnc(task4);
int t5 = startTaskAysnc(task5);

int stopTaskAysnc(t1);
int stopTaskAysnc(t2);
int stopTaskAysnc(t3);
int stopTaskAysnc(t4);
int stopTaskAysnc(t5);

in startTaskAysnc(), I simply initiate a socket connection to remote server to get the size of the file(and this certainly is gonna take some time), after successfully getting the fileSize, I will start 5 threads to download different parts of the file. like the following(the code is simplified to make it more easy to follow):
public void startTaskAsync(DownloadTask task) {
    Future<Void> future = executorService.submit(new Callable<Void>(
        public Void call () {
            // this is a synchronous call
            int fileSize = getFileSize();
            System.out.println(Thread.currentThread.isInterrupted());
            ....
            Future<Void> futures = new Future<Void>[5];
            for (int i = 0; i < futures.length; ++i) {
                futures[i] = executorService.submit(new Callable<Void>(){...});
            }

            for (int i = 0; i < futures.length; ++i) {
                futures[i].get(); // wait for it to complete
            }
        }
    ));
    synchronized (mTaskMap) {
        mTaskMap.put(task.getId(), future);
    }
}

public void stopTaskAysnc(int taskId) {
    executorService.execute(new Runnable(){
        Future<Void> future = mTaskMap.get(taskId);
        future.cancel(true);
    });
}

I noticed a weird behavior that after I called stopTaskAsync() for all 5 tasks, there would always be at least one task that got stopped(i.e. Thread.currentThread.isInterrupted() return true), and the other 4 tasks kept running.
And I have tried your suggestions by setting an UncaughtExceptionHandler, but nothing comes out from that.
EDIT:
The problem was solved in this link: Can't stop a task which is started using ExecutorService

A: Well, the javadoc of Future.cancel(boolean) says that:

If the task has already started, then the mayInterruptIfRunning
  parameter determines whether the thread executing this task should be
  interrupted in an attempt to stop the task.

so it's quite certain that the thread that executes the task is interrupted. What could have happened is that one of the

... do many other things here..

is accidentally clearing the Thread's interrupted status without performing the desired
handling. If you'll put a breakpoint in Thread.interrupt() you might catch the criminal.
Another option I can think of is that the task terminates before capturing the interrupt, either because it's completed or thrown some uncaught exception. Call Future.get() to determine that. Anyway, as asdasd mentioned, it is a good practice to set an UncaughtExceptionHandler.

A: What you're doing is very dangerous: you're using a thread pool to execute tasks (which I'll call downloaders), and the same thread pool to execute tasks which

*

*wait for the downloaders to finish (which I'll call controllers)

*or ask the controllers to stop

This means that if the core number of threads is reached after the controller has started, the downloaders will be put in the queue of the thread pool, and the controller thread will never finish. Similarly, if the core number of threads is reached when you execute the cancelling task, this cancelling task will be put in the queue, and won't execute until some other task is finished.
You should probably use a thread pool for downloaders, another one for controllers, and the current thread to cancel the controllers.

A: I think you'll find solution here. The main point is that cancel method raises InterruptedException. Please check if your thread is still running after cancellation? Are you sure that you didn't try to interrupt finished thread? Are you sure that your thread didn't fail with any other Exception? Try to set up UncaughtExceptionHandler.


text:
Q: Handle multiple sockets in a Vue project Right now I have a Vue frontend that interacts with a single socket, using Vue-native-socket.
I need my app to listen to more than one socket, although on the documentation page of Vue-native-socket there is no information on how to implement that.
Is there any way to do this? Not necessarily with this library, I don't mind rewriting the code with another library, as long as it works.

A: This could be as simple as just connecting two sockets and setting up their respective listeners. From a quick glance, most of what vue-native-socket accomplishes (in the context of the question) can be achieved using a vuex store as well, or writing your own plugin, or both!
Here's a simple solution:
store.js
const state = {
  signalSocket: undefined,
  dataSocket: undefined
}

const getters = {
  signalSocket: state => state.signalSocket,
  dataSocket: state => state.dataSocket,
}

const mutations = {
  signalSocket (state, v) {
    state.signalSocket = v
  },
  dataSocket (state, v) {
    state.dataSocket = v
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations
})

App.vue
<template>
  ...
</template>

<script>
export default {
  computed: {
    signalSocket: {
      get () { return this.$store.getters.signalSocket },
      set (v) { this.$store.commit('signalSocket', v) }
    },
    dataSocket: {
      get () { return this.$store.getters.dataSocket },
      set (v) { this.$store.commit('dataSocket', v) }
    }
  },
  mounted () {
    this.signalSocket = new WebSocket('...')
    this.dataSocket = new WebSocket('...')
    ...
  }
}
</script>

If you want this variable to be available everywhere, much like vue-socket-native, you could add the following to your main.js
main.js
import Vue from 'vue'
import Store from './store'

Vue.use({
  install (Vue, options) {
    Object.defineProperty(Vue.prototype, '$signalSocket', {
      get () {
        return store.getters.signalSocket
      },
      set (v) {
        return store.commit('signalSocket', v)
      }
    })
    Object.defineProperty(Vue.prototype, '$dataSocket', {
      get () {
        return store.getters.dataSocket
      },
      set (v) {
        return store.commit('dataSocket', v)
      }
    })
  }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is  a good solution for including content from another website? Is <iframe> a good solution for including some portion of some site into another?
I've heard before that it is a security compromise, ain't it?
Thanks.

A: Yes there are security concerns for your users, plus that <iframe> can just bust itself and take over the entire page, redirecting from yours.  Any malware they're hosting, XSS attacks, etc. your users would be exposed to, just as if they visited the other site directly.
More than this, unless you own the content from the other site, should you really be taking their content in pieces and displaying it in your site to begin with?


text:
Q: Python multiprocessing apply_async never returns result on Windows 7 I am trying to follow a very simple multiprocessing example:
import multiprocessing as mp

def cube(x):
    return x**3

pool    = mp.Pool(processes=2)
results = [pool.apply_async(cube, args=x) for x in range(1,7)]

However, on my windows machine, I am not able to get the result (on ubuntu 12.04LTS it runs perfectly).
If I inspect results, I see the following:
[<multiprocessing.pool.ApplyResult object at 0x01FF0910>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0950>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0990>,
 <multiprocessing.pool.ApplyResult object at 0x01FF09D0>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0A10>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0A50>]

If I run results[0].ready() I always get False.
If I run results[0].get() the python interpreter freezes, waiting to get the result that never comes.
The example is as simple as it gets, so I am thinking this is a low level bug relating to the OS (I am on Windows 7). But perhaps someone else has a better idea?

A: I was running python 3 and the IDE was spyder in anaconda (windows ) and so this trick doesn't work for me. I tried a lot but couldn't make any difference. I got the reason for my problem and is the same listed by dano in his note. But after a long day of searching I got some solution and it helped me to run the same code my windows machine. This website helped me to get the solution:
http://python.6.x6.nabble.com/Multiprocessing-Pool-woes-td5047050.html
Since I  was using the python 3, I changed the program a little like this:
from types import FunctionType
import marshal

def _applicable(*args, **kwargs):
  name = kwargs['__pw_name']
  code = marshal.loads(kwargs['__pw_code'])
  gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])
  defs = marshal.loads(kwargs['__pw_defs'])
  clsr = marshal.loads(kwargs['__pw_clsr'])
  fdct = marshal.loads(kwargs['__pw_fdct'])
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  del kwargs['__pw_name']
  del kwargs['__pw_code']
  del kwargs['__pw_defs']
  del kwargs['__pw_clsr']
  del kwargs['__pw_fdct']
  return func(*args, **kwargs)

def make_applicable(f, *args, **kwargs):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  kwargs['__pw_name'] = f.__name__  # edited
  kwargs['__pw_code'] = marshal.dumps(f.__code__)   # edited
  kwargs['__pw_defs'] = marshal.dumps(f.__defaults__)  # edited
  kwargs['__pw_clsr'] = marshal.dumps(f.__closure__)  # edited
  kwargs['__pw_fdct'] = marshal.dumps(f.__dict__)   # edited
  return _applicable, args, kwargs

def _mappable(x):
  x,name,code,defs,clsr,fdct = x
  code = marshal.loads(code)
  gbls = globals() #gbls = marshal.loads(gbls)
  defs = marshal.loads(defs)
  clsr = marshal.loads(clsr)
  fdct = marshal.loads(fdct)
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  return func(x)

def make_mappable(f, iterable):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  name = f.__name__    # edited
  code = marshal.dumps(f.__code__)   # edited
  defs = marshal.dumps(f.__defaults__)  # edited
  clsr = marshal.dumps(f.__closure__)  # edited
  fdct = marshal.dumps(f.__dict__)  # edited
  return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)

After this function , the above problem code is also changed a little like this:
from multiprocessing import Pool
from poolable import make_applicable, make_mappable

def cube(x):
  return x**3

if __name__ == "__main__":
  pool    = Pool(processes=2)
  results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]
  print([result.get(timeout=10) for result in results])

And I got the output as :
[1, 8, 27, 64, 125, 216]

I am thinking that this post may be useful for some of the windows users.

A: There are a couple of mistakes here. First, you must declare the Pool inside an if __name__ == "__main__": guard when running on Windows. Second, you have to pass the args keyword argument a sequence, even if you're only passing one argument. So putting that together:
import multiprocessing as mp

def cube(x):
    return x**3

if __name__ == "__main__":
    pool    = mp.Pool(processes=2)
    results = [pool.apply_async(cube, args=(x,)) for x in range(1,7)]
    print([result.get() for result in results])

Output:
[1, 8, 27, 64, 125, 216]

Edit:
Oh, as moarningsun mentions, multiprocessing does not work well in the interactive interpreter:

Note
Functionality within this package requires that the __main__ module be
  importable by the children. This is covered in Programming guidelines
  however it is worth pointing out here. This means that some examples,
  such as the multiprocessing.Pool examples will not work in the
  interactive interpreter.

So you'll need to actually execute the code as a script to test it properly.


text:
Q: printing scrollable panel with image inside in vb Good Day everyone. i have a problem in printing the  image in my scrollable panel. can anyone help me with this?
i wanted to resize the images first (so it can fit the 8.5 by 11" paper) before showing it in print preview then printing it
in my case, i have a form(form1) with a panel (dock=fill) and i wanted to print the images (2 images) inside it. but, the trigger of the printing of image is in the next form
in btnnext(form1)
     Form2.Show()
     Me.Hide()
and the printing code is in the form2. i am new in vb and i don't have any idea about printing the scrollable panel. i tried different codes in other forums but it didn't print the whole image but only the screenshot of the form. any response will be appreciated., thank you so much

Public Class Form2

Private WithEvents pd As New Printing.PrintDocument
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    Using bmp As New Bitmap(Form1.pb1.Width, Form1.pb1.Height)
        Form1.panel1.DrawToBitmap(bmp, New Rectangle(0, 0, Form1.pb1.Width, Form1.pb1.Height))
        e.Graphics.DrawImage(bmp, e.MarginBounds)
    End Using
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    PrintDocument1.Print()
End Sub
End Class

-
^it only prints what you can see in the screen. not the whole panel..

A: Basically, keep everything the same, but instead of printing the whole first image on the whole page, and print the second image to a ratio of its location and size relative to the MarginBounds
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    Using bmp As New Bitmap(Form1.pb1.Width, Form1.pb1.Height)
        Form1.pb1.DrawToBitmap(bmp, New Rectangle(0, 0, Form1.pb1.Width, Form1.pb1.Height))
        'Print pb1 to fill the whole page
        e.Graphics.DrawImage(bmp, e.MarginBounds)
    End Using
    Using bmp2 As New Bitmap(Form1.pb2.Width, Form1.pb2.Height)
        Form1.pb2.DrawToBitmap(bmp2, New Rectangle(0, 0, Form1.pb2.Width, Form1.pb2.Height))

        Dim x as Double = Form1.pb2.Location.X - Form1.pb1.Location.X
        x = x * e.MarginBounds.Width / Form1.pb1.Width
        x = x + e.MarginBounds.X

        Dim y as Double = Form1.pb2.Location.Y - Form1.pb1.Location.Y
        y = y * e.MarginBounds.Height / Form1.pb1.Height
        y = y + e.MarginBounds.Y

        Dim width as Double = Form1.pb2.width
        width = width * e.MarginBounds.Width / Form1.pb1.Width

        Dim height as Double = Form1.pb2.Height
        height = height * e.MarginBounds.Height / Form1.pb1.Height

        e.Graphics.DrawImage(bmp2, New Rectangle(x, y, width, height))
    End Using
End Sub


text:
Q: Flutter Camera Plugin Doesn't save on DCIM Folder I've set Android permissions for read, write and camera on the manifest xml and I am able to take the picture and save it into the temporary folder but the app crashes when I switch the
CameraController.takePicture(dcimPath)

method to the DCIM(pictures) folder rather than the temporary folder. Also plugins like album_saver aren't working when I try to save from the temporary folder to the DCIM folder.
Using a plugin like image_picker is not an option since I'm trying to build a camera app


text:
Q: How to fix error when load Json from a server I want to get a JSON from a server but this error appears in the console:

You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor()

The JSON is like a list of names, for example

["leaderboard01", "leaderboard02", …]

This is my code:
public class BC_PlayerInfo : MonoBehaviour
{
    public string LeaderboardId = "";

    public BC_PlayerInfo(JsonData jsonData)
    {
        LeaderboardId = SafeGet(jsonData, "leaderboardId");
    }

    private string SafeGet(JsonData jsonData, string key)
    {
        var returnValue = "";

        try
        {
            returnValue = jsonData[key].ToString();
        }
        catch (Exception e)
        {
        }

        return returnValue;
    }
}

And...
private void GetLeaderboadsList()
{
    WebClient webClient = new WebClient();

    string result = webClient.DownloadString("https://xxxxxxxxx.com/wp-json/vendor/v1/carambolaEventsNames");

    Debug.Log("Usuario creado en la WEB: " + result);

    List<string> leaderboardIds = new List<string>();

    lblist.Clear();

    var leaderboardsList = JsonMapper.ToObject(result);

    foreach (JsonData leaderboardId in leaderboardsList) lblist.Add(new BC_PlayerInfo(leaderboardId));

    foreach (var leaderboardId in lblist)
    {
        string _leaderboardId = leaderboardId.LeaderboardId;
        Debug.Log("LeaderboardName: " + _leaderboardId);
    }
}

What am I doing wrong?

A: You can't instantiate objects that inherit from MonoBehavior, by using this line:
lblist.Add(new BC_PlayerInfo(leaderboardId));

you are creating a new instance of a Monobehavior, which is not allowed by Unity. See this post for more details: https://answers.unity.com/questions/653904/you-are-trying-to-create-a-monobehaviour-using-the-2.html
As for your solution, does this class really need to inherit from monobehavior? I would just remove that inheritance or create a separate class that does not inherit from monobehavior.


text:
Q: Android ListView/Adapter - IllegalStateException when updating ArrayList First off, I have looked around the site and could not find a solution to my question, other than "hide the ListView". This is not a viable solution in my case!
So, the problem:
I have created my own "EndlessAdapter" which allows me to populate the ArrayList<> backing the ListView with more data as the user scrolls to the bottom of the List. This all works perfectly, except for when the user selects a Row whilst the List is updating, or changes orientation whilst the List is updating (I suppose it could be any UI interactions).
I have wrapped my mAdapter.notifyDatasetChanged() method in a try catch, but I can never seem to catch this IllegalStateException, so I do not know where is it occurring!
Is there a way, whilst the Adapter is updating the ListView, that I can block the user from interacting with the application until its finished? The long part of the EndlessAdapter process is the downloading of the new data. Updating the ListView is a fast process imo.
I really need to get this issue sorted. Id rather not post up source code, but if need be I can try and post up the vitals? Otherwise I would be very appreciative if someone with experience in this could have a chat over Email or IM?
Here is the stack trace:
04-05 21:11:35.363: ERROR/AndroidRuntime(25707): java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class com.mimminito.heatdroid.view.DealsView$DealAdapter)
Here is a link to a sample of my code:
http://pastebin.com/wfmWSGwQ
I create the Adapter in the onCreate(). I then assign the Adapter to the ListView once the XML has been parsed. In the same method I call the updateList() method. This gets the data that has been downloaded, and then notifies the mAdapter that its data has been changed (all run on the UI thread)
Thanks for your time
Adam

A: You're doing both the adding to the list and the notify in the UI-thread as it says? This is the only way to guarantee that the list is not used by the UI and your other threads at the same time.


text:
Q: Finding overlapping attributes in two different layers using QGIS? I have two layers - one with country borders, and one with river basin borders - and I need to find a way to generate a list of basins that occur in each country.
Is there a way to find overlapping attributes (basins and countries) from two different layers using QGIS?

A: What you want to do is called a Spatial Join.

A common GIS task is to join the attributes from one spatial data
  layer to another. In this example we will join the attribute table
  from a polygon layer to a points layer, based on which polygon
  contains the points.

In QGIS, you can do that by using the JOIN ATTRIBUTES BY LOCATION TOOL.

You can then set your target and join vector layers.

I suggest that you set the river basins as the target vector layer and countries as the join layer. That way, your output would be a basins shapefile with the attributes of the countries shapefile. You could then generate your list from there.


text:
Q: NumPy matrix plus column vector I am using numpy.matrix. If I add a 3x3 matrix with a 1x3, or 3x1, vector, I get a 3x3 matrix back.
Should this not be undefined?
And if not, what is the explanation to this?
Example:
a = np.matrix('1 1 1; 1 1 1; 1 1 1')
b = np.matrix('1 1 1')
a + b #or a + np.transpose(b)

Output:
matrix([[2, 2, 2],
        [2, 2, 2],
        [2, 2, 2]])

A: This is called "broadcasting". From the manual:

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is "broadcast" across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation.

A: If you do wish to add a vector to a matrix, you can do so by selecting where it should go:
In [155]: ma = np.matrix(
     ...:     [[ 1.,  1.,  1.],
     ...:      [ 1.,  1.,  1.],
     ...:      [ 1.,  1.,  1.]])

In [156]: mb = np.matrix([[1,2,3]])

In [157]: ma[1] += mb # second row

In [158]: ma
Out[158]:
matrix([[ 1.,  1.,  1.],
        [ 2.,  3.,  4.],
        [ 1.,  1.,  1.]])

In [159]: ma[:,1] += mb.T # second column

In [160]: ma
Out[160]:
matrix([[ 1.,  2.,  1.],
        [ 2.,  5.,  4.],
        [ 1.,  4.,  1.]])

But I'd like to warn that you are not using numpy.matrix as stated.  In fact, you are using numpy.ndarray because np.ones returns an ndarray and not a matrix.
The adding is still the same, but create some matrices, and you'll find that they behave differently:
In [161]: ma*mb
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

ValueError: matrices are not aligned

In [162]: mb*ma
Out[162]: matrix([[ 6.,  6.,  6.]])

In [163]: ma*mb.T
Out[163]:
matrix([[ 6.],
        [ 6.],
        [ 6.]])

In [164]: aa = np.ones((3,3))

In [165]: ab = np.arange(1,4)

In [166]: aa*ab
Out[166]:
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])

In [167]: ab*aa
Out[167]:
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])


text:
Q: Could not find function "ksvm" I am just a beginner in using R. What I want is to use Support Vector Machine in R to predict/classify the status of bank. I also normalized my data already...
I divided my data into 2 parts: training and test part like this: (I have 7260 observations):
prediction1_train<-prediction1_n[1:5000, ]
prediction1_test<-prediction1_n[5001:7260, ]
prediction1_train_target<-prediction1[1:5000,7]
prediction1_test_target<-prediction1[5001:7260,7]
install.packages("e1071")

I've chosen
chooseCRANmirror()

but when I applied
model<-ksvm(STT~.,data=prediction1_train,kernel="linear",cost=10,scale=FALSE)

Error: could not find function "ksvm"

So, pleased help me and tell me what should I do.

A: ksvm() is a part of kernlab library. You need to install kernlab package before executing your code.
install.packages("kernlab")
library(kernlab)

You can find more details at this link.


text:
Q: How to read csv file from S3 bucket and create dataframe in pyspark? I am trying to read csv file from s3 and create dataframe but not getting the result. Could you please help me how to do this?
Accesskey and Secret key I am not putting here. I imported all the libraries and created spark connection.
Example:
spark = SparkSession.builder.appName("CsvReader").getOrCreate()

spark._jsc.hadoopConfiguration().set("fs.s3a.access.key", 'access_key')
spark._jsc.hadoopConfiguration().set("fs.s3a.secret.key", "secret_key")
spark._jsc.hadoopConfiguration().set("fs.s3a.impl","org.apache.hadoop.fs.s3a.S3AFileSystem")
spark._jsc.hadoopConfiguration().set("com.amazonaws.services.s3.enableV4", "true")
spark._jsc.hadoopConfiguration().set("fs.s3a.aws.credentials.provider","org.apache.hadoop.fs.s3a.BasicAWSCredentialsProvider")
spark._jsc.hadoopConfiguration().set("fs.s3a.endpoint", "eu-west-3.amazonaws.com")

df = spark.read.format('csv').options(header='true', inferSchema='true').load('s3a://itx-acm-medaff-dev-sourcefiles/hta/Inbound/RawLayer/non_onco_cell_gene/non_onco_cell_gene_20201119.csv')

Error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/spark-2.0.0-bin-hadoop2.7/python/pyspark/sql/readwriter.py", line 147, in load
    return self._df(self._jreader.load(path))
  File "/usr/local/spark-2.0.0-bin-hadoop2.7/python/lib/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 933, in __call__
  File "/usr/local/spark-2.0.0-bin-hadoop2.7/python/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/usr/local/spark-2.0.0-bin-hadoop2.7/python/lib/py4j-0.10.1-src.zip/py4j/protocol.py", line 312, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o232.load.
: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2195)
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2638)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2651)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:92)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2687)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2669)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:371)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
        at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$12.apply(DataSource.scala:352)
        at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$12.apply(DataSource.scala:350)
        at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
        at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
        at scala.collection.immutable.List.foreach(List.scala:381)
        at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
        at scala.collection.immutable.List.flatMap(List.scala:344)
        at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:350)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:149)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:132)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:280)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:211)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2101)
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2193)
        ... 28 more

A: Hi it seems you are missing the jar , if you are using the spark-submit command make sure that it is available across all nodes at the same location (it can be on hdfs / s3/ local filesystem) , if you are using the pyspark shell try to copy paste the jar in the spark jars folder (if you are using anaconda + pyspark )
that folder will be inside   ~\Anaconda3\Lib\site-packages\pyspark\jars

https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws/2.7.3

Hope this helps and solves yours issue .
PS while downloading the jar make sure it matches with the hadoop version that you have


text:
Q: Socket.io connection to server I cant seem to get the socket to connect to the server, im not getting any errors but the socket does not seem to be making a connection with the server
var request=require("request");
var server;

request({url: 'http://localhost:3000/api/designrooms'}, function (err,response, body) {
    var designroomID = JSON.parse(body)[0]._id;
    console.log(designroomID);
    server = request({url: 'http://localhost:3000/api/designrooms' + designroomID})
});

var io = require("socket.io").listen(server);

io.on('connection',function(socket){
    console.log("connected");
});

A: Try paste this into developer console (press enter) and see debug result.
localStorage.debug = '*';

A: javascript and node are asynchronous.
In your case, this line
var io = require("socket.io").listen(server);
is executed before this line :
`server = request({url: 'http://localhost:3000/api/designrooms' + designroomID})`

due to your request callback. So, your server isn't initialized.
Try to move your listener inside the request callback.


text:
Q: Horizontal view is showing, but I want it to be vertical view I am developing a windows store app using Universal Windows 8.1 framework. I know it's outdated but my project is suppose to be using this framework so can't help it.
Now the problem is that I have successfully made it horizontal for the desktop, but for the mobile I want it vertical, but it is still showing horizontal. I used gridview for horizontal and for phone listview but still no result.
Here is the xaml code
<Page
x:Class="MedicinesApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MedicinesApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"

Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
    <CollectionViewSource x:Name="FruitsCollectionViewSource" IsSourceGrouped="True"/>
    <DataTemplate x:Key="template">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding}"/>
            <TextBlock Text="{Binding ElementName=listView, Path=DataContext.Test}" Margin="20 0" />
        </StackPanel>
    </DataTemplate>
</Page.Resources>
<ListView
    ItemsSource="{Binding Source={StaticResource FruitsCollectionViewSource}}"
    x:Name="FruitGridView"
    Padding="30,20,40,0"
    SelectionMode="None"
    IsSwipeEnabled="false"
    IsItemClickEnabled="True"
    ItemClick="FruitGridView_ItemClick">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid HorizontalAlignment="Center" Width="250" Height="250">
                <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
                    <Image Source="{Binding Path=DiseaseImageSource}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
                </Border>
                <StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Disease Name" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextBlockStyle}" Height="30" Margin="15,0,15,0"/>
                        <TextBlock Text="{Binding Path=DiseaseName}" Style="{StaticResource TitleTextBlockStyle}" Height="30" Margin="15,0,15,0"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Category of Disease" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,87,10"/>
                        <TextBlock Text="{Binding Path=CategoryOfDisease}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource BaseTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
                    </StackPanel>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text='{Binding Key}' Foreground="Gray" Margin="5" FontSize="30" FontFamily="Segoe UI Light" />
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
            <GroupStyle.Panel>
                <ItemsPanelTemplate>
                    <VariableSizedWrapGrid MaximumRowsOrColumns="2" Orientation="Vertical" />
                </ItemsPanelTemplate>
            </GroupStyle.Panel>
        </GroupStyle>
    </ListView.GroupStyle>
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid GroupPadding="0,0,70,0" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

What am I missing?

A: Define both datatemplates in XAML resources (give them keys TemplateHori and TemplateVerti for example)
<Page.Resources>
<DataTemplate x:Key="TemplateHori">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding}"/>
        <TextBlock Text="{Binding ElementName=listView, Path=DataContext.Test}" Margin="20 0" />
    </StackPanel>
</DataTemplate>
<DataTemplate x:Key="TemplateVerti">
    <StackPanel Orientation="Vertical">
        <TextBlock Text="{Binding}"/>
        <TextBlock Text="{Binding ElementName=listView, Path=DataContext.Test}" Margin="20 0" />
    </StackPanel>
</DataTemplate>
</Page.Resources>

add page size changing event in constructor:
public MainPage()
{
 this.InitializeComponent();
 Window.Current.SizeChanged += Current_SizeChanged;
}

and in page size changing event compare with and height:
void Current_SizeChanged(object sender, Window.UI.Core.WindowSizeChangedEventArgs e)
{
  var b=Window.Current.Bounds;
     if (b.Width>b.Height)
        {
            FruitGridView.ItemTemplate = (DataTemplate)Resources["TemplateHori"];
        }
        else
        {
            FruitGridView.ItemTemplate = (DataTemplate)Resources["TemplateVerti"];
        }
}


text:
Q: How to write a unit test to see if a property is set to indexed=False? If I have a model like this:
class Person(ndb.Model):
  name = ndb.StringProperty()
  age = ndb.IntegerProperty(indexed=False)

How can I test if age's index is set to False?

A: All you need is:
self.assertFalse(Person.age._indexed)

without any complication.

A: properties = Person._properties
assertEqual(properties["age"], GenericProperty('age', indexed=False))

depending on what else is happening with your code, there may need to be different attributes in your assert statement.
Use Person._properties to see what you should be expecting. Alternately, you could parse just indexed=False, or just the bool from the _properties output and use a much simpler assertion that provides a much more specific test.


text:
Q: Converting nested tuple to list in elixir trying to do:
def nested_tuple_to_list(tuple) when is_tuple(tuple) do
  ...
end

expecting to get:
    iex> example = {"foo", "bar", {"foo", "bar"}}
    iex> example_as_list = nested_tuple_to_list(example)
    iex> example_as_list
    ["foo", "bar", ["foo", "bar"]]

my question is what is the best way to do this?

A: Use Tuple.to_list/1 and map the resulting list with the same function, and add a fallback clause for non-tuple inputs:
defmodule A do
  def nested_tuple_to_list(tuple) when is_tuple(tuple) do
    tuple |> Tuple.to_list |> Enum.map(&nested_tuple_to_list/1)
  end
  def nested_tuple_to_list(x), do: x
end

{"foo", "bar", {"foo", "bar"}} |> A.nested_tuple_to_list |> IO.inspect

Output:
["foo", "bar", ["foo", "bar"]]

If you want to transform tuples inside lists as well, you can add:
def nested_tuple_to_list(list) when is_list(list) do
  list |> Enum.map(&nested_tuple_to_list/1)
end

This can be easily extended to handle Maps as well.

A: There is a library that can do this and many other transforms of nested data.
iex(1)> h PhStTransform.transform

        def transform(data_structure, function_map, depth \\ [])

uses the given function_map to transform any Elixir data structure.
function_map should contain keys that correspond to the data types to be
transformed. Each key must map to a function that takes that data   type and optionally the depth list as arguments.
depth should always be left at the default value since it is meant for internal recursion.
Examples
iex> atom_to_string_potion = %{ Atom => fn(atom) -> Atom.to_string(atom) end }
iex> PhStTransform.transform([[:a], :b, {:c, :e}], atom_to_string_potion)
[["a"], "b", {"c", "e"}]

iex> foo = {"foo", "bar", {"foo", "bar"}}
{"foo", "bar", {"foo", "bar"}}

iex> PhStTransform.transform(foo, %{Tuple => fn(tuple) -> Tuple.to_list(tuple) end})
["foo", "bar", ["foo", "bar"]]

https://hex.pm/packages/phst_transform


text: Q: Chromium infinitely loading extensions? I just recently updated my raspberry pi 2 model b using the command sudo apt-get update && sudo apt-get upgrade shortly after, I opened up chromium to do something, and it came up with the "Aw, snap!" Page. Along with it came a box in the upper right corner of my monitor, which said something about an extension having crashed. This extension I have on other devices, but have never put it on this device. Anyway I was just wondering if there was some way to remove this extension without opening up chromium? Thanks for the help, and my apologies for being such a noob :)


text:
Q: Handling generic types extending non-generic base For PLC (Programmable Logic Controller) communication I have an abstract class PlcValueAbstract and extending generic class PlcValue<T>. I have these classes so I can specify what to read (T) but to leave the read implementation up to the class doing PLC communication / interop. I need the ability to read multiple of these at the same time, that's where the PlcValueAbstract comes in.
Right now I have a method ReadMultiple(IDictionary<string, PlcValueAbstract> values) which will read values from registers (PLC) into the paired PlcValueAbstract. To achieve this, I check if the PlcValueAbstract is either PlcValue<int> or PlcValue<short> (will be extended to more types) and handle byte[] to PlcValue<> conversion (IPAddress.NetworkToHostOrder(BitConverver.ToInt32(bytesFromLibrary))). However, now my code becomes cluttered with type checks (and exceptions) for every (different) method invocation which uses type T on PlcValue<T>.
Unfortunately I can't rely on conversion from byte[] to T either, because we use different brands of PLC's with different register sizes (or API types) and different endianness, so I can't constrain any of my PlcValue<T> code to support byte[] only.
I have a gut feeling that I'm overcomplicating the issue and thus having to do split type implementations for every supported generic type, which is really cumbersome. Is there a solution where I can move all the type mumbo-jumbo to just a few methods?
On request here's part of the implementation:
PlcValueAbstract:
public abstract class PlcValueAbstract
{
    internal PlcValueAbstract()
    {
    }

    public abstract Type GetUnderlyingType();
}

PlcValue:
public class PlcValue<T> : PlcValueAbstract
{
    public PlcValue(T value)
    {
        this.Value = value;
    }

    public T Value
    {
        get;
        set;
    }

    public override Type GetUnderlyingType()
    {
        return typeof(T);
    }
}

SiemensPlc:
public class SiemensPlc
{
    public void WriteMultiple(IDictionary<string, PlcValueAbstract> data)
    {
        IDictionary<string, byte[]> plcData = data.Select(e => BuildWrite(e.Key, e.Value))
            .ToDictionary(x => x.Key, x => x.Value);
        return library.Write(plcData);
    }

    public void Read(IDictionary<string, PlcValueAbstract> data)
    {
        byte[][] response = library.Read(data.Keys);
        PlcValueAbstract[] values = data.Values.ToArray();

        for (int i = 0; i < response.Length; i++)
        {
            byte[] res = response[i];
            PlcValueAbstract pv = values[i];

            if (pv is PlcValue<int>)
            {
                PlcValue<int> v = (PlcValue<int>)pv;
                v.Value = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(res, 0));
            }
            else if (pv is PlcValue<short>)
            {
                PlcValue<short> v = (PlcValue<short>)pv;
                v.Value = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(res, 0));
            }
            else
            {
                throw new Exception("Invalid type");
            }
        }
    }

    private KeyValuePair<string, byte[]> BuildWrite(string address, PlcValueAbstract value)
    {
        byte[] data;
        if (value is PlcValue<int>)
        {
            data = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(((PlcValue<int>)value).Value));
        }
        else if (value is PlcValue<short>)
        {
            data = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(((PlcValue<short>)value).Value));
        }
        else
        {
            throw new ArgumentException("Value type is not supported", "value");
        }

        return new KeyValuePair<string, byte[]>(address, data);
    }

The above code is a bit of a simplification, the actual code also handles address specification for the different data types.

A: My thinking is that something like this should work:
public abstract class PlcValueAbstract
{
    internal PlcValueAbstract()
    {
    }

    public abstract Type GetUnderlyingType();
    public abstract SetValue(byte[] bytes);
}

public class PlcValueInt : PlcValue<int>
{
    public override SetValue(byte[] bytes)
    {
        Value = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 0));
    }
}

I've made the generic class abstract (not shown) and then there is a setValue method on the base abstract class that takes a byte array and its job is to set the value.
You then derive your concrete classes from this, one for each type you need, and that just needs to implement the one method to parse your result into the value.
Then your problem code will just look like:
for (int i = 0; i < response.Length; i++)
   {
       byte[] res = response[i];
       PlcValueAbstract pv = values[i];
    pv.SetValue(res);

}
This code has not been tested or compiled but the principles should be sound, even if it needs a bit of tweaking to get it working.
You are essentially shuffling your type check code around, removing the need for checking what the type is in favour of having a class declaration for each of your datatypes.
The main reason this works is because the method signature for SetValue doesn't need to know what the underlying type is, it just needs to take a certain input and then does whatever it wants internally so it can easily be called without knowing anything more.

A: It looks as though what you need may be to define an IPlcValue interface which contains members to find an item's underlying type, as well as to convert that type to or from a series of bytes [the routine to convert from a series of bytes could be written to use a stream, or could accept an array of bytes along the length of the valid portion of the array and a nextOffset value, the latter being passed as a ref int].  In addition to that, one should define an IPlcValue<T> interface which contains a Value member of type T.  Once one has done those things, one could define class(es) PlcIntegerMsbFirst and/or PlcIntegerLsbFirst which would implement IPlcValue<int>, a PlcString which implements IPlcValue<String> [if any PLCs use strings], etc.  Code which has a collection of IPlcValue items could convert them all to or from a sequence of bytes without having to know about their underlying types; code which knows that something should be a number could access it as IPlcValue<int> without having to know whether it was stored MSB-first or LSB-first, etc.

A: I finally spent some time and thought on this issue and came up with a solution. I added an IntermediateReadResult abstract class that is passed on to the PlcValueContainerBase (PlcValueAbstract in the original question), which in turn will pass it to PlcValueContainer<T> (PlcValue<T> in the original question), which will tell the IntermediateReadResult that it wants to perform an Action with a value of type T. The IntermediateReadResult in turn passes this on to some implementation in the implementation class (MitsubishiIntermediateReadResult in the example below) that will actually do the value conversion. A similar approach is taking for performing the writes. There is some small discrepancy between reads and writes in that for a read of multiple data objects I build one IntermediateReadResult for every data container, while for writes I have only one IntermediateWriteData. This is not clearly visible from the small example below, but can be figured because only the type is passed (as generic argument) onto the Apply<TValue> method.
The effect of the explained structure is that now I can have the following set of implementation classes for a PLC type to implement data reading and writing using PlcValueContainers:

*

*BrandDataConverter

*BrandIntermediateReadResult

*BrandIntermediateWriteData

*BrandPlc
There might be additional classes necessary depending on the PLC supplier's API, but those are always required of course. All the Brand classes live in their own BrandPlc assembly so I don't create dependencies on all PLC brands if I need only one (or two). I also have some wrapping code and an abstract PLC class to hide internal API from consumer classes (I don't want the consumers to apply some CustomIntermediateReadResult by accident), but other than that the following code example covers most of what is required:
public abstract class PlcValueContainerBase
{
    ...

    internal abstract void ApplyReadResult(IntermediateReadResult intermediateReadResult);

    internal abstract void ContributeWrite(IntermediateWriteData intermediateWriteData);

    ...
}

public class PlcValueContainer<TValue> : PlcValueContainerBase
{
    public TValue Value { get; set; }

    internal override void ApplyReadResult(IntermediateReadResult intermediateReadResult)
    {
        intermediateReadResult.Apply<TValue>(value => Value = value);
    }

    internal override void ContributeWrite(IntermediateWriteData intermediateWriteData)
    {
        intermediateWriteData.Append(Address, Value, Length);
    }
}

public abstract class IntermediateReadResult
{
    protected internal abstract void Apply<TValue>(Action<TValue> valueAction);
}

class MitsubishiIntermediateReadResult : IntermediateReadResult
{
    private readonly short[] data;

    public MitsubishiIntermediateReadResult(short[] data)
    {
        this.data = data;
    }

    protected override void Apply<TValue>(Action<TValue> valueAction)
    {
        valueAction(MitsubishiDataConverter.ConvertFromPlc<TValue>(data));
    }
}


text:
Q: Null in relationship belongs to in laravel? I have table products and job_statuses and there is a relation between them in migration products:
$table->unsignedBigInteger('job_status_id')->index()->nullable();
$table->foreign('job_status_id')->references('id')->on('job_statuses')->onDelete('set null');

In Product model:
public function job()
{
    return $this->belongsTo(JobStatus::class);
}

in blade dd :
 @foreach ($products as $product)

     @dd($product->job)

 @endforeach

I got null
The weird thing that when I do the same way but in tinker the relation is worked!

A: you have to pass the foreign key in relationship. by default laravel assumes the foreign key as relationname_primarykey of related table. in your case the relationship name is job but the foreign key is job_status_id. so the relationship is not biulding. change like
public function job()
{
    return $this->belongsTo(JobStatus::class, 'job_status_id');
}

and a note. as you are using nullable you should check for relationship existence first.


text:
Q: python C-extension setup failed with "unable to find vscvarsall.bat" on windows-7 On my windows-7, when I wanted to build a C-extension using "distutils", it failed with "unable to find vscvarsall.bat". A little bit web search told me that I may need Visual Studio 2008. I confirmed that indeed, my python2.7 was compiled by Visual Studio 2008 (MSC v. 1500). Now I have 2 questions:

*

*Do I really need to install VS 2008 to get my C-extension built by "distutils"?

*If this is true, since VS is an expensive commercial package, does this limit python application development? Why has python-windows not been compiled by free compiler, eg MINGW?

A: Since you have a C-extension you will need to compile all C Extensions to be used by your python installation using the same version of the C compiler used to build the python executable from the source. Hence, the answer to your first question is yes - you will need VS 2008 to build the C-extension.
About the second query - please refer here to understand how to setup MinGW with Python 2.7.2. This example uses Windows XP, however I guess it should work on Win 7 as well provided the correct paths have been provided.
Hope this helps


text:
Q: Weird escape sequence I need to identify what this escape sequences represents. I see this sequence is autogenerating on my server's console, but I'm not sure what is the reason for that.
Escape sequence:
^[[[D
I've checked this chart of escape sequences as reference: http://ascii-table.com/ansi-escape-sequences-vt-100.php , but haven't found anything matching.

A: NOTE: This is as I understand things, so it might be a bit off!
The characters ^[ typically signifies the Escape key itself. That's a Control (^) + a open square bracket ([).
excerpt from Escape characters - ASCII escape character

The ASCII "escape" character (octal: \033, hexadecimal: \x1B, or ^[, or, in decimal, 27) is used in many output devices to start a series of characters called a control sequence or escape sequence. Typically, the escape character was sent first in such a sequence to alert the device that the following characters were to be interpreted as a control sequence rather than as plain characters, then one or more characters would follow to specify some detailed action, after which the device would go back to interpreting characters normally. For example, the sequence of ^[, followed by the printable characters [2;10H, would cause a DEC VT102 terminal to move its cursor to the 10th cell of the 2nd line of the screen. This was later developed to ANSI escape codes covered by the ANSI X3.64 standard. The escape character also starts each command sequence in the Hewlett Packard Printer Command Language.

On systems where you're using UTF-8 this escape sequence is actually 2 characters, so it's now ^[ followed by an additional [.
excerpt from ANSI escape code - Sequence Elements

There is a single-character CSI (155/0x9B/0233) as well. The ESC+[ two-character sequence is more often used than the single-character alternative, for details see C0 and C1 control codes. Only the two-character sequence is recognized by devices that support just ASCII (7-bit bytes) or devices that support 8-bit bytes but use the 0x80–0x9F control character range for other purposes. On terminals that use UTF-8 encoding, both forms take 2 bytes (CSI in UTF-8 is 0xC2, 0x9B)[discuss] but the ESC+[ sequence is clearer.

Knowing the above 2 pieces of information this would make your escape sequence Esc+[+D which works out to be, big surprise, the backspace character.
excerpt from ANSI Escape sequences
Esc[ValueD     Cursor Backward: Moves the cursor back by the specified
               number of columns without changing lines. If the cursor is
               already in the leftmost column, ANSI.SYS ignores this
               sequence.

References

*

*Esc Key

*End-of-transmission character

*Control Characters

*Escape Characters

*ANSI escape code

*ANSI Escape sequences - (ANSI Escape codes)

A: This sounds like a bad copy paste into a shell profile script.
As @slm indicated, ' ^[ + [ ' is the usual escape sequence, but you're saying you have '^[ + [ + ['. When I look through my terminal emulator's escape codes, I don't see any codes which are ESC followed by 2 brackets.
Since an ESC is a non-printable character, it is often represented in text editors as ^[. I'm guessing someone was editing a profile script which had this escape code, and tried to copy/paste it onto another system. But they copied the visual representation of ESC (^[) instead of the ESC itself.
However this would result in just seeing ^[[D, not ^[[[D. For this, maybe the copy/paste was done by typing it instead, and it's a typo.
In any case, to fix this, you'll need to find the profile script which has this and fix it. If using bash, try the following:
fgrep -r '[[[' /etc/bashrc /etc/bashrc.d /etc/bash_profile /etc/profile /etc/profile.d ~/.profile ~/.bashrc ~/.bash_profile

Once you've found it, it's easy to fix. In the vi editor, just delete the ^[[ characters and in insert mode do Ctrl + v then ESC. This will insert a literal ESC character.


text:
Q: FRC Java Mecanum Drive I am the programmer for my FRC Team 4468 and we are using mecanum wheels this year. We are trying to control the robot with two joysticks, one for moving in a direction (mecStick), and another for rotation (rotStick) using this line of code.
 myDrive.mecanumDrive_Cartesian(mecStick.getX(), mecStick.getX(), rotStick.getY(), 0);

The robot will move in the Y direction (fowards, backwards), and will rotate but won't move in the X axis. Could someone tell me what i'm doing wrong please.
Thanks :-)
public class RobotTemplate extends SimpleRobot {

RobotDrive myDrive = new RobotDrive(1,2,3,4);
Joystick mecStick = new Joystick(1);
Joystick rotStick = new Joystick(2);

public void robotInit() {

}

public void autonomous() {

}

public void operatorControl() {

    //myDrive.setSafetyEnabled(true);

    myDrive.mecanumDrive_Cartesian(mecStick.getX(), mecStick.getX(), rotStick.getY(), 0);

    Timer.delay(0.01);

   }

}

A: Looks like you pass mecStick.getX() twice, one should probably be mecStick.getY(). I'm not familiar with the RobotDrive class, so I'm not sure which should be switched. The WPILib Javadoc is your friend, you can find a copy hosted by team 2168 at http://team2168.org/javadoc/. Look for RobotDrive on the left bottom list, and check there.
Best of luck from 1902, Exploding Bacon!


text:
Q: Use OR in Regex Expression I have a regex to match the following:
somedomain.com/services/something

Basically I need to ensure that /services is present.
The regex I am using and which is working is:
\/services*

But I need to match /services OR /servicos. I tried the following:
(\/services|\/servicos)*

But this shows 24 matches?! https://regex101.com/r/jvB1lr/1
How to create this regex?

A: The (\/services|\/servicos)* matches 0+ occurrences of /services or /servicos, and that means it can match an empty string anywhere inside the input string.
You can group the alternatives like /(services|servicos) and remove the * quantifier, but for this case, it is much better to use a character class [oe] as the strings only differ in 1 char.
You want to use  the following pattern:
/servic[eo]s

See the regex demo
To make sure you match a whole subpart, you may append (?:/|$) at the pattern end, /servic[eo]s(?:/|$).
In C#, you may use Regex.IsMatch with the pattern to see if there is a match in a string:
var isFound = Regex.IsMatch(s, @"/servic[eo]s(?:/|$)");

Note that you do not need to escape / in a .NET regex as it is not a special regex metacharacter.
Pattern details

*

*/ - a /

*servic[eo]s - services or servicos

*(?:/|$) - / or end of string.

A: Well the * quantifier means zero or more, so that is the problem. Remove that and it should work fine:
(\/services|\/servicos)

Keep in mind that in your example, you have a typo in the URL so it will correctly not match anything as it stands.
Here is an example with the typo in the URL fixed, so it shows 1 match as expected.

A: First off you specify C# (really .Net is the library which holds regex not the language) in this post but regex101 in your example is set to PHP. That is providing you with invalid information such as needed to escape a forward slash / with \/ which is unnecessary in .Net regular expressions. The regex language is the same but there are different tools which behave differently and php is not like .Net regex.

Secondly the star * on the ( ) is saying that there may be nothing in the parenthesis and your match is getting null nothing matches on every word.

Thirdly one does not need to split the whole word. I would just extract the commonality in the words into a set [ ]. That will allow the "or-ness" you need to match on either services or servicos. Such as
(/servic[oe]s)
Will inform you if services are found or not. Nothing else is needed.


text:
Q: Find the Fourier series S(t) of the period 2$\pi$ Find the Fourier series S(t) of the period $2\pi$ function
$f(t)=\begin{cases}
-1& \text{if −$\pi$ < t < 0;}\\
\;\;1& \text{if $\:$0 < t < $\pi$;}\\
\;\;0&\text{if $t = −\pi, 0, or \;\pi$ }
\end{cases}$
Use MATHEMATICA to graph partial sums $S_N(t)$ of the Fourier series for f(x) with
N = 3, 6, 12, 24. What do you notice? Depending on the correctness of your $S_N(t)$, your graphs should portray what is known as Gibbs's phenomenon.
For Fourier sine coefficients $b_n$ of the square wave, I get:
$b_n =\frac{2}{\pi} \int\limits_0^\pi$sin nx dx = $\frac{2}{\pi}[\frac{-cos\; nx}{n}] x = 0$ to $\pi$
$\frac{cos n\pi}{n}=\begin{cases}
0& \text{if n is even}\\
\frac{4}{n\pi}& \text{if n is odd}
\end{cases}$
Thus for n = 1, 2, 3, 4, 5...
I get:
{$\frac{4}{\pi},0,\frac{4}{3\pi}, 0, ... $}
I have difficulty in partial graphing sums. I need some help.

A: You are not summing the coefficients, but rather the sine series having these coefficients.  Thus you want the graphs of
$$\frac{4}{\pi} \sin{x} + \frac{4}{3 \pi} \sin{3 x} + \cdots + \frac{4}{(2 N+1) \pi} \sin{(2 N+1) x}$$
over $x \in [-\pi,\pi]$ for various values of $N$.


text:
Q: Symfony Heroku crashed app H10 I upload symfony application witjout error, begin call heroku run bash, check validate db and run doctrine:schema:update --force and check doctrine:schema:validate everything ok, but when open app heve error
check log and see this
2016-12-04T16:28:54.236638+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=academy-lern.herokuapp.com request_id=449cbb19-d0d8-49da-aba7-bed4b9483a61 fwd="176.241.128.140" dyno= connect= service= status=503 bytes=

I enter to heroku run bash and open parameters yml everything ok, paraeters for my addons add
this my log
2016-12-04T17:09:11.123385+00:00 heroku[web.1]: State changed from crashed to starting
2016-12-04T17:09:14.402866+00:00 heroku[web.1]: Starting process with command `vendor/bin/heroku-php-apache2 web/`
2016-12-04T17:09:16.514245+00:00 heroku[web.1]: Process exited with status 127
2016-12-04T17:09:16.528905+00:00 heroku[web.1]: State changed from starting to crashed
2016-12-04T17:09:16.448703+00:00 app[web.1]: bash: vendor/bin/heroku-php-apache2: No such file or directory

I have ProcFile
echo "web: vendor/bin/heroku-php-apache2 web/" > Procfile

what I'am doing wrong ?

A: In symfony > 3 dir bid created in vendor in old version in roo app
so for version > 3.0
vendor/bin/heroku-php-apache2 web/

for < 3.0
bin/heroku-php-apache2 web/


text:
Q: Bitmap Image from Hex string - extra bytes being added I have a Hex string that's coming from postscript file.
<< /ImageType 1
/Width 986 /Height 1
/BitsPerComponent 8
/Decode [0 1 0 1 0 1]
/ImageMatrix [986 0 0 -1 0 1]
/DataSource <
803fe0503824160d0784426150b864361d0f8844625138a4562d178c466351b8e4763d1f904864523924964d27944a6552b964b65d2f984c665339a4d66d379c4e6753b9e4f67d3fa05068543a25168d47a4526954ba648202
> /LZWDecode filter >> image } def

Below are the methods that I am using. I have commented out the method for updating color.
public static void ProcessImageColourMapping()
{
    string imageDataSource = "803fe0503824160d0784426150b864361d0f8844625138a4562d178c466351b8e4763d1f904864523924964d27944a6552b964b65d2f984c665339a4d66d379c4e6753b9e4f67d3fa05068543a25168d47a4526954ba648202";
    string imageDataSourceUpdated = GetUpdatedImage(imageDataSource);
}

public static string GetUpdatedImage(string strImageDataSource)
{
    string imageDataSourceUpdated = "";

    byte[] imageBytes = StringToByteArray(strImageDataSource);
    Bitmap bitmapImage = ByteArrayToBitmap(imageBytes);
    //UpdateColour(bitmapImage);
    byte[] imageBytesUpdated = BitmapToByteArray(bitmapImage);
    imageDataSourceUpdated = ByteArrayToString(imageBytesUpdated);

    return imageDataSourceUpdated;
}

public static byte[] StringToByteArray(String imageHexString)
{
    int numberOfChars = imageHexString.Length / 2;
    byte[] byteArray = new byte[numberOfChars];
    using (var sr = new StringReader(imageHexString))
    {
        for (int i = 0; i < numberOfChars; i++)
            byteArray[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
    }
    return byteArray;
}

public static Bitmap ByteArrayToBitmap(byte[] byteArray)
{
    int width = 986; //width and height are taken from postscript file for testing a single hex string.
    int height = 1;
    Bitmap bitmapImage = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
    BitmapData bmpData = bitmapImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
    try
    {
        Marshal.Copy(byteArray, 0, bmpData.Scan0, byteArray.Length);
    }
    finally
    {
        bitmapImage.UnlockBits(bmpData);
    }
    return bitmapImage;
}

public static byte[] BitmapToByteArray(Bitmap bitmap)
{
    BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
    int numbytes = bmpdata.Stride * bitmap.Height;
    byte[] bytedata = new byte[numbytes];
    try
    {
        Marshal.Copy(bmpdata.Scan0, bytedata, 0, numbytes);
    }
    finally
    {
        bitmap.UnlockBits(bmpdata);
    }
    return bytedata;
}

public static string ByteArrayToString(byte[] byteArray)
{
    StringBuilder hex = new StringBuilder(byteArray.Length * 2);
    foreach (byte b in byteArray)
    {
        hex.AppendFormat("{0:x2}", b);
    }
    return hex.ToString();
}

Issue:
In below code, I am not updating anything for incoming Hex string imageDataSource.
Converting it to byte[] - then to Bitmap - Back to byte[] - and finally back to Hex string.
So, imageDataSourceUpdated should have same value as imageDataSource.
However, when I finally check the value for imageDataSourceUpdated, it comes out as:
803fe0503824160d0784426150b864361d0f8844625138a4562d178c466351b8e4763d1f904864523924964d27944a6552b964b65d2f984c665339a4d66d379c4e6753b9e4f67d3fa05068543a25168d47a4526954ba64820200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.....
So many zeros being appended.
Can please guide what I am missing here.

A: You are passing some input string, but the width of the image (and so 1/4 of the size of the byte array) is set to 986 in your sample, which would yield the behaviour you observe - you're not actually passing 986 * 4 bytes of data, but the Bitmap does have that many. So you'll get the first X bytes you actually copied to the bitmap, and then all zeros. In other words, it seems your issue is with your sample data, not with the methods themselves - those work just fine.


text:
Q: How to properly reorder the raster data from bottom up to top down? When creating a raster I set the lower-left x/y values, and asc file has the following "header":
ncols        1731
nrows        1863
xllcorner    17548488.944545675069
yllcorner    -8069349.376163828187
dx           500.162987955558
dy           500.081943659035

Note that the raster data is going from bottom to top.
However, now it seems that I need to reorder the raster data so that my raster data will appear from top to bottom, instead of bottom to top. In the above case, I want the dy to assume negative value.
Is there any built-in function for this?
I could have reorder it manually:
   using (var ds = Gdal.Open(demInputTiff, Access.GA_Update))
    {
        var nCol = ds.RasterXSize;
        var nRow = ds.RasterYSize;
        double[] geoTransform = new double[6];
        ds.GetGeoTransform(geoTransform);

        if (geoTransform[5] < 0)
            return; //no need transformation

        geoTransform[3] += geoTransform[5] * (nRow -1);
        geoTransform[5] *= -1;

        ds.SetGeoTransform(geoTransform);

        Band band = ds.GetRasterBand(1);
        var allValues = new int[nCol * nRow];
        var noData = band.NoDataValue();
        band.ReadRaster(0, 0, nCol, nRow, allValues, nCol, nRow, 0, 0);

        //manual reordering, crude way of iterating through the array
        var allValues2 = new int[nCol * nRow];
        for (int i = 0; i < nRow; i++)
        {
            for (int j = 0; j < nCol; j++)
            {
                allValues2[(nRow - i - 1) * nCol + j] = allValues[i * nCol + j];
            }
        }

        band.WriteRaster(0, 0, nCol, nRow, allValues2, nCol, nRow, 0, 0);

        ds.FlushCache();
    }

But I'm pretty sure that this is not the most efficient way of doing things, both memory and speed wise. There is also an issue of whether .Net array can hold that big the array size or not.
Is there a built-in function for this?


text:
Q: TS5023: Unknown compiler option 'preserveWhitespaces' I followed the angular 5 to 6 migration guide (https://update.angular.io/).
One of the things it tells you to do is to set compiler option called preserveWhitespaces
I did it for both main tsconfig.json as well as tsconfig.app.json and both throw TS5023: Unknown compiler option 'preserveWhitespaces'. during the compilation.


text:
Q: Wordpress autopoulate menu with woocommerce categories I need to autopopulate my main navigarion menu with not empty woocommerce categories
$non_empty_categories = get_categories(array('taxonomy' => 'product_cat'));
I have maximally 2-deep subcategories under each category.
I am using Max Mega Menu plugin for this (Screenshot) and I just need to automatically populate this menu, manualy is just too much work for future (categories will change often).
Code snippet, or working plugin should be the best for this.
PS: JS Submenu plugin did NOT worked for me.
Thanks for helping me


text:
Q: How to send firebase web app user verification email to admin panel for review I am developing website using firebase services. It is a website for a club. This website is not for everyone. Only club members should have access to the files and other members' data. So if a user has signed up in this website and requested the verification email, I need to send that email to Admin panel email not to the user. Then they can review the request by contacting the user and forward the email after confirmation. Is there any way I can do this?
Creating user account for all the members and giving access is not very easy and practical (But possible) in this situation because this club is 50+ years old and there are more than 5000 members are available also they all are working in different countries. So we can't create every single user account and we can't let unauthorized people accessing the data.

A: It's important to keep the individual actions/steps separate in your use-case:

*

*authentication
The user signs-in to Firebase Authentication to your app. This validates that the credentials the user enters, are what Firebase Authentication (or the social identity provider) has stored for that user. This does nothing more than allowing me to prove that I am Frank, and makes it "impossible" for any other user of your app to prove that.

*email verification
Since many authentication mechanisms are based on a combination of email address and a password, it can be crucial to know that the email address was entered correctly. Through Firebase Authentication's email verification mechanism, you can ensure that the user has access to the email address they entered.

*authorization
Based on an authenticated user, you can grant access to other resources within your app. This is beyond the scope of Firebase Authentication though, and depends on those other resources.
For example, if you use the Firebase Realtime Database or Cloud Firestore, you'd use the security rules of those databases to ensure all data access is authorized. A simple example of only allowing gmail users access to data in the Realtime Database, can be found in my answer to this question: How do I lock down Firebase Database to any user from a specific (email) domain?. If you have a custom domain for all users that you want to allow, this approach would be it unnecessary to validate all of them by hand: you can just allow all verified email addresses from your custom domain.
If your specific scenario allows users to enter any domain, you'll typically have a predefined list of email addresses. In that case, consider storing that list in the database, and verifying against that in your security rules. An example of that for Cloud Firestore can be found in my answer to this question: Prevent user account creation with sign in by email in firestore


text:
Q: How can i store a lot of images in asp.net I have a lot of images (more than 8TB, and they become more every day) and I want to organize them in groups in asp.net
In fact I want to create an archive program for my images.
How can I store them in different HDD?

A: You can make a configraton that makes each group Read from defirent path for example

If you have 8 HD each one 2 TB you will have 8 paths and you can map them for 8 groups or more

Group 1 >> D:\images

Group 1 >> E:\images

Group 1 >> F:\images


text:
Q: How to check for 2 different format in a column using pandas to_datetime func? I want to format a column with 2 different datetime format using to_datetime
...
28            4/30/2016 22:51
29            4/30/2016 22:48
...
3595353    10/1/2016 00:11:02
3595354    10/1/2016 00:10:13
...

In order to read the CSV File i used bike_df = pd.read_csv('Bike_Trips.csv')
The two format is then defined for to_datetime frmt1 = '%m/%d/%Y %H:%M' and frmt2 = '%m/%d/%Y %I:%M:%S'
I then attempted to convert two different format by running these two code in succession
bike_df['starttime'] = pd.to_datetime(bike_df['starttime'], format = frmt1, errors = 'coerce')
bike_df['starttime'] = pd.to_datetime(bike_df['starttime'], format = frmt2, errors = 'coerce')

However when errors = 'coerce' is used the datetime changes but NaT is used as the format is different
29        2016-04-30 22:48:00
                  ...
3595353                   NaT

however, when error = 'ignored' is used nothing changes
29            4/30/2016 22:48
                  ...
3595353    10/1/2016 00:11:02

Am I doing something wrong here?

A: You have several problems with your code:

*

*The value of errors parameter can be raise, coerce or ignore (not ignored otherwise raise is used)

*The frmt2 is incorrect because contains %I for hours which should start from 01, not 00 as in your sample.

However fixing above does not give working solution.
But is not that OK for you to use pandas builtin functionality to parse datetimes?
bike_df['starttime'] = pd.to_datetime(bike_df['starttime'],
                                      infer_datetime_format=True)

where infer_datetime_format turns on guessing of format based on input data
~~~ UPDATE ~~~
I see the way to recognize using two different formats like this (note that I have tested it on 4 fake entries):
# 1) create new column temp_starttime
# and store there datetimes recognized using first format
bike_df['temp_starttime'] = pd.to_datetime(bike_df['starttime'], format=frmt1, errors='coerce')
# 2) get not recognized rows
not_recongized = bike_df[bike_df.temp_starttime.isnull()]
# 3) inplace fill not recognized rows with values recognized using second format
bike_df['temp_starttime'].fillna(pnd.to_datetime(not_recongized['starttime'], format=frmt2, errors='coerce'), inplace=True)
# 4) delete starttime column
del bike_df['starttime']
# 5) inplace rename temp_starttime to starttime
bike_df.rename(columns={"temp_starttime": "starttime"}, inplace=True)


text:
Q: Installing .NET application on IIS 7.5 issues I am trying to install a webservice that some other guy wrote in .NET. I have some basic IIS understanding. The webservice works just fine on my dev computer, but when I try to move the webservice to a production server, bad things happens.
The webservice is located at C:\inetpub\wwwroot\ on the dev server. But on this production server it is to be located at D:\services\.
I have managed to install an application on the production server and everything seems fine and dandy. But when I Test Settings in the initial setup, I get an Invalid application path error. I can just close it down and still install it, but then when I try to access the webservice (at http://myserver.com/webservice/GetData) nothing happens. Just a blank page, and when I check the response headers, there's a 500 error.
I don´t know what is going on here or where the problem is. Here's the config file here so someone might notice something odd.
EDIT: The config file is from my dev server. I just copied it to my production server...but that obviously didn't work :-)
UPDATE: I noticed that my dev server run in an Application pool with Net 4 and in "classic" "mode". On the production server it was in NET 4 but in "integrated" mode. So i changed it to "classic". I still get a blank page. But checking the log will output this:

2012-10-03 14:57:00 ip removed GET /boo/GetData - 80 - ip removed Mozilla/5.0+(Windows+NT+6.1;+WOW64;+rv:15.0)+Gecko/20100101+Firefox/15.0.1 404 2 1260 203

UPDATE 2: Thank you guys for your help. Your comments helped what to look for. After a lot of log looking, and rights management I found this Microsoft KB.
After checking ISAPI and CGI Restrictions on server level i found out that .NET 4 and .NET 4 64 was not allowed. After allowing both, FINALLY my webservice started to talk.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
    <identity impersonate="true" />
    <!-- Impersonate NT AUTHORITY/IUSR -->
    <compilation targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b7735c561131e089" />
      </assemblies>
    </compilation>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <httpErrors existingResponse="PassThrough" />
    <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
        <directoryBrowse enabled="false" />
  </system.webServer>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <standardEndpoints>
      <webHttpEndpoint>
        <!--
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
            via the attributes on the <standardEndpoint> element below
        -->
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
  <connectionStrings>
    <add name="Entities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=someip;initial catalog=db_90;User ID=user1;Password=access2;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

A: This may be a better question for stackoverflow.com but I'll take a stab at it for now.
From an IIS perspective if you can find out the specific 500 error it may give a big clue. Check the IIS logs in c:\inetpub\logs\Logfiles\w3svc{siteid}.  Find the records for your failed tests and towards the end of the records you should see a 500{space}{something}{space}{something}. It's the {something}'s that have further clues.
Another test is to create a simple test.aspx in the root folder of the site and make sure that the IIS site works well too.


text:
Q: Nested table object usage in FORALL in oracle I am trying to insert data from a collection into the table using FORALL, I expected the process to be fast but unfortunately process is rather slow and didn't show any major performance improvement.
Below code:
create or replace Procedure data_test (E in nchar, J in number)
      AS

      Exec_data JR_Table;   //Created a nested table variable

      BEGIN

    select JR_Type (job_id, e_id,  USER_NAME, start_time, end_time)
                    bulk collect into Exec_data   //Bulk collect into this variable
                    from ( taBLE);

                     FORALL counter in Exec_data.first..Exec_data.last    //insert using FORALL
                insert into DATA_TEMP1 Values
                (Exec_data(counter).JOB_ID, Exec_data(counter).E_ID, Exec_data(counter).START_TIME, Exec_data(counter).END_TIME;

                commit;

                End;

Above doesn't produce any satisfactory results with just 1300 records to insert in table and time taken is 6min, Instead I want to try using FORALL in below way:
FORALL counter in Exec_data.first..Exec_data.last    //insert using FORALL
                    insert into DATA_TEMP1 Values
                    (Exec_data(counter));

Expecting above code change will speed up the process.
When tried to compile the code getting error:

Error(474,33): PL/SQL: ORA-00932: inconsistent datatypes: expected - got -

I am sure their should be a way to get this work. I am not a core Oracle developer, I was able to write the above code by studying in few sites.


text:
Q: Trying to setPage() from a HttpsURLConnection
I'm trying to get the page from a HttpsURLConnection to setPage() on a component.
java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection cannot be cast to javax.net.ssl.HttpsURLConnection

That's an error I get.
Any fixes?
URL url = new URL("https://www.lalala.tk/website.html");
HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();

A: You are importing the wrong class. I bet somewhere in your code there is
import javax.net.ssl.HttpsURLConnection;

But instead, it should be
import sun.net.www.protocol.http.HttpURLConnection;

Try to replace the imports and I am sure it will work out.


text:
Q: Can we always find some polynomial for which this holds? I do not know if this is an easy exercise but is this true:

For every $n \in \mathbb N$ there exist at least one polynomial $P$ in one variable with integer coefficients such that the set $\{P(1),\dots,P(n)\}$  consists of only prime numbers and all of them are different?

A: Let $V$ be the $n \times n$ Vandermonde matrix whose $(i,j)$ entry is $i^{j-1}$, $i=1..n$, $j=1..n$.  Note that this is invertible, and $V (1,0,\ldots,0)^T = (1,\ldots,1)^T$.  Let $p_1, \ldots, p_n$ be primes such that $p_i \equiv 1 \mod \det(V)$ (by Dirichlet's theorem, infinitely many such primes exist).
Then $V^{-1} (p_1, \ldots, p_n)^T = (a_0, \ldots, a_{n-1})^T$ is a vector of integers, and $P(x) = \sum_{j=0}^{n-1} a_j x^j$ satisfies $P(i) = p_i$ for $i=1 \ldots n$.


text:
Q: A couple questions about partially ordered sets Is a set of all integers or the set of positive integers a partially ordered set? With respect to the relation's "divides"?
And is there a partially ordered set that isn't a lattice? Or are all partially ordered sets lattices?

A: Yes, the divisibility relation partially orders $\Bbb Z^+$. It does not partially order $\Bbb Z$, because on $\Bbb Z$ it isn't antisymmetric: for instance, $1\mid-1$ and $-1\mid 1$, but $1\ne -1$.
A partially ordered set need not be a lattice: the relation of equality is a partial order on any set, and $\langle X,=\rangle$ is not a lattice if $X$ has more than one element.


text:
Q: Uniform convergence in real valued injective functions sequence If $f_{n}$ is a sequence of real valued injective functions that converges uniformily to $f$, then is it necessary that $f$ be injective? Thanks in advance!

A: Easy counter-example :
Pick $f_n(x):= \frac{x}{n+1}$ for $x\in[0,1],n\in\mathbb{N}$
$\frac{1}{n+1}\ge\lvert{f_n-0}\rvert$ which means that $\frac{1}{n+1}\ge {sup_{x\in[0,1]}\lvert{f_n-0}\rvert}$, which means that $f_n$ converges uniformly towards the trivial function, yet $f_n$ is clearly injective while the zero function clearly isn't


text:
Q: How to select the overall price of rooms booked by the same person I created a table:
Create table rooms
(
roomNo int not null,
hotelNo int not null,
hotelName varchar (40) not null,
roomType varchar (40)
default 'standard' check (roomType in ('single', 'double', 'master',
'standard', 'president')),
price decimal (8,2) check (price>=0 and price<=99999),
guestNo int null
)

roomNo and hotelNo are the primary key and guestNo is a foreign key.
The table is populated with values:
(101, 123456, 'Home','standard',300, 54321)
(101, 654321, 'Ibis','standard',300, Null)
(101, 987654, 'Hiton','president',15000, null)
(222, 987654, 'Hiton','standard',300, 12345)
(321, 987654, 'Hiton','master',1000, 11111)
(333, 123456, 'Home','single',100, null)
(333, 987654, 'Hiton','standard',300, 12345)
(567, 654321, 'Ibis','standard',300, null)
(888, 654321, 'Ibis','single' ,100, null)
(999, 654321, 'Ibis','double' ,200, null)

How can I answer the question "Select the overall price of rooms booked by the same person."?
I want get the sum price as 600 but based on this query I get 1900:
select sum(price)
from rooms r inner join guests g
on r.guestNo = g.guestNo and g.guestName = g.guestName

A: If you want the total price for each person then you need to group by that value:
select g.guestNo, sum(r.price)
from rooms r inner join guests g
on r.guestNo = g.guestNo
group by g.guestNo
order by g.guestNo;

   GUESTNO SUM(R.PRICE)
---------- ------------
     11111         1000
     12345          600
     54321          300

If you're only interested in guests with more than one room entry then you can add a having clause to check how many there were:
select g.guestNo, sum(r.price)
from rooms r inner join guests g
on r.guestNo = g.guestNo
group by g.guestNo
having count(r.roomNo) > 1
order by g.guestNo;

   GUESTNO SUM(R.PRICE)
---------- ------------
     12345          600

Read more.
Your data model seems odd, incidentally; it seems strange to record a specific guest against the room. Maybe you should remove guestNo from that and have another table that links a room to a guest, perhaps for a date range. Price might vary too, so that might need to be in that booking table instead, or in yet another table (to allow for seasonal pricing etc.)?


text:
Q: TypeError: 'list' object is not callable, Maximum Pairwise Product when I Run this function I get this error, I don't know where is the problem ?
def max_product(number):
    n = len(number)
    indexMax1 = 0
    indexMax2 = 0
    for f in range(n):
        if f > number[indexMax1]:
            indexMax1 = number.index(f)
    for s in range(n):
        if(s > number[indexMax2] and indexMax2 != indexMax1):
            indexMax2 = number.index(s)
    return number(indexMax2)*number(indexMax1)

A: Seems like the error is in the last line
return number(indexMax2)*number(indexMax1)

You are trying to call number(indexMax2) and number(indexMax1). I think what you wanted to do is multiply elements of number with indices indexMax2 and indexMax1. You need to change the brackets to square brackets:
return number[indexMax2]*number[indexMax1]

Please specify the types of input variables in your future questions.

A: def max_product(number):
    n = len(number)
    indexMax1 = 0
    indexMax2 = 0
    for f in range(n):
        if f > number[indexMax1]:
            indexMax1 = number.index(f)
    for s in range(n):
        if(s > number[indexMax2] and indexMax2 != indexMax1):
            indexMax2 = number.index(s)
    return number[indexMax2]*number[indexMax1]

A: As Lior Cohen stated in his comment, this is just a matter of parenthesis instead of brackets. The correct code is:
def max_product(number):
    n = len(number)
    indexMax1 = 0
    indexMax2 = 0
    for f in range(n):
        if f > number[indexMax1]:
            indexMax1 = number.index(f)
    for s in range(n):
        if(s > number[indexMax2] and indexMax2 != indexMax1):
            indexMax2 = number.index(s)
    return number[indexMax2]*number[indexMax1]


text:
Q: How can I find what type of Server is running in the background of Windows (seen in services.) We have a sensor connected to Computer#1. The sensor is driven by Software XY. This software has a Data Server XY running in the background in Windows. I can see this server by executing "services" after pressing the windows key.
I want to be able to access this Data Server (first in Computer #1, and eventually send/access this information to/from Computer#2).

*

*How can I know what type of server is this? (I need to know this to find out how to connect to it, right?) In the Services application I can only see:

*Service name = XYDataServer

*Display Name = XY Data Server

*Description = Distributes XY data to listening clients

*Path to executable = C:\Program Files\XY\DataServer\XYDataServer.exe

*Additional information which does not say much really
Additional information: the seller of the sensor and software gave us a .NET Assembly  (a .dll) and a word file with some information of the .dll (Namespace, Constructors, Methods, etc.) but no other instructions. I am at a loss on how to proceed. My rational was to first find out what kind of server this is (SQL, Windoes), and then decide how to approach it (pick programming language, download examples, etc.)

A: There some tips and technics for information gathering about your target server but they are not precise.
To identify which OS is running on the server you can find a clue by ping command. Firstly, you should find IP address of the target server(if you don't have it, you can sniff send/receive package with third party applications like Wireshark). Than ping your target server IP address. Finally, look for TTL in your ping result like this.
TTL=64 = *nix - the hop count so if your getting 61 then there are 3 hops and its a *nix device. Most likely Linux.
TTL=128 = Windows - again if the TTL is 127 then the hop is 1 and its a Windows box.
TTL=254 = Solaris/AIX - again if the TTL is 250 then the hop count is 4 and its a Solaris box.

For identifying which database is active on the server , you can scan open ports on the server. In example, SQL Server default port is 1433.


text:
Q: Google Cloud Endpoint / How to get json-body request? I'm trying to get json body when a POST request is sent to an endpoint.
I defined my methods and classes like this:
class UserRequest(messages.Message):
    f1 = messages.IntegerField(1)
    f2 = messages.StringField(2)

class UserResponse(messages.Message):
    content = messages.StringField(1)

USER_RESOURCE = endpoints.ResourceContainer(
    UserRequest)

@endpoints.api(name='echo', version='v1')

class EchoApi(remote.Service):

@endpoints.method(
    USER_RESOURCE,
    UserResponse,
    path='echo',
    http_method='POST',
    name='echo')
def echo(self, request):
    data = {x.name: getattr(request, x.name) for x in request.all_fields()}
    return UserResponse(content=str(data))

When I send a curl post to my endpoint without a body included in :
curl -x POST http://localhost:8080/_ah/api/echo/v1/echo?f1=asdf&f2=qwert

I got f1 and f2 with request.f1 and request.f2.
But when I make a curl call with a body :
curl -H "Content-Type: application/json" -X POST -d '{"f1": "asdf", "f2":"qwert"}' http://localhost:8080/_ah/api/echo/v1/echo

The request object doesn't contains f1 and f2 values, and they are hold in the <request._Message__unrecognized_fields()>.
I want to know if it's possible to get directly the json body as a classic request.


text:
Q: How to "move" specific old emails from one Gmail account to another? I have an old Gmail account, and I need to move only some emails from this old account to a new Gmail account. There are many tutorials that show how to move all old emails using POP3 forwarding, but I can't find any instructions that guide me to select old emails and forward them.
Note that when I mean "forward", I mean to move them to the new mail account as they are in the current state, i.e. no "Fwd:" in the subject and the email sender must remain the original email's sender.
I know this is possible because a browser extension named "Multi Email Forward" by CloudHQ allows this, but it's only available if one upgrades from a free account (which I can't afford).


text:
Q: What is the right embedding between $C^{\infty}_c (\mathbb{R}^n)$ and $H^1(\mathbb{R}^n)$? There exists an embedding relation "$\subset$" or "$\supset$" between $C^{\infty}_c (\mathbb{R}^n)$ and $H^1(\mathbb{R}^n)$?
Could anyone give me an example? Thank you in advance!

A: A smooth compactly supported function has weak derivatives of all order that are in every $L^p$ space. In particular,
$$ C^\infty_c (\mathbb R^n)\subset H^1(\mathbb R^n).$$
In fact more is true, $C^\infty_c(\mathbb R^n)$ is dense in $H^1(\mathbb R^n)$. A $C^1_c$ function that is not smooth shows that $H^1\neq C^\infty_c$.
"bump functions" are your standard example of a function in $C^\infty_c$, and there's lots of discussion on them already on MSE. For example : Where can we find examples of smooth functions with compact support? Is there a book?. This example is related to the smooth but non-analytic function in this wikipedia page.
These examples are for 1 variable but it is trivial to modify them for higher dimensions by e.g. forcing them to be radially symmetric, or multiplying toegether one for each coordinate.


text:
Q: webview in native view? I was wondering if anyone has created a reader app for iOS that allows the user to view a webpage in a native environment rather than in a webview? I'm trying to use a screen scrape method, but I'm having trouble entering in the url so that the page displays.

A: I am not sure by what you mean when you say viewing a webpage in a native environment, i'm guessing you want to strip the webpage of everything except select things that you want to display?  You can do this by downloading the web page itself, in a simplified version, downloading index.html from a web server.  You would then have to create some type of a parser that would go through the html file and grab things that you would like to show like things that are between

 tags, which would be body paragraphs and so forth.  The parser would return an array of objects, for this simplified example we will say an array of strings, each string holds the body of text that was between different
 tags.  You would then dynamically create textfields or a textfield and format the content as you wish and display it as you want.
Here is some code to get you started:
NSURL *url = [NSURL URLWithString:@"http://www.google.com"]
NSString *webPageString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];

Excuse any typo in that code, i free hand wrote it on a pc so a method name might be slightly wrong or capitalized wrong if you copy it in. You can then experiment on your favorite website by stripping parts of it that you want and displaying them in an app as you wish.


text:
Q: How to configure Eclipse to compile using Oracle javac 1.7.0_09? I am trying to compile following piece of code:
public class DuplicateMainExample {
    public static void main(String[] args) {
        System.out.print("A1");
    }

    public static void main(String... args) {
        System.out.print("A2");
    }
}

In Eclipse it's working fine, but with warnings on the both methods - "Duplicate method main(String[]) in type DuplicateMainExample"
Using javac (java version "1.7.0_09") I have an compilation error:
>javac DuplicateMainExample.java
DuplicateMainExample.java:8: error: cannot declare both main(String...) and main
(String[]) in DuplicateMainExample
        public static void main(String... args) {
                           ^
1 error

How to compile in Eclipse using javac?

A: Simply because you have declared the same method with exactly the same signature twice ... Only one main method for class should be declared .
Eclipse have embedded its own compiler and in the case of two main methods it gets the last one, the eclipse compiler and the javac compiler are two different compilers ...
Take a look at this older post for more information ...
If you want to compile with javac you could try using the ant javac adapter from within eclipse ... However i think that ECJ is even better than javac(my opinion) ...

A: Eclipse will never use javac. Its ability to do dynamic highlighting is intimately connected with its own compiler, which has special abilities to operate incrementally.
If you want an IDE that uses javac, you might investigate intellij.


text:
Q: How to add an image in an xsl sytlesheet in a table cell I am trying to add an image inside a table in XSL:FO, but the image is not reflecting in the PDF.
<fo:table-cell border-style="solid" border-color="black" border-width="0.4pt" number-columns-spanned="1" text-align="center" display-align="center">
                  <fo:block font-family="isocpeur" line-height="12pt" font-size="12pt" font-weight="bold" space-before.optimum="1.5pt" space-after.optimum="1.5pt" keep-together="always">
                   <fo:external-graphic
                    content-width="scale-down-to-fit"
                    content-height="scale-down-to-fit"
                    scaling="uniform"
                    src="src\com\createpdf\image\LOGO.png"/>
                </fo:block>
                </fo:table-cell>

A: You've specified a relative path. The FO processor evaluates this path based on the directory where the XSLFO file resides.
To remove ambiguity, use an absolute path instead (i.e. starting with the drive letter, C:\folder\ etc.)
You haven't specified a size for the image. I suspect content-width="scale-down-to-fit" needs a size to scale to.
<fo:external-graphic width="1cm"...

And what are the symptoms/what do you see in the PDF? In Antennahouse Formatter, if it can't find an image, it will place a placeholder. That helps narrow down the problem.