text:
Q: C# Custom Button I'm attempting to write a custom button user control. I have run into a challenge when drawing the image.
Is there a simple way to draw the image accounting for the ImageAlign and TextImageRelation? (Kind of like StringFormat makes text aligning a breeze)
Or do I have to do all the aligning logic and stuff manually?
Thanks

A: What functionality are you trying to achieve? Perhaps it should instead inherit from the Button class (asssuming WinForms), and override appropiate methods. Depending on what you need to do, you will propably get much of the lower levels of functionality in the button for free, if you do this.
To get back to your question; No, if you need to draw stuff yourself, there is no magic easy way to determine where the individual pixels should go :-) One great helper in doing this, that you should be aware of, is the Graphics.DrawString method. It lets you measure the dimensions of a given text string when drawn on the control with the selected font and size.

A: I do not know of anything that does this stuff for you, but be aware of the ControlPaint class as that has a bunch of handy utility methods for painting controls.


text:
Q: Python/Scipy: Find "bounded" min/max of a matrix I think it is easiest to specify my problem, the generalized case is difficult to explain.
Say I have a matrix
a with dimensions NxMxT,

where one can think about T as a time-dimension (to make the question easier). Let (n,m) be the indices through NxM. I might call (n,m) the state-space identifier. Then I need to find the python/scipy equivalent of
for each (n,m):
     find a*(n,m) = min(a(n,m,:) s.t. a*(n,m) > a(n,m,T)

That is, find the smallest state-space value that is still higher than the last (among time dimension) observation - for the whole state-space.
My first attempt was to first solve the inner problem (find a that is higher than a[...,-1]):
aHigherThanLast = a[ a > a[...,-1][...,newaxis] ]

And then I wanted to find the smallest among all of these for each (n,m). Unfortunately, aHigherThanLast now contains a 1-D array of all these values, so I don't have the (n,m) correspondence anymore. What would be a better approach to this?
As an additional problem: The state-space is variable, it could also be 3 or more dimensions (NxMxKx...), and I cannot hard-code this. So any kind of
for (n,m,t) in nditer(a):

is not feasible.
Many thanks!
/edit:
a = array([[[[[[[[ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.]]]],

          [[[[ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.]]]]],

         [[[[[ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.]]]],

          [[[[ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.],
             [ 0.,  2.,  1.]]]]]]]])
# a.shape = (1L, 1L, 2L, 2L, 1L, 1L, 10L, 3L). so in this case, T = 3.
# expected output would be the sort of
# b.shape = (1L, 1L, 2L, 2L, 1L, 1L, 10L), which solves

*

*b[a,b,c,d,e,f,g] > a[a,b,c,d,e,f,g,-1] (b is higher than the newest observation)

*

*There is no element in i in a that satisfies both
-- a[a,b,c,d,e,f,g,t] > a[a,b,c,d,e,f,g,-1]
-- a[a,b,c,d,e,f,g,t] < b[a,b,c,d,e,f,g] (b is the smallest element that is higher than the newest observation)
So, given that the previous array is a simple stack if [0,2,1] along the last observation, I would expect
b = ones((1,1,2,2,1,1,10))*2

however,
 - if, among some (a,b,c,d,e,f,g), there was not only the value of either {0,1,2}, but also {3}, then I would still want the 2 (as it is the smaller of i = {2,3} that satisfies i > 1.
 - if among some (a,b,c,d,e,f,g) there was only the value {0,1,3}, I would want the 3, as i = 3 would be the smallest number that satisfies i > 1.
Hope that cleared it up a bit?
/edit2:
Appreciate the answer a lot, it works. How would I adjust it if I wanted the opposite, i.e. the largest among those that are smaller? I didn't try to get through that complicated indexing logic, so my (weak) attempt of only changing the first three lines did not succeed:
        b = sort(a[...,:-1], axis=-1)
        b = b[...,::-1]
        mask = b < a[..., -1:]
        index = argmax(mask, axis=-1)
        indices = tuple([arange(j) for j in a.shape[:-1]])
        indices = meshgrid(*indices, indexing='ij', sparse=True)
        indices.append(index)
        indices = tuple(indices)
        a[indices]

Also, a[...,::-1][indices], my second attempt, was not fruitful either.

A: I think Mr. E is on the right track. You definitely start by sorting the array without that last time value:
b = np.sort(a[..., :-1], axis=-1)

You would now ideally use `np.searchsorted to find where the first item larger than the end value is, but unfortunately np.searchsorted only works on flattened arrays, so we have to do some more work, like creating a boolean mask, then finding the first True using np.argmax:
mask = b > a[..., -1:]
index = np.argmax(mask, axis=-1)

You now have the indices, to extract the actual values, you need to do some indexing magic:
indices = tuple([np.arange(j) for j in b.shape[:-1]])
indices = np.meshgrid(*indices, indexing='ij', sparse=True)
indices.append(index)
indices = tuple(indices)

And you can now finally do:
>>> b[indices]
array([[[[[[[ 2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.]]],

          [[[ 2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.]]]],

         [[[[ 2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.]]],

          [[[ 2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.]]]]]]])
>>> b[indices].shape
(1L, 1L, 2L, 2L, 1L, 1L, 10L)

To get the largest among those that are smaller, you could do something like:
mask = b >= a[..., -1:]
index = np.argmax(mask, axis=-1) - 1

i.e. the largest among those that are smaller is, the item right before the smallest among those that are equal or larger. This second case makes it more clear that this approach gives garbage result if there is no item that fulfills the condition. In this second case, when that happens, you will get a -1 for an index, so you could check that the results are valid doing np.any(index == -1).
You can set the index to -1 if the condition cannot be satisfied for the first case by doing
mask = b > a[..., -1:]
wrong = np.all(~mask, axis=-1)
index = np.argmax(mask, axis=-1)
index[wrong] = -1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stability region of midpoint method using Solve and RegionPlot I've been trying to obtain the stability region in the $(\lambda_R, i\lambda_I)$ plane of the midpoint rule $$y_{n+1}= y_{n-1}+2h\dot{y}_n,$$ for the model problem $\dot{y}=\lambda y$.  The roots for the characteristic polynomial when $y_n=x^n$ are $$x_{1,2}=h\lambda \pm \sqrt{1+h^2\lambda^2} $$ So what I need is to find what values of $\lambda=\lambda_R+i\lambda_I$ satisfy the conditions $|x_1| \leq 1$ and $|x_2|\leq 1$ simultanously. I know from literature that it is found to be a segment in the imaginary axis: $(-i,i)$, but I wanted to find it myself. I tried with:
Solve[Abs[(x + I y) + Sqrt[1 + (x + I y)^2]] <=  1 &&
      Abs[(x + I y) - Sqrt[1 + (x + I y)^2]] <= 1, {x, y}, Complexes]

It doesn't work, the evaluation never ends. I'm also interested in the plot of the region of stability, which I should find with RegionPlot as follows:
RegionPlot[Evaluate@ComplexExpand[Abs[z - Sqrt[1 + z^2]] <= 1 /. z -> x + I y] &&
           Evaluate@ComplexExpand[Abs[z + Sqrt[1 + z^2]] <= 1 /. z -> x + I y],
           {x, -2, 2}, {y, -2, 2}]

But is shows a blank plot, I'm guessing it could be because I'm trying to display a segment and not a "region" per se.
Any thoughts and help will be greatly appreciated.
Cheers,
Franco.


text:
Q: Gaussian process regression, multiple optima on marginal likelihood I have performed Gaussian process regression on a data set $D$. The marginal likelihood function that can be seen in the contour plot below (that I plot against the two hyper-parameters: $\sigma_n$ (noise standard deviation) and $l$ (characteristic length)) contains two optimum. From the graphs produced it appears (to my eye) that there is a better fit corresponding to hyper-parameters at the stationary point with the smaller marginal likelihood.
The function generated using hyper-parameters corresponding to smaller marginal likelihood is the plot in the middle. The function generated using hyper-parameters corresponding to larger marginal likelihood is the bottom plot.

I have read that when multiple optima occur then the posterior distribution should be looked at. Is this correct? If so could someone please shed some light on this. If not does anybody have any suggestions?
Thank you


text:
Q: How to get the second solution? I have this exercise:
Solve for $x$, $(\log x)^{10} = 3$
My development was:
$\log x = \sqrt[10]3$
$10^{\sqrt[10]3} = x$ , this is my solution.
But I still need a solution, according to the symbolab. Which is: $x = \frac{1}{10^{3^{\frac{1}{10}}}}$
But I have not managed to get it on my own, how can I get to this result? Thanks in advance.

A: Let's try this with a much simpler problem: suppose you want to find $y$ such that
$y^{10} = 1.$
Obviously $y = \sqrt[10]1 = 1$ is a solution.
Is there any other solution? Why or why not?
Your solution method has much in common with the method for finding that $y = 1$
in the example above: you have something to the $10$th power, so you assume all you have to do is take the $10$th root.
But this does not give complete solutions, just as taking the square root does not completely solve equations like $x^2 = 1.$


text:
Q: Creating a Python dictionary Is it possible to create a dictionary like this?
data = {(136-00000-0001 : 072-00000-0001,072-00000-0002,072-00000-0003),
        (136-00000-0002 : 072-00000-0002,072-00000-0003,072-00000-0004)}

text = input("Put your 072-XXXXX-XXXX number in here: ")
wrapper =[]

for number in text:
 if number in data.keys()
  wrapper.append(data[number]

 for w in wrapper:
  print(w, end=" ")

I have a wrapper called 136-xxxxx-xxxx where 3*072-xxxxx-xxxx are in it.
All I want to do is, asking for a 072-xxxxx-xxxx number and the program is giving me
the Wrapper number of it back.
For example:

*

*asking for 072-00000-0004

*answer -> it´s inside 136-00000-0002

The only way I know is, for example that morse thing, where
morse = {"a":".-", "b":"-...", but is there a way like this for my example at the top?

A: You would need to store multiple values for your keys in a list,tuple etc.. You cannot have more than one value for a key.
data = {"136-00000-0001" : ["072-00000-0001","072-00000-0002","072-00000-0003"],"136-00000-0002" : ["072-00000-0002","072-00000-0003","072-00000-0004"]}
print ( data.values())

[['072-00000-0001', '072-00000-0002', '072-00000-0003'], ['072-00000-0002', '072-00000-0003', '072-00000-0004']]

To append to a keys values:
data["136-00000-0001"].append("whatever")

Check if value is in the dict and print the key,value pair.:
In [5]: for k,v in data.items():
            if "072-00000-0004" in v:
                print (k,v)
   ...:
136-00000-0002 ['072-00000-0002', '072-00000-0003', '072-00000-0004']

Use strings if you want use the format 072-00000-0002 will  give an error  SyntaxError: invalid token
.

A: In Python 2.x:
>>> data = {"136-00000-0001":["072-00000-0001","072-00000-0002","072-00000-0003"],"136-00000-0002":["072-00000-0002","072-00000-0003","072-00000-0004"]}
>>> text = raw_input("Put your 072-XXXXX-XXXX number in here: ")
Put your 072-XXXXX-XXXX number in here: 072-00000-0004
>>> for d in data:
...     if text in data[d]:
...         print d
136-00000-0002

And for Python 3 you have to use input() instead of  raw_input() and print() as a function.
>>> data = {"136-00000-0001":["072-00000-0001","072-00000-0002","072-00000-0003"],"136-00000-0002":["072-00000-0002","072-00000-0003","072-00000-0004"]}
>>> text = input("Put your 072-XXXXX-XXXX number in here: ")
Put your 072-XXXXX-XXXX number in here: 072-00000-0004
>>> for d in data:
...     if text in data[d]:
...         print(d)
136-00000-0002


text:
Q: The usage of words rancid, stale, putrid, decayed, rotten, spoiled, decomposed Could you please compare these words in terms of meaning and daily usage in reference to only foods?
Could you give specific examples from daily life.For example which words can be used for bread, milk, yogurt, cheese, vegetables, fruits or cooked meals and the conditions in which food placed that the words suggest?

A: *

*spoiled  generally refers to food that needs to be thrown away

*stale refers to baked goods that are no longer fresh

*rotten refers to produce like fruits and vegatables, although it can occasionally be used with meats

*decayed and decomposed refer to items are partly rotted away;  you might use these words to describe the carcass of an animal

*rancid and putrid are words usually used when there is a terrible smell.
The first four words are used often to describe food. The last four words occasional describe food (rancid meat, e.g.), but are probably used to describe garbage more than food.


text:
Q: Unable to install SciPy I need to use the module skimage, which calls the module SciPy (I need to find contours)
import numpy
from sys import argv
from PIL import Image
from skimage import measure

# Inicialization
spritesToFind = argv[1]
spriteSize = argv[2]
sheet = Image.open(argv[3])
sheet.verify()

# To grayscale, so contour finding is awesome
grayscale = sheet.convert('L')

# Let numpy do the heavy lifting for converting pixels to pure black or white
data = np.asarray(grayscale).copy()

# Find the contours we need
contours = measure.find_contours(r_grey, 0.8)

# Now we put it back in PIL land
sprite = Image.fromarray(data)
sprite.save(str(Counter), "PNG")

I set upon an epic 5 hour journey to figure out to how solve the problem which is:
Traceback (most recent call last):
 File "algo.py", line 4, in <module>
from skimage import measure
 File "/usr/local/lib/python2.7/dist-packages/scikit_image-0.9.3-py2.7-linux-i686.egg/skimage/measure/__init__.py", line 3, in <module>
from ._regionprops import regionprops, perimeter
 File "/usr/local/lib/python2.7/dist-packages/scikit_image-0.9.3-py2.7-linux-i686.egg/skimage/measure/_regionprops.py", line 5, in <module>
from scipy import ndimage
ImportError: No module named scipy

So I figured I had to install SciPy. I began with pip and easy_install, couldn't get the thing to work. I downloaded both numpy and scipy tarballs and configured them, but scipy required libraries, which I had, just newer versions, but it didn't want them, even though I pointed them at it. Next thing I needed was gfortran, which I couldn't install because none of the libraries would work( there is a link of gfortran on linuxmint.community but you can't reach it because atpurl says the package is virtual). I tried everything. Can you give me some help? All I want is SciPy to work.
SciPy:
Blas (http://www.netlib.org/blas/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [blas]) or by setting
the BLAS environment variable.

A: Rather than try to install this module yourself I'd recommend just using it from your distributions repository. I found this module available, so this command should install it for you.
$ sudo apt-get install python-scipy

If you're going to be doing a fair amount of Python development I'd encourage you to setup your own dedicated instance of Python rather than depend on the one provided by the distribution. True you can use this version, and probably not have too many issues doing so, but when you start to have to install a lot of dependencies (libraries/modules) it can become problematic to do so.
I wrote up detailed notes on how to do this for Python in this U&L Q&A titled: Upgrading Python 2.6. libpython2.6.so.1.0 missing.


text:
Q: Inno Setup AfterInstall function called for each file I want to call a function after installing a folder, but the InstallEnv function is seems to be called several times, maybe for each file is the folder (to be confirmed). Is there a way to call it only once after it installed all of those files? I can't use the Run section because I want to do error catching with the return code.
Source: "InputFiles\virtualenv-1.8.2\*"; DestDir: "{tmp}/virtualenv"; \
    Flags: recursesubdirs; AfterInstall: InstallEnv;

A: There is no way to call it at the end of the installation of that group of files, from within a single entry.  However it is possible to call the function at the appropriate time by making use of a dummy entry:
[Files]
Source: "InputFiles\virtualenv-1.8.2\*"; DestDir: "{tmp}\virtualenv"; Flags: recursesubdirs
Source: dummy.txt; DestDir: {tmp}; AfterInstall: InstallEnv

The Source file must exist but it can be a zero-byte file.  As installation is into {tmp} it will be deleted after install anyway so its contents are irrelevant.
This works because [Files] entries are installed in the order specified.

A: Yes, it executes once per each file. The reference says about it (emphasized by me):

A BeforeInstall or AfterInstall function for a [Files] section entry
  using a wildcard is called once per file matching the wildcard. Use
  CurrentFileName to check for which file the function is called.

And no, there is no way to call it once after all the files are installed. If you were going to run it only once, it wouldn't be a problem, since you might declare a flag variable, indicating that the function was already called, but you want to detect if it's the last call, and for this there is no workaround.
Well, maybe if you would know, which file will be the latest installed from that folder, you might check that against the result of the CurrentFileName function call, but I doubt that you can determine which one will be installed as last at compilation time (since at runtime, there is currently no way to get list of files to be installed).


text:
Q: Can't boot Windows 10 after installing, Ubuntu 20.04 pre-installed on different drive I have been using Ubuntu for a few months, and was trying to install Windows 10 as dual-boot for software/games that don't work in Wine.

*

*Ubuntu 20.04 is installed on a 120GB Kinston SSD.

*1TB Seagate HDD with 250GB NTFS partition where I want to install Windows 10 Pro.

*HDD has the rest of the space allocated as an NTFS partition with ~650GB of files that I cannot lose or back-up.

I used gdisk in Ubuntu Terminal to convert 250GB partition on HDD to GPT as the entire drive was MBR(as stated above I cannot lose files on other partition). I then booted to the Windows install USB and installed Windows 10 Pro on the 250GB NTFS partition, after which it should automatically reboot into Windows to finish the setup.
In my case it rebooted into Ubuntu, I checked the partition in Ubuntu and confirmed that Windows did get installed. I rebooted and got into my BIOS and noticed that the Windows 10 partition was not in my boot order and not showing up at all, only Ubuntu on my SSD and the Install USB.
I tried reinstalling Windows with the partition this time deleted(250GB as Free Space), and created the partition in in install manager, Windows then made a 16Mb MBR partition in addition to the GTP partition for Windows. The results however were the same. Booting back onto the Install USB I entered Command Prompt from Repair option and used the bootrec /ScanOS command which returned that there are no detected Windows 10 installs.
I have confirmed that I do have EFI Ubuntu installed. Any assistance would be greatly appreciated.

A: It seems the install actually did work, and the conversion from MBR to GPT as well.
I found this guide Use Grub Customizer to Change Boot Order & Make Windows Default for GRUB customizer and that showed the Windows Boot Loader. I moved Windows Boot Loader up to just below Ubuntu. After rebooting the GRUB menu showed and I was able to boot into Windows. Multiple reboots later I have yet to experience any issues.
Thanks for the replies, All my data drives can be accessed from within Ubuntu and all the data seems to be fine.


text:
Q: how to add additional column in sql I have this query
SELECT Count(IN_Invoices.in_id) NoOfInv,
       sum(in_total) AMTsum,
       CLOI_ClientOrderItems.cl_Id
  from (select distinct
               MasterOrderId,
               cl_Id
          from CLOI_ClientOrderItems) as CLOI_ClientOrderItems
       inner Join IN_Invoices
            on IN_Invoices.MasterOrderId = CLOI_ClientOrderItems.MasterOrderId
group by
       CLOI_ClientOrderItems.cl_id

The query result is
NoOfInv   AMTsum      cl_id
7         245        100000pri
247       181110.29  100001pro

Grandtotal,presentmonthtotal,firstpreviousmont,secondpr,remainingamount
i have date of issue column in my table that contained dates
 presentmonthtotal ->need to search it in date of issue column and display that month details


text:
Q: Getting NullPointerException when using RecyclerView on addFocusables I'm new with RecyclerView and I'm trying to use it in my code, problem is that I'm getting exception like this,
E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.myapp.debug, PID: 10430
    java.lang.NullPointerException
            at android.support.v7.widget.RecyclerView.addFocusables(RecyclerView.java:1486)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.ViewGroup.addFocusables(ViewGroup.java:914)
            at android.view.View.addFocusables(View.java:6711)
            at android.view.FocusFinder.findNextFocus(FocusFinder.java:92)
            at android.view.FocusFinder.findNextFocus(FocusFinder.java:65)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:681)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.ViewGroup.focusSearch(ViewGroup.java:683)
            at android.view.View.focusSearch(View.java:6617)
            at android.widget.TextView.onCreateInputConnection(TextView.java:5717)
            at android.view.inputmethod.InputMethodManager.startInputInner(InputMethodManager.java:1121)
            at android.view.inputmethod.InputMethodManager.onWindowFocus(InputMethodManager.java:1370)
            at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3141)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

here is my code:
 public class TravelersListAdapterV2 extends RecyclerView.Adapter<TravelersListAdapterV2.ViewHolder> {

        private final Context context;
        private final LayoutInflater inflator;
        private LayoutInflater mInflater;
        private int invalidTop;
        private List<BookingReservation.Rooms2.Guest> items;

        public static class ViewHolder extends RecyclerView.ViewHolder {

            TextView travelers_row_header;

            public ViewHolder(View view) {
                super(view);
                view.findViewById(R.id.dateOfBirth);
                travelers_row_header = (TextView)   view.findViewById(R.id.travelers_row_header);
            }
        }

        public TravelersListAdapterV2(Context context, List<BookingReservation.Rooms2.Guest> items) {
            inflator = LayoutInflater.from(context);
            this.items = items;
            this.context = context;

        }

        @Override
        public TravelersListAdapterV2.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflator.inflate(R.layout.row_required_traveller_fields, parent, false);
            ViewHolder vholder = new ViewHolder(view);
            return vholder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            final BookingReservation.Rooms2.Guest item = items.get(position);
            holder.travelers_row_header.setText(context.getResources().getString(R.string.passenger) + " " + (position + 1));
        }

        @Override
        public int getItemCount() {
            try {
                return items.size();
            } catch (Exception e) {
                return 0;
            }
        }
    }

not sure if this is worth mentioning but I'm using the support library like this:
compile ('com.android.support:recyclerview-v7:22.0.+')
            {
                exclude module: 'support-v4'
                exclude module: 'support-annotations'
            }

Thanks

A: compile ('com.android.support:recyclerview-v7:23.0.0+')
or
set a LayoutManager on your RecyclerView.


text:
Q: get first, second and third date of each file opened - Pandas I have this code to group by col1 to get the nsmallest dates in order of the times the file was opened but it seems to come in random order but that is what I don't need.
Here is my code.
data=(df.groupby(['col1']).date
   .apply(lambda x: pd.Series(x.value_counts()
                               .nsmallest(3).index))
   .unstack(level=1).fillna(0).astype(str))

output:
  col1              0                                1                          2
  file 1    2020-05-07 09:52:44.502     2020-05-06 04:53:32.449     2020-05-18 06:12:27.872
  file 2    2020-05-08 09:02:44.502     2020-05-04 04:53:32.449     2020-05-19 06:12:27.872

The output that I want:
       col1                 0                                1                          2
      file 1   2020-05-06 04:53:32.449  2020-05-07 09:52:44.502     2020-05-18 06:12:27.872
      file 2    2020-05-04 04:53:32.449 2020-05-08 09:02:44.502     2020-05-19 06:12:27.872

DATA:
'{"col1":{"0":"file1","1":"file2","2":"file3","3":"file","4":"file1","5":"file2","6":"file3","7":"file4","8":"file3","9":"file1"},"date":{"0":"2020-05-01 00:38:38.154","1":"2020-05-01 00:38:53.904","2":"2020-05-01 00:43:52.487","3":"2020-05-01 03:35:40.399","4":"2020-05-01 04:19:32.615","5":"2020-05-01 04:22:15.545","6":"2020-05-01 04:22:47.439","7":"2020-05-01 04:23:48.706","8":"2020-05-01 04:25:26.140","9":"2020-05-01 04:28:36.257"}}'

btw, the date is string format and I cannot convert it to datetime because I need to concat a string to each date in the next stage for some differentitation.
Please help, how can I get the output in the desired order.

A: I think you want this:
df['count'] = df.sort_values('date').groupby('col1').cumcount()

df.set_index(['col1', 'count']).query('count <= 2')['date'].unstack()

Output:
count                        0                        1                        2
col1
file   2020-05-01 03:35:40.399                      NaN                      NaN
file1  2020-05-01 00:38:38.154  2020-05-01 04:19:32.615  2020-05-01 04:28:36.257
file2  2020-05-01 00:38:53.904  2020-05-01 04:22:15.545                      NaN
file3  2020-05-01 00:43:52.487  2020-05-01 04:22:47.439  2020-05-01 04:25:26.140
file4  2020-05-01 04:23:48.706                      NaN                      NaN


text:
Q: Firebase createUserProfileDocument() is returning undefined the createUserProfileDocument() method from firebase is returning undefined for some reason, therefore, it's throwing an error on my broswer's console.
The error thrown is:

App.js:23 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') at App.js:23:1

the code:
import React from 'react';
import './App.css';
import { connect } from 'react-redux';
import { Switch, Route } from 'react-router-dom';
import HomePage from './pages/homepage/homepage.component';
import ShopPage from './pages/shop/shop.component';
import Header from './components/header/header.componet';

import { auth, createUserProfileDocument } from './firebase/firebase.utils';
import SignInAndSignUpPage from './pages/sign-in-and-sign-up/sign-in-and-sign-up.component';
import { setCurrentUser } from './redux/user/user.actions';

class App extends React.Component {
    unsubscribeFromAuth = null;

    componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

    componentWillUnmount() {
        this.unsubscribeFromAuth();
    }

    render() {
        return (
            <div className='App'>
                <Header />
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route exact path='/shop' component={ShopPage} />
                    <Route
                        exact
                        path='/signin'
                        component={SignInAndSignUpPage}
                    />
                </Switch>
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});

export default connect(null, mapDispatchToProps)(App);

The portion of code related to my error is the following:
componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {  // This is Line 23......
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

I console.logged(userRef) as you can see, and it returns undefined. This is my first experience with firebase so I am not sure where the error is.
I googled and found an answer here in stackoverflow which is alike to my issue: TypeError: Cannot read properties of undefined (reading 'onSnapshot')
However, that problem is specifically related to how the developer was passing the method as an array and not a method, which does not help my situation.
EDIT: Adding firebase.utils code.
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';

const config = {
  apiKey: 'AIzaSyDxUMY8sUpOMAoxEyHo41ONilzjL2woWHk',
  authDomain: 'crown-db-d4416.firebaseapp.com',
  projectId: 'crown-db-d4416',
  storageBucket: 'crown-db-d4416.appspot.com',
  messagingSenderId: '887003208895',
  appId: '1:887003208895:web:778f8f55a0ad2c72953a0a',
  measurementId: 'G-6TGCRVN7D3',
};

export const createUserProfileDocument = async (userAuth, additionalData) => {
  if (!userAuth) return;

  const userRef = firestore.doc(`users/${userAuth.uid}`);
  const snapShot = await userRef.get();

  console.log(snapShot);
  if (!snapShot.exists) {
    const { displayName, email } = userAuth;
    const createdAt = new Date();

    try {
      await userRef.set({
        displayName,
        email,
        createdAt,
        ...additionalData,
      });
    } catch (error) {
      console.log('Error creating user: ', error.message);
    }
  }
};

firebase.initializeApp(config);

export const auth = firebase.auth();
export const firestore = firebase.firestore();

const googleProvider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () => {
  auth
    .signInWithPopup(googleProvider)
    .then((res) => {
      console.log(res.user);
    })
    .catch((error) => {
      console.log(error.message);
    });
};

export default firebase;

A: Your createUserProfileDocument function doesn't return anything, so that explains why this code then fails:
const userRef = await createUserProfileDocument(userAuth);
console.log(userRef);
userRef.onSnapshot((snapshot) => {

The solution is to return the userRef from createUserProfileDocument as your calling code expects:
export const createUserProfileDocument = async (userAuth, additionalData) => {
  ...
  return userRef;
};


text:
Q: Cant change app.css with adminlte in laravel project After i run npm run watch, my app.css in public folder changes. I included link to that stylesheet inside my master blade of adminlte in laravel but nothing changes. When i open the mywebsite.test/portal/css/app.css it is not same as the file in my public directory.
I tried including my public app.css files in a few places but nothing helps. I included it like this
<link href="{{ asset('css/app.css') }}" rel="stylesheet">

when i write something like this
#logotest {
  color: red !important;
  padding: 150px;
}

iside my app.scss it showes after compiling in css/app.css, but in my html
<link href="http://mywebsite.test/portal/css/app.css" rel="stylesheet">

there is no trace of my changes

A: make sure APP_URL in you .env  does not contain /portal because asset() will build from APP_URL.
after committing changes to .env run php artisan cache:clear


text:
Q: How can I get the username from a MS Access front end MDW in a SQL back end audit table? I have an MS Access 2003 mdb and mdw which is connected to a SQL server backend. The tables are linked using a system DSN. I have a trigger on a SQL back end table which inserts a record into another back end audit table on insert, update, and delete. This all works well, but the trigger is using system_user to get the person making the record change, and the table is just recording the username the DSN is setup to use when that change is made in the linked Access table. If the DSN is set to use the generic sql username 'foo' and the MDW is using the user specific name 'bar', the audit table on the backend if recording all changes by all users as the user 'foo'. The users are logging in to the mdb with an mdw file, and I'd like to record the username from the mdw in the SQL backend. Is this at all possible?

A: From Access VBA you can use the CurrentUser() function to return the MDW user name.  You need to find a way to tell SQL Server about that name.  If you're building and submitting the DML statements from Access, you could add the CurrentUser value as a field expression.
I'm curious about using both Access user level security and SQL Server authentication.  At first blush it sounds like a "belt and suspenders" approach ... except that SQL Server can be a very effective belt, while Access user level security is a comparatively ineffective set of suspenders.  I would question what benefit ULS adds to your application.
Consider discarding ULS and switching to Windows Authentication for SQL server.  That could be a simpler, cleaner, and more secure approach.

A: I bet @@spid in the trigger works because it is executed by the process doing the DML.
Just be aware that this may not always be reliable because sometimes Access opens additional connections without having any way of running your special code to log the user against the spid in use.
Update
Have you considered using the CONTEXT_INFO variable that is specific to each SQL Server session?
DECLARE @Info varbinary(30)
SET @Info = Convert(varbinary(30), 'My Username')
SET CONTEXT_INFO @Info
SELECT Left(Convert(varchar(30), CONTEXT_INFO()), CharIndex(0x0, CONTEXT_INFO()) - 1)

This may mean hitting a table behind the scenes anyway, but it's surely going to be faster than doing it yourself.


text:
Q: Custom response headers not sent by server (Rails Devise) I'm trying to retrieve 3 response headers (Rails Devise Auth Headers: uid, client, access-token) in every request to a Rails Server.
Using Postman (http client) it's working.
With OkHttp (java http client) the headers just don't show up in the client (i've checked using Wireshark).
When i'm in debug mode it just work...

A: The additional headers with postman are due to postman sending  an Origin header and the server is replying with CORS headers, i.e. Access-Control-.... These headers are send within the normal HTTP header, i.e. not after the response.
But these access control headers are only relevant when the access is done from a browser because they control the cross origin behavior of XHR. Since you are not inside a browser they should be irrelevant for what you are doing. What is relevant are the body of the response and some of the other headers and here you'll find no differences. Also irrelevant should be if multiple requests are send within the same TCP connection (HTTP keep-alive done by postman) or with multiple connections (OkHttp) because each request is independent from the other and using the same TCP connection is only a performance optimization.
If you really want to get these special headers you should add an Origin header within you OkHttp request. See the OkHttp examples on how to add your own headers. But like I said: these access control headers should be irrelevant for the real task and there should be no need to get to these headers.

A: There is a property "config.batch_request_buffer_throttle" in the file "config/initializers/devise_token_auth.rb" of the Rails Project. We changed it from 5 seconds to 0 seconds.
It is a property to keep the current token available for that amount of time to the following requests.
As the original documentation: "Sometimes it's necessary to make several requests to the API at the same time. In this case, each request in the batch will need to share the same auth token. This setting determines how far apart the requests can be while still using the same auth token."
So when we did the request using Postman or in Java Debug the 5 seconds was running allowing Devise to generate new tokens then retrieve them to the client.


text:
Q: How do I get file names in Fineuploader's onAllComplete event I'm trying to retrieve the filenames for the successfully uploaded files in the onAllComplete() event.  My code below returns "undefined" for the getName() call.  I'm not sure if the file name is in fact no longer defined at this point or if I'm attempting to access it incorrectly.  Any help will be much appreciated.  Thanks!
var uploader = $('#fine-uploader').fineUploader({
    ...
    callbacks: {
         onAllComplete: function(succeeded, failed) {
            if (failed.length > 0) {
                alert("Error: Some files were not uploaded");
            } else {
                if (succeeded.length > 0 ) {
                    alert("Success!");
                }
                this.reset();
            }
            for (var id in succeeded) {
                alert(this.getName(id))
            }
        },
        ...
    },
...
});

A: The this.reset() is clearing the file names.


text:
Q: changing background color of rows in listview through an adapter I'm trying to implement a gmail like selection behavior: When I click on a item, it's either selected or deselected and a custom color is drawn over the selected items. I'm using this as a reference.
For some reason it only works after I select/deselect a few items. After that, getView() is called and everything works as expected.
Why isn't getView() called from the beginning?
ListActivity:
@Override
public void onListItemClick(ListView parent, View view, int position, long id) {
    super.onListItemClick(parent, view, position, id);
    mSimpleCursorAdapter.toggleSelected(new Integer(position));
}

Adapter:
 public ArrayList<Integer> selectedIds = new ArrayList<Integer>();

@Override
 public View getView(int position, View convertView, ViewGroup parent) {
    mCursor = (Cursor) getItem(position);
    ViewHolder holder = null;
    int col = -1;

    if(convertView == null)
    {
        holder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.row, parent, false);

        holder.mTitle = (TextView) convertView.findViewById(R.id.titleID);
        convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    col = mCursor.getColumnIndex(ReminderColumns.TITLE);
    holder.mTitle.setText(mCursor.getString(col));

    if (selectedIds.contains(position)) {
        convertView.setSelected(true);
        convertView.setPressed(true);
        convertView.setBackgroundColor(mContext.getResources().getColor(R.color.orange));
    }
    else
    {
        convertView.setSelected(false);
        convertView.setPressed(false);
        convertView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
    }
return convertView;
}

public void toggleSelected(Integer position)
{
    if(selectedIds.contains(position))
    {
        selectedIds.remove(position);
    }
    else
    {
        selectedIds.add(position);
    }
}

A: Have you tried adding notifyDataSetChanged()?
Perhaps adding it like this would help:
@Override
public void onListItemClick(ListView parent, View view, int position, long id) {
    super.onListItemClick(parent, view, position, id);
    mSimpleCursorAdapter.toggleSelected(new Integer(position));
    mSimpleCursorAdapter.notifyDataSetChanged();
}


text:
Q: AWS Lambda Event Payload for MSK trigger I'm trying to deserialize value to restore Kafka message value. But i can not find proper deserializer.  I receive following value:
AAAAAAKWBQACDkdMIE5hbWUgc3QuIEhlcm9pdiBQcmFjaRpiLjI4LCBhcHAuMTUwDktoYXJraXYES0gKODU0MzQSMDk4NDMyMzIzAK61xYSfXgIKMTE6MzICDFRSMTIzMghLeWl2

But when i'm trying to get string representation of deserialized message by:
        var bytes = Convert.FromBase64String("AAAAAAKWBQACDkdMIE5hbWUgc3QuIEhlcm9pdiBQcmFjaRpiLjI4LCBhcHAuMTUwDktoYXJraXYES0gKODU0MzQSMDk4NDMyMzIzAK61xYSfXgIKMTE6MzICDFRSMTIzMghLeWl2");
        var jsonBack = Encoding.UTF8.GetString(bytes);

And it's only partially able to deserialize it. with extra symbols. I can't find any docs on how it serialized and can not see the structure of it. Does anyone seen the same while working with AWS Lambda with MSK trigger for .Net
Bellow i give an example of message from aws docs. But there's no word about what's kept in value (Key & value of message and what's the form)

A: I have created a class that I use for this. I ran into similar issue when I started working with this because AWS only has given the example of node JS. So from there I created the below class that works just fine. Try it. Use this class as the type of payload received to your lambda function. So your handler signature would look like below. Please note that you would need to base64decode the 'body' property in the class 'KafkaMessage' below.
public async Task FunctionHandler(MSKEvent evnt, ILambdaContext context)
{
//do some magic.
}

/// <summary>
/// Represents an MSK event. MSK event is the event when lambda is triggered via a kafka topic.
/// </summary>
public class MSKEvent
{
    /// <summary>
    /// The source of the event.
    /// </summary>
    public string EventSource { get; set; }

    /// <summary>
    /// The AWS arn of the event source.
    /// </summary>
    public string EventSourceArn { get; set; }

    /// <summary>
    /// The collection of records.
    /// </summary>
    public Dictionary<string, IEnumerable<KafkaMessage>> Records { get; set; }
}

/// <summary>
/// Represents a kafka message.
/// </summary>
public class KafkaMessage
{
    /// <summary>
    /// The kafka topic name this message belongs to.
    /// </summary>
    public string Topic { get; set; }

    /// <summary>
    /// The kafka partition this message belongs to.
    /// </summary>
    public int Partition { get; set; }

    /// <summary>
    /// The offset of this message.
    /// </summary>
    public int Offset { get; set; }

    /// <summary>
    /// The created timestamp in unix ms of this message.
    /// </summary>
    public long Timestamp { get; set; }

    /// <summary>
    /// The timestamp type.
    /// </summary>
    public string TimestampType { get; set; }

    /// <summary>
    /// Base64 encoded message body. Base64 decode this field to obtain the actual message.
    /// </summary>
    [JsonProperty("value")]
    public string Body { get; set; }
}


text:
Q: Getting Error in building centrifuge index and couldn't build genome sequence for classification For metagenomic sequence classification, I used Centrifuge, which requires sequence and taxonomy files and sequence ID to taxonomy ID mapping. Whenever I try to create Makefile and Standard, an error occurs.
time centrifuge-compress.pl tmp_p_compressed+h+v/archaea taxonomy  --noDustmasker -map tmp_p_compressed+h+v/all-archaea.map \
        -o reference-sequences/all-compressed-archaea.fna.tmp -t 1 -maxG 50000000 2>&1 | tee centrifuge-compress-p_compressed+h+v.log && \
mv reference-sequences/all-compressed-archaea.fna.tmp.fa reference-sequences/all-compressed-archaea.fna && mv reference-sequences/all-compressed-archaea.fna.tmp.size reference-sequences/all-compressed-archaea.size && \
mv reference-sequences/all-compressed-archaea.fna.tmp.map reference-sequences/all-compressed-archaea.map
Could not find Jellyfish.

real    0m0.041s
user    0m0.028s
sys     0m0.009s
mv: cannot stat 'reference-sequences/all-compressed-archaea.fna.tmp.fa': No such file or directory
make[1]: *** [Makefile:229: reference-sequences/all-compressed-archaea.fna] Error 1
make[1]: Leaving directory '/home/tushar/nirjhar/centrifuge/indices'
make: *** [Makefile:137: p_compressed+h+v] Error 2

I am using https://github.com/DaehwanKimLab/centrifuge repository.


text:
Q: How to extract value of column based on value change in other column python I have dataframe with two columns i want extract value of first column based on second column, if in last 3 rows of column 2 value change from 0 to any value then extract value of column 1.
df=pd.DataFrame({'column1':[1,5,6,7,8,11,12,14,18,20],'column2':[0,0,1,1,0,0,0,256,256,0]})
print(df)
   column1  column2
0        1        0
1        5        0
2        6        1
3        7        1
4        8        0
5       11        0
6       12        0
7       14      256
8       18      256
9       20        0

out_put=pd.DataFrame({'column1':[20],'column2':[0]})

print(out_put)
   column1  column2
0       20        0

A: I believe you need check difference with last values to first in last 3 values of second column:
df1 = df.tail(3)
df2 = df1[df1['column2'].eq(0).view('i1').diff().eq(1)]

print (df2)
   column1  column2
9       20        0

Details:
#last 3 rows
print (df1)
   column1  column2
7       14      256
8       18      256
9       20        0

#compare second colum for equality
print (df1['column2'].eq(0))
7    False
8    False
9     True
Name: column2, dtype: bool

#convert mask to integers
print (df1['column2'].eq(0).view('i1'))
7    0
8    0
9    1
Name: column2, dtype: int8

#get difference
print (df1['column2'].eq(0).view('i1').diff())
Name: column2, dtype: int8
7    NaN
8    0.0
9    1.0
Name: column2, dtype: float64

#compare by 1
print (df1['column2'].eq(0).view('i1').diff().eq(1))
7    False
8    False
9     True
Name: column2, dtype: bool

And last filter by boolean indexing.


text:
Q: SQLAlchemy DataError closes transaction I have a model with a UUID type primary key.  Users can query the model by its ID.  If a user inputs a non-uuid type id, I want to be able to catch the error and marshal my own message.  However, DataErrors close the transaction and prevent me from validating all of the remaining ids.
How can I reopen the transaction or prevent it from closing?
Code:
try:
    some_model.query.filter_by(id=1).first()
except DataError:
    errors.append('failed :(')

other_model.query.filter_by(id=valid_uuid).first() # InternalError - Would work if it came first.

Error:
InternalError: (InternalError) current transaction is aborted, commands ignored until end of transaction block

A: My implementation of the UUID primary key column was poor.  I removed my implementation and instead chose to use the sqlalchemy-utils package.  The UUIDType column was a drop in replacement and removed the DataErrors.


text:
Q: IE automation VBA - How to access a span button without any text I am trying to do IE automation using VBA and facing a problem in clicking a span element.
I want to click on the below element.

Below is the code for the HTML Page. Since it is an intranet page, can't post the link for the same.

Below are the options I have tried using other reference posts.
Find the Span element by ID and then find the parent for it, which seems to be the  tag.
doc.getElementById("KEY_TOOLTIP_Export-btnIconEl").ParentNode.Click

Tried with class name as well.
doc.getElementsByClassName("x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item").Item(0).ParentNode.Click

I am able to find the element in the parent frame using the debugging option, so that should rule out the iFrame, isn't it?
I am very new to HTML, JavaScript so not understanding what else to check.

A: If the provide code not inside the Iframe tag, you could use the following code to find the element.
Sub Test()
    Dim IE As Object
    Dim selectItem As Object

    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Visible = True
        .Navigate "<website url>"

        While IE.ReadyState <> 4
            DoEvents
        Wend
        'Find element by ID property.
       'Set selectItem = IE.document.getElementById("KEY_TOOLTIP_Export-btnIconEl")
       'Debug.Print SelectItem.innerText
       'selectItem.Click

       'Find element by Class Name
       Set selectItem = IE.document.getElementsByClassName("x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item")(0)

       Debug.Print selectItem.innerText
       selectItem.Click

    End With
    Set IE = Nothing
End Sub

Note: please remember to change the website url to your owns.
In order to see the effect more clearly, I have added the onclick event in the span tag and a tag. The Html resource as below:

The screenshot:

If the elements inside the iframe tag, Html resource like this:

You could use the following code to find the iframe element first, and then, access the span element.
   Set selectItem = IE.document.getElementsByTagName("iframe")(0).contentDocument.getElementById("KEY_TOOLTIP_Export-btnIconEl")
   'Debug.Print selectItem.innerText 'debug, check the inner text.
   selectItem.Click


text:
Q: Is it possible to use socket.io server with pure html5 websockets? I want to use sockets in my web app. I don't want to use socket.io library on client-side. It's OK for server-side though. Can I do this?
Now with socket.io on server and pure websocket on client I have destroying non-socket.io upgrade error. I've googled that it means that I have to use socket.io-client library on client-side. Is there any way to avoid that? I don't want client to be tight with this library and use pure html5 websocket instead.
If it's not possible what should I use for server to connect with pure html5 websockets?
If someone is curious here is my server code (coffeescript file)
# Require HTTP module (to start server) and Socket.IO
http = require 'http'
io = require 'socket.io'

# Start the server at port 8080
server = http.createServer (req, res) ->
    # Send HTML headers and message
    res.writeHead 200, { 'Content-Type': 'text/html' }
    res.end "
Hello from server!
"

server.listen 8080

# Create a Socket.IO instance, passing it our server
socket = io.listen server

# Add a connect listener
socket.on 'connection', (client) ->

    # Create periodical which ends a message to the client every 5 seconds
    interval = setInterval ->
        client.send "This is a message from the server!  #{new Date().getTime()}"
    , 5000

    # Success!  Now listen to messages to be received
    client.on 'message', (event) ->
        console.log 'Received message from client!', event

    client.on 'disconnect', ->
        clearInterval interval
        console.log 'Server has disconnected'

And here is a client-side

A: I've found this library, seems OK for my needs https://npmjs.org/package/ws


text:
Q: Какую роль играют имена классов перед аргументами функций и методов? Вт к примеру кусок кода:
namespace App\Bot;

use App\WordPress\Functions as WordPressFunctions;

class Base
{
    private $logger;
    private $wp_facade;

    public function __construct($logger, WordPressFunctions $wp_facade)
    {
        $this->logger = $logger;
        $this->wp_facade = $wp_facade;
    }
}

для чего в данном случае

WordPressFunctions

перед

$wp_facade

Кому какая польза от этого ?

A: Это так называемый type hinting - контроль типа для входящего параметра. Если в класс будет передан параметр не того типа, как указано перед параметром, то получите ошибку.


text:
Q: cannot install a driver I built a simple driver using this tatourial (https://learn.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/writing-a-very-small-kmdf--driver).
I tried to install my driver but when i run the devcon tool i got:
Device node created. Install is complete when drivers are installed...
Updating drivers for Root/MyFiestDriver from C:\Users\WDKRemoteUser\Downloads\drive-download-20220107T092709Z-001\MyFiestDriver.inf.
devcon.exe failed.

i checked the logs and got the following error massages:
     [Device Install (UpdateDriverForPlugAndPlayDevices) - Root/MyFirstDriver]
>>>  Section start 2022/01/07 12:36:43.703
      cmd: devcon.exe  install MyFirstDriver.inf Root/MyFirstDriver
     ndv: INF path: C:\Users\WDKRemoteUser\Downloads\drive-download-20220107T092709Z-001\MyFirstDriver.inf
     ndv: Install flags: 0x00000001
     ndv: {Update Device Driver - ROOT\SYSTEM\0001}
     ndv:      Search options: 0x00000080
     ndv:      Searching single INF 'C:\Users\WDKRemoteUser\Downloads\drive-download-20220107T092709Z-001\MyFirstDriver.inf'
     dvi:      {Build Driver List} 12:36:43.734
     dvi:           Searching for hardware ID(s):
     dvi:                root/MyFirstDriver
     dvi:      {Build Driver List - exit(0x00000000)} 12:36:43.812
!    ndv:      No matching drivers found in single INF
     dvi:      {DIF_SELECTBESTCOMPATDRV} 12:36:43.828
     dvi:           Default installer: Enter 12:36:43.828
     dvi:                {Select Best Driver}
!    dvi:                     Selecting driver failed(0xe0000228)
     dvi:                {Select Best Driver - exit(0xe0000228)}
!    dvi:           Default installer: failed
!    dvi:           Error 0xe0000228: There are no compatible drivers for this device.
     dvi:      {DIF_SELECTBESTCOMPATDRV - exit(0xe0000228)} 12:36:43.859
!    ndv:      Unable to select best compatible driver. Error = 0xe0000228
     ndv:      No drivers found for device.
     ndv: {Update Device Driver - exit(00000103)}
!    ndv: No better matching drivers found for device 'ROOT\SYSTEM\0001'.
     ndv: {Update Device Driver - ROOT\SYSTEM\0002}
     ndv:      Search options: 0x00000080
     ndv:      Searching single INF 'C:\Users\WDKRemoteUser\Downloads\drive-download-20220107T092709Z-001\MyFirstDriver.inf'
     dvi:      {Build Driver List} 12:36:43.906
     dvi:           Searching for hardware ID(s):
     dvi:                root/MyFirstDriver
     dvi:      {Build Driver List - exit(0x00000000)} 12:36:43.922
!    ndv:      No matching drivers found in single INF
     dvi:      {DIF_SELECTBESTCOMPATDRV} 12:36:43.922
     dvi:           Default installer: Enter 12:36:43.937
     dvi:                {Select Best Driver}
!    dvi:                     Selecting driver failed(0xe0000228)
     dvi:                {Select Best Driver - exit(0xe0000228)}
!    dvi:           Default installer: failed
!    dvi:           Error 0xe0000228: There are no compatible drivers for this device.
     dvi:      {DIF_SELECTBESTCOMPATDRV - exit(0xe0000228)} 12:36:43.953
!    ndv:      Unable to select best compatible driver. Error = 0xe0000228
     ndv:      No drivers found for device.
     ndv: {Update Device Driver - exit(00000103)}
!    ndv: No better matching drivers found for device 'ROOT\SYSTEM\0002'.
!    ndv: No devices were updated.
<<<  Section end 2022/01/07 12:36:44.062
<<<  [Exit status: FAILURE(0x00000103)]

i used the inf file visual studio generated for me and couldn't find anyway to fix this.
the inf file i use looks like that:
    ;
; MyFirstDriver.inf
;

[Version]
Signature="$WINDOWS NT$"
Class=System ; TODO: specify appropriate Class
ClassGuid={4d36e97d-e325-11ce-bfc1-08002be10318} ; TODO: specify appropriate ClassGuid
Provider=%ManufacturerName%
CatalogFile=MyFirstDriver.cat
DriverVer = 01/04/2022,10.43.33.93
PnpLockdown=1

[DestinationDirs]
DefaultDestDir = 12
MyFirstDriver_Device_CoInstaller_CopyFiles = 11

[SourceDisksNames]
1 = %DiskName%,,,""

[SourceDisksFiles]
MyFirstDriver.sys  = 1,,
;

;*****************************************
; Install Section
;*****************************************

[Manufacturer]
%ManufacturerName%=Standard,NTamd64

[Standard.NTamd64]
%MyFirstDriver.DeviceDesc%=MyFirstDriver_Device, Root\MyFirstDriver ; TODO: edit hw-id

[MyFirstDriver_Device.NT]
CopyFiles=Drivers_Dir

[Drivers_Dir]
MyFirstDriver.sys

;-------------- Service installation
[MyFirstDriver_Device.NT.Services]
AddService = MyFirstDriver,%SPSVCINST_ASSOCSERVICE%, MyFirstDriver_Service_Inst

; -------------- MyFirstDriver driver install sections
[MyFirstDriver_Service_Inst]
DisplayName    = %MyFirstDriver.SVCDESC%
ServiceType    = 1               ; SERVICE_KERNEL_DRIVER
StartType      = 3               ; SERVICE_DEMAND_START
ErrorControl   = 1               ; SERVICE_ERROR_NORMAL
ServiceBinary  = %12%\MyFirstDriver.sys

;
;--- MyFirstDriver_Device Coinstaller installation ------
;

[MyFirstDriver_Device.NT.CoInstallers]
AddReg=MyFirstDriver_Device_CoInstaller_AddReg
CopyFiles=MyFirstDriver_Device_CoInstaller_CopyFiles

[MyFirstDriver_Device_CoInstaller_AddReg]
;

[MyFirstDriver_Device_CoInstaller_CopyFiles]
;

[MyFirstDriver_Device.NT.Wdf]
KmdfService =  MyFirstDriver, MyFirstDriver_wdfsect
[MyFirstDriver_wdfsect]
KmdfLibraryVersion = 1.15

[Strings]
SPSVCINST_ASSOCSERVICE= 0x00000002
ManufacturerName="<Your manufacturer name>" ;TODO: Replace with your manufacturer name
DiskName = "MyFirstDriver Installation Disk"
MyFirstDriver.DeviceDesc = "MyFirstDriver Device"
MyFirstDriver.SVCDESC = "MyFirstDriver Service"

A: I had the same issue.
In your case you are passing "root/MyFirstDriver" to devcon, but you have defined the id in the inx/inf file to be the similar but not identical string "root\MyFirstDriver". I am guessing that is why your devcon command is failing.
In my case the strings were identical, but I still got the "No matching drivers found in single INF" error. Eventually I found a Debug Win32 driver as I was using was not going to work. Switching the sample project to x64 Release build fixed the issue for me.


text:
Q: C# Regex; Double Quote Issue I'm a little stumped here.  I had this method, which was working fine until just recently:
internal static bool IsZplFormat(string szString)
{
    var regex = new Regex(@"\^XA.*\^XZ\\r\\n");
    return regex.IsMatch(szString);
}

That would work fine given the following string (taken from my unit test):
const string zplSample = "^XA blah blah blah ^XZ\r\n";

What appears to be happening now, is that I'm getting something like this:
const string zplSample = "^XA blah blah \"blah ^XZ\r\n";

And now my regex doesn't match anymore.
I thought the .* should match all characters, but it seems to be getting tripped up on that double quote.  Any ideas on how I can get this working again?

A: Testing here...
string zplSample  = "^XA blah blah blah ^XZ\r\n";
string zplSample1 = "^XA blah blah \"blah ^XZ\r\n";

Console.WriteLine(new Regex(@"\^XA.*\^XZ\r\n").IsMatch(zplSample));
Console.WriteLine(new Regex(@"\^XA.*\^XZ\r\n").IsMatch(zplSample1));

Console.ReadKey();

Output
True
True

What did I change? The regex pattern to @"\^XA.*\^XZ\r\n". (From two backslashes to one) (\\r\\n)


text:
Q: Прикладное программирование vs web-программирование На данный момент очень популярна разработка web-приложений (+ всякие решения для sharepoint и прочее). Наверное, начинать лучше именно в этой области (если интересует именно зарплата и перспектива её роста).
Собственно, вопрос: прикладное программирование вымирает? Что делать, если web-разработка дико неинтересна (не важно по какой причине, вот не нравится и всё), а хочется работать, например, над интересными проектами и получать адекватную зарплату в то же время (если сравнивать, можно получать n денег за разработку под sharepoint при опыте в m лет и n/2 при том же опыте, но при разработке, например, Win-приложения)?
upd: вопрос состоит в том, реально ли сейчас найти работу не web и в то же время с адекватной зарплатой.

A: Еще как реально! Нужно знать куда смотреть.
Вы, видимо, просто не представляете сколько всего интересного за пределами Web.
Одними из основных направлений считаю - автоматизация (с элементами ИИ), data mining, и т.п.
И я бы на вашем месте еще бы сузил вопрос:

*

*Какие именно из "web-приложений" вам не нравятся? Т.е. насколько широко Ваше понятие "приложение". Если же оно просто заканчивается на sharepoint, php, js и т.п., то, пожалуй скажу, что вы заблуждаетесь. Если больше, укажите пожалуйста хотя бы области, которые не нравятся.

*Что вы называете интересными проектами? Больше конкретики... А то так гадать, куда же вам предложить пойти мы можем вечно.

UPD1
Насчет прикладных решений, вы ошибаетесь, никуда они не делись, просто остались невидимые "невооруженным" глазом направления. Для которых продукция, общепризнанных лидеров рынка, просто неприменима по каким-то причинам. И поверьте, платят там неплохо. Это в том числе узко специализированные прикладные проекты, которым просто не нужен веб. Вариантов масса, надо просто найти человека, который даст возможность развиться.
Я полагал, вы имели ввиду весь спектр веб-решений. В том числе работа с различными API.
Например, работа с API какого-то банка, но ПО разрабатывается, например, под Андроид. С одной стороны это можно назвать веб-приложением, но с другой стороны это все же прикладуха для пользователя. Со стороны программиста это тоже больше прикладуха, имхо.
Возможно вам будут интересны разработки для новых течений в области хранения и обработки информации, например, такие как OLAP.
Одно, чего мне не хватало в процессе учебы, это чтобы кто-то показал, что есть на свете. Чтобы кто-то мог рассказать о новых технологиях, новых течениях и т.п. Поэтому я могу вас понять, до наших краев информация доходит весьма и весьма медленно. Не из чего выбрать, так как реально не знаешь из чего выбирать.
И еще, за границей особенной разницы между зарплатами прикладных программистов и веб-программистов не наблюдается (лично мое наблюдение из того, что видел/искал). Причина в том, что у нас з/п веб-программистов низки, а прикладных программистов еще ниже. имхо.
A: Вариант - desktop-клиент, работающий через web-сервисы
A: Насчет программирования может и да, на рынке софта образовались свои флагманы они обновляются свое ПО каждую неделю, месяц, конкурировать тяжело. И что же делать обычным кодерам ПО, они и идут в веб-разработку или к тем же флагманам присоединяются.
Ну если веб-разработка неинтересна, может разработка приложений или игр для смартфонов на андроиде была бы интересной, или для смартфонов с другими ОС; но по мне для андроида самое оно: он за считаные годы завоевал такую большую часть рынка смартов, тем более выходят каждую неделю новые тачфоны с супер характеристиками - это целый мир для творчества и идей.
A: Пишите на .NET, если web не нравится, да и если писать на .net, то при необходимости и под web можно спокойно писать.
Ну, а по факту, сейчас все движется к mobile-web, разные Pad'ы и Phone'ы стали популярными среди широкого круга людей, и поэтому разработка под них популярна и перспективна. А web сейчас выходит на уровень настольных программ, так что можно и тут расти, те же SaaS и PaaS, облака, SL, Flesh, ExtJS и т.д., могут творить чудеса.
A: Про Web здесь писали уже выше, скажу о прикладном программировании: оно не умрет ни когда!Далеко не все завязано на вебе, начиная от микроконтроллеров и заканчивая робототехникой и ИИ (искуственный интеллект), разработки НАСА...
A: Прикладное программирование не умирает, оно будет жить еще долго, однако технология действительно становиться ВЭБ. ВЭБ тоже прикладное программирование. Не понимаю что значит "скучно". Мое мнение (писал неоднократно на разных форумах уже), пора делать RIA приложения. Все плюсы налицо, кроссплатформенность, отсуствие необходимости инсталляции, легкое обновление, да и интерфейсы современные под ВЭБ уже обгоняют по юзабилитети классические приложение.
УЧИТЕ ВЭБ НЕ ПОЖАЛЕЕТЕ!


text:
Q: ConTeXt: Missing Chapter Numbers Code
Minimum working example (MWE):
\setuphead[chapter][number=yes,]
\setuphead[section][number=no,]
\setuphead[subsection][placehead=hidden,]

\definehead[scenesubsection][subsection]

\starttext
  \dorecurse{5}{
    \chapter{Chapter Name}
    \section{Section Name}
    \startscenesubsection
    \input tufte
    \stopscenesubsection
  }
\stoptext

Problem
The chapter headings should be enumerated 1 through 5, but some chapter numbers are either hidden or enumerated incorrectly.
The following figure shows the MWE output:

Question
How can the problems with chapter numbering be resolved?
Additional Details
$ context --version
mtx-context     | current version: 2017.05.14 19:09

Work Around
Using placehead=no causes the spacing to change when framing an entire section:

A: Use a custom counter:
\definecounter[ChapterNumber][
  way=bytext,
  prefix=no,
]

\define[1]\CustomChapter{%
  \incrementcounter[ChapterNumber]
  \rawcountervalue[ChapterNumber]
  \hspace[medium]
  #1
}

\setuphead[chapter][
  align=middle,
  number=no,
  textcommand=\CustomChapter,
]

\setuphead[section][
  align=middle,
  number=no,
]

\setuphead[subsection][
  placehead=hidden,
  number=no,
]

\definehead[scenesubsection][subsection]


text:
Q: Question about the univalence axiom versus skeleta. Here, Dan Licata writes:

[Univalence] can be used to build algebraic structures in such a
  way that isomorphic structures are equal (e.g. equality of groups is
  group isomorphism).

He writes something similar here:

A consequence of the univalence axiom is that isomorphic types are
  equivalent (propositionally equal).

Now nLab writes:

A category is skeletal if objects that are isomorphic are necessarily
  equal; so this is a notion irredeemably violating the principle of
  equivalence of category theory.

Is there not a contradiction here? How can we claim that:

*

*skeletons violate the principle of equivalence

*univalence upholds it

when apparently, univalence implies that every category is skeletal?

A: Well, Homotopy Type Theory introduces some extraordinary equality, which approach requires special attention, and so the n-Lab article is a little bit out of this context, as it uses categories over some classical set theory, while HoTT defines its own 'precategories' and 'categories'.
For a motivating example, when we arrange four small balls in $2\times 2$ matrix, we give an interpretation of the multiplication $2\times 2$ of numbers, but as a number this arrangement equals to $4$:
$$2\times2\ =\ 4 $$
Similarly, we might want that e.g. the Klein group $V_4$ and the product group $\Bbb Z_2\times\Bbb Z_2$ would be equal, as groups (independently of exactly which four elements build them and how).
$$\Bbb Z_2\times\Bbb Z_2\ =\ V_4$$
As you have found, categories --as defined in HoTT-- are indeed necessarily skeletal in that setting.

*

*That 'Skeletons violate the principle of equivalence' refers to the fact that the property 'skeletal' is not invariant under category equivalence.

*As every category (in the sense and context of HoTT[!]) is skeletal, category equivalence here seems to coincide to category isomorphism, hence -by Univalence- to equality.
In HoTT the notion 'skeletal' just gets meaningless.
But the whole HoTT theory is still under development, terms and definitions are not necessarily in their finalized form yet..


text:
Q: How to Enforce HTTPS For ASMX Service I have a number of existing ASMX web services running on IIS7, and want to change them so that all requests and responses must be made over HTTPS.
The site is also running other pages like PHP and Classic ASP, so I can't just change the site root to serve HTTPS pages.
How can I set this per ASMX serivce (application), so that if somebody visits http://www.mydomain.com/MyService/ServiceName.asmx it either redirects them to https://www.mydomain.com/MyService/ServiceName.asmx or  returns a 404 error ?
Thoughts and best approach ?

A: Have you tried with URL rewrite?
<rewrite>
    <rules>
        <rule name="Force HTTPS" stopProcessing="true">
            <match url="(.*)/ServiceName.asmx" />
            <conditions>
                <add input="{HTTPS}" pattern="^OFF$" />
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>

A: A simpler solution would be just to include the following code in the constructor of each service - allowing you to decide it on each service individually.
if (!HttpContext.Current.Request.IsSecureConnection)
{
    var sslUrl = HttpContext.Current.Request.RawUrl.Replace("http://", "https://");

    Response.Clear();
    Response.Write(string.Format("This service requires a SSL connection please go to {0}", sslUrl));
    Response.End();

    // Or simply redirect
    // Response.Redirect(sslUrl);
}

A: The redirect that @oexenhave used did not work for me. Instead I used the following (with a tip of the hat to @oexenhave for doing most of the good work)
if (!HttpContext.Current.Request.IsSecureConnection)
{
  var sslUrl = HttpContext.Current.Request.RawUrl.Replace("http://", "https://");
  Context.RewritePath(sslUrl);
}

Add this into the asmx constructor.

A: I will encourage you to use WCF instead of ASMX  http://msdn.microsoft.com/en-us/library/aa480190.aspx.
For your above question, does this solve your issue?
http://msdn.microsoft.com/en-us/library/aa302409.aspx
Thanks...


text:
Q: How to get started building a web browser? I decided to put some effort in building a web browser from scratch. What are the common functions, architectures, and features of modern web browsers that I should know before getting started?
Any recommendations are highly appreciated!

A: You could start with well-formed and valid XHTML, which should be easier than the tag soup your browser will encounter in real "life".
Then you must find a way to bend the real HTML from the web to your needs.
But don't kid yourself: A browser isn't a small project.

A: Sounds like a really interesting project, but it will require you to invest an enormous effort.
It's no easy thing, but from an academic point of view, you could learn so much from it.
Some resources that you could check:

*

*HTMLayout.NET: fast, lightweight and embeddable HTML/CSS renderer and layout manager component.

*GeckoFX: Windows Forms control that embeds the Mozilla Gecko browser control in any Windows Forms Application.

*SwiftDotNet: A Browser based on Webkit in C#

*Gecko DotNetEmbed

*Gecko#

*Rendering a web page - step by step
But seeing it from a realistic point of view, the huge effort needed to code it from scratch reminded me this comic:

(source: geekherocomic.com)
Good Luck :-)

A: ...then start worrying about security
(non-functional and cross cutting concerns should be generally considered up front though :) )

A: Most modern web browsers are giant beasts, and probably fairly poorly designed because they (and the web itself) evolved in a rather haphazard way.
You need to start by first making the goals of your project (and what you hope to achieve) very explicit. Is this something you're just doing for fun, or do you expect other people to use your browser? If you expect others to use it, what will the incentive for them be? It is unrealistic to expect that you will develop a new browser from scratch that everyone will be able to use as a replacement for Chrome, Safari, Firefox, IE, Opera, etc. All of those projects have a 10-15 year head start on you, and by the time you've caught up to them, they will be another 10-15 years ahead of you. Plus they have a lot more man power behind them, and so if you want your project to be successful, you will need that man power at some point.
This is the reason that Apple and Google, big companies with lots of resources, did not start from scratch. Not even Microsoft started from scratch. The original IE was based on Mosaic. The only significant browsers still around today that were started from scratch are Opera, Konqueror and Lynx, which unfortunately all have minuscule market share. Let's forget about Lynx for the moment, since it's a text-only browser and presumably the only reason it's still around is because it serves that specific niche. Opera is arguably one of the best browsers ever made, and yet it's never had a great market share, so remember that success and innovation are not the same thing. KHTML is the engine behind Konqueror, which never itself became very successful, but is the basis of WebKit that both Apple and Google use. I think one could definitely argue that if KHTML had never been made, neither Safari or Chrome would exist. Interestingly enough, both KHTML and Opera were largely produced by Norwegian programmers working in the same building in Oslo.
You need to look at building a web browser like building an operating system, because that's essentially what a browser is -- it's an operating system for running web apps. And like an operating system, a web browser is a very complex piece of software with many components. Of course, people have been successful at creating new operating systems from scratch. Linus Torvalds comes to mind. He made Linux, one of the most successful operating systems ever.
Of course, you face an additional challenge, which makes building a new successful browser harder than building a new successful OS. Browsers are expected to flawlessly run all the legacy code floating around on the web. Now suppose that Linus Torvalds had been told that his new OS wouldn't matter unless it was perfectly backwards compatible with UNIX or some existing OS. I doubt he would have bothered, and Linux probably wouldn't exist today. Realistically, of course, the only reason Linux became popular was because it was designed well and the GNU project was able to make tools for porting huge amounts of existing code to Linux. Without GNU's ideological support for Linux, it never would have had a chance.
So assuming you really are ambitious (or foolhardy) enough to try to make a new successful browser, the thing you should be focusing on is architecture and design. There is no practical reason to build a new browser from scratch unless you are sure you can improve upon the design of existing browsers in some way. That means you need to familiarize yourself enough with the code of WebKit and Gecko enough to understand the design decisions they made, but you shouldn't be attempting to copy their design because otherwise you might as well just use their code.
My personal thoughts (without having done enough research) is that today's browsers are not modular enough. If I were going to make a new browser, I would find a way to make it easy to swap things in and out (like replace one JavaScript engine with another), and give the user a lot more control than they currently have with existing browsers. Modern browsers and web designers have taken almost all control away from the user. Why can't I, the user, tell the web browser how I want it to render content being displayed on my machine? The original HTML only gave guidelines for how to structure content, and over time, newer standards have become more and more dogmatic, to the point where the user is now at the total mercy of the web designer. The appeal of Linux was that it gave back control to the user, and that's why so many geeks supported it and made it into a successful OS.
The other thing I would spend time researching, if I were you, is operating system design principles. Designing a good browser, should at least in theory, require the same principles as designing a good OS -- especially in regards to concurrent processes, security models, etc.
Finally, after having done lots and lots of research, this is where you should start coding I think:

*

*Re-engineer Mosaic, but with your own design ideas. This is also what I would suggest if your are just doing it for fun or your own educational benefit. Read the original HTML 1.0 and HTML 2.0 specs, as well as the HTTP 1.1 specs and the current URI specs, and make sure your browser adheres to all those specs. You can of course download existing software that already handles the transport protocols, URI conventions, etc. but if you're serious about designing your own browser, I think it is a good exercise to do these things from scratch as well, so you get a good sense of how all the puzzle pieces fit together. At the end of step 0, you should have a browser that is at least comparable to what was state-of-the-art in the 90's. This is a good first milestone. And you can actually download the original Mosaic at ftp://ftp.ncsa.uiuc.edu/Mosaic/ and see how it compares with your browser. It's also a good exercise to see how current websites render in an ancient browser like Mosaic.

*Add support for the DOM to your browser. Focus on W3C DOM Level 1 and Level 2 first, since pretty much all current browsers support those completely. Then look at Level 3 and Level 4. The DOM is extremely fundamental to web programming, and so if you're going to actually build a modern web browser, it's entire design has to take this into consideration. Since you are writing the browser in C# you may want to take into consideration how you could leverage the existing .NET object model to your advantage.

*Look at existing scripting engines and see if you can port them to your project. I'd discourage you from writing your own JavaScript interpreter, not only because that's a very large project in itself, but because so much work has already been put into optimizing JS compilers (e.g. V8). So unless you're a guru in compiler design, your hand-built JS interpreter will likely be inferior to what's already out there, even if it follows the EMCAScript specs flawlessly. Again, I think the scripting engine should be something that is a completely separate module from the actual browser anyway, so I think it would be much more useful to have a framework that allows you to substitute any scripting engine, rather than build a scripting engine that only works with your browser.

*Look at the HTML / CSS / JS source code for the top 10-20 websites in North America (Google, Facebook, YouTube, Twitter, Wikipedia, Amazon, popular blogging platforms, etc.) and engineer your browser to work well with these sites. This is a somewhat more tractable problem to solve than making a browser that adheres to all the existing standards (something that current browsers still don't do perfectly) much less making a browser that correctly renders all the web sites on the web (nobody can do that). People will complain that your browser breaks standards and so-forth, but that's not as big of a problem as people complaining that they can't access Google or Facebook with your browser. I can't think of any browser that correctly followed all (or even most) standards on its first release, so I say don't even bother trying. If you can make something that people will want to use enough that there will ever be a 2nd or 3rd version, then you can worry about standards at that point.

A: very ambitious project but one developer can't do this alone you need a team(project manager , testers ...) and maybe you should review your choise of language c# works only on windows(i know mono on linux but it is not the same)
anyway i wish you good luck and i ll be happy to use your browser :D

A: You mean as in writing your own rendering engine?
I can only say good luck. Many man years have gone into the current generation of the various browsers, If you want to do better than either of them you will need some serious skills. If you have to ask where to start, you probably have more than a few years of study to go before it would make any sense to attempt such a task.
That said, here are some (obvious) pointers:

*

*write lots of code that does small things, like solve all the projecteuler.net problems

*learn everything you can about your toolkit and its community standards

*write lots more code

*get a real solid grasp of finite state machines

*write yet more code

*learn all about the tcp/ip stack and how it's used for http

*learn all you can about http

*learn the standards (html, xml, sgml, css)

*celebrate your 150th birthday.

*get started on the actual browser project.

edit below here
I didn't mean for it to be either motivating or demotivating, just an attempt to show you that a browser is a really big project and that really big projects require a whole lot of thought. Blunt honesty sprinkled with humour.
I've been programming for over two thirds of my life and I like to think that I am a pretty decent programmer, but it would be foolish of me to think that I'd stand half a chance at writing a decent web browser from scratch.
Ofcourse, if this is what you want to do, don't let my comment stand in your way. You can probably do better than Internet Explorer.

A: Well break it down into pieces.  What is a Web browser?  What does it do?  It:

*

*Fetches external content.  So you need a HTTP library or (not recommended) write this yourself.  There's a lot of complexity/subtlety to the HTTP protocol eg handling of expires headers, different versions (although it's mostly 1.1 these days), etc;

*Handles different content types.  Theres a Windos registry for this kind of thing that you can piggyback.  I'm talking interpreting content based on MIME type here;

*Parses HTML and XML: to create a DOM (Document Object Model);

*Parses and applies CSS: this entails understanding all the properties, all the units of measure and all the ways values can be specified (eg "border: 1px solid black" vs the separate border-width, etc properties);

*Implements the W3C visual model (and this is the real kicker); and

*Has a Javascript engine.

And that's basically a Web browser in a nutshell.  Now some of these tasks are incredibly complex.  Even the easy sounding ones can be hard.  Take fetching external content.  You need to deal with use cases like:

*

*How many concurrent connections to use?

*Error reporting to the user;

*Proxies;

*User options;

*etc.

The reason I and others are colletively raising our eyebrows is the rendering engine is hard (and, as someone noted, man years have gone into their development).  The major rendering engines around are:

*

*Trident: developed by Microsoft for Internet Explorer;

*Gecko: used in Firefox;

*Webkit: used in Safari and Chrome 0-27;

*KHTML: used in the KDE desktop environment.  Webkit forked from KHTML some years ago;

*Elektra: used in Opera 4-6;

*Presto: used in Opera 7-12;

*Blink: used in Chrome 28+, Opera 15+, webkit fork;

The top three have to be considered the major rendering engines used today.
Javascript engines are also hard.  There are several of these that tend to be tied to the particular rendering engine:

*

*SpiderMonkey: used in Gecko/Firefox;

*TraceMonkey: will replace SpiderMonkey in Firefox 3.1 and introduces JIT (just-in-time) compilation;

*KJS: used by Konqueror, tied to KHTML;

*JScript: the Javascript engine of Trident, used in Internet Explorer;

*JavascriptCore: used in Webkit by the Safari browser;

*SquirrelFish: will be used in Webkit and adds JIT like TraceMonkey;

*V8: Google's Javascript engine used in Chrome and Opera;

*Opera (12.X and less) also used its own.

And of course there's all the user interface stuff: navigation between pages, page history, clearing temporary files, typing in a URL, autocompleting URLs and so on.
That is a lot of work.

A: It's an insanely ambitious project (especially for a single developer) but something I'd love to do someday - you could learn so much from it.
I don't know a lot about how the protocols work (something that you definitely need to research) or much about what goes on in a browser but a great place to start would be the source of the open-source browsers, primarily Chrome and Firefox. Chrome is an especially good project to look at as they only do what I'd expect you to start with: the chrome and the backend of the browser. Forget creating a rendering engine at first - use Webkit or Gekko.

A: As everyone else has already said, a web browser is a huge project.  You've got to worry about tcp/ip&sockets, rendering html, using css, creating a DOM model, executing javascript, dealing with malformed markup and code, and handling all types of files before you can even think about all the things people expect from a browser (ie bookmarks, history, private browsing, security, etc.)  It's a huge project.
That being said, it can be done.  My suggestion would be to go look at the source of Firefox.  I know that you said you want to build a browser from scratch, but it would be very helpful to learn from an open-source project, first.
I would download the Firefox source, and slowly strip it down.  In other words, I would take the source and remove all bookmarking functionality.  Then, I'd remove the ability to handle addons.  Then, I'd delete all code regarding saving files.  I would continue this process until I got a very basic web browser. I'd look over that code.
Then, I'd start building my own.  I'd take the knowledge I'd gained from taking apart Firefox, and I'd put it into building a new browser.
A whole lot of luck to you!

A: You really have a lot of free time in your hand, haven't you? AFAIK, most browsers were written in C++, not all users have the .NET framework installed on their computers and if they do it might not be the version you need.
This could take you years but anyway, there are many open source browsers out there, FireFox, Google Chrome .. etc, you could start by having a look on the code, good luck with that :)


text:
Q: Solving nonlinear first order differential equations I have the differential equation
$$x^{2}y'{(x)} + 2xy{(x)} = y^{2}{(x)}$$
With initial condition $y{(1)} = 1$ and I want to solve this, by observation, we can see the LHS is $x^{2}y{(x)}$ but I am unfamiliar with tackling the RHS and was wondering where to go from here.
$$x^{2}y{(x)} = \int y^{2}{(x)} \ dx$$

A: This suggests the change of unknown $z=x^2y$, leading to an equation in separeted variables.

A: First, write the ode as
$$ x^{2}y'{(x)} + 2xy{(x)} = y^{2}{(x)} \implies y'+2\frac{y}{x}=\frac{y^2}{x^2}. $$
Now, use the change of variables $y=x u$ in the above ode which yields
$$ xu'+3u = u^2 \implies \int \frac{du}{u^2-3u} = \int \frac{dx}{x}. $$
I think you can finish it now.

A: In addition to Julián's answer, note that the LHS is precisely the derivative of $x^2 y(x)$, which readily leads to the change of variables that he pointed out. Thus, you have:
$$\frac{dz}{dx} = \left(\frac{z}{x^2}\right)^2,$$
which can now easily solved.
Cheers!

A: Note that
$$
x^{2}y'{(x)} + 2xy{(x)} = [x^2 y(x)]'
$$
Then
$$
[x^2 y(x)]' = y^{2}{(x)}
$$
Putting $z(x)=x^2 y(x)$, i.e. $z^2(x)/x^4=y^2(x)$, we have
$$
z'(x) = \frac{z^2(x)}{x^4}
$$
separable variables equation.


text:
Q: Replace a nested array in Mongo (using Meteor) I have a document in this structure
{
  _id: 'playlistId',
  list_of_songs: [
    {
      _id: 'songId',
      song_title: 'Hello World',
      song_artists: [
        {
          artist_name: 'Aaron',
        }, {
          artist_name: 'Ben',
        }
      ]
    }
  ]
}

I'm intending to replace the entire array list_of_songs.$.song_artists for 'Hello World' in an update operation
newArrayOfArtists = [{...}, {...}, {...}]

Playlist.update({  _id: 'playlistId', }, {
  $set: {
    'list_of_songs.0.song_artists': newArrayOfArtists
  }
}

but I'm hitting this error
cannot use the part (...) to traverse the element (...)

Am I doing something wrongly, or is this due to a limitation of MongoDB (see Updating nested arrays in mongoDB via mongo shell)? I'm at a total loss here, many thanks for helping.


text:
Q: Connection Strings between Web Application and SQL Server Greetings.
I'm writing a web application that is supposed to connect to a SQL Server database; the connection is formed from the following database string:
<add key="DatabaseConnectionString" value="server=DEVPC1\SQLEXPRESS;uid=USERID;pwd=PASSWORD;database=DATABASE"/>

However, whenever I try and run the web application, I get a connection error, specifically:
An error occurred attempting this login:
Login failed for user 'USERID'.

Any suggestions on how to go about debugging this? I'm not really familiar with SQL, so any suggestions would be greatly appreciated.

A: This is is not a coding error, it indicates the authentication credentials are wrong. Are you able to connect with the database using these credentials using SSMS? Are you sure you are connect to the right server?

A: it will help if you replace USERID and PASSWORD with your actual credentials along with "DATABASE" (unless this is the name of your database ofcourse :) )

A: Does user exist in the Db? ConnectionStrings.com is a good reference.


text:
Q: Left align menu icon Im trying to left align a menu icon.
The icon is displaying above the menu name but I would like to align in to the left of the menu name.
The CSS I have is:
.icon_name_here:before {
content: '';
width: 24px;
height: 24px;
display: inline-block;
float: left;
background: url('http://url_of_icon_here.com') no-repeat left;}

How / what do I have to do to align the icon to the left of the menu name?

A: Without posting a relevant code its hard to give a exact answer. I've tried to re-build on the assumption of the CSS you posted and here I've build a demo. See the DEMO .
CSS is like this.
ul{margin:0;padding:0;}
ul li {padding:4px;}

.icon_name_here:before {
content: '';
width: 24px;
height: 24px;
display: block;
float: left;
padding:4px;
background: url('http://lorempixel.com/24/24/') no-repeat 0 0;}

HTML is like it.

Item1

Item2

Updates
you have to add a display:inline-block on  tag. Check the uploaded image.
HOME

A: use display: inline style for both image and  Text

A: You can use this method like a variant. It can be helpfull when you want to use sprites
HTML

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, beatae consequatur dolore doloribus dolorum harum, laboriosam magnam natus, numquam odit officiis quia quisquam suscipit tempora voluptatum. Facere quae quis sed?

CSS
.your-content {
    position: relative;
    padding: 0 0 0 10px; /*space between block edge and displaying of your text*/
}
.your-content:after {
    content:'';
    position: absolute;
    top: 0px; /*position of your icon*/
    left: 0px; /*position of your icon*/
    width: px; /*width of your icon*/
    height: px; /*height of your icon*/
    background: url(img/your-icon-bg.png)  no-repeat;
}


text:
Q: The item you have requested is not available in any store Greetings for the day.
I am able to open my app on Appstore. Through appstore I am also able to view in iTunes. But when I try to open direct iTunes link the message comes "The item you have requested is not available in xx store".
Note: My app is available for all stores & I repeat I am able to view in iTunes from appstore url.
Any idea why the direct link is not getting open?
Any help is appreciated!

A: Is the url encoded?? url sometimes you use might have some mistakes.please check da.

A: I am done with the ultimate solution.
What I did is: I changed the url.
I replace the url with the same url that I was able to open from the Appstore via view in iTunes.
This worked for me ! :)


text:
Q: What does it mean by 'local file system?' I'm currently reading about hadoop and I  came across this which has puzzled me (please bear in mind that I am a complete novice when it comes to hadoop) -
Use the Hadoop get command to copy a file from HDFS to your local file
system:
$ hadoop hdfs dfs -get file_name /user/login_user_name

What is a local file system?  I understand that a HDFS partitions a file into different blocks throughout the cluster (but I know there's more to it than that). My understanding of the above command is that I can copy a file from the cluster to my personal (i.e. local) computer? Or is that completely wrong? I'm just not entirely sure what is meant by a local file system.

A: LocalFS means it may be your LinuxFS or WindowsFS. And which is not part of the DFS.
Your understanding is correct, using -get you are getting file from HDFS to Local FS and you cannot use both hadoop and hdfs. Command should be like below
hdfs dfs -get file_name local_path or hadoop fs -get file_name local_path

A: As per the file system logic, you can divide the filesystem into different drives. in the same way, you can create hadoop file system as a separate filesystem in linux file system.
Your local file system would be the File system over which you have installed the hadoop.your machine act as local in this case when copying file from your machine to the hadoop.
you might want to look at :HDFS vs LFS

A: THINK of a cluster node (server) as having to fulfill 2 needs:

*

*the need to store its own operating system, application and user data-related files; and

*the need to store its portion of sharded or "distributed" cluster data files.

In each cluster data node then there needs to be 2 independent file systems:

*

*the LOCAL ("non-distributed") file system:

*

*stores the OS and all OS-related ancillary ("helper") files;

*stores the binary files which form the applications which run on the server;

*stores additional data files, but these exist as simple files which are NOT sharded/replicated/distributed in the server's "cluster data" disks;

*typically comprised of numerous partitions - entire formatted portions of a single disk or multiple disks;

*typically also running LVM in order to ensure "expandability" of these partitions containing critical OS-related code which cannot be permitted to saturate or the server will suffer catastrophic (unrecoverable) failure.

AND

*the DISTRIBUTED file system:

*

*stores only the sharded, replicated portions of what are actually massive data files "distributed" across all the other data drives of all the other data nodes in the cluster

*typically comprised of at least 3 identical disks, all "raw" - unformatted, with NO RAID of any kind and NO LVM of any kind, because the cluster software (installed on the "local" file system) is actually responsible for its OWN replication and fault-tolerance, so that RAID and LVM would actually be REDUNDANT, and therefore cause unwanted LATENCY in the entire cluster performance.

LOCAL <==> OS and application and data and user-related files specific or "local" to the specific server's operation itself;
DISTRIBUTED <==> sharded/replicated data; capable of being concurrently processed by all the resources in all the servers in the cluster.
A file can START in a server's LOCAL file system where it is a single little "mortal" file - unsharded, unreplicated, undistributed; if you were to delete this one copy, the file is gone gone GONE...
... but if you first MOVE that file to the cluster's DISTRIBUTED file system, where it becomes sharded, replicated and distributed across at least 3 different drives likely on 3 different servers which all participate in the cluster, so that now if a copy of this file on one of these drives were to be DELETED, the cluster itself would still contain 2 MORE copies of the same file (or shard); and WHERE in the local system your little mortal file could only be processed by the one server and its resources (CPUs + RAM)...
... once that file is moved to the CLUSTER, now it's sharded into myriad smaller pieces across at least 3 different servers (and quite possibly many many more), and that file can have its little shards all processed concurrently by ALL the resources (CPUs & RAM) of ALL the servers participating in the cluster.
And that the difference between the LOCAL file system and the DISTRIBUTED file system operating on each server, and that is the secret to the power of cluster computing :-) !...
Hope this offers a clearer picture of the difference between these two often-confusing concepts!
-Mark from North Aurora