text:
Q: WebBrowser.DrawToBitmap() or other methods? I am trying to capture the content of the WebBrowser control. DrawToBitmap() would work perfectly, but it is not supported in documentation for the WebBrowser control.  I have been trying to find another way to capture the contents of the WebBrowser control and save them to a local image file.
Does anyone have any workarounds or other methods to save the contents of the WebBrowser control to a local image file?

A: The Control.DrawToBitmap doesn't always work so I resorted to the following native API calls that provide more consistent results:
The Utilities class. Call Utilities.CaptureWindow(Control.Handle) to capture a specific control:
public static class Utilities
{
    public static Image CaptureScreen()
    {
        return CaptureWindow(User32.GetDesktopWindow());
    }

    public static Image CaptureWindow(IntPtr handle)
    {

        IntPtr hdcSrc = User32.GetWindowDC(handle);

        RECT windowRect = new RECT();
        User32.GetWindowRect(handle, ref windowRect);

        int width = windowRect.right - windowRect.left;
        int height = windowRect.bottom - windowRect.top;

        IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
        IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);

        IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
        Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, ApiConstants.SRCCOPY);
        Gdi32.SelectObject(hdcDest, hOld);
        Gdi32.DeleteDC(hdcDest);
        User32.ReleaseDC(handle, hdcSrc);

        Image image = Image.FromHbitmap(hBitmap);
        Gdi32.DeleteObject(hBitmap);

        return image;
    }
}

The Gdi32 class:
public class Gdi32
{
    [DllImport("gdi32.dll")]
    public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
    [DllImport("gdi32.dll")]
    public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
    [DllImport("gdi32.dll")]
    public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
    [DllImport("gdi32.dll")]
    public static extern bool DeleteDC(IntPtr hDC);
    [DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);
    [DllImport("gdi32.dll")]
    public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}

The User32 class:
public static class User32
{
    [DllImport("user32.dll")]
    public static extern IntPtr GetDesktopWindow();
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowDC(IntPtr hWnd);
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
    [DllImport("user32.dll")]
    public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
}

The constants used:
    public const int SRCCOPY = 13369376;

The structs used:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int left;
    public int top;
    public int right;
    public int bottom;
}

A friendly Control extension method:
public static class ControlExtensions
{
    public static Image DrawToImage(this Control control)
    {
        return Utilities.CaptureWindow(control.Handle);
    }
}

This is a code snippet from my CC.Utilities project and I specifically wrote it to take screenshots from the WebBrowser control.

A: The following method can capture the entire window image even if the window is larger than the size of screen. Then it can capture the image of the contents of the page if the window be resized to the webBrowser.Document.OffsetRectangle.Size
class NativeMethods
{
    [ComImport]
    [Guid("0000010D-0000-0000-C000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IViewObject
    {
        void Draw([MarshalAs(UnmanagedType.U4)] uint dwAspect, int lindex, IntPtr pvAspect, [In] IntPtr ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [MarshalAs(UnmanagedType.Struct)] ref RECT lprcBounds, [In] IntPtr lprcWBounds, IntPtr pfnContinue, [MarshalAs(UnmanagedType.U4)] uint dwContinue);
    }

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    public static void GetImage(object obj, Image destination, Color backgroundColor)
    {
        using(Graphics graphics = Graphics.FromImage(destination))
        {
            IntPtr deviceContextHandle = IntPtr.Zero;
            RECT rectangle = new RECT();

            rectangle.Right = destination.Width;
            rectangle.Bottom = destination.Height;

            graphics.Clear(backgroundColor);

            try
            {
                deviceContextHandle = graphics.GetHdc();

                IViewObject viewObject = obj as IViewObject;
                viewObject.Draw(1, -1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, deviceContextHandle, ref rectangle, IntPtr.Zero, IntPtr.Zero, 0);
            }
            finally
            {
                if(deviceContextHandle != IntPtr.Zero)
                {
                    graphics.ReleaseHdc(deviceContextHandle);
                }
            }
        }
    }
}

Usage :
Bitmap screenshot = new Bitmap(1024, 768);
NativeMethods.GetImage(webBrowser.ActiveXInstance, screenshot, Color.White);

A: I am using DrawToBitmap (Visual Studio 2008 C#) to capture big images (user signed invoices,content out of the screen). Basically it is working well but I am getting blank images. About 100 employees are using this software, about every 2 weeks I can see one blank image.
I have done a lot of testing and one funny thing I found is:
I created a button to generate the image from the webbrowser. Usually is OK but if I click the webbrowser first, then click the create-button, the blank image will appear.

A: I used OleDraw method as in this topic on SO, but integrated it in a class derived from WebBrowser. This allows to do normal Control.DrawToBitmap not only for the WebBrowser, but for a form with WebBrowser in it as well. This also works if the form is hidden (covered by another form, including MDI parent form) and should work when user has locked session with Win+L (I haven't tested it).
public class WebBrowserEx : WebBrowser
{
    private const uint DVASPECT_CONTENT = 1;

    [DllImport("ole32.dll", PreserveSig = false)]
    private static extern void OleDraw([MarshalAs(UnmanagedType.IUnknown)] object pUnk,
        uint dwAspect,
        IntPtr hdcDraw,
        [In] ref System.Drawing.Rectangle lprcBounds
    );

    protected override void WndProc(ref Message m)
    {
        const int WM_PRINT = 0x0317;

        switch (m.Msg)
        {
            case WM_PRINT:
                Rectangle browserRect = new Rectangle(0, 0, this.Width, this.Height);

                // Don't know why, but drawing with OleDraw directly on HDC from m.WParam.
                // results in badly scaled (stretched) image of the browser.
                // So, drawing to an intermediate bitmap first.
                using (Bitmap browserBitmap = new Bitmap(browserRect.Width, browserRect.Height))
                {
                    using (var graphics = Graphics.FromImage(browserBitmap))
                    {
                        var hdc = graphics.GetHdc();
                        OleDraw(this.ActiveXInstance, DVASPECT_CONTENT, hdc, ref browserRect);
                        graphics.ReleaseHdc(hdc);
                    }

                    using (var graphics = Graphics.FromHdc(m.WParam))
                    {
                        graphics.DrawImage(browserBitmap, Point.Empty);
                    }
                }
                // ignore default WndProc
                return;

        }

        base.WndProc(ref m);
    }
}


text:
Q: Disabled form checkout Magento 2 I want disabled all inputs in form checkout in Magento 2.

In the photo it looks like I want it to be seen, but I do not know in which Magento file you have to modify that.
I do photo only one input, but I want all form disabled, because only can buy if is logged and I don't want that the data can be changed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Git ignores credentials stored in .git-credentials I have two local repositories which are hosted on the same server and I have configured Git to store my credentials in the .git-credentials file via the following command.
git config credential.helper store

However, the fetch/pull/push without entering credentials only work in one repository. In the other repository, Git always asks for credentials and ignores the .git-credentials file.

A: I have solved my problem. My config command was missing the global option. Without this option I have only configured it for one repository.
The correct command would have been:
git config --global credential.helper store


text:
Q: XSL: Is there an easy way to prevent widows? I was hoping to call ..
<xsl:call-template name="widow-fix">
  <with-param name="text" select="text"></with-param>
</xsl:call-template>

And then it would look for the last space in the text and replace it with #160; when finalized.

Should be able to support
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

and

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Please use a different character, like # to answer/prove, so the result when I test would be
Lorem ipsum dolor sit amet, consectetur adipiscing#elit.

and

Lorem ipsum dolor sit amet, consectetur adipiscing#elit.

A: All that you need is to replace the last space in every text node:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="p | text()">
    <xsl:apply-templates select="." mode="widow-fix"/>
</xsl:template>

<xsl:template match="* | @*">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="* | @*" mode="widow-fix">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" mode="widow-fix"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="text()[contains(., ' ')]" mode="widow-fix">
    <xsl:call-template name="text">
        <xsl:with-param name="text" select="."/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="text">
    <xsl:param name="text"/>

    <xsl:variable name="substring-before" select="substring-before($text, ' ')"/>
    <xsl:variable name="substring-after"  select="substring-after($text, ' ')"/>

    <xsl:choose>
        <xsl:when test="contains($substring-after, ' ')">
            <xsl:value-of select="$substring-before"/>
            <xsl:text> </xsl:text>

            <xsl:call-template name="text">
                <xsl:with-param name="text" select="$substring-after"/>
            </xsl:call-template>
        </xsl:when>

        <xsl:otherwise>
            <xsl:value-of select="$substring-before"/>

            <xsl:text>#</xsl:text>
            <xsl:value-of select="$substring-after"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

The mode="widow-fix" can process both text nodes and paragraphs preserving the enclosing tag.
I used such document as a test source
<book>

Highly random content

in this book
</book>

which converts to the following
<book>

Highly random#content

in this#book
</book>

A: You need "select=text()", and you can do the replacement with one of the xs: string functions, but I wouldn't describe the result as preventing widows.


text:
Q: Cannot connect to azure VM. CredSSP issue After I received a windows update on my PC I cannot connect to my azure vm via RDP. How can I connect to Azure in order to install the update?

A: This is a known issue.

Root Cause Analysis
To resolve a vulnerability issue with Credential Security Support
  Provider protocol (CredSSP), a monthly Windows update in May was
  applied which does two things:

*

*Correct how Credential Security Support Provider protocol (CredSSP) validates requests during the authentication process

*Change the group policy Encryption Oracle Remediation default setting from Vulnerable to Mitigated.

Here is a blog written by Micah to give a solutions by editing Local Group Policy.
Hope this helps!


text:
Q: How does signing with a strong name protect against forging a set of assemblies? Signing with a strong name (keypair stored in a .snk file) is (among other uses) meant to protect against forging assemblies.
For example: I ship my assembly signed with a strong name, then some other developer uses my assembly and so his assembly now contains a reference to mine, mentioning the public key of my keypair. Some user installs that developer assembly and my assembly and happily uses that developer's code. If anyone else tries to produce an assembly that looks like a version of mine and convince the user that it's an "update worth installing" that forged assembly won't load because I control my keypair and that forged assembly is not signed with the same keypair. Okay, cool.
But what prevents a malicious party from forging both my assembly and that dependent assembly of the other developer and "shipping" them both? They grab my assembly and that developer's assembly, tamper both, sign the forged version of my assembly with whatever key, then add a reference to it into the forged version of the dependent assembly, sign it too and then ship both. I mean maliciously "shipping" two assemblies should not be much harder than "shipping" one assembly.
How does signing with strong names protect against forging multiple assemblies?

A: Strong naming an assembly is really not meant to protect the signed assembly. It is to protect the other assembly that is loading the signed assembly.
For example, if an EXE is trusted and wants to load a known DLL from a known location (such as the GAC, a network share, the internet, etc.) it can do so using a strong name with some level of confidence that the assembly has not been tampered with.
But, if the whole set of assemblies is disassembled then re-assembled and re-signed, then yes, you're right they could just re-write the lines of code that load the rest of the assemblies such that it loads them with the new (fake) key.
But this kind of tampering would be evident. In other words, the strong name signing provides clear evidence of tampering, but doesn't prevent it in all cases. Add to that the fact that a local admin can disable strong name verification altogether (for "development" purposes) and it's obvious that strong name signing is not a bulletproof security mechanism.
Same goes for Authenticode and driver signing though. We've all seen a product out there that instructs users to "ignore the security warning". That's basically what the EXE would be doing if strong name verification were disabled or the entire set of assemblies had their signatures stripped - it would be ignoring the warning.

A: Strong Naming is all about, well ... "naming". I quote from here: Using Strong Name Signatures
"Strong names offer a powerful mechanism for giving .NET Framework assemblies unique identities."
That's all what you'll ever get from this mechanism. It means I can forge your assembly and all assemblies it references, but I will not be able to pretend "you did it". I will not be able to pretend you are the publisher of these assemblies.


text:
Q: Populating ArrayCollection with HTTPService I am creating a RSS Feed application based on a data, and I have the following:
I have an ArrayCollection that is pre-populated with data. I am sorting through the ArrayCollection, get 1 piece of data (condition), and need to connect to an RSS feed which returns me the title, and I set my ArrayCollection in correspondence to condition -> title.
        public function updateArrayList(list:ArrayCollection):ArrayCollection {
            trace(list);
            for(var i:int = 0; i < list.length; i++) {
            //  Alert.show(list.getItemAt(i).condition);
                getRSSUpdate(list.getItemAt(i).condition);
                list.getItemAt(i).title = getRSS.lastResult.article.title;
            }
            return list;
        }

        public function getRSSUpdate(condition:String):void {
            getRSS = new HTTPService();
            getRSSParam = new Object;
            getRSSParam.condition = condition;
            getRSS.method = "POST";
            getRSS.url = "http://localhost/site/remoteRequests/flash/rss/getRSS.php";
            getRSS.send(getRSSParam);
        }

Basically, I want to iterate through the list ArrayCollection, and update list.getItemAt(i).title with result passed from the HTTPService.
This doesn't work! Help!

A: First make a result event on httpservice in that only you will access the result for the request.
In that method you will get resultEvent from that take out the required value if it return the response as xml you can directly do like this lastResult.article.title
<mx:HTTPService id="yahooHTTPService"
    url="http://search.yahooapis.com/WebSearchService/V1/webSearch"
    method="GET"
    makeObjectsBindable="true" result="httpServiceResult(event)"
    fault="httpServiceFault(event)" showBusyCursor="true">
</mx:HTTPService>

here is an example http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html#193905


text:
Q: Is there any difference between these sets? $ C=\{x\in A| x\in B\}$ and $D=\{x \in A \wedge x \in B\}$ $C=\{x\in A| x\in B\}$ and $D=\{x \in A \wedge x \in B\}$ and $E=\{x\in B|x\in A\}$
I think that $D$ is not a set because it has not properties. And the set $E$ and $C$ are the same set because has the same elements.But they are mencioned in different ways. I mean $C$ is a set which elements belong $A$ and have the property that belong $B$. And $E$ is a set which elements belong $B$ and have the property that belong $A$.
As it is written $D$ cannot be a set since to be one there are 2 options, either it is indicated which are its elements or it is indicated to which set its elements belong so that they fulfill some property.

A: They are all the same, the difference is only in the emphasis: $C$ is viewed as a subset of $A$, and $E$ is viewed as a subset of $B$.
There is a flaw in the definition of $D$, it should rather say $\{x: x\in A\ \wedge x\in B\}$.


text:
Q: Link to a specific branch, tag or commit, or a specific file within it, or a specific line within that file? I create a tutorial, where I want to introduce some testing frameworks like Mockito, WireMock and EasyMock. I want to explain it step by step. Additionaly I want to provide examples, where the reader of the tutorial can try to recreate these. Therefore I want to to give them the opportunity to look into my source code and use it when they are not able to recreate the test. And then they can use the actual version to continue and then again, when they are not able to create the next test, I want to to give them the possibility to use my new version with the new test.
My idea is to use different commits and link them to the tutorial. How can I do this or is there any better approach to reach what I just explained?

A: Easy Peasy!
The basic approach is this: browse to exactly what you want on GitHub, and then share the URL. GitHub URLs are stable permalinks, even when you navigate to an old revision or another branch.

*

*Open the repo in Github.

*Browse to Branch, tag or commit you want.

*

*For branch/tag, there's a drop down in the upper left of the files listing.

*For a specific commit:

*

*Click on Commits at the top of the files listing. This will take you to a page showing all the diffs. (You can share this URL if you want. Otherwise continue to the next step.)

*Clink on Browse files in the upper right corner.

*You are now looking at a repository view just like the one where you started, except this view is of a specific branch, tag or commit. It's like a GitHub time machine.

*

*If you want to link to the entire repo at this branch/tag/commit, copy the URL right now.

*If you want to link to a particular file at this branch/tag/commit, navigate to the file in the listing, then copy that URL.

*If you want to link to a particular line in the file, click on a line number, then click on the ... button that appears next to it and then click Copy permalink

*If you want to link to a range of lines in the file, hold down the shift key and clink on the other end of the range of lines. The lines will be highlighted. Click on the ... button that appears next to it and then click Copy permalink

All that said, unless you are walking them through your many iterations of the code, I'm not sure giving them links to versions in git history is the way to go. Let's say they want to clone your repo. Then they'd have to git checkout example-2-version-3 or something.
The more typical approach is to put the different versions in a directory hierarchy, making it far easier to browse, whether on GitHub or a local clone of your repo.


text:
Q: remove parent without removing childs in vanilla javascript I've read this question to remove parent without remove childs, but it don't work if the child node is a node type 3 (text)

            Hello world
             How are you ?

For example, I want to remove  tag (parent of Hello world node type text and i) using vanilla javascript.
After removing u tag I would like to have:

        Hello world
         How are you ?

A: The answer is short
Using the https://stackoverflow.com/users/7230746/tom-oeser answer in this question redefining the logic taken text node parent first.
function unwrap(node) {
    node = node.parentNode;
    node.replaceWith(...node.childNodes);
}


text:
Q: Как определить при помощи Aiogram что все файлы отправлены? Когда пользователь отправляет пачкой фотографии в перемешку с видео, я хочу знать когда все файлы уже были отправлены.
Есть код:
def get_buffer_path(user_id: int, file_name: str) -> str:
    return os.path.join(settings.BUFFER_PATH, f'{user_id}_temp', file_name)

@dp.message_handler(content_types=['photo'])
async def handle_docs_photo(message: types.Message):

    date_time_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    buffer_path = get_buffer_path(message.from_user.id, f'image_{date_time_str}.jpg')
    await message.photo[-1].download(destination_file=buffer_path, make_dirs=True)

Здесь есть недостаток:
На каждое отправленное фото, неважно раздельно или вместе с какими-то другими фото, отправляется новое сообщение, а хотелось бы сразу за раз определять по 1-5 фоток, и 1 раз отправить сообщение об успехе, также код не учитывает видео.


text:
Q: Remote desktop connection to kvm virtual machine starts working after vnc-logon? I am running a Windows XP on kvm inside my debian system. Everything runs smoothly and I can connect via VNC as well as via Remote Desktop.
VNC connection is naturally supported right from boot up and always works for me. For Remote Desktop I have to wait until the Windows service is started until I can logon.
Sometimes, however, Remote Desktop seems to not start at all: Regardless of how long I wait, I cannot logon via Remote Desktop connection. But if I then logon via VNC, also Remote Desktop always works instantaneously.
I really wonder why this is the case. Might this come from any misconfiguration?
thx

A: The VNC connection you speak of is not a service in the guest, it's a console connection to the hypervisor, and has nothing to do with whether the guest OS is up or not.
RDP depends on the guest OS (Windows) services to be up and running, especially networking. I suspect what happens is your Windows guest doesn't bring up some parts of it's network stack until you connect via a console and login, at which point, since the stack RDP depends on is up and running, it (RDP) will also work.
I vaguely recall desktop Windows editions (2000 and XP especially) failing to bring up the NIC before everything else, thus failing automated logons, but it's been a very long while since I've run into this issue


text:
Q: How much disk space does a GCP Function have? I am looking into different FaaS providers and am interested how much disk space I have per function. A function in AWS Lambda has 512 MB of disk space available (see here) and Azure functions have up to 1000 GB of disk space, depending on the pricing model (see here).
How much does a GCP Function have?
When searching the documentation, I could only find that functions do have disk storage, but not how much (see here).

A: Maybe a better documentation redirection is (as per 2021-10-14):

The filesystem itself is entirely writeable (except for files used by the underlying OS) and is stored within the Cloud Functions instance's memory.

https://cloud.google.com/functions/docs/concepts/exec#file_system
So as per Chris' response/comments,

Cloud Function doesn't have a 'disk space'

Or to be more accurate, the disk space IS the memory space.

A: Currently cloud functions can be configured for 8GB of memory, which as correctly noted includes the 'filesystem'

A: A google Cloud function can have between 128 MiB and 2 GiB of memmory.

You can find here the quotas for  Cloud Functions


text:
Q: Speeding up tensorflow 2.0 inference? Am following the excellent post here:
https://pgaleone.eu/tensorflow/tf.function/2019/05/10/dissecting-tf-function-part-3/
but am wondering if there are additional routes to speeding up inference for tensorflow 2.0 models.
Am noticing there is quite a bit of over-head on a single call for a simple model. For example, calling a single row prediction might be .5 ms while 2500 row prediction is about 50 ms. So that is only 100x longer with 2500x data.
Is there a nice path to calling these from cython or simply using RT? This is a smallish network and should be fast on CPU.


text:
Q: Automatically delete profile images that aren't in use need a bit of help, I am trying to create a PHP script that will be initiated by a button from the admin page, which will find all image names in the database under "photos" and then delete any images from my directory 'userimages' that are no longer in use in the database?
I honestly have no idea where to start with this because its kind of confused me a bit? Is there a simple way to go about this?

A: You should get all image names as array
than read all images name from the folder
if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }

    closedir($handle);
}

compare and remove difference
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);


text:
Q: Connection problems of esp8266 As soon as I am connecting 3.3 v from Arduino to ch_pd and vcc of esp8266, the port connected to Arduino becomes unavailable. Can you let me know how to proceed. I am using pin 2 of Arduino to tx of esp8266 and pin 3 to rx.

A: ESP8266 require much current. Maybe regulator of arduino is not capable of powering much current and thatswhy its output voltage drops when you connect ch_pd and vcc.
Try using another power source.


text:
Q: How to add dynamically a collapse in javascript I used bootstrap collapse, now I want to add a collapse section dynamically by clicking add new banner in javascript and this is the code.
<button type="button" name="submit"  style="margin-left:250px;" class="btn
btn-primary" onclick="bannerfunction();">Add Banner</button>

    <button class="btn btn-link collapsed" type="button" data-
 toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-
 controls="collapseTwo">
      Collapsible Group Item #2
    </button>

    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus
  terry richardson ad squid. 3 wolf moon officia aute, non cupidatat
 skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch
 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee
 nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer
labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur
butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim
 aesthetic synth nesciunt you probably haven't heard of them accusamus
 labore sustainable VHS.

check the image link here
enter image description here


text:
Q: What causes our Sun to oscillate around its mean Galactic orbit? According to this answer on Astronomy.SE,

The Sun executes oscillations around its mean orbit in the Galaxy, periodically crossing the Galactic plane. I borrowed this illustration (not to scale!) from http://www.visioninconsciousness.org/Science_B08.htm to show this oscillatory motion.
  As the Sun is currently above the plane and moving upwards, and each cycle takes about 70 million years with an amplitude of 100pc (Matese et al. 1995), it will be roughly 30 million years before we cross the plane again.

What causes this kind of motion? Does Newtonian Physics have an explanation? If yes, what is it? If no, what General Relativity explanation have we got?

A: The plane where the Sun and most of the Milky Way are comfined to is neither a plane nor a disk: it is a dense, matter filled section with non-zero width. This means this "disk" also generates a gravitational potential that traps the Sun. In a way, we can say that the Sun has its galactic orbit centered both at the galactic centre and its planar oscillations centred at the galactic "disk". If this approximated disk had a constant density and the Sun were never perturbed in non-planar directions, then the orbit would indeed be confined to a plane; but matter is non-uniformly arranged within the galaxy and this anisotropy provides the non-planar perturbation needed to create an harmonic motion around the galactic plane not only for our Sun, but (at least theoretically) for all celestial bodies.

A: I feel like the existing answers make the explanation seem too complicated, so I'll add a simple explanation.
Imagine "throwing" a new star into the galaxy, aiming for the orbit to be approximately (but NOT exactly) along the galactic plane. Would you expect the orbit to magically get locked into the galactic plane? Of course not--that would violate conservation of momentum. Would you expect it to forever continue in its own plane? Of course not--that's only expected for a spherical mass, and the galaxy isn't a spherical mass. The closer parts of the galaxy to the star will pull the star toward them too, and hence you get a wobble.

A: It's good old Newtonian gravity! The plane of the galaxy can be approximated as a disk made up of stars and gas, with a density $\rho(|z|)$, that decreases with absolute distance $|z|$ from the plane.
If you were to assume that the Sun was close enough to $z=0$ and that the radial variation in $\rho$ was negligible enough to treat the disk as an infinite plane (this is not bad, the amplitude of the Sun's motion is only about 10% of the radial scale length of the disk density), then you could construct a little cylinder through the plane, with one face at   $z=0$, where $g=0$, and use Gauss's law for gravity to estimate the gravitational acceleration at height $z$.
$$ g(z) \simeq -4\pi G \int_0^{z} \rho(z)\ dz$$
Now $\rho(z)$ approximates to an exponentially decaying function with a scale height of maybe 200-300 pc. If we are closer to $z=0$ than that, then the density can be roughly said to be a constant $\rho_0$. Putting this into the equation above, we see that
$$g(z) =-4\pi G\rho_0 z.$$
But this is simple harmonic motion with an angular frequency $\sqrt{4\pi G\rho_0}$.
The density of the disk near the Sun is estimated to be 0.076 solar mass per cubic parsec (Creze et al. 1998). Using this value, we get an approximate predicted oscillation period up and down through the disk plane of 95 million years.
Note added: The previous paragraph is the reverse of what is actually done - the dynamics of stars in the solar vicinity are used to estimate the density in the plane. However, just counting up stars and estimating the contribution of gas does give a similar result - and in the process, illustrates that the contribution of dark matter to the density of the disk is very small.


text:
Q: Why use alias to resolving fan trap? I just have been confused with SAP universe and fan trap.
Why use alias to resolve the fan trap? Does it generate useless and redundancy sql? and what is the sql difference after used alias?


text:
Q: How can I make images fit into a 200 pixel square box using CSS? I have a bunch of images which all fit into a 400px × 400px box (that is, one of their dimensions is 400px and the other is smaller). I would like to be able to, using CSS, but jquery/javascript if necessary, fit that image to a 200px by 200px box, so that two edges of the image touch the box, and there is a gap between the other two edges of the box.
Aspect ratio must be maintained.
My HTML is as follows:

And my CSS is:
div.images div.small
{
    width:200px;
    height:200px;
    line-height:200px;
    text-align:center;
}
div.images div.small img
{
    vertical-align:middle;
    max-width:200px;
    max-height:200px;
}

You can see a sample here.
Unfortunately, my landscape images hug the top of the box, whereas I would like them to be centered. Also, I'm not sure of the wisenees of relying upon max-width/max-height.
How can I center my images within these boxes?

A: I set this up on my computer and it worked fine. After looking at your example page, the problem is because you've set the image to display:block. Either remove that rule from your general img rule (weird thing to set globally, anyway), or change the image rule you posted above to this:
div.images div.small img
{
    vertical-align: middle;
    max-width: 200px;
    max-height: 200px;
    display: -moz-inline-box; /* Firefox 2 */
    display: inline-block;
}

By default, the img element and other "replaced" elements (Flash, etc) are "inline-block" - this means they flow inline like text, but have a width and height.

A: I needed to do the same some time ago, and I found a good implementation in this link.
"Center an image inside a div, vertical and horizontal, without knowing the image's size".
It works for me as intended.

A: I ran into this vertical centering problem once and to get it working correctly in all browsers, I resorted to javascript / jQuery:
$(document).ready(function() {
    $('img').each(function() {
        image_height = $(this).height();
        margin_top = (200 - image_height) / 2;
        $(this).css('margin-top', margin_top + 'px');
    });
});

Please note that you will need $(window).load instead of $(document).ready if the image dimensions are not given in the html.

A: have you tried using:
display:block;
margin-left:auto;
margin-right:auto;

that should center block level elements

A: Here is a solution that will work no matter what size you want. It will downscale but not upscale, center both vertically and horizontally, and only uses CSS. It took me a while to figure it out.
Put your  inside a
, then position the div as you want (i.e., give it the size you want, make sure to set the position attribute), then apply this:
.mydiv > .myimg {
    vertical-align: bottom;
    max-height:     100%;
    max-width:      100%;
    position:       absolute;
    margin:         auto;
    top:            0;
    right:          0;
    bottom:         0;
    left:           0;
}


text:
Q: Add a column in a table with a first letter must be 0? I want to add a column S_order_no in a table Sales_order with a constraint that the first letter must start with 0. So that if we try to write the first letter other than 0 it throws an error.
Is it possible?. If yes please explain with an example.

A: CREATE TABLE Sales_order(
    S_order_no varchar(6) primary key check(S_order_no Like 'O%'),
    S_order_date Date,

);

A: You can try:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Sales_order(
    S_order_no varchar(6) primary key,
    S_order_date Date,
    CONSTRAINT CHK_order_no CHECK (left(S_order_no, 1) = '0')
);


text:
Q: Кастомные подписи в диаграмме с накоплением У меня есть вот такая простая таблица и с помощью ggplot создаю столбчатую диаграмму. Помогите сделать подписи с суммой чисел над каждым столбцом (это главное), как на второй картинке.
library(tidyverse)

data <- data.frame(
  quarter=c("Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q3", "Q3", "Q3"),
  product=c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
  profit=c(10, 12, 13, 10, 12, 13, 10, 12, 0)
)

p <- ggplot(data, aes(x = quarter, y = profit, fill = product)) +
  geom_col(position = 'fill')
p

Функция geom_text отображает значения в обратном порядке. Если возможно, то как сделать так чтобы ноль не отображался?
p +  geom_text(aes(label=profit), col='black', size=4)

A: data %>%
group_by(quarter) %>%
mutate(common_profit = sum(profit)) %>%
ggplot( aes(x = quarter, y = profit, fill = product,group=quarter)) +
geom_col(position ="fill") +
geom_text(data=subset(data,profit != 0),aes(label =profit), position = position_fill(vjust = 0.5))+
geom_text(aes(label =common_profit,y =rep(1.05,nrow(data)),x=rep(1:length(unique(data$quarter)), each=length(unique(data$quarter)))))

Добавление итогов сверху почему-то ломает масштабирование, возможно, кто-либо сможет заменить последний geom_text


text:
Q: BouncyCastle version conflict, vendors not cooperating I am currently stuck in integrating Java packages because of a version conflict with BouncyCastle.
We have internally developed a component to handle data files sent to our local Revenue Service (not "the" IRS, but an equivalent tax authority in another European country) using official Java APIs provided and maintained by them. Another module of our platform uses a component from a Certification Authority to perform certified timestamping of files. Both have to be integrated into a single web application deployed at customer sites.
As you may know, BouncyCastle packages, on which both packages depend, have undergone several public API changes, so that consequent versions are no more binary compatible.
Revenue Service provides "cryptotools.jar" package which depends on the following:
<dependency org="org.bouncycastle" name="bcprov-jdk15on" rev="1.49"/>
<dependency org="org.bouncycastle" name="bcpkix-jdk15on" rev="1.49"/>

Certification Authority's provides "jades-kernel" timestamping package which depends on
<dependency org="org.bouncycastle" name="bcmail-jdk15"     rev="1.45"/>
<dependency org="org.bouncycastle" name="bcprov-jdk15"     rev="1.45"/>
<dependency org="org.bouncycastle" name="bcprov-ext-jdk15" rev="1.45"/>
<dependency org="org.bouncycastle" name="bctsp-jdk15"      rev="1.45"/>

Having both packages on classpath results in all BouncyCastle packages to be dumped into my WEB-INF/lib folder, which normally doesn't sound bad

But if I try to start the web application with all of these packages inside I get an Error saying that a class extends a final method. I won't post the stack trace, it's irrelevant for my question
If I remove any of the two versions (1.45 or 1.49) of BC, one of the modules won't compile. Well, they are both already compiled, so they won't simply link to their referenced classes/methods.
I have reported this situation to the CA (with which we have a maintenance contract for the Java APIs), using the older BC version (which has security vulnerabilities found by Black Duck, so that my customer is making my life painful). The CA is not cooperating yet. They would need to release a new version of their cryptography APIs compatible with more recent versions of BouncyCastle.
Me and my boss (C-level boss) are escalating the issue to CA hierarchy, and, according to our local humour, soon we will be escalating up to Francis
Mentioning humour, please allow me to share my current feeling in a visual fashion

Question time, now back to serious discussion
Suppose our vendor does not cooperate, or at least not timely for our regulatory deadlines. Revenue Service will not obviously downgrade their Java APIs to an older BC version.
How do we get out of this dependency hell? I know, for example, that log4j had a "bridge" package to mitigate breaking API changes between 1.x and 2.x versions for those packages who haven't upgraded yet. How do we make two modules coexist when they depend on different BC versions?
I will post a possible workaround but it's not our preferred solution.

A: Essentially Java is not built for this and Maven certainly isn't (as there is an underlying assumption that any newer version is a perfectly fine replacement for an older version when resolving these kind of conflicts).
It is my understanding that you have a monolithic application, so as you cannot physically split up the classpaths you can do it logically.
A way to handle this could be to run your application in multiple classloaders so that the jar files never "touch".   I asked a "how to run in multiple classloaders" question earlier - Want to run non-threadsafe library in parallel - can it be done using multiple classloaders? - and this approach combined with loading a jar which is not on the classpath may be doable.

A: A workaround may be to split up the web application into multiple applications each deployed in a different context and communicating via web service. The secondary applications will be just private.
The timestamping module will have its classpath with older BC version, and the tax service module will have a different classpath. The "main" front end web application won't have any dependency to BC at all.
This doesn't solve the Black Duck issue because the customer will mandate an upgrade or require a lot of paperwork to allow a policy exception.


text:
Q: Phenomenon of decreased improvement over time I was struggling to find a suitable stack to ask this questions, but I'm hoping that the answer is founded in maths.
I was wondering if there is a name or theory on the fact that if you do something a lot, the improvement rate goes down. For example, if you start working out you gain a lot of musscles in the first weeks, after that, the improvements will go down and it will get a lot harder to get the same improvements as in the first weeks.
So, is there a theorem supporting this in general, and what is it called?

A: This is called "diminishing marginal returns" and is not a theorem or law, rather it is an assumption often made in economics. The mathematical statement of this idea is that a particular production function is concave (or the discrete analog).
It's important to stress that there is no law of nature ensuring that all production functions will have decreasing marginal returns. Many have increasing returns, especially at the low levels of production. Nonetheless, it is a common phenomenon and so is a property of interest.


text:
Q: Facebook shows wrong Author when sharing Link of Wordpress post Whenever I post a link of a post from my blog on Facebook, Facebook shows the wrong author.
Screenshot:

The meta tag in my header.php has another author in it.
<meta name="author" content="MYAUTHORNAME">

I searched the web and tried to add this:
<meta property="article:author" content="https://www.facebook.com/MYSITE" />
<meta property="article:publisher" content="https://www.facebook.com/MYSITE" />

But still no effect. I don't know where the author tag on Facebook is coming from.

A: Check if you dont have a publisher meta:
<meta property="article:author" content="https://www.facebook.com/fareedzakaria" />
<meta property="article:publisher" content="https://www.facebook.com/cnn" />

Source: https://developers.facebook.com/docs/sharing/best-practices#crawl
Also check if your code is valid using this:
https://developers.facebook.com/tools/debug/og/object/ insert the url and press "fetch new scrape information" and see if that fixes it.


text:
Q: Should I repartition dataframe on a column before groupBy? Dataframe df1 contains 10 million rows. Column PID contains 256 unique values.
In pyspark, I plan to execute the following query just once.
df1.createTempView("df1")
spark.sql(""" SELECT PID, count(*) as Count
              FROM df1
              GROUP BY PID""")

Will the execution be faster if I first repartition on column PID?
I was told that it will, but based on my understanding, as the query has to be executed only once, it will not.
Repartitioning on PID before execution will cause data shuffling, so will group by without repartitioning.


text:
Q: mysql not starting up on wamp I am trying to start up mysql via WAMP ("Start all services"), but the WAMP icon in the task bar remains orange, and mysql remains unstarted. I examined the error log and this is what I found:
131220 17:13:01 [Note] Plugin 'FEDERATED' is disabled.
131220 17:13:01 InnoDB: The InnoDB memory heap is disabled
131220 17:13:01 InnoDB: Mutexes and rw_locks use Windows interlocked functions
131220 17:13:01 InnoDB: Compressed tables use zlib 1.2.3
131220 17:13:01 InnoDB: Initializing buffer pool, size = 128.0M
131220 17:13:01 InnoDB: Completed initialization of buffer pool
InnoDB: Error: log file .\ib_logfile0 is of different size 0 50331648 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
131220 17:13:01 [ERROR] Plugin 'InnoDB' init function returned error.
131220 17:13:01 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
131220 17:13:01 [ERROR] Unknown/unsupported storage engine: InnoDB
131220 17:13:01 [ERROR] Aborting

131220 17:13:01 [Note] wampmysqld: Shutdown complete

Does anyone know how to fix this? After seeing the error log I thought innodb was not on so I set innodb = on in my.ini, but that didn't work either.
If it helps: WAMP worked fine before, but yesterday I shutdown mysql manually like
mysqladmin -u root -p shutdown

and now WAMP doesn't work. Perhaps that has something to do with the problem I'm encountering?


text:
Q: Filter recycler list When i search for first time list shows correct data but second time if i search same keyword again it duplicates list.Previous entries are not deleted.
    I tried to clear filter_list but it doesnot load data second time on list and if i add announcements in filter list in constructor it doesnot add items in filter list. How to resolve this issue??
public void filter(String charText) {

    charText = charText.toLowerCase(Locale.getDefault());
    filter_list.addAll(announcement);
    announcement.clear();

    if (charText.length() == 0) {

        announcement.addAll(filter_list);

    } else {

        for (GT gt : filter_list) {

            if (gt.getTitle().toLowerCase(Locale.getDefault())
                    .contains(charText)) {

                announcement.add(gt);

            }

        }

    }

notifyDataSetChanged();

}

A: First copy your list to temp list in you adapter
sampleListTemp = new ArrayList<String>();
sampleListTemp = sampleList;

Now implement this function in adapter and call with string whcich you want to filter
public void setFilter(String str) {
        sampleList = new ArrayList<String>();
        if (eventsListTemp.size() > 0) {
            for (int i = 0; i < eventsListTemp.size(); i++) {
                if (sampleListTemp.get(i).contains(str.toLowerCase())) {

                    sampleList.add(sampleListTemp.get(i));
                }
            }
        }
        notifyDataSetChanged();
    }

and when you want full list than just pass blank str.


text:
Q: remove empty lines from HTML, except in  blocks I'm using Editorial to write posts of my WordPress blog with markdown.
The markdown parser outputs HTML code perfectly, and the Editorial embedded viewer shows the result with the expected format and style.
But when I paste that HTML in the WordPress mobile editor, it shows the text in a wrong format, showing too many empty lines.
For example:
# Header
Hello world, **this is Markdown!**

Other markdown paragraph!.

Is parsed to:

Header

Hello world, this is Markdown!

Other markdown paragraph!.

Which is showed in the viewer as:

Which is what I expected.
The WordPress mobile app, on the other hand, shows that HTML code as:

As you can see, there are too many empty lines.
I think that the CSS sheet of WordPress has the margin of paragraphs and headers configured to put one empty line above, and one empty line below. But I cannot modify that CSS, so my brute-force solution was to remove the blank lines between paragraphs in the HTML code. This works fine, but the process is tedious.
So I want to use the powerful tools of Editorial to build a workflow to automatize the process.
The goal is to write a python script which takes the generated HTML and erases the empty lines, being careful to not erase the empty lines located at code blocks, which are source code examples.
I'm thinking about a solution using regular expressions to find the empty lines and discard the code blocks, but I'm pretty new to Python and its libraries, so the code snippets I have tried didn't work.
Anybody could provide me an example of how to achieve this, or a general guideline to write it myself?
PD: Post this kind of question without any example/sourcecode of what I have tried is a very bad idea, I know, but my python code is a noob-messy-bunch of code without any sense, so I decided to not post it.

A: Let's assume you have loaded the html as text (HTML):
HTML = """
html
html

html

code-start
code
code

code
code-end

"""

new_html = ""
is_code = False
for line in HTML.split('\n'):
    # disable empty line remover when code starts
    if line == 'code-start':
        is_code = True
    # check for empty line/is_code
    if is_code or line != '':
        new_html += line+'\n'
    # enable empty line remover when code ends
    if line == 'code-end':
        is_code = False

print new_html

Of course you have to replace code-start and code-end with valid html tags.
This is just a quick and dirty approach but should help you.


text:
Q: Sort by custom field (MySQL date format) when mixing date and text? I use a Wordpress grid plugin to display my review posts and sort them using a custom field where I add the date in the custom field in the post like this: January 1, 2022 (%M %d, %Y). But in some reviews, I don't have a release date and use T.B.A (to be announced) and these always sort themselves at the top. Is there any clever way to make these go to the bottom or will I have to add some random date to them (which I want to avoid).
Thank you.

A: It is better to save dates in  the proper mysql qway yyyy-mm-dd for sorting and making calculatios
your problem can be easy solved by change the value in the order the way you need

CREATE TABLE mytb(mydate varchar(50))

INSERT INTO mytb VALUES('January 1, 2022'),('December 1, 2021') ,('December 5, 2021'),('TBA')

SELECT *
FROM mytb
ORDER BY CASE WHEN mydate = 'TBA' THEN '999-21-31'
                           ELSE STR_TO_DATE(mydate,'%M %d, %Y') END ASC

| mydate           |
| :--------------- |
| December 1, 2021 |
| December 5, 2021 |
| January 1, 2022  |
| TBA              |

db<>fiddle here


text:
Q: Order of executing Chef recipes in a single cookbook I have a single cookbook with two recipes: recipe/install.rb and recipe/configure.rb.
In install.rb, I install all packages, gem_packages and configure, using them in configure.rb. I am installing one gem_package in install.rb, and using it as require <that-gem> in configure.rb.
Regardless of the order of runlist, chef-client execution fails mentioning <that-gem> is missing. If I run with install recipe first and then run configure recipe, things work fine. Isn't there a way where a single chef-run runs both the recipes in order? I tried mentioning include_recipe and all possible solutions.

A: There are two phases to a Chef client run.

*

*First is the resource compilation stage, where all the ruby is
loaded, node attributes are resolved and a run list generated.

*Next is the execution phase, where the recipes in the run list
are executed.
Gems that your recipes rely on need to be available by the execution stage which presents a bit of a chicken or the egg problem, so you need to use a few tricks to get the gems installed first.
When installing gems for Chef to use, install them with chef_gem.
chef_gem "your_gem"

require 'your_gem'

This can get a bit tricky if you start using gems in libraries, as libraries are required at compile time and you can't get actions to occur before compile time. In this case you need to fail nicely on the load so the gem can be installed.
begin
  require 'your_gem'
rescue LoadError
  warn "Load of [your_gem] failed. Should be installed by install.rb"
end

Then be sure not to use any of the objects the gem provides in the Chef run before the install can occur.


text:
Q: determining which client sent data using sockets I have a problem.
In my code i have an array of players, everyone with his "in" and "out" to the server.
From Server to Clients i can communicate well and without any problem and every client shows in his GUI the change sent by Server.
The problem is the communication from Clients to Server. As Server, I want to recieve petitions from every player to do some work. The problem is that i dont know from which index i recieve the petition and I cant check every players[index].in.readUTF() cause it blocks the program.
Some help? in.avaiable() doesnt work for me.
To show it clearer:
When a player logs into the Server i do this in the Server Side.
socket = serverSocket.accept();
out = new DataOutputStream(menuPrincipal.socket.getOutputStream());
in = new DataInputStream(menuPrincipal.socket.getInputStream());
players[i] = new player(i,out,in);

Then i have a thread in Server side waiting from messages.
The problem is that i dont know from which index of players array (from which player) will come the message. I cant check an index of players that is not sending anything to Server cause it will block the program.
So thats how it works:
From Server to Client I just do:

*

*player[i].out.writeUTF(message) from Server side

*Client just does in.readUTF() and all works fine

From Client to Server I do:

*

*out.writeUTF(message) from Client

*But then on the Server side i have to choose one player[i].in to read which i dont know  which player is.

A: So you say you've managed to send data from the Server to the Client, and it works fine. The same principle applies when sending data from client to server.
Have a Listening thread, on the server side. Inside the packet, you can include the name, or the IP address, of the user sending the data. IE:
Data Recieved by Server: 'message, hello chris, sender, reciever'

Your server can then split up the packet into it's meaningful sections using a string tokenizer.
Action: 'message'
Message: 'hello chris'
Sender: 'sender'
Reciever: 'reciever'.

Then you have all the data necessary to continue.
This implementation means that all the data you need is contained within the packet that you have received, and you don't have to check where it came from. The extra few bytes of data won't slow you down as much as having to perform a search every time you receive a packet.
Edit In response to OP Edit
Alternatively, instead of implementing an Array, you can implement a HashMap<String,Player>. That way, all you need to do is grab the username from the packet sent, using my description above, and pass it to the hashmap. The hashmap can return the User object that represents the client, and there is no need, again, for an index lookup.
You can find the documentation on the Java Hashmap here.
Finally, I noticed you've got a player class. The Java convention is that all classes start with an upper case letter. That is:
player should be Player.
Final edit in response to your comment
Your problem is an issue of bad design, I'm afraid. The clients should all be communicating to the server via the same channel, in this context. That way all the server has to do is listen out for any messages, parse them, and move them on. Adjust your implementation so that your client's all talk to the server via the same stream, and that will eliminate your issue.

A: Ok first let me give you a small background on how sockets work, before giving you the solution and it is vital to understand what is going on.
Socket Explanation (Reference)
A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. Note the word bidirectional. This means that for each connection between a client and a server, you have two streams: an input stream and an output stream. These can be accessed by both socket objects that one sets up on the server side and client side.

Your Problem

From Server to Client I just do player[i].out.writeUTF(message) and
  Client then just checks his "in", doing in.readUTF() and all works
  fine. From Client to Server i do out.writeUTF(message) from Client but
  then, on the Server side i have to choose one player[i].in to read
  which i dont know which player is.

Therefore, if I understood correctly, you have a difficulty in how to determine which client sent you a message. This is easy to solve if you use multithreading correctly, as each client will be handled on a separate thread.
A vital step is how clients are handled initially. Consider the following code. In order to keep it short, I did not focus greatly on conventions.
ArrayList<ClientWorker> clientWorkers = new ArrayList<ClientWorker>();
int idCounter = 0;

    public void listenSocket(){
      try{
        int port = 9090
        server = new ServerSocket();
      } catch (IOException e) {
        System.exit(-1);
      }
      while(true){
        ClientWorker w;
        try{
    //server.accept returns a client connection
          clientWorker = new ClientWorker(server.accept(), idCounter, );
          idCounter++;
          clientWorkers.add(clientWorker);
          Thread t = new Thread(clientWorker);
          t.start();
        } catch (IOException e) {
          System.exit(-1);
        }
      }
    }

Ok so through that code, we are handling new clients and assigning them with a unique key. Instead of array, I am using arraylists so that it can increase and descrease in size according to the number of users connected to the server. Once a client is received, I create a clientWorker instance. Furthermore, a unique key is assigned for each connected user, which can be used to fetch its object from the arraylist (if required).
The ClientWorker class looks something like this:
    class ClientWorker implements Runnable {
      private Socket client;
      public int id

    //Constructor
      ClientWorker(Socket client, int id) {
        this.client = client;
        this.id = id;
      }

      public void run(){
        String line;
        BufferedReader in = null;
        PrintWriter out = null;
        try{
          in = new BufferedReader(new InputStreamReader(client.getInputStream()));
          out = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException e) {
          System.out.println("in or out failed");
          System.exit(-1);
        }

        while(true){
          try{
//ANY DATA I GET FROM THIS STREAM IS FROM THIS PARTICULAR CLIENT ONLY!
            line = in.readLine();
            System.out.println("RECEIVED FROM CLIENT "+ id +" " + line);
           }catch (IOException e) {
            System.exit(-1);
           }
        }
      }
    }

This thread calls the run() method. Since each client has a separate thread, the data handled from a particular thread is sent from that particular client and not someone else. Therefore, one can distinguish each client's data easily.
Sorry its a long answer. It took sometime so that I reach my point.
References


text:
Q: Eclipse -->Android Studio support jars I have a project in eclipse that I am moving to Android Studio. I did the import and then looked at my version control for deleted files and noticed these:
cmuench-air:POS cmuench$ git status | grep 'deleted';

deleted:    .gitignore
deleted:    .settings/org.eclipse.core.resources.prefs
deleted:    .settings/org.eclipse.jdt.core.prefs
deleted:    ic_launcher-web.png
deleted:    libs/android-support-v4.jar
deleted:    logo-web.png
deleted:    proguard-project.txt
deleted:    project.properties

The ones that stood out to me are:

*

*libs/android-support-v4.jar

*ic_launcher-web.png

I think the android support jar is for older platforms of android. The other one is the logo.
Why do you think these got changed?
NOTE: The path of these files did NOT change; it was a delete. (It didn't say renamed after I added it to my staging area in git.


text:
Q: no main manifest attribute, when trying to run a jar file I'm trying to run this Java GUI application but I'm not sure how to get it to run. The project is located here: https://gitee.com/gangshushu/v7/tree/master/admon_gui/one-jar.
My initial attempt was:
java -jar one-jar-ant-task-0.97.jar
But I end up with the error:

no main manifest attribute, in one-jar-ant-task-0.97.jar

Doing some search around, Failing to run jar file from command line: "no main manifest attribute", I ended up running:
java -cp one-jar-ant-task-0.97.jar Main
But I end up with another error message:

Error: Could not find or load main class Main
Caused by: java.lang.ClassNotFoundException: Main

Searching around gave me some information overload here: What does "Could not find or load main class" mean?
How do I run this Java program? This is my first time trying to run a jar file, and I'm a little stuck.
Am I trying to run the Java program the wrong way?

A: Your main class is in a package, you need to specify in what package to find your main class. Try the following command line:
java -cp one-jar-ant-task-0.97.jar com.beegfs.admon.gui.program.Main


text:
Q: What actions to take when people leave the team? Recently one of our key engineers resigned. This engineer has co-authored a major component of our application. We are not hitting Truck number yet though, but we're getting close :)
Before the guy waltzes off, we want to take actions necessary to recover from this loss as smoothly as possible and eventually 'grow' the rest of the team to competently cover the parts he authored.
More about the context: the domain the component covers and the code are no rocket science but still a lot of non-trivial stuff. Some team members can already cover a lot of this but those have a lot on their plates.
These are the actions that come to my mind:

*

*Improve tests and test coverage - especially for the non-trivial stuff,

*Update high level documents,

*Document any 'funny stuff' the code does (we had to do some heavy duct-taping),

*Add / update code documentation - have everything with 'public' visibility documented.

Finally the questions:
What do you think are the actions to take in this situation? What have you done in such situations? What did or did not work well for you?

A: As a contractor for 30 years, I've left teams dozens of times.
Sometimes I get called back.  Sometimes not.
The folks that had to call me back did not -- somehow -- understand that I was a contractor and was leaving.  This, BTW, was generally manifest early in the project.  Some organizations have low turnover -- people have worked together for years and have yellow post-it notes with critical system information posted in the cubicles and there is no written documentation that's correct.
The folks that did not call me back were, perhaps, unhappy and deleted all my code.  Who knows?
However, organizations that made a habit of the following were happy.

*

*Bug Tracking.  This is critical.  There shouldn't be "TODO:" comments in the code.  These are feature requests or potential bugs that should be formally tracked.  All the duct tape and band-aids must be formally and completely documented as bug fixes or future enhancements.

*Testing.  Also critical.  If the build is broken, no one goes home.

*Keeping Requirements, Design and Deployment Documentation Current.  This requires active, constant reviews and walkthroughs.  It requires an organization that expects and manages turnover.  No one should have the same job for more than a few years.  Shuffle, reshuffle, and re-reshuffle until the documentation makes this painless.

*Tracking objectives and deliverables.  If you're not actively managing the code being produced, you don't know what people are working on and you don't know what's half-finished or what's half-broken.  ("FOB" Flat On Back.  i.e., "OOT", On the Operating Table.  Also, Undergoing Surgery.  We used to say "tits up", but had to stop when some engineers objected to this. Too colorful. And they're right, it's inappropriate.)
This will allow you to stop them from writing new code just before they leave.
The bottom-line is that you need a 360-degree view of what the team has going in (requirements) what the team has coming out (tested, documented code) and what the team has in process (new code, fixes).
If you have that view, an individual person on the team can be replaced.

A: Some more tipps in addition to what already has been said:

*

*Let him write a status summary about everything he has been working on. What is definitely done, what "should" work, what is half-done, what is untouched.

*Let him document all sideline tasks he might be (informally) responsible for; like checking the log files of a customer's server once a month. In a perfect world, all those tasks would be already documented, but in real life, something might have creeped in.

*It's crititical to find out if this is the beginning of a mass exodus. Maybe something is going wrong in the project and others are likely to follow soon. If so, you want to counteract while possible.

*If the engineer has direct contact to your client, let him document who his contact persons are and what their position is. Your existing records might not be accurate in that regard, and not knowing those people might lead to embarrasing situations.

*If the engineer has VPN access to your customer's servers, make sure you know who they are; make sure his account is suspended and a new account for the replacement is created in time.

A: I ask him to stop coding completely and devote his time:

*

*coaching others

*review his comments in code (to adapt them to the situation)

*and write a document he would have written if he knew he would leave in a week.

I try to put priority in modules he owned to make other developer work with them.
Remember after he left, it's too late to do coaching or ask him questions (in good conditions).
When he leaves, take that opportunity to ask him how he think you could improve your organization. Former employees have nothing to lose and their feedback is honest and then always valuable.

A: When I first changed position in the first company I worked for I made a spreadsheet that contained a list of all work I'd done in rows, and columns for:

*

*the project/product it was for

*the specific area of the project

*the business/project manager

*the complexity of the work

*who it was being handed to

*whether it was handed over, to be handed over or didn't need to be

*the date it was handed over

*the name of any documents for it (which were stored in an accompanying articles.zip)

*any comment on it

This was updated over the course of the handover (and filtered and sorted for priorities) and eventually became a legend and archive of all my work and a TODO list for any documentation/discussions that were needed, and people to make sure are happy with handovers.
I gave to my old manager so they (or anyone else) could get my work/documents without having to ask me.
I was asked for blank copies of it a lot and it became the informal de facto handover document for any handovers.
Although, when I left as a developer, I was still scheduled into coding until my last hour (and was late for my leaving do for it), so definitely agree with Pierre on stopping any new work to make sure the handover goes well.

A: You seemed to have covered the key points:

*

*Update/create important documentation on the component/system you have been putting off.

*Note down common pitfalls, gotchas, etc that they may know but the team doesn't

*Improve tests for difficult/complex sections that are missing them.

Other things they may be helpful:

*

*Have someone partner with them to do a "brain dump" during the end. This is much quicker, but less precise, then documentation when you are out of time.

*Try to be on good terms with the leaving employee, you might need to hire them back for a few hours in a consulting role outside of hours (if you really get stuck).

At least, this is what I have learnt after watching my former employers lose 3 of their 4 key technical staff in my first 2 years there...

A: Consider doing all those things on any major project in the future. It's what my company is doing after learning their lesson the hard way.
There are always at least two pairs of eyes on any code project. That way the effect of someone leaving is always limited.
And always keeping your tests/documentation up to date goes a long way too.


text:
Q: Can't build Xamarin UrhoSharp.Forms sample project in release mode When i'm trying to build xamarin urhosharp sample project "FormsSample.Droid" in release mode and i set linking to "Sdk Assemblies Only", i got an error:

Severity Code Description Project File Line Suppression State Error
  The "LinkAssemblies" task failed unexpectedly.
  Xamarin.Android.XamarinAndroidException: error XA2006: Reference to
  metadata item '!!0[] System.Array::Empty()' (defined in 'Urho.Forms,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=null') from
  'Urho.Forms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
  could not be resolved. ---> Mono.Cecil.ResolutionException: Failed to
  resolve !!0[] System.Array::Empty() at
  Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference) at
  Mono.Linker.Steps.MarkStep.MarkInstruction(Instruction instruction) at
  Mono.Linker.Steps.MarkStep.MarkMethodBody(MethodBody body) at
  Mono.Linker.Steps.MarkStep.ProcessMethod(MethodDefinition method) at
  Mono.Linker.Steps.MarkStep.ProcessQueue() at
  Mono.Linker.Steps.MarkStep.Process() at
  Mono.Linker.Steps.MarkStep.Process(LinkContext context) at
  Mono.Linker.Pipeline.Process(LinkContext context) at
  MonoDroid.Tuner.Linker.Process(LinkerOptions options, LinkContext&
  context) at Xamarin.Android.Tasks.LinkAssemblies.Execute()
  --- End of inner exception stack trace --- at Xamarin.Android.Diagnostic.Error(Int32 code, Exception innerException,
  String message, Object[] args) at
  Xamarin.Android.Tasks.LinkAssemblies.Execute() at
  Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
  at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext()
  FormsSample.Droid

When i set linking to "None" everything works perfectly but generated *.apk file is really big.

A: Issue resolved. Answer which i got from Xamarin Member:

It's a known issue. Should be fixed in the next nuget update. Also I'd
  recommend to use "generate APK per ABI" option cause UrhoSharp has 5
  native libs - ~7-14mb each.


text:
Q: Does typescript transpile the Transformed code generated by Angular Compiler I was watching The Angular Compiler 4.0 - TOBIAS BOSCH and suddenly at 1:30 of the video it was said that AST is transformed into typescript code if we use AOT compilation or javascript code if we use JIT compilation.Compilation process a snapshot of the video. now I am super confused what actually is happening under the hood? Whether (.ts) is transpiled to js first by typescript compiler and then angular compiler comes into the play or angular compiler do the job and typescript compiler comes into the play? I went through this What does the angular compiler "compile"?
 but apparently my doubt is not clear yet? Can anyone help me out on this?

A:
Whether (.ts) is transpiled to js first by typescript compiler and then angular compiler comes into the play or angular compiler do the job and typescript compiler comes into the play

*

*With AOT compiler you have angular html -> TS (to ensure types are correct) - > JS

*With JIT you have angular html -> embedded in js and parsed / executed on the fly


text:
Q: Objects are not valid as a React child (found: object with keys {en, nl}). If you meant to render a collection of children, use an array instead I am setting up a React app. I am getting the error "Objects are not valid as a React child (found: object with keys {en, nl}). If you meant to render a collection of children, use an array instead."
19 stack frames:
throwOnInvalidObjectType
node_modules/react-dom/cjs/react-dom.development.js:13231
reconcileChildFibers
node_modules/react-dom/cjs/react-dom.development.js:14133
reconcileChildren
node_modules/react-dom/cjs/react-dom.development.js:16990
updateHostComponent
node_modules/react-dom/cjs/react-dom.development.js:17632
beginWork
node_modules/react-dom/cjs/react-dom.development.js:19080
HTMLUnknownElement.callCallback
node_modules/react-dom/cjs/react-dom.development.js:3945
invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js:3994
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js:4056
beginWork$1
node_modules/react-dom/cjs/react-dom.development.js:23964
performUnitOfWork
node_modules/react-dom/cjs/react-dom.development.js:22776
workLoopSync
node_modules/react-dom/cjs/react-dom.development.js:22707
renderRootSync
node_modules/react-dom/cjs/react-dom.development.js:22670
performSyncWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js:22293
scheduleUpdateOnFiber
node_modules/react-dom/cjs/react-dom.development.js:21881
updateContainer
node_modules/react-dom/cjs/react-dom.development.js:25482
(anonymous function)
node_modules/react-dom/cjs/react-dom.development.js:26021
unbatchedUpdates
node_modules/react-dom/cjs/react-dom.development.js:22431
legacyRenderSubtreeIntoContainer
node_modules/react-dom/cjs/react-dom.development.js:26020
render
node_modules/react-dom/cjs/react-dom.development.js:26103
Here you can find the index.tsx file.
import * as ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import MainApp from './router'

const page = (
  <BrowserRouter>
    <MainApp />
  </BrowserRouter>
)

const app = document.getElementById('root');
ReactDOM.render(page, app)

Here you can find the router.tsx file
import * as React from 'react'
import { ThemeProvider } from '@material-ui/styles';
import AppWrapper from './App'
import { SnackbarProvider } from 'notistack';
import { theme } from './jss/theme';
import { CssBaseline } from '@material-ui/core';

const Router = (props: any) => (
    <ThemeProvider theme={theme}>
        <CssBaseline />
        <SnackbarProvider autoHideDuration={3000} maxSnack={3}>
            <AppWrapper {...props} />
        </SnackbarProvider>
    </ThemeProvider>
)

export default Router

Here you can find the App.tsx file
import React from 'react';
import { Route, Switch } from 'react-router-dom'
import CssBaseline from '@material-ui/core/CssBaseline';
import Home from './routes/Home'
import Header from './components/header/Header'

const routes = [
  {
    path: '/', component: Home, exact: true
  }, {
    path: '/home', component: Home
  }
]

function App() {
  return (
    <Switch>
      {
        routes.map(({ exact, component: Component, path }) =>
          <Route key={`parent${path}`} exact={exact} path={path} render={prop =>
            <React.Fragment>
              <CssBaseline />
              <Header />
              <main>
                <Component {...prop}></Component>
              </main>
              <CssBaseline />
            </React.Fragment>
          }
          />
        )
      }
    </Switch>
  );
}

export default App;

A: I'm not sure this is the issue, but your imports look a little strange:
import * as React from 'react'
import * as ReactDOM from 'react-dom';

Should be:
import React from 'react'

And
import ReactDOM from 'react-dom';


text:
Q: Is there a way to convert an .eot to .woff or call another file in css I have this big chunk of text that looks something like this:
url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAHnQABMAAAABHZAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABqAAAABwAAAAcbWcNJUdERUYAAAHEAAAANQAAADgF/) format("woff")

I would like to rather call the text like so src: url("Font.woff");
I don't have the woff file for the font, can I convert the .eot file I have to woff? If so how? Otherwise is there way to call a .txt file from my styles.css so I don't have this monstrosity paragraph in there.

A: CSS: Using @fontface
@font-face {
font-family: 'Montserrat'; /* Gewünschter Name */
src: url('../../../fonts/Montserrat-Medium.eot');
/* für IE9 */
src: url('../../../fonts/Montserrat-Medium.eot') format('embedded-opentype'), /* für IE6-IE8 */
url('../../../fonts/Montserrat-Medium.woff') format('woff'), /* für moderne Browser */
url('../../../fonts/Montserrat-Medium.ttf') format('truetype');
/* für Safari, Android, iOS */
}

A: The answer was drag your eof into google chrome's url and it will save it for you as a .wof - that simple.


text:
Q: Draw custom Back button on iPhone Navigation Bar I've got a UIView with a NavigationBar and I'd like to add a button which looks like the style of a Back Button. I'm not using a UINavigationController and was wondering if this could be done without it?
The style of the button should look like this:
Thanks

A: You need to set up a custom stack of UINavigationItem objects and push them on to the UINavigationBar. This is the only way I know of to get a true back button. I haven't tested this code, but you should do something like this:
UINavigationItem *previousItem =
    [[[UINavigationItem alloc] initWithTitle:@"Back title"] autorelease];

UINavigationItem *currentItem =
    [[[UINavigationItem alloc] initWithTitle:@"Main Title"] autorelease];

[navigationBar setItems:[NSArray arrayWithObjects:previousItem, currentItem, nil]
               animated:YES];

To handle when the buttons are pressed you should set yourself as the navigation bar's delegate and implement the UINavigationBarDelegate delegates.

A: You can also update this by modifying the backBarButtonItem on the previous view controller (not the currently viewed one).


text:
Q: Run drush cc from host using bind mounts I managed to have some containers with this config in order to run a Drupal app:
version: '3.1'

services:

  drupal:
    depends_on:
      - postgres
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - 8080:80
    volumes:
      - type: bind
        source: ./workspace
        target: /opt/workspace
    networks:
      - beayoga
    restart: always

  postgres:
    image: postgres:13.2
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - pg_data:/var/lib/postgresql/data
    networks:
      - beayoga
    restart: always

  pgadmin:
    depends_on:
      - postgres
    image: dpage/pgadmin4
    ports:
      - 443:443
      - 8081:80
    environment:
      - PGADMIN_DEFAULT_EMAIL=foo@bar.com
      - PGADMIN_DEFAULT_PASSWORD=foobar
    networks:
      - beayoga

volumes:
  pg_data:

networks:
  beayoga:

It is working well, when changing a file from my host I can see the changes in my container (using the interactive terminal) and when changing a file from the my container I can see the changes in my host.
When I want to see the changes, I have to run this command:
./vendor/bin/drush cc
When I run it from my container, I get this:
www-data@5c6c061c1519:/opt/workspace$ ./vendor/bin/drush cc
 Choose a cache to clear [all]:
  [0] Cancel
  [1] drush
  [2] theme-registry
  [3] router
  [4] css-js
  [5] render
  [6] plugin
  [7] bin
  [8] views

Then I can choose [5] to see the changes in my webpage.
I want to run this same command from my host, so that in the future, I won't need to connect to the container with the interactive terminal.
When I run the exact same command, from my host, I get this:
➜  workspace git:(dev) ✗ ./vendor/bin/drush cc
 Choose a cache to clear [all]:
  [0] Cancel
  [1] drush

I only have those two options that are displayed, and I cannot choose [5] render
Does somebody know what is happening and how can I get the whole list of choices ?
What I've tried so far:
I see some answers on google suggesting that it could be something related to the database. So I installed psql in my host and added the name of the postgres container in my /etc/hosts file (using the ip given when running docker inspect), but I still had the same 2 items showing in the list with no more...
Edit
To answer @Patrick W comment:
Render and status on remote (container)
www-data@5c6c061c1519:/opt/workspace$ ./vendor/bin/drush cc render
 [success] 'render' cache was cleared.
www-data@5c6c061c1519:/opt/workspace$ ./vendor/bin/drush status
 Drupal version   : 9.1.4
 Site URI         : http://default
 DB driver        : pgsql
 DB hostname      : postgres
 DB port          : 5432
 DB username      : postgres
 DB name          : postgres_development
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : my_custom_theme
 Admin theme      : seven
 PHP binary       : /usr/local/bin/php
 PHP config       :
 PHP OS           : Linux
 Drush script     : /opt/workspace/vendor/drush/drush/drush
 Drush version    : 10.4.0
 Drush temp       : /tmp
 Drush configs    : /opt/workspace/vendor/drush/drush/drush.yml
 Install profile  : standard
 Drupal root      : /opt/workspace/web
 Site path        : sites/default
 Files, Public    : sites/default/files
 Files, Temp      : /tmp

Render and status on host
➜  workspace git:(dev) ✗ ./vendor/bin/drush cc render

In CacheCommands.php line 261:

  'render' cache requires a working Drupal site to operate on. Use the --root and --uri options, or a site @alias, or cd to a directory containing a Drupal settings.php file.

➜  workspace git:(dev) ✗ ./vendor/bin/drush status
 Drupal version : 9.1.4
 Site URI       : http://default
 DB driver      : pgsql
 DB hostname    : postgres
 DB port        : 5432
 DB username    : postgres
 DB name        : postgres_development
 PHP binary     : /usr/bin/php
 PHP config     : /etc/php.ini
 PHP OS         : Linux
 Drush script   : /home/david/Desktop/beayoga/workspace/vendor/drush/drush/drush
 Drush version  : 10.4.0
 Drush temp     : /tmp
 Drush configs  : /home/david/Desktop/beayoga/workspace/vendor/drush/drush/drush.yml
 Drupal root    : /home/david/Desktop/beayoga/workspace/web
 Site path      : sites/default

However I'm in the exact same directory, since they are bound together...
Do you know how Drupal gets to know if it is installed ? Maybe it try to look on another folder which isn't on the host ?


text:
Q: How can I make a custom WinPE? I should make a custom winpe that :

*

*Have an automatic IP Address such as 192.168.17.253/24

*and after the system booted up, it could ping the another IP Address such as : 192.168.17.243

A: http://www.msfn.org/board/topic/83722-how-to-make-a-basic-winpe-20-cd/
This should get you started.  Despite the instructions mentioning XP and Vista the Windows AIK has been updated for windows 7/8.  The same steps should work.


text:
Q: moment(aDate).utcOffset(aDate).format() method is stripping date like +00:00Z When I invoke
moment("2001-09-11T00:00:00+00:00").utcOffset("2001-09-11T00:00:00+00:00").format()

"2001-09-11T00:00:00Z" gets returned.  Is there any way to have +00:00 displayed instead of Z?

console.log(moment("2001-09-11T00:00:00+00:00").utcOffset("2001-09-11T00:00:00+00:00").format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


text:
Q: Value of PHP variables not transferring with include statement OK, I know that I am being stupid about this, but I can't seem to figure out how I am being so.
I have variables for social media links in a separate .php file so that my client can change them without having to see too much code.
I include that .php file in my normal code where I want the links to be. But, for some reason the value of the variable is not being transmitted. I even tried to make a "global" variable. Here is my code.
File: socialMediaURLs.php
<?php

    global $facebook = 'https://www.facebook.com/MenCoachingMen';
    $googlePlus = 'https://plus.google.com/104275309033865331192/posts';
    $twitter = 'https://twitter.com/MenCoachingMen';
    $rss = 'http://mencoachingmen.org/category/podcast/feed/';
    $vimeo = 'https://vimeo.com/mencoachingmen';
    $youtube = 'https://www.youtube.com/channel/UCy_Pth5x-O7rcX9nMx1e8qw';

?>

File: socialLinks.php
<?php include './socialMediaURLs.php'; ?>

    <a href="<?php echo $facebook;?>">

    <a href="<?php echo $googlePlus;?>">

    <a href="<?php echo $twitter;?>">

    <a href="<?php echo $rss;?>">

    <a href="<?php echo $vimeo;?>">

    <a href="<?php echo $youtube;?>">

I ran a test like so:
<?php
    if($facebook){
        echo $facebook;
    }else{
        echo 'Facebook NULL';
    }
?>

I put this after the include statement and before the rest of the code. And it prints out 'Facebook NULL'. So, I know that the value is not being transmitted. Now, if I put in the included .php file (where the variables are stored) a echo "Hello World!"; line, "Hello World!" does print out on the screen. So, I know that the file is being included correctly (ie the path is correct).
I then placed this code after the 'include' and before the rest of the code:
$facebook = 'https://www.facebook.com/MenCoachingMen';

When I do that, the URL is included within the page. So, I know that my php statements within the code is correct. That means that it has to be a transmission of the value of the variable after including it. Please help. I know this must be a stupid mistake somewhere. Thank you.

A: A global variable must be used inside a function.
function name(){
    global $globalvar = "some info";
}

to pass a variable OUT of it and into the script. You can't pass variables to other scripts using global variables. Consider using $_SESSION['name'] variables to pass variables from script to script.
http://php.net/manual/en/book.session.php

A: <?php include 'socialMediaURLs.php'; ?> <--- top main public_html/www
<?php include 'directory1/socialMediaURLs.php'; ?> <-- one folder deep
<?php include 'directory1/directory2/socialMediaURLS.php'; ?> <-- two folders deep

//calling a file FROM two folders deep TO A FILE IN the root folder!
<?php include('../../socialMediaURLS.php'; ?>  <--- main index public_html/www
//ETC......
<?php include('../../directory1/socialMediaURLS.php'; ?>

I hope this helps. Think of it like DIR and CD commands.


text:
Q: Approximate a measurable set with an elementary set of equal measure? Let $A \subset [0,1]$ be a measurable set.
we know that A is measurable iff for every $\varepsilon>0$ there is an elementary set B such that $\mu(A \Delta B) <\varepsilon$
Where $A\Delta B$ is their symmetric difference.
For a given $\varepsilon$. Can we choose B such that $\mu(B) =\mu(A) $?

A: You can do this. We have $\mu (A\Delta B) \leq \mu (A\Delta C)+\mu (B\Delta C)$. So first make the first term less than $\epsilon /2$ and then increase or decrease the length of one of the intervals in $C$ to make $\mu (A)=\mu (B)$.  Use the fact that $|\mu(A)-\mu (C)| <\epsilon /2$.


text:
Q: Java JRE vs GCJ I have this results from a speed test I wrote in Java:
Java

real        0m20.626s
user        0m20.257s
sys         0m0.244s

GCJ

real        3m10.567s
user        3m5.168s
sys         0m0.676s

So, what is the purpose of GCJ then? With this results I'm sure I'm not going to compile it with GCJ!
I tested this on Linux, are the results in Windows maybe better than that?
This was the code from the application:
public static void main(String[] args) {
    String str = "";
    System.out.println("Start!!!");
    for (long i = 0; i < 5000000L; i++) {
        Math.sqrt((double) i);
        Math.pow((double) i, 2.56);
        long j = i * 745L;
        String string = new String(String.valueOf(i));
        string = string.concat(" kaka pipi"); // "Kaka pipi" is a kind of childly call in Dutch.
        string = new String(string.toUpperCase());
        if (i % 300 == 0) {
            str = "";
        } else {
            str += Long.toHexString(i);
        }
    }
    System.out.println("Stop!!!");
}

I compiled with GCJ like this:
gcj -c -g -O Main.java
gcj --main=speedtest.Main -o Exec Main.o

And ran like this:
time ./Exec                     // For GCJ
time java -jar SpeedTest.jar    // For Java

A: On x86 and AMD64, Hotspot only uses SSE for floating point, but I see that on x86 gcj doesn't seem to support SSE and uses the much slower 387 instructions:
gcj -O3 -mfpmath=sse --main=Bench Bench.java -o Bench
jc1: warning: SSE instruction set disabled, using 387 arithmetics
/tmp/ccRyR50H.i:1: warning: SSE instruction set disabled, using 387 arithmetics

so that could explain the speed difference.
Note that when GCC does use SSE, it greatly outperforms Hotspot on floating point, since GCC generates SIMD instructions while Hotspot only uses the unpacked SSE arithmetic.

A: OpenJDK's native Java compiler is, itself, written in Java; as a consequence, you need a working previous version of Java in order to build a new version.
If you're starting from scratch on a platform for which no existing JDK binaries are readily available (or if you're working within certain Free Software projects whose charters prohibit the use of proprietary build dependencies), then GCJ (or some of its underlying components) can be one potential solution to the chicken-and-egg problem of getting a working, albeit somewhat inefficient bootstrap Java in place, in order to move on to build the more desirable OpenJDK.
In fact, back when OpenJDK was first announced, significant effort (via the IcedTea project) was spent in fixing up GCJ to get it to the point where it was up to the task.

A: GCJ is obsolete. It was started a long time ago because people wanted an open-source alternative to the Sun JDK, and it was never particularly good. Now that Sun open-sourced their JDK, there's absolutely no reason to use GCJ (but it still lurks in some Linux distros).

A: "So, what is the purpose of GCJ then?"
Some have pointed that your "benchmark" isn't fair. However, even if it was, I can still see a use for GCJ. Suppose you want to write a kernel in Java. With a JVM, you have to port the VM to a standalone environment, and then you would have to write the low lever code in C. With an AOT compiler, you can work around this issue with some glue code and then can do the low level code in Java too. No need to port the compiler in this case.
Also, we have to separate the technique from the benchmarks. Perhaps the AOT technique can be more powerful than the JIT technique provided that we invest enough development effort in it.

A: It's not a fair comparison when you do the AOT (Ahead-Of-Time) compile with little optimisation (-O).  Try at least -O2.
It's also not as simple as one is faster than the other on a single contrived test.  AOT compilation works best in some scenarios.  JVMs work better in others, and it also depends heavily on the quality of the JVM.  In the real world, ecj is noticeably faster at building OpenJDK when AOT-compiled rather than when running on the JVM.  For long-running applications, the JVM is likely to win because it can make use of dynamic optimisations not possible ahead-of-time.  ecj suffers because for the short period it's compiling, the JVM is still interpreting code.  HotSpot compiles and optimises code when it determines it's worthwhile (a 'hot spot').
BTW, it's the FAQ that's out of date.  GCJ supports most of 1.5, certainly enough to build OpenJDK.  Without GCJ still 'lurking in some Linux distros', it wouldn't be possible to build OpenJDK in the first place.

A: You have stumbled onto another product of the "Software Freedom at any cost!" line of thinking. GCJ was created to allow compilation and execution of Java code without depending on anything deemed "non-free" by GNU project.
If you value software freedom enough to take a 12x performance hit, then by all means, go for it!
The rest of us will happily use Sun's (er, Oracle's) incredible HotSpot JVM.
See also: The GCJ FAQ: "I have just compiled and benchmarked my Java application and it seems to be running slower than than XXX JIT JVM. Is there anything I can do to make it go faster?"
Also: "It has been merged with GNU Classpath and supports most of the 1.4 libraries plus some 1.5 additions." So it's just a bit out of date as well.


text:
Q: Unable to use virt-manager On Ubuntu server 11.10 I am trying to install a virtual machine using virt-manager. I believe that I have everything right, but when I go and run the command virt-manager I get the following error message:
File "/usr/share/virt-manager/virt-manager.py", line 383, in <module>
  main()
File "/usr/share/virt-manager/virt-manager.py", line 285, in main
  raise RuntimeError(_("Unable to initialize GTK: %s") % gtk_error)
RuntimeError: Unable to initialize GTK: could not open display

I want to use virt-manager so that I can quickly and efficiently create multiple (6) virtual machines, but is there any other alternative that does not take hours per host system, and is still lightweight?
My machine is as follows:

*

*Ubuntu Server 11.10

*8 cores @ 2.5ghz

*64 gb ram

*Packages:

*

*qemu-kvm

*libvirt-bin

*virt-manager

*bridge-utils

*gnome-core

A: Are you running X on the server ? If not, you can run it from a second machine over ssh
ssh -X user@server

Or you can run a light weight X session on the server, run a web interface (convirt or similar), or run virsh (command line interface).
https://help.ubuntu.com/community/KVM/Virsh

A: Have an ubuntu laptop/desktop in the same network as your server. Install virt-manager on it. Use:
virt-manager -c qemu+ssh://root@your-server-ip-or-name/system as command.
Alternatively, read on at http://wiki.libvirt.org/page/FAQ

A: Sorry to revive this old question, but I've encountered the same problem trying to run virt-manager via ssh+X11 with Putty from a Windows client machine.
For me, the following steps solved the problem:

*

*Have xauth and xterm installed on the server

*Have XMing running on the windows (client) machine

*Run Putty with X11 forwarding (on client, connecting to server)

*Log in as root, or other privileged user (using Putty from client)

*Execute virt-manager on the server. It should bring up a separate dialog in Xming on the client showing virt-manager

So I think you were missing the X server on Windows, which is what Xming is providing.


text:
Q: Cant access codeigniter session variable until page refresh Am using codeigniter to build an eCommerce site.
I have a method on controller where users enter their delivery information before checkout, the method saves the delivery information and creates a new session variable called "orderid" which has the value of the orderid as its value. After setting the session variable the method redirects to the checkout controller where i retrieve the "orderid" from the session to retrieve the order from the db for the user to confirm the information before paying.
The problem is, when the user is redirected to the checkout page, they dont see their delivery  data.
When do this
echo $this->session->userdata('orderid');

I can see the value
But when i pass it to my method that supposed to return an array of data
$order = $this->orders->get_order($this->session->userdata('orderid'));
print_r($order);

I get an empty array array()
When the checkout page is refreshed it behaves correctly.
What could be the problem

A: In order for the session to work you have to add $this->load->library('session'); to your __contruct() function
public function __construct() {
parent::__contruct();
$this->load->library('session');
}

A: You cannot access session value like this
$order = $this->orders->get_order($this->session->userdata('orderid'));

You can use the following method it ll be work fine for you
$orderid=$this->session->userdata('orderid');
$order = $this->orders->get_order($orderid);

**please remembere  load session library at constructor or in this function
$this->load->library('session');