text:
Q: DLL Hell with .NET Core Class Library I'm building a COM Library to expose SignalR to a non-NET software but it has a lot of references loading different versions, I even lost a lot of time trying to get the strict version of everything but it just breaks even more.
Using the library on a test Console App works fine because of the binding redirections on the app.config of the EXE but I can't put a .config file on the production EXE.
I hope I have other alternatives than this.
Real example (Assembly Binding Log Viewer)
*** Assembly Binder Log Entry  (29/06/2021 @ 14:02:43) ***

The operation failed.
Bind result: hr = 0x80070002. The system cannot find the file specified.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Sybase\PowerBuilder 11.5\PB115.EXE
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = System.Text.Json, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
 (Fully-specified)
LOG: Appbase = file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = PB115.EXE
Calling assembly : Microsoft.AspNetCore.SignalR.Protocols.Json, Version=5.0.7.0, Culture=neutral, PublicKeyToken=adb9793829ddae60.
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Program Files (x86)\Sybase\PowerBuilder 11.5\PB115.EXE.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: System.Text.Json, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/System.Text.Json.DLL.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/System.Text.Json/System.Text.Json.DLL.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/DotNET/bin/System.Text.Json.DLL.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/DotNET/bin/System.Text.Json/System.Text.Json.DLL.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/System.Text.Json.EXE.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/System.Text.Json/System.Text.Json.EXE.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/DotNET/bin/System.Text.Json.EXE.
LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sybase/PowerBuilder 11.5/DotNET/bin/System.Text.Json/System.Text.Json.EXE.
LOG: Attempting download of new URL file:///C:/Users/user/Documents/project/bin/Release/System.Text.Json.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\user\Documents\project\bin\Release\System.Text.Json.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: System.Text.Json, Version=5.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
WRN: Comparing the assembly name resulted in the mismatch: Revision Number
ERR: The assembly reference did not match the assembly definition found.
ERR: Run-from-source setup phase failed with hr = 0x80131040.
LOG: Attempting download of new URL file:///C:/Users/user/Documents/project/bin/Release/System.Text.Json/System.Text.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/Documents/project/bin/Release/System.Text.Json.EXE.
LOG: Attempting download of new URL file:///C:/Users/user/Documents/project/bin/Release/System.Text.Json/System.Text.Json.EXE.
LOG: All probing URLs attempted and failed.


text:
Q: URL Rewrite and Wordpress? Im fairly new to Wordpress development and i have run into a problem.
We recently launched a new site made in Wordpress. On our old site we had a rule in htaccess that rederected traffic from /ABC123 to /bil.php?regno=ABC123. The rule was "any URL that ends with /XXXNNY where X is a letter, N is a number and Y i either redirects to /bil.php?regno=XXXNNY".
Here is the htaccess rule from the old page:
# If formated like ABC123 or ABC12A
RewriteRule ^([A-Za-z]{3}[0-9]{2}[A-Za-z0-9])$ bil.php?regno=$1 [L]

Now, I need the same redirect rule on our new Wordpress site (except it should redirect to /begagnad-bil/?regnr=XXX123).
Adding the rule above to the htaccess file doesn't work.
I also tried adding the following code to the beginning of my functions.php file inside the theme folder.
add_action( 'init', 'pmg_rewrite_add_rewrites' );
function pmg_rewrite_add_rewrites()
{
    add_rewrite_rule(
        '^([A-Za-z]{3}[0-9]{2}[A-Za-z0-9])$',
        '/begagnad-bil/?regnr=$1',
        'top'
    );
}

...but this doesn't work either.
edit: I also flush the rules by clicking Save under Settings -> Permalinks in the Wordpress admin.
How would one do such a redirect on a Wordpress site?
Thank you

A: You need to add the 301 directive at the end of your rule like so
RewriteRule ^([A-Za-z]{3}[0-9]{2}[A-Za-z0-9])$ begagnad-bil/?regnr=$1  [R=301,L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: An object or column name is missing or empty GEOMETRY I'm trying to do a geometric union but it's not working
select b.[Region],geometry::UnionAggregate(geom.MakeValid()) into dbo.DRShape
from [dbo].[departements2] a join [dbo].[BM_REGIONFR] b
on a.[code_insee] = b.[dep_2]
group by b.Region

Msg 1038, Niveau 15, État 5, Ligne 1
  An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.

A: You are trying to create a table using SELECT INTO, the table needs a column name for each column. Your second column result is missing an alias (that will turn into a column name).
select
    b.[Region],
    geometry::UnionAggregate(geom.MakeValid()) AS Geo -- Add Alias!!
into
    dbo.DRShape
from [dbo].[departements2] a join [dbo].[BM_REGIONFR] b
on a.[code_insee] = b.[dep_2]
group by b.Region

If you comment the INTO dbo.DRShape and you see that your query runs OK, means that the problem is the creation of your new table.


text:
Q: Setting my GameWindow to fullscreen will stretch it to the desktop resolution Setting my GameWindow to fullscreen stretches it, how do I set it fullscreen without losing the original window resolution with the use of black bars?
This is my code:
using System;
using System.Collections.Generic;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.GraphicsLibraryFramework;
using OpenTK.Windowing.Desktop;
using System.Drawing;

namespace OnlineGame
{
    public class Game : GameWindow
    {
        public Game(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings)
             : base(gameWindowSettings, nativeWindowSettings)
        {
            WindowState = WindowState.Fullscreen;
        }

        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            if (KeyboardState.IsKeyDown(Keys.Escape))
            {
                Close();
            }

            base.OnUpdateFrame(e);

            GL.Clear(ClearBufferMask.ColorBufferBit);
            GL.ClearColor(Color.CornflowerBlue);

            this.SwapBuffers();
        }
    }
}

A: Use GL.Viewport to set the viewport rectangle to a sub-area of the window. "Copy" operations as GL.Clear are not affected by the rectangle of the viewport. Therefore, you also need to set a Scissors Test.
You need to know the current size of the window (current_w, current_h) and the original size of the window (original_w, original_h). Compute the aspect ration of the current window (current_aspect) and the aspect ratio of the original window (original_aspect):
double current_aspect = (double)current_w / current_h;
double original_aspect = (double)original_w / original_h;

Compute the sub-area and set the viewport and scissor rectnagle:
int w = (int)(current_w * original_aspect / current_aspect);
int x = (current_w - w) / 2;
GL.Scissor(x, 0, w, this.Size.Y);
GL.Viewport(x, 0, w, this.Size.Y);

Clear the entire window with the black color. Then restrict the viewport rectangle and enable the scissors test.
Note  you must set the clear color (GL.ClearColor) before the GL.Clear instruction.
protected override void OnUpdateFrame(FrameEventArgs e)
{
    if (KeyboardState.IsKeyDown(Keys.Escape))
    {
        Close();
    }

    base.OnUpdateFrame(e);

    int original_w = ...;
    int original_h = ...;
    int current_w = this.Size.X;
    int current_h = this.Size.Y;
    double current_aspect = (double)current_w / current_h;
    double original_aspect = (double)original_w / original_h;

    GL.Disable(EnableCap.ScissorTest);
    GL.Viewport(0, 0, current_w, current_h);
    GL.ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL.Clear(ClearBufferMask.ColorBufferBit);

    GL.Enable(EnableCap.ScissorTest);
    if (current_aspect > original_aspect)
    {
        int w = (int)(current_w * original_aspect / current_aspect);
        int x = (current_w - w) / 2;
        GL.Scissor(x, 0, w, this.Size.Y);
        GL.Viewport(x, 0, w, this.Size.Y);
    }
    else
    {
        int h = (int)(current_h * current_aspect / original_aspect);
        int y = (current_h - h) / 2;
        GL.Scissor(0, y, this.Size.X, h);
        GL.Viewport(0, y, this.Size.X, h);
    }

    GL.ClearColor(Color.CornflowerBlue);
    GL.Clear(ClearBufferMask.ColorBufferBit);

    // [...]

    this.SwapBuffers();
}


text:
Q: Which methods can a subclass inherit in Java? Sorry I am a newbie to Java. I am trying to get my head around inheritance and subclass/superclass relationships in Java.
If classA is a subclass of classB, will classA's protocol feature all methods that belong to classA or only those declared public and package?
Can classA's protocol feature private methods inherited from its superclass ClassB?

A: Firstly, the word "inherited" isn't quite the right term. You mean "visible".

*

*public and protected are always visible

*private is not visible

*default (a.k.a. "package") visibility - ie no specified visibility - is visible only if the subclass is in the same package (as it be would for any class in the same package)

A: All public and protected methods and variables will be inherited. Any methods with the same signature in the subclass will override the superclass behavior. The subclass will not inherit private methods and variables. Default (a.k.a package visibility level) will be inherited if in the same pacakge and by subclasses.

A: ClassA will inherit all of classB's public and protected methods. It will NOT include classB's private methods.

A: ClassB's private methods are not visible to ClassA. If you want to give ClassA access to internal methods of ClassB (without those methods becoming part of ClassB's public interface) you should make them protected instead of private.

A: Public methods, labeled by public are available to every class.
Protected methods, labeled by protected are available to subclasses and friendly classes, which are classes in the same package.
Friendly methods, labeled by nothing (i.e. default) are available to friendly classes.
Private methods are available only to the class itself.
Static methods, labeled by static are available to without an object to access them. These are called by ClassName.foo(), SuperClassName.foo() (unnecessary if not overriden, foo() is acceptable), or ClassName.foo() (unnecessary, foo() is acceptable)
Dynamic (check vocab???) labeled by nothing (i.e. default) are available only if one has an object of the class. ex: bar.foo(), this.foo() (unnecessary, foo() is acceptable), or super.foo() (unnecessary if not overridden, foo() is acceptable)
Overriden methods, annotated by @Override are only available through super.foo
So in an instance of ClassB, all protected and public members and methods of ClassA will be accessible. In a static call, only static methods are accessible.

A: Private methods are not inherited.  Only protected, public and default methods are inherited.
Class A will provide the methods that are public in both classA and ClassB


text:
Q: Prove that: $\cos 4A-\cos 4B=8(\cos A-\cos B)(\cos A + \cos B)(\cos A - \sin B)(\cos A + \sin B)$ Prove that: $\cos 4A-\cos 4B=8(\cos A-\cos B)(\cos A + \cos B)(\cos A - \sin B)(\cos A + \sin B)$
My Attempt:
$$L.H.S=\cos 4A - \cos 4B$$
$$=2\sin \dfrac {4A+4B}{2}.\sin \dfrac {4B-4A}{2}$$
$$=2\sin (2A+2B).\sin (2B-2A)$$
How do I proceed further?

A: HINT:
From the RHS,
use  Prove that $\cos (A + B)\cos (A - B) = {\cos ^2}A - {\sin ^2}B$
and by  Prove $ \sin(A+B)\sin(A-B)=\sin^2A-\sin^2B $,
$$\sin(A+B)\sin(A-B)=\sin^2A-\sin^2B=1-\cos^2A-(1-\cos^2B)$$
Can you take it from here?

A: Start on the right:
\begin{align}
&8(\cos{A}-\cos{B})(\cos{A}+\cos{B})(\cos{A}-\sin{B})(\cos{A}+\sin{B}) \\
&= 2(2\cos^2{A}-2\cos^2{B})(2\cos^2{A}-2\sin^2{B}) \\
&= 2(\cos{2A}-\cos{2B})(\cos{2A}+\cos{2B}) \\
&=  2\cos^2{2A}-2\cos^2{2B} \\
&= \cos{4A}-\cos{4B},
\end{align}
using $\cos{2\theta}=2\cos^2{\theta}-1=1-2\sin^2{\theta}$ liberally.


text:
Q: How to compare two sheets row wise with different no. of rows in both the sheets. Sheet1 should be compared with specific no of rows in Sheet2 I'm new to macro designing. I have two sheets in an excel sheet and both need to be compared row wise. The problem is that my first sheet contains 10 data rows but the other sheet has around 1000 rows. I need to compare my data(10 rows) in sheet1 with a specific number of rows in the sheet2 on the basis of date.
How do I fetch these specific number of rows?
And also, once compared, the differences should be highlighted and pasted into a new sheet named sheet3.


text:
Q: How change MIDI file? In www.jsresources.org is example, but still problems:
What is velocity? beats per minute? why not 120 but 64? why ticks means not 1.3 millisecond interval but 0.5 second? How place shorter note?
How read instruments from file?
My sample code
Synthesizer synthesizer;
synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
MidiChannel chan = synthesizer.getChannels()[0];
chan.programChange(1152, 14);

reads MidiChannel from system (global?) not from file.

A: Velocity is the volume or gain of a note. It goes from 0 to 127 - higher the number, louder the note will be.
64 was chosen probably because it is a medium level (not too loud).
To be able to use shorter notes, you will have to change the resolution of your sequence - this is the "tempo based" resolution and works in ticks per quarter note:
sequence = new Sequence(Sequence.PPQ, 1);

Increasing the second argument, you will have more ticks per quarter note, and consequently shorter notes.
You could also use:
sequence = new Sequence(Sequence.SMPTE_30, 1);

This would give you a division type of 30 frames per second. The second argument is giving you a maximum resolution of 1 note per frame.
It's all in the documentation.
Here's a sample - modified from your example link - it should save a file on your desktop. You might have to change that to a different location:
import java.io.File;
import java.io.IOException;
import javax.sound.midi.Sequence;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
import javax.sound.midi.InvalidMidiDataException;

public class CreateSequence {

    private static final int VELOCITY = 64;

    public static void main(String[] args) {

        File outputFile = new File(System.getProperty("user.home")
                + "//Desktop//file.midi");
        Sequence sequence = null;
        try {
            sequence = new Sequence(Sequence.SMPTE_30, 2);

        } catch (InvalidMidiDataException e) {
            e.printStackTrace();
            System.exit(1);
        }

        Track track = sequence.createTrack();
        int note = 40;
        for (int tick = 0; tick < 215;) {
            track.add(createNoteEvent(ShortMessage.NOTE_ON, ++note, VELOCITY,
                    tick));
            track.add(createNoteEvent(ShortMessage.NOTE_OFF, note, VELOCITY,
                    tick += 3));
        }

        try {
            MidiSystem.write(sequence, 0, outputFile);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static MidiEvent createNoteEvent(int nCommand, int nKey,
            int nVelocity, long lTick) {
        ShortMessage message = new ShortMessage();
        try {
            message.setMessage(nCommand, 0, nKey, nVelocity);
        } catch (InvalidMidiDataException e) {
            e.printStackTrace();
            System.exit(1);
        }
        MidiEvent event = new MidiEvent(message, lTick);
        return event;
    }
}

Reading from file is a whole new question. Check the docs!


text:
Q: Difference between when the callback runs in JavaScript vs C# JavaScript callback runs only when the call stack is empty. That happens either when the program execution finishes or when the main program calls await.
The callback in case of Task library in C#:

*

*Assuming single thread program, behaves the same as JS (assuming await is used and not .Wait which would cause deadlock).

*However in case of using Task.Run, or configure await false, the callback will run immediately when the response is ready. I am assuming each thread has its own call stack.
Is this correct distinction between when the callback runs in case of JS and C#?

A:
Is this correct distinction between when the callback runs in case of JS and C#?

Not really.
In JavaScript, the continuation always runs on the main thread when it is not doing anything else. Even if you await a Promise that's already complete, it's as though you called setTimeout without a delay. The code always yields whenever there's an await. IMO, the JavaScript approach is cleaner and easier to understand than C#. However, the .NET team adopted a different approach for C#, I assume for performance reasons.
In C#, the first thing to note is that await may continue executing synchronously. If the awaitable is already complete, then there's no yielding that takes place and no continuation exists at all - the code just continues executing in the same method. If the awaitable is not already complete, then a continuation is attached to the awaitable along with the current context (SynchronizationContext.Current or TaskScheduler.Current).
When the awaitable completes, then it executes all its continuations. If it's possible, then the continuation is executed on the current thread (the one that completed the awaitable). If this kind of "inline continuation" isn't possible, then the continuation is queued to the context (SynchronizationContext / TaskScheduler). What happens then is entirely dependent on the context. E.g., UI contexts will queue continuations to the UI message processing loop, which is pretty much the same as setTimeout in JavaScript. As another example, the thread pool context will queue continuations to the thread pool.

A: Main difference is: single-thread vs multi-thread
I think, in your case, callback is called from different thread.
Learn more about TaskScheduler and SynchronizationContext to achieve your endeavour.


text:
Q: How to send non-English unicode string using HTTP header? I am novice to HTTP related matters.
My question is in iOS development, I would like to send a string using HTTP Header, so I'm using:
[httpRequest setValue:@"nonEnglishString" forHTTPHeaderField:@"customHeader"];

The receiving server is Python(Google App Engine), saving the string value in the db model as StringProperty using:
dataEntityInstance.nonEnglishString = unicode(self.request.headers.get('customHeader')

However, the problem is when I try to send non-English string like Korean, it's saved in HTTP header like this:
Customheader = "\Uc8fc\Uba39\Uc774 \Uc6b4\Ub2e4";

and when it's received by Google App Engine and saved in DataStore, it's changed to be like:
??? ??

as if it can't find the proper characters for the unicode value.
Is it not POSSIBLE or ALLOWED to send non-English string using HTTP Header?
If my iOS uses just setHTTPBody, it can transfer non-English strings and save to App Engine's DataStore properly.
[httpRequest setHTTPBody:[httpBody dataUsingEncoding:NSUTF8StringEncoding]];

But I just can't find the right way to achieve same goal using HTTP Headers, like what many APIs like Foursquare's do and saving the strings in the proper forms in Python based Google App Engine's DataStore

A: It is possible to use character sets other than ISO 8859-1 in HTTP headers, but they must be encoded as described in RFC 2047.

A:
Is it not POSSIBLE or ALLOWED to send non-English string using HTTP Header?

It's not possible as per HTTP standards to put non-ISO-8859-1 characters directly in an HTTP header. That gives you ASCII ("English"?) characters plus common Western European diacriticals.
However in practice you can't even use the extended ISO-8859-1 characters, because servers and browsers don't agree on what to do with non-ASCII characters in headers. Safari takes RFC2616 at its word and treats high bytes as ISO-8859-1 characters; Mozilla takes UTF-16 code unit low bytes, which is similar but weirder; Opera and Chrome decode from UTF-8; IE uses the local system code page.
So in reality all you can put in an HTTP header is simple ASCII with no control codes. If you want anything more, you'll have to come up with an encoding scheme (eg UTF-8+base64). The RFC2616 standard suggests RFC2047 encoded-words as a standard form of encoding, but this makes no sense given the definitions of when they are allowable in RFC2047 itself, and nothing supports it.

A: RFC 8187 describes the way you could pass header value in different encoding:
Extended notation, using the Unicode character U+00A3 ("£", POUND SIGN):

     foo: bar; title*=utf-8'en'%C2%A3%20rates


text:
Q: Secure registration form I have a registration form
function Users_Registration()
{
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var usernames = $("#usernames").val();
    var emails = $("#emails").val();
    var passs = $("#passs").val();
    var rpasss = $("#rpasss").val();

    if(usernames == "")
    {
        $("#signup_status").html('
Enter LogIn.
');
        $("#usernames").focus();
    }
    else if(emails == "")
    {
        $("#signup_status").html('
Enter Email.
');
        $("#emails").focus();
    }
    else if(reg.test(emails) == false)
    {
        $("#signup_status").html('
Enter Valid Email.
');
        $("#emails").focus();
    }
    else if(passs == "")
    {
        $("#signup_status").html('
Enter Password.
');
        $("#passs").focus();
    }
    else if(rpasss == "")
    {
        $("#signup_status").html('
Введите пароль повторно.
');
        $("#rpasss").focus();
    }
    else if(rpasss != passs)
    {
        $("#signup_status").html('
Password doesn't match
');
        $("#rpasss").focus();
    }
    else
    {
        var dataString = 'usernames=' + usernames + '&emails=' + emails + '&passs=' + passs + '&rpasss=' + rpasss + '&page=signup';
        $.ajax({
            type: "POST",
            url: "reg2.php",
            data: dataString,
            cache: false,
            beforeSend: function()
            {
                $("#signup_status").html('

Wait..

');
            },
            success: function(response)
            {
                $("#signup_status").hide().fadeIn('slow').html(response);
            }
        });
    }
}

PHP
if(isset($_POST["page"]) && !empty($_POST["page"]))
{

    $user_name = trim(strip_tags(strtolower($_POST["usernames"])));
    $email_address = trim(strip_tags($_POST['emails']));
    $password = trim(strip_tags($_POST['passs']));
    $rpassword = trim(strip_tags($_POST['rpasss']));

I have some validation in PHP
The from is working. But I dont want to put captcha.
There is way to make it secure?
My point is to make registration form disappear after 30 seconds. So you have to reopen it.
seTTimeOut(); It is after what time to run.
Should I use Interval???

A: How does a captcha and the disappearance of the form provide the same security?
Captcha is to prevent automated scripts from filling in the form.
The scripts don't take 30 seconds to fill in the form and send the request, thus not providing the same functionality as the captcha.
Should post this in comment but too low rep.

A: window.setInterval(function(){
    $('#someid').val('');
    // repeat for other form fields
}, 30000);

So yes, it is possible. But I strongly agree with all of the above comments - this is probably something that is best left not done. Stef Heylen's answer is spot on.


text:
Q: Rails deployment to Windows Server I am trying to serve up a Rails application to a Windows Server that runs on a PostgreSQL DB. Was wondering if anyone had any resources/experience that would help this brutal process. I keep running into the Nokogiri build problem where, I can successfully bundle install but then when I run rake db:create it throws this error:
'require': cannot load such file -- 'nokogiri\nokogiri' (LoadError)

A: Nokogiri won't support windows and ruby 2.2.x until the next release (which should be very soon).
see flavorjones's reply and post

Hi all, I just emailed nokogiri-talk about a Windows release. If you don't subscribe, you should ... TL;DR we're going to get this out the door this week, honest. Thanks for your patience.

I believe there are issues because it doesn't suport native builds (relying on prebuilt DLLs instead.


text:
Q: select option from select box click save button perform database update I have a select box with three options. When an option is selected a save button is then click which performs a database update on the field. This will involve having two submit buttons in one form. I have created a different action on each submit button, this will be the save button:
if ($_POST['update_status'] == 'Save') {
    $keys = array_keys($_POST['order_status']);
    //perform the database update to change the option value
}

if(isset($_POST['order_selected'])) {
    //send email
}

At the moment my select box for each option is embedded in a table like:
echo '<select name="order_status[] id="id"">';
echo '<option value = "Pending"  name="order_status['.$i.']" class = "pending"' .        ($row['status'] == 'Pending' ? ' selected=selected' : '') . '>Pending</option>';
echo '<option value = "Approved" name="order_status['.$i.']" class = "approved"' . ($row['status'] == 'Approved' ? ' selected=selected' : '') . '>Approved</option>';
echo '<option value = "Disapproved" name="order_status['.$i.']" class ="disapproved"' .    ($row['status'] == 'Disapproved' ? ' selected=selected' : '') . '>Disapproved</option>';
echo '</select>';

now at the moment I have the update query working, except it is outside of the form and works by posting a unique order I.D from the database and then performing he update. however I can only do 'approved'. 'pending' is not an issue as I have already set a flag in the database when an order is created, as default pending.
Instead of have this functionality outside of the form, I would like to be apple to select a dropdown item, hit save, and then the database update query is run changing the value in the select box, within the same form, if this would be possible?.
at the moment I have the query and submit button outside of the form which looks like:
<?php
    if (!empty($_POST)) {
        $id = intval($_POST['approval']);
        $query = "UPDATE Orders SET status = 'Approved' WHERE id = $id";
        mysql_query($query);
    }
    $query = "SELECT ID, Orderno, status FROM Orders WHERE status = '0'";
    $result = mysql_query($query);
?>

<select name="approval">
<?php while ($row = mysql_fetch_assoc($result)): ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Orderno']; ?></option>
<?php endwhile; ?>
</select>
<input type="submit" action ="" value="Approve Order" />

Many Thanks, any pointers on how I should be tackling this are much appreciated.

A: I'm pretty confused by your question, but if you are trying to have the database query run without having the user leave the page, and then update the attributes of some of your HTML elements, you are going to have to use AJAX.


text:
Q: Функция arrayCopy() Где то прячется ошибка, подтолкните на путь истинный ))
void arrayCopy(int destination[], int source[], int size) {
for ( int i = 0; i < size; i++ ) {
    for ( int j = 0; j < size; j++ ) {
        destination[i] = source[j];
    }
}
}

A: Вы в своем коде сделали size * size операций, хотя должны были сделать только size операций:
for (int i = 0; i < size; ++i) {
    destination[i] = source[i];
}

Как упражнение (и с учетом вашего предыдущего вопроса) можете попробовать оформить функцию, производяющую копирования из массива source в массив dest, когда заданы величины sourceSize и destSize. Упражнение здесь, понятно, на обработку ситуаций, когда длины не совпадают.
A: Для копирования памяти есть специальная функция memcpy. С ней можно переписать твою функцию так:
void arrayCopy(int destination[], int source[], int size)
{
    memcpy(destination, source, size*sizeof(int));
}


text:
Q: Migrate .Net/C# projects wit OdbcConnection to SqlConnection with Informix DB we have tons of old C#-code using OdbcConnection with Informix DB. The code use types like DbConnection, DbCommand, DbParameter, where parameter binding done nameless with ? symbol everywhere in code. Now I need to modernize that code (alone, all previos developers gone already) and use SqlConnection instead of OdbcConnection.
Is that possible without caveats?
Is it possible, as alternative, to have second opened connection (SqlConnection) together with opened OdbcConnection? What about nested/parallel transactions?
Again, the question is specific to Informix DB, not MS SqlServer.
Many thanks.

A: The MS SQL .NET Provider (which gives you SqlConnection, SQLCommand, etc) will not be able to connect to an Informix database. This provider is just for SQL Server, you can't use it against any other database.
To connect .NET applications with Informix you need a 'suitable' .NET Provider.
The ODBC .NET Data Provider acts a bridge between .NET and any ODBC Driver. You current code appears to use it (eg. DbConnection = OdbcConnection()).
The ODBC .NET Provider is still available in latest versions of .NET (including .NET Core) so you should be able to keep using it with any current Informix ODBC driver (like 4.50.FC7).
Another (better) option would be to use the 'Informix .NET Provider' (included in the same install package as the Informix ODBC driver, 'Informix Client SDK'). This .NET Provider is specific to Informix databases and has supports more Informix features than the 'generic' ODBC .NET Provider.
https://www.ibm.com/docs/en/informix-servers/12.10?topic=guide-overview-informix-net-provider
In terms of 'nested' transactions, Informix support the SAVEPOINT SQL statement to split complex transactions into smaller units. You can use that method to do 'nested' transactions (I think SQLServer does the same)
https://www.ibm.com/docs/en/informix-servers/14.10?topic=statements-savepoint-statement


text:
Q: What version of Windows 7 for ASP.NET development on Visual Studio I am about to upgrade my pc, and operating system at the same time. I was wondering what version of Windows 7 to get pre-installed, given that I want to do some ASP.NET development using Visual Studio.
Specifically :

*

*Will all versions of Windows 7 run an IIS server & be suitable for ASP.NET development ?

*Are all good for running SQL Server etc ?

*Will Windows 7 have any probs running old versions of Visual Studio (Ie. 2003 & 2005 versions).

Are there any other things I need to consider ?
I'm probably going for the 32 bit version of Windows 7.
Thanks in advance,
Bazza

A: I would suggest you get the 64-bit version: there's really no reason to be running a 32-bit operating system in this day and age (unless you have some esoteric hardware that doesn't have 64-bit drivers, but that's exeedingly rare: especially on Windows 7).
I think IIS 7.5 is included in Home Premium, but I think the Professional SKU is probably the best bang-for-buck version. You don't actually need IIS for ASP.NET work anyway, the development server that's included with Visual Studio is usually the best option anyway (it doesn't require Administrator privileges to debug).
Other than that, they'll all run SQL Server fine, and I see no reason why older versions of Visual Studio won't run, either (there may be issues with UAC, but nothing too dramatic for day-to-day use).


text:
Q: Meaning of AT commands shortcut I just wonder what is actually shortcut AT means. I know alot of AT commands, but what is actual "AT" shortcut? I googled it, but no luck.

A: AT stands for ATtention. It is a way of interacting with the modem. Every command line starts with "AT" or "at". They are called AT commands because the
characters AT must precede each command to get the ATtention of the modem
As already told by wmz, you can find more about it here:
AT Commands - WikiPedia
Command: AT Attention Code
Values: n/a
Description: The attention code precedes all command lines except A/, A: and escape sequences.

A: If you mean modem commands - if memory serves - this comes from first letters of ATtention [which modem should pay] to command
I do not have any sources, although Wiki seems to agree:
http://en.wikipedia.org/wiki/Hayes_command_set

The following text lists part of the Hayes command set (also called
  the AT commands: "AT" meaning attention).


text:
Q: In MVC, how do I specify JSON serialization when not using ActionResult return types? With ASP.NET MVC 5, you can skip the ugly "ActionResult" return type, and instead, specify a 'real' class. However, it seems that MVC wants to return the .ToString() version of my object as Content instead of the JSON serialized version of my object that I want - similar to ASP.NET MVC WebApi2.
Given this controller... how do I get a JSON result without changing the method at all?
public class MyController : Controller
{
    public Thing GetSomething()
    {
        return new Thing { Name = "Justin_Example" };
    }
}

A: I am not sure if it is what you need but you can set return type as JsonResult.
Here is an example:
public JsonResult GetSomething()
{
    var thing = new Thing { Name = "Justin_Example" };
    return Json(thing , JsonRequestBehavior.AllowGet);
}


text:
Q: How can I detect the pressed key in VB.NET I know about KeyDown, KeyPress and KeyUp events, but i don't know how to detect the key that i pressed.
Is there a way to captute the value of key pressed?
For example: I press 'W' and some string gets the value of 'W'

A: This tells you what key was pressed:
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

        MsgBox(e.KeyChar)

End Sub

You should be able to rework it to suit your needs.
Edit:
If you need to detect non-character key presses such as F1 etc. you can't use the keypress event as it is not raised by non-character keys.  Then you will have to use the KeyUp or KeyDown event. I prefer the KeyUp event for one simple reason,  the KeyDown event fires as long as the key it kept down, so keep that in mind.
Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp

    MessageBox.Show(e.KeyValue)

End Sub

This will return the int number of the key that was pressed, but it does not distinguish between upper and lower case.
You should be able to detect these with something like this:
If Control.ModifierKeys = Keys.Shift Or Control.ModifierKeys = Keys.Control Then
        MsgBox("SHIFT or CTRL key pressed with " & e.KeyValue & ".")

    Else

        MessageBox.Show(e.KeyValue)

    End If

Example Usage: To see if the enter key for example was pressed:
Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp

    IF e.KeyValue = 13 Then

       MessageBox.Show("Enter Key Was Pressed")

    End If

End Sub

For a list of what value represents what key see:
Dec      Char                       Dec Char      Dec Char     Dec Char
--------------                      ---------     ---------     ----------
 0  NUL (null)                      32  SPACE     64  @         96  `
 1  SOH (start of heading)          33  !         65  A         97  a
 2  STX (start of text)             34  "         66  B         98  b
 3  ETX (end of text)               35  #         67  C         99  c
 4  EOT (end of transmission)       36  $         68  D        100  d
 5  ENQ (enquiry)                   37  %         69  E        101  e
 6  ACK (acknowledge)               38  &         70  F        102  f
 7  BEL (bell)                      39  '         71  G        103  g
 8  BS  (backspace)                 40  (         72  H        104  h
 9  TAB (horizontal tab)            41  )         73  I        105  i
10  LF  (NL line feed, new line)    42  *         74  J        106  j
11  VT  (vertical tab)              43  +         75  K        107  k
12  FF  (NP form feed, new page)    44  ,         76  L        108  l
13  CR  (carriage return)           45  -         77  M        109  m
14  SO  (shift out)                 46  .         78  N        110  n
15  SI  (shift in)                  47  /         79  O        111  o
16  DLE (data link escape)          48  0         80  P        112  p
17  DC1 (device control 1)          49  1         81  Q        113  q
18  DC2 (device control 2)          50  2         82  R        114  r
19  DC3 (device control 3)          51  3         83  S        115  s
20  DC4 (device control 4)          52  4         84  T        116  t
21  NAK (negative acknowledge)      53  5         85  U        117  u
22  SYN (synchronous idle)          54  6         86  V        118  v
23  ETB (end of trans. block)       55  7         87  W        119  w
24  CAN (cancel)                    56  8         88  X        120  x
25  EM  (end of medium)             57  9         89  Y        121  y
26  SUB (substitute)                58  :         90  Z        122  z
27  ESC (escape)                    59  ;         91  [        123  {
28  FS  (file separator)            60  <         92  \        124  |
29  GS  (group separator)           61  =         93  ]        125  }
30  RS  (record separator)          62  >         94  ^        126  ~
31  US  (unit separator)            63  ?         95  _        127  DEL

ASCII table was found at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

A: Use the Char.ConvertFromUtf32 function.  So if you are using a text box and are looking at the keydown event for instance:
Private Sub txtData_Keydown(sender As Object, e As KeyEventArgs) handles txtData.keydown
    if e.keyvalue>64 and e.keyvalue <91 then 'if its a letter a-z A-Z keydown always gives uppercase A to Z
       Dim eChr As String = Char.ConvertFromUtf32(If(e.Shift, e.KeyValue, e.KeyValue + 32))
    endif

where e.shift indicates whether the shift key was pressed (uppercase vs lowercase).
eChr will now be a string containing the '(L)letter' you pressed.
With Keydown, you have to be careful to trap only the keys you are interested in. Pressing the shift key, arrow keys, functions etc will also trigger this event.


text:
Q: Calculate Riemann sums for $f(x)=4+3x^3$ for $x \in [-2,1]$ I have the following exercise:
Let $f(x)$ = $4+3x^3$, $x$ $\in$ $[-2; 1]$. Calculate the Riemann sums for $f$ on $[-2; 1]$ by dividing the interval into n equal sub-intervals and taking midpoints as sample points. Find the limit of Riemann sums as $n \to \infty$.
I have used the general formula
$\lim_{n \to \infty}$ $\frac{1}{n}$$\sum_{k=1}^{n}$$f(\frac{x_{k-1}+x_k}{2})$
Then I used $x_k$ formula($x_k=a+\frac{k(b-a)}{n}$) and got $\frac{x_{k-1}+x_k}{2}$ = $\frac{6k-3-4n}{2n}$
Then I plugged in my $x_k$ sample points and got the following:
\begin{align}
&\lim_{n \to \infty}\frac{1}{n}\sum_{k=1}^{n}4+(3\frac{6k-3-4n}{2n})^3\\&=
\lim_{n \to \infty}\frac{3}{2n^3}\sum_{k=1}^{n}(6k-(3+4n))^3\\&=
\lim_{n \to \infty}\frac{3}{2n^3}\sum_{k=1}^{n}(216k^3-108k^2(3+4n)+18k(3+4n)^2-(3+4n)^3)\\&=
\lim_{n \to \infty}\frac{3}{2n^3}(-n(3+4n)^3)\sum_{k=1}^{n}216k^3-\sum_{k=1}^{n}108k^2(3+4n)+\sum_{k=1}^{n}18k(3+4n)^2\\&=
\lim_{n \to \infty}\frac{3}{2n^3}(-n(3+4n)^3)216\sum_{k=1}^{n}k^3-108(3+4n)\sum_{k=1}^{n}k^2+18(3+4n)^2\sum_{k=1}^{n}k\\&=
\lim_{n \to \infty}\frac{3}{2n^3}(-n(3+4n)^3)216(\frac{n(n+1)}{2})^2-108(3+4n)(\frac{n(n+1)(2n+1)}{6})+18(3+4n)^2(\frac{n(n+1)}{2}) \end{align}
The limit of the last part is $-\infty$, however, I should get $\frac{3}{4}$ as it is another way to calculate the definite integral. Can someone please tell if there is something I have done wrong or there is a better way to solve this problem?

A: Mistake $1$:
$$\lim_{n \to \infty}\frac{1}{\color{blue}n}\sum_{k=1}^{n}\left[4+\color{red}3(\frac{6k-3-4n}{2n})^3\right]= \color{red}{4}+
\lim_{n \to \infty}\frac{3}{\color{red}{8n^4}}\sum_{k=1}^{n}(6k-(3+4n))^3$$
Mistake $2$:
\begin{align}&\lim_{n \to \infty}\frac{3}{2n^3}\sum_{k=1}^{n}(216k^3-108k^2(3+4n)+18k(3+4n)^2-(3+4n)^3)\\&=
\lim_{n \to \infty}\frac{3}{2n^3}\color{red}{(-n(3+4n)^3)}\sum_{k=1}^{n}216k^3-\sum_{k=1}^{n}108k^2(3+4n)+\sum_{k=1}^{n}18k(3+4n)^2 \end{align}
Correction:
\begin{align}&\color{blue}4+\lim_{n \to \infty}\frac{3}{\color{blue}{8n^4}}\sum_{k=1}^{n}(216k^3-108k^2(3+4n)+18k(3+4n)^2-(3+4n)^3)\\&=4+
\lim_{n \to \infty}\frac{3}{\color{blue}{8n^4}}\left[\color{red}{(-n(3+4n)^3)}\color{blue}+\sum_{k=1}^{n}216k^3-\sum_{k=1}^{n}108k^2(3+4n)+\sum_{k=1}^{n}18k(3+4n)^2\right] \end{align}
Mistake $3$:
The general formula should be
$$\lim_{n \to \infty}\frac{\color{red}{b-a}}{n}\sum_{k=1}^{n}f\left(\frac{x_{k-1}+x_k}{2}\right)$$


text:
Q: Setting pins as output Code - micro-controller So i am using the MSP432 and i am confused on how the code for setting pin to desired function works.
so for example from the manual i have found that:
  PxIE = 0b // means that x pin is dsiabled
  PxIE = 1b// means that x pin is enabled

now if we have the code shown below:
  P1IE |= 0x02 // what does this code do

i understand that | means or and that 0x02 is hexadecimal for 0b10 so how does that make the pin 1 enabled?

A: I'm not familiar with that variety of microcontroller but the standard is to use a zero base for the pin numbering and the binary pattern is a one to one mapping to the pins.
Pin   76543210
PxIE  00000010b // = 0x02 Pin 1 is enabled.

The |= operator is bitwise inclusive OR and assignment operator.  C |= 2 is same as C = C | 2. So in your example,
P1IE |= 0x02

is the same as
P1IE = P1IE | 0x02

and if P1IE = 8, for example then adding
P1IE = 00001000b
0x02 = 00000010b
       ---------
       00001010b = 0x0A = 10 (decimal)

See C++ operators.

From comment:

Why do we use 0x02?

0x02 = 10b so that enables the second pin, pin 1.

How does 00001010b mean its enabled.. it says that a binary value of 1 means it enabled how does 00001010b = 1

It doesn't. The syntax in your question means that pin 1 is enabled along with whatever pins are alread enabled.
// Another example
// Bits   76543210
// P1IE = 01101000b // Bits 6, 5 and 3 are already set.
// We now want to set bit 1 as well
//        00000010b = 0x02

We can do this without knowing what bits are already set by using the "bitwise inclusive OR" operator.
 P1IE |= 0x02               // One way of doing it.
 P1IE |= 0x00000010b        // Another way.
 P1IE = P1IE | 0x00000010b  // Another way.

A: You have the wrong syntax and identifiers for an MSP432. Maybe you are reading documentation for the MSP430?
If you are using CMSIS-style code on the MSP432, you would use commands like
P2->DIR |= BIT3; // set pin P2.3 to output mode
P2->OUT |= BIT3; // set pin P2.3 state to 1

See chapter 12 in the MSP432 Technical Reference Manual for a description of all of the registers used by the GPIO ports.


text:
Q: open word print preview page by c# I intend to send ajax from chrome to c# controller, and use c# to open a word document and switch to print preview,
just as clicking ctrl+p in word 2010/2013.
sendKeys.Send ("^p")

was tried, and it only triggers word 2003 style print dialog box.
Inserting macro into word document doesn't work either.
Is there a way I can achieve it? Thanks!
Edited:
What I would prefer is as below:

A: You can use the PrintDialog class


text:
Q: Getting the stage to follow the players Y axis. (Flash As3) I'll try my best to give you as much detail as I can.
I have created a platform game and I have already implemented movement and collision.
My game Loop runs this (I only have one eventListener)
    private function level1GameLoop():void
    {
        groundCollision();
        movementCode();
        scrollLevel();
    }

Ground collision takes care of making sure the player doesn't fall (ground is the level overall, apologies for the bad naming convention(s).
    private function groundCollision():void
    {
        if (ground.bottom.hitTestPoint(character.x + 13, character.y, true || ground.bottom.hitTestPoint(character.x + 13, character.y, true)))
        {
            trace("h");
            while (ground.bottom.hitTestPoint(character.x + 13, character.y, true || ground.bottom.hitTestPoint(character.x + 13, character.y, true)))
            {
                character.incrementUp();
                if (ground.bottom.hitTestPoint(character.x + 13, character.y, true || ground.bottom.hitTestPoint(character.x + 13, character.y, true)))
                {
                }
                else{
                    character.keepOnGround();
                }
            }
        }
    }

and then you have your typical movement code
        else if (rightKey)
        {
            character.moveRight();
            lookingRight = true;
            lookingLeft = false;
        }
        else if (leftKey)
        {
            lookingLeft = true;
            lookingRight = false;
            character.moveLeft();
        }

Before scrolling the level, I tested to see does my character hit all of the platforms and yes he does.
So now I want to implement scrolling.
In the class definition I have set up a variable called container which is a sprite.
    private var container:Sprite = new Sprite();

I have then added my children on to the stage before starting the game loop
        addChild(container);
        container.addChild(ground);
        container.addChild(character);
        addChild(timerGIF);//this does not need to scroll

I have then tested the game again, and the collision works fine.
Now I have tried many attempts to scroll the player and keep him on center of the screen making sure that the collisions still function correctly.
private function scrollLevel():void
        {
        /*
        _camera.x = character.x - stage.stageWidth * 0.5;
        _camera.y = character.y - stage.stageHeight * 0.5;
        //"camera" must not show areas outside of the game world
        if (_camera.x < 0)
        {
            _camera.x = 0;
        }
        //Right
        if (_camera.x > (container.width) - stage.stageWidth)
        {
            _camera.x = (container.width) - stage.stageWidth;
        }
        //Bottom
        if (_camera.y > (container.height) - stage.stageHeight)
        {
            _camera.y = (container.height) - stage.stageHeight;
        }
        //Top
        if (_camera.y < 0)
        {
            _camera.y = 0;
        }

        container.scrollRect = _camera;
        */

        //ground.x = -character.x + stage.stageWidth / 2;
    //  ground.y = -character.y + stage.stageHeight / 2;

            /*var offset:int = 10;
            var distance:Number = character.x - ((stage.stageWidth / 2) + offset);
            var distance2:Number = character.y - ((stage.stageHeight / 2));
            var ease:int = 5;
            if (distance < 0)
            {
                distance *= -1;
            }
            if (distance2 < 0)
            {
                distance2 *= -1;
            }
            if (character.x < (stage.stageWidth / 2))
            {
                var variable:int = distance / ease;
                //character.x += variable;
                container.x += variable;

            }
            if (character.x > (stage.stageWidth / 2))
            {
                var variable2:int = distance / ease;
                //character.x -= variable2;
                container.x -= variable2;

            }

            /*if (character.y < (stage.stageHeight / 2))
            {
                var variable3:int = distance2 / ease;
                character.y += variable3;
                //container.y += variable3;

            }

            if (character.y > (stage.stageHeight / 2))
            {
                var variable4:int = distance2 / ease;
                character.y -= variable4;
                //container.y -= variable4;

            }*/

            /*var camera:Point = new Point();

            // Set the camera coordinates to the char coordinates.
            camera.x = character.x;
            camera.y = character.y;

            // Adjust the world position on the screen based on the camera position.
            ground.x = -camera.x + (stage.stageWidth / 2);
            ground.y = -camera.y + (stage.stageHeight / 2);*/

    }

None of these seem to work, since the collision then gets all muddled up.
By this I mean, my character ends up floating, or falling through
Other things to mention, ground is a movie clip and is basically my level(once again, poor naming conventions, apoligiez).
Inside ground there are hitTest box's and objects that the character will get.

A: You are doing a great job, but in the very difficult way, first things first, you should know that when you want your character to move inside the container in a certain direction, you have to adjust all the other children of the container to move in the opposite direction, so it gives the feeling that the character moves in the desired direction.. this my friend is the hard way, and I think the reason made you go that way is that you want timerGIF to stay not changed all the time.. but this can be achieved in a very more easier way by reversing your code like that...
//reverse your strategy for coding:

var container:Sprite = new Sprite();
addChild(container);
addChild(ground);
addChild(character);
container.addChild(timerGIF);

//define some very imp vars that you will need to adjust for each level to
//prevent recoding in each level, just set the vars to the new level properties

var level_width:Number=1600;
var level_hight:Number=1200;
var screen_width:Number=800;
var screen_hight:Number=600;

//the ease of camera is the speed of camera, and whoever you want the camera to
//follow just pass it as a camera_target (that will be in this case your character)

var camera_speed:Number=5;
var camera_target:Object=charachter;

//then add your scroll function (named hear as camera();)

function camera(wide, high, target, speed) {
  if (target!=null) {
      cam_x = ((screen_width/2)-target.x-x)/speed;
      cam_y = ((screen_hight/2)-target.y-y)/speed;
      x+=cam_x;
      y+=cam_y;
  }
  if (x>0) {
      x=0;
  }
  if (x<wide*-0.5) {
      x=- wide/2;
  }
  if (y>0) {
      y=0;
  }
  if (y<high*-0.5) {
      y=- high/2;
  }
  //now the code to keep container and all its children not scrolled is just:
  container.x=- x;
  container.y=- y;
}

Finally put this following line in your level1GameLoop() replacing scrollLevel();
function level1GameLoop():void
{
    groundCollision();
    movementCode();
    //scrollLevel();
    camera (level_width, level_hight, camera_target, camera_speed);
}

Have a nice day sir...

A: Check this code, is for starling, but the you can use the logic
http://wiki.starling-framework.org/extensions/fluocam


text:
Q: Mounting multiple volumes on a docker container? I know I can mount a directory in my host on my container using something like
docker run -t -i -v '/on/my/host:/on/the/container' ubuntu /bin/bash

Is there a way to create more than one host-container pair? e.g. a comma-separated list, or pass in an array?

A: You can have Read only or Read and Write only on the volume
docker -v /on/my/host/1:/on/the/container/1:ro \

docker -v /on/my/host/2:/on/the/container/2:rw \

A: Docker now recommends migrating towards using --mount.
Multiple volume mounts are also explained in detail in the current Docker documentation.
From: https://docs.docker.com/storage/bind-mounts/
$ docker run -d \
  -it \
  --name devtest \
  --mount type=bind,source="$(pwd)"/target,target=/app \
  --mount type=bind,source="$(pwd)"/target,target=/app2,readonly,bind-propagation=rslave \
  nginx:latest

Original older answer should still work; just trying to keep the answer aligned to current best known method.

A: Pass multiple -v arguments.
For instance:
docker -v /on/my/host/1:/on/the/container/1 \
       -v /on/my/host/2:/on/the/container/2 \
       ...

A: You can use -v option multiple times in docker run command to mount multiple directory in container:
docker run -t -i \
  -v '/on/my/host/test1:/on/the/container/test1' \
  -v '/on/my/host/test2:/on/the/container/test2' \
  ubuntu /bin/bash

A: On Windows: if you had to mount two directories E:\data\dev & E:\data\dev2
Use:
docker run -v E:\data\dev:c:/downloads -v E:\data\dev2 c:/downloads2 -i --publish 1111:80 -P SomeBuiltContainerName:SomeLabel

A: I saw a comment asking if read-write or read-only was the default option; read-write is the default option. (making a post because I haven't enough rep to comment)
Per docker documentation, running the following:
docker run -d \
--name devtest \
--mount source=myvol2,target=/app \
nginx:latest

and then using docker inspect devtest and locating the "RW" option in the "Mounts" section of the output:
"Mounts": [
    {
        "Type": "volume",
        "Source": "/var/lib/docker/volumes/myvol2/_data",
        "Destination": "/app",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
],

lets us see that the default option lets the volume be both read- and write-able.

To set your volume as read-only (again per official documentation), add readonly after your source and destination tags:
docker run -d \
--name=nginxtest \
--mount source=nginx-vol,destination=/usr/share/nginx/html,readonly \
nginx:latest

Run docker inspect nginxtest and locate "Mounts":
"Mounts": [
    {
        "Type": "volume",
        "Source": "/var/lib/docker/volumes/nginx-vol/_data",
        "Destination": "/usr/share/nginx/html",
        "Driver": "local",
        "Mode": "",
        "RW": false,
        "Propagation": ""
    }
],

(Note: I don't know why official documentation swaps between target and destination tags, but I am working under the assumption they can be used interchangeably.)

A: For a runable example:
docker run -v /Users/brandomiranda/iit-term-synthesis:/home/bot/iit-term-synthesis \
           -v /Users/brandomiranda/pycoq:/home/bot/pycoq \
           -v /Users/brandomiranda/ultimate-utils:/home/bot/ultimate-utils \
           -ti brandojazz/iit-term-synthesis:test bash

but first do:
docker pull brandojazz/iit-term-synthesis:test

A: Or you can do
docker run -v /var/volume1 -v /var/volume2 DATA busybox true


text:
Q: remove objects and save change using hibernate i want remove player from list player but i can not i use relation OneTomany
but update does not remove the player
public void delete_player(Player playerId,Member member){
Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.getTransaction();

    tx.begin();
    try {
        member.getPlayers().remove(playerId);

        session.saveOrUpdate(member);

          tx.commit();

    } catch (RuntimeException e) {
        tx.rollback();

    }
    }


text:
Q: How to add javadoc for ecpliselink 1.x alt text http://filaty.com/i/1005/60197/Screenshot.png
As It appears in the image, I cannot add the javadoc for eclipselink 1.1.x that already bundled with eclipse.
So, Is there any workaround?


text:
Q: FileInputStream creation When FileInputStream is first created, I understand that it takes in the data that the file has. Now let's say I modify the file with FileOutputStream and I haven't closed FileInputStream, will it change the data that the FileInputStream has inside or will it remain the same? If it remains the same, is there a way to just add the new changes to the FileInputStream instead of reading the entire file again?

A: FileInputStream does not take the data from the file. Data is taken on demand when you call read().
If you try to modify the file with FileOutputStream and I haven't closed FileInputStream on Windows this will fail with Exception. On Unix/Linux system you will read part of the old and part of the new file (which was overwritten by FileOutputStream). If you really need to read and write in same file at the same time, it will be better to use RandomAccessFile


text:
Q: Service injection in AngularJs I am new to AngularJS and I can't seem to figure out what went wrong with my service injection.
Service -- ErrorTranslatorForApiCalls.js
(function() {
    var errorTranslatorModule = angular.module('exceptionHandler');

    errorTranslatorModule.factory('apiStatusTranslator', function() {
        var translateStatusToFriendlyMessage = function (status) {

            var friendlyMessage = "Error occured while performing the action";

            switch (status) {
            case 401:
                friendlyMessage =  "You are unauthorized to perform this action";
                break;
            }

            return friendlyMessage;
        };

        return {
            translateStatusToFriendlyMessage : translateStatusToFriendlyMessage
        };
    });
});

Here is where I injected it -- GroupSearch.js
(function () {

    agGrid.initialiseAgGridWithAngular1(angular);

    var module = angular.module('groupEditor', ["ngRoute", "ngResource", "agGrid", "exceptionHandler"]);

    module.constant('BASEURL', 'http://localhost/XXX.XXX.XXX/api/group/');
    module.controller('SearchController', ['$scope', '$resource', 'BASEURL', "apiStatusTranslator", function ($scope, $resource, BASEURL, apiStatusTranslator) { ............ REST OF CODE GOES HERE;

My HTML JavaScript includes
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.min.js"></script>
<script src="Scripts/angular-route.js"></script>
<script src="Scripts/ag-grid.min.js"></script>
<script type="text/javascript" src="Services/ErrorTranslatorForApiCalls.js"></script>
<script type="text/javascript" src="Controllers/GroupSearch.js"></script>

A: As a user suggested, console error print would help here. However, if what you put in code block is exactly your code, there is an error. You are missing "])" at the end in your controller code.
 module.controller('SearchController', ['$scope', '$resource', 'BASEURL', "apiStatusTranslator", function ($scope, $resource, BASEURL, apiStatusTranslator) { }

])//This is missing


text:
Q: lxml.html extract a string by searching for a keyword I have a portion of html like below

The Keyword:The text

I want to get the string "The keyword: The text".
I know that I can get xpath of above html using Chrome inspect or FF firebug, then select(xpath).extract(), then strip html tags to get the string. However, the approach is not generic enough since the xpath is not consistent across different pages.
Hence, I'm thinking of below approach:
Firstly, search for "The Keyword:" using (the code is for scrapy HtmlXPathSelector as I am not sure how to do the same in lxml.html)
hxs = HtmlXPathSelector(response)
hxs.select('//*[contains(text(), "The Keyword:")]')

When do pprint I get some return:
>>> pprint( hxs.select('//*[contains(text(), "The Keyword:")]') )
<HtmlXPathSelector xpath='//*[contains(text(), "The Keyword:")]' data=u'The Keyword:'>

My question is how to get the wanted string: "The keyword: The text". I am thinking of how to determine xpath, if xpath is known, then of course I can get the wanted string.
I am open to any solution other than lxml.html.
Thanks.

A: from lxml import html

s = '
The Keyword:The text
'

tree = html.fromstring(s)
text = tree.text_content()
print text

A: You can modify the XPath slightly to work with your current structure - by getting the parent of the label, then looking back for the fist a element, and taking the text from that...
>>> tree.xpath('//*[contains(text(), "The Keyword:")]/..//a/text()')
['The text']

But that may not be flexible enough...


text:
Q: Two column incremental beamer slide in RMarkdown I'm trying to get a two column layout in a beamer presentation slide in rmarkdown which shows differences between say, A and B, item by item. An MWE is as follows:
---
  title: "Presentation Title"
author: "Name"
institute: "Institute"
date: "date"
output:
  beamer_presentation:
  incremental: true
theme: "Berlin"
colortheme: "dove"
fonttheme: "structurebold"
classoption: "aspectratio=169"

# Section 1

## A vs B

::: columns

:::: column
### A
- Item A1
- Item A2
::::

:::: column
### B
- Item B1
- Item B2
::::

:::

This however, means that A1 appears, then A2, then B1, then B2.
I am looking for a solution that will give A1, then B1; A2, then B2. Is that possible with beamer and rmarkdown?
Thanks

A: You could do the overlays manually:
---
title: "Presentation Title"
author: "Name"
institute: "Institute"
date: "date"
output:
  beamer_presentation:
    keep_tex: true
    incremental: true
    includes:
      in_header: preamble.tex
theme: "Berlin"
colortheme: "dove"
fonttheme: "structurebold"
classoption: "aspectratio=169"
---

# Section 1

## A vs B
::: columns

:::: column
### A
\begin{itemize}
\item<1-> Item A1
\item<3-> Item A2
\end{itemize}
::::

:::: column
### B
\begin{itemize}
\item<2-> Item A1
\item<4-> Item A2
\end{itemize}
::::

:::


text:
Q: Vercel Deployment Error 404 with my HTML5 and CSS project I´m having a problem with vercel. I'm done trying everything.
I tried to deploy, multiple times, my node app with express and nothing works, I always get:
" 404: NOT_FOUND
Code: NOT_FOUND "
Here's my index.js:
const exp = require('constants');
const express = require('express');
const res = require('express/lib/response');
const app = express();
const path = require('path');

//express server port

app.listen(process.env.PORT || 3000, () =>{
 console.log("Server status: Online.")
});

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "/views/index.html"));
});

app.get("/register", (req, res) => {
    res.sendFile(path.join(__dirname, "/views/register.html"));
});

app.get("/login", (req, res) => {
    res.sendFile(path.join(__dirname, "/views/login.html"));
});

app.use(express.static("public"));

and my vercel.json:
{
    "version": 2,
    "builds": [
        {
            "src": "./app.js",
            "use": "@vercel/node"
        }
    ],

    "routes": [
        {
            "src": "/(.*)",
            "dest": "/"
        }
    ]
}

I tried deleting node_modules, changing "app.js" to "index.js", almost everything, but nothing worked.


text:
Q: unable to send email via smtp over ssl i am writing a ruby script to send email using 'mail' gem.
and my smtp settings on my local machine:
mailer_options:
    address: smtp.gmail.com
    port: 587
    domain: gmail.com
    user_name: example@gmail.com
    password: example_password
    authentication: :login
    enable_starttls_auto: true
    ssl: true

when i try to send the email with the above smtp settings i get the following exception:---
/opt/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/net/smtp.rb:585:in 'connect': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol (OpenSSL::SSL::SSLError)
i tried installing ssl certificate by command
openssl s_client -connect gmail.com:443
but it does not help, thanks for any comments and answer.

A: Port 587 starts out plain text, and then "upgrades" to ssl via starttls if you want smtp from the start to use ssl, then you need to use port 465.
so either of these should fix your issue.
Remove enable_starttls_auto and set the port to 465
or
Remove ssl: true and rely on starttls to upgrade your connection to ssl


text:
Q: Airflow - How to mark a task as Success programmatically? I have a DAG that inserts data into a SQL Server database. Some of the tasks take 24+ hours to run as the database its inserting into is not high performing.
I need to mark the tasks as complete automatically if they take more than 24 hours to run, as I need to move on from them so I can start inserting the next days worth of data (the DAG runs daily and the data source has new data coming in every day). How can I do this programmatically, where I don't have to go into the UI to mark it as 'Success' or 'Failed'?

A: You could follow a similar approach as shown in this StackOverflow post: kill or terminate subprocess when timeout. Then once the timeout occurs, you just need to make sure you don't raise any Exception.


text:
Q: Pinch gesture is not working in Xcode 8 swift 3 This is a code for changing background colour on pinching.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var mylabel: UILabel!
    let background = UIColor(red: 1.0, green: 0.98, blue: 0.96, alpha: 1.0)
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = background
        let pinchGesture = UIPinchGestureRecognizer(target: self,  action:#selector(pinchAction(sender1:)))
        self.view.addGestureRecognizer(pinchGesture)

    }

    func pinchAction(sender1 sender:UIPinchGestureRecognizer){

        if sender.state == .began{
            mylabel.text = "Pinch Began"
            view.backgroundColor = UIColor.yellow
        }
        if sender.state == .changed{
            mylabel.text = String(format:"Pinch scale: %1.3f",sender.scale)
        }
        if sender.state == .ended{
            mylabel.text = "Pinch Ended"
            view.backgroundColor = background
        }
    }
}

I have also marked "user interaction  enabled " in story board but still nothing happen on pinching.


text:
Q: undefined local variable or method for extended module NOTE: the question was edited to reflect the issue.
i would like to work with knife-api rubygem. enclosed a snippet of my code
require 'chef'
require 'chef/knife'
require 'knife/api'

module X
  module Y
    module Z
      include Chef::Knife::API

      def self.foo
        resp = knife_capture :search, ['*:*']
        puts resp
      end
    end
  end
end

when X::Y::Z.foo is called, it returns
gems/knife-api-0.1.7/lib/knife/api.rb:41:in `ensure in knife_capture': undefined local variable or method `revert_io_channels' for X::Y::Z (NameError)

it appears that he enclosing scope functions (Chef::Knife within knife-api) are inaccessible within X::Y::Z.foo.
how should i make this work?

A: This gem is a fork of another project that is no longer maintained. Looking at the gem code, it appears there were several issues introduced to the latest version (0.1.7) through some bad refactoring of the original code. That version was released a year ago and it hasn't had any commits since. The repo also does not accept issue tickets, and it has no tests. If you must use this gem, I would try a pessimistic constraint gem 'knife-api', '< 0.1.7' and see if that works. However it might be a better idea to skip it entirely. I made an attempt to fix the issues and submit a PR. You can also try pulling the gem from my forked repo https://github.com/msimonborg/knife-api

A: In a complete non-answer, do not use the knife-api gem. It should not exist. The correct gem to use if you want to access Chef API data from Ruby code is chef-api (I know, we're real creative with names). If you want to do something very small, check out the knife exec command which just exposes the raw Chef object API (not as refined as chef-api, but built in).


text:
Q: Adding html ID to rails select options We're using simple_form and trying to add an id to each of a specific select_tag's options. Here is our select:
<%= f.input :category, collection: %w{ Football Basketball Golf Soccer }, :include_blank => "Choose one" %>

Here is what it can look like after we add the id/ids
<select class="select required form-control" id="sport_category" name="sport[category]">
  <option value="">Choose one</option>
  <option value="Football">Football</option>
  <option id="addBehavior" value="Basketball">Basketball</option>
  <option value="Golf">Golf</option>
  <option value="Soccer">Soccer</option>
</select>

But this would work as well (adding an id to each option)
<select class="select required form-control" id="sport_category" name="sport[category]">
  <option value="">Choose one</option>
  <option id="football" value="Football">Football</option>
  <option id="basketball" value="Basketball">Basketball</option>
  <option id="golf" value="Golf">Golf</option>
  <option id="soccer" value="Soccer">Soccer</option>
</select>

We want to add js behavior to trigger an event when a specific option is selected and were planning to use getElementById to target the option. This is why we want to add an id to the options..really only the Basketball option.

A: Try using,
<%= f.input :category, collection: %w{ Football Basketball Golf Soccer }.map { |category| [category, category, {:id => category}]}, :include_blank => "Choose one" %>

When I tried it, it gave me the html
<option value="">Choose one</option>
<option id="football" value="Football">Football</option>
<option id="basketball" value="Basketball">Basketball</option>
<option id="golf" value="Golf">Golf</option>
<option id="soccer" value="Soccer">Soccer</option>

There might be a cleaner way to do it, but it works.
If you also do,
<%= f.input :category, collection: [["Football", "football"], ["Basketball", "basketball", {:id => "basketball"}], ["Golf", "golf"], ["Soccer", "soccer"]], :include_blank => "Choose one" %>

That gave me the html,
<option value="">Choose one</option>
<option value="Football">Football</option>
<option id="basketball" value="Basketball">Basketball</option>
<option value="Golf">Golf</option>
<option value="Soccer">Soccer</option>

Again, there might be a cleaner way to do it! But it works for me at least.
Hope this helps

A: You can use:
<%@array = ['Football', 'Basketball', 'Golf Soccer']%>

<%= f.select :category, ,options_for_select([['Choose One']] + @a.collect{|p| [p,{:id => p]}) %>

Hope it helps :)


text:
Q: How to select rows containing non unique keys using a unique key? I have the following MySQL table;
----------------------------
| id |   pid   | operation |
----------------------------
| 5  |   12    |  pending  |
| 7  |   19    |  sent     |
| 8  |   12    |  replaced |
| 9  |   16    |  sent     |
| 12 |   12    |  closed   |
| 14 |   21    |  sent     |
----------------------------

id is a unique operation id, while pid is product id implying which operation is done for which product and therefore not unique. I need to list all operations of a product, using only an operation id.
I can do this by using a sub select like;
SELECT * FROM operations WHERE pid = (SELECT pid FROM operations WHERE id = 8);

This query lists the exact results I need, like;
----------------------------
| id |   pid   | operation |
----------------------------
| 5  |   12    |  pending  |
| 8  |   12    |  replaced |
| 12 |   12    |  closed   |
----------------------------

The question is; how can I do this without a sub select?

A: You can use join like this
SELECT a.* FROM operations a
join operations b on a.pid =b.pild
WHERE b.id=8

A: Use JOIN:
SELECT o1.*
FROM operations o1 join
     operations o2 on o1.pid=o2.pid
WHERE o2.id = 8

Result:
id  pid operation
-------------------
5   12  pending
8   12  replaced
12  12  closed

Sample result in SQL Fiddle


text:
Q: TypeError: list indices must be integers, not str (MAPNIK) I am writing a function to calculate the shortest path to certain points along roads rather than as the crow flies, however i keep getting the error:

Traceback (most recent call last):   File
  "P:\understandinggis\assessment2\Assessment2.py", line 177, in

      if shortestPath1(g, line) <= maxDist:   File "P:\understandinggis\assessment2\Assessment2.py", line 14, in
  shortestPath1
      azF,azB,distance = g.inv(line["coordinates"][l][0], line["coordinates"][l][1], lines["coordinates"][l+1][0],
  line["coordinates"][l+1][1]) TypeError: list indices must be integers,
  not str

here's the line of code it refers to:
def shortestPath1 (g, line):
        #initialise cumulativelength
        cumulativeLength = 0
        for l in range(len(line)-1):
                azF,azB,distance = g.inv(line['coordinates'][l][0], line['coordinates'][l][1], lines['coordinates'][l+1][0], line['coordinates'][l+1][1])
                cumulativeLength += distance
                return cumulativeLength


text:
Q: Compare two source code files and report differences in python Let's suppose there are two source code files written in Javascript (file1.js and file2.js).
I want to compare them using python and spot the different portions of code found in file1, which are not present in file2 (basically the different lines of code found in file1).
How to do it in an efficient way?

A: *

*Using difflib library:
Python has a Module which is specially used for comparing the differences between the files. To get differences using the difflib library, we have to call the unified_diff() function to this comparison.

There is one Class available for comparing the differences between the files which named as Differ inside the difflib library.
You can try any of the above I guess both works fine, just import the library first like from difflib import Differ
from difflib import Differ

with open('file1.txt') as file_1, open('file2.txt') as file_2:
    differ = Differ()

    for line in differ.compare(file_1.readlines(), file_2.readlines()):
        print(line)


text:
Q: Tracking API for iOS devices Can I track how often people use my app or game on iOS device, as far as I know Apple does not provide any features for this.
Maybe I can use thrid API if it exist.
Thanks a lot.

A: Edit: Right, Apple will only tell you downloads.
Flurry analytics is pretty good. http://flurry.com

A: I can recommend the two options that I know of: Flurry and the TestFlight SDK - more specifically the Checkpoint API.

A: I would use Flurry for sure. Always worked like a charm for me.


text:
Q: Generate Random Gamma in Rcpp I have vector shape and scale parameters to generate numbers from random gamma distribution. I couldn't find a way in R like;
lambda<-matrix(rgamma(p,ak,scale=1/bk),p,1)

So I'm trying to generate in a loop and it seems I lose time which is the main purpose to use Rcpp.
for(int i = 0; i<p;i++){
lambda(i)=arma::conv_to<double>::from(arma::randg<arma::mat (1,1,arma::distr_param(ak(i),pow(bk(i),-1))));
}

edit: I have simulated all 3 methods and compare time.
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]

arma::mat rg(const arma::mat& w,double scale,int num) {
int p = w.n_rows;
arma::mat lambda(num,p,arma::fill::zeros);

for (int j=0;j<num;j++){
for(int i = 0; i<p;i++){
    lambda(j,i)=arma::conv_to<double>::from(arma::randg<arma::mat>(1,1,arma::distr_param(w(i),scale)));
}
}
return mean(lambda.rows(0,num-1),0);
}

These are R codes;
fun<-function(w,sca,num){
p=nrow(w)
lambda=matrix(0,num,p)
for (jj in 1:num){
    for (i in 1:p){
        lambda[jj,i]=rgamma(1,w[i],scale=sca)
    }
}
return(colMeans(lambda))
}

fun2<-function(w,sca,num){
p=nrow(w)
lambda=matrix(0,num,p)
for (jj in 1:num){
        lambda[jj,]=rgamma(p,w,scale=sca)
}
return(colMeans(lambda))
}

Here is result;
  a=matrix(c(1,2,3))

  microbenchmark(rg(a,2,100000),fun(a,2,1e5),fun2(a,2,1e5))
  Unit: milliseconds
              expr       min        lq      mean    median        uq       max neval
    rg(a, 2, 1e+05)  891.6197  900.0092  952.3833  915.6609  991.7918 1271.9117   100
    fun(a, 2, 1e+05) 1018.6645 1059.3994 1171.9160 1130.7481 1200.3192 1754.3445   100
   fun2(a, 2, 1e+05)  321.8309  339.2670  373.5317  355.5914  395.1515  604.4365   100

A: Do you understand that arma::randg is from the Armadillo namespace?
Whereas R::rgamma (scalar) or Rcpp::rgamma (vectorised) are from R / Rcpp with the parameterization of rate = 1/scale -- which I explained to you in this earlier question of yours?
Edit: This is basically the same answer as the last time: a simple C++ call to the C++ versions of rgamma compared to the R version using the "1/over" parameterization.
R> set.seed(42); stem(rgamma(100, 0.5, 2.0)) # calling from R

  The decimal point is 1 digit(s) to the left of the |

   0 | 00000000000001111111112222222333345566677777778888990111111122345666
   2 | 002257268
   4 | 235788
   6 | 269457
   8 | 70345
  10 | 28
  12 | 1
  14 |
  16 | 0

R> cppFunction("NumericVector callrgamma(int n, double shape, double scale) {
+                                        return(rgamma(n, shape, scale)); }")
R> set.seed(42); stem(callrgamma(100, 0.5, 1.0/2.0))  # calling from C++

  The decimal point is 1 digit(s) to the left of the |

   0 | 00000000000001111111112222222333345566677777778888990111111122345666
   2 | 002257268
   4 | 235788
   6 | 269457
   8 | 70345
  10 | 28
  12 | 1
  14 |
  16 | 0

R>


text:
Q: deploy a dacpac that contains a fulltext index with msdeploy How to deploy a dacpac that contains a FULLTEXT INDEX (built from a database project) to SQL Server using msdeploy?
MSdeploy skips creation of the fulltext indexes, and fails when creating objects that depend on the (now missing) fulltext indexes.
Is there an hidden option to exclude/include creation of fulltext indexes?

A: We had same problem with deployment using sqlpackage. Root cause is order of statements on building deployment plan with switched on IncludeTransactionalScripts option. Depended objects deploy before full-text index.
Solution
So we just set
IncludeTransactionalScripts=False

when deployment has new full-text index.
Hope it helps.


text:
Q: How to pass my access and secret keys properly for GlueContext? I have a glue notebook from which I am trying to read a specific file from a different AWS account. When I try to run a spark session and read it. The code works perfectly and I get the spark df but when I try to use glueContext.create_dynamic_frame() I get an Access Denied error.
This is what my code looks like so far. Is it cause I am not passing the AWS session credentials correctly?
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from pyspark.sql import SparkSession

access_key=''
secret_key=''

spark = SparkSession.builder \
            .config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.3,com.amazonaws:aws-java-sdk:1.7.4") \
            .config("fs.s3a.impl","org.apache.hadoop.fs.s3a.S3AFileSystem") \
            .config("fs.s3a.access.key", access_key) \
            .config("fs.s3a.secret.key", secret_key) \
            .getOrCreate()

sc = spark
glueContext = GlueContext(sc)
spark = glueContext.spark_session

dynamicFrame = glueContext.create_dynamic_frame.from_options(
                connection_type="s3",
                connection_options={"paths": ["s3://test/enterprise_survey.csv"]},
                format="csv",
                format_options={
                    "withHeader": True
                },
            )

When I try to run the code I get the following error:
Py4JJavaError: An error occurred while calling o458.getDynamicFrame.
: java.io.IOException: com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: N9EQPCTNJZSSENXP; S3 Extended

A: You should avoid typing your actual creds in the code itself. Rather use a role that can access your services.
For S3 update the s3 bucket policy in the other account which would allow the job to read the data and also add IAM policy to job's account to read data from S3 in other account.


text:
Q: NoSuchElementException - Could not complete schema update - (SQLite,Hibernate,JPA,JSF,Spring) We're always getting this hibernate exception at the server start-up. I don't know where I can search for the error. Maybe somebody knows what's wrong??
Until know, we have ignored this exception because it does not affect the application.
INFO: HV000001: Hibernate Validator 4.3.0.Final
14.06.2012 07:45:59 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
14.06.2012 07:45:59 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
14.06.2012 07:45:59 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
14.06.2012 07:45:59 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000299: Could not complete schema update
java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
at org.hibernate.tool.hbm2ddl.ColumnMetadata.<init>(ColumnMetadata.java:48)
at org.hibernate.tool.hbm2ddl.TableMetadata.addColumn(TableMetadata.java:153)
at org.hibernate.tool.hbm2ddl.TableMetadata.initColumns(TableMetadata.java:200)
at org.hibernate.tool.hbm2ddl.TableMetadata.<init>(TableMetadata.java:58)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.getTableMetadata(DatabaseMetadata.java:114)
at org.hibernate.cfg.Configuration.generateSchemaUpdateScript(Configuration.java:1133)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:212)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:178)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:497)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:257)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:530)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:496)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:657)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:630)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:339)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

Thanks!
Regards
Matthias

A: Here is how the ColumnMetada source looks like:
ColumnMetadata(ResultSet rs) throws SQLException {
    name = rs.getString("COLUMN_NAME");
    columnSize = rs.getInt("COLUMN_SIZE");
    decimalDigits = rs.getInt("DECIMAL_DIGITS");
    isNullable = rs.getString("IS_NULLABLE");
    typeCode = rs.getInt("DATA_TYPE");
    typeName = new StringTokenizer( rs.getString("TYPE_NAME"), "() " ).nextToken();
}

So you probably have a problem with the TYPE_NAME column. Does this appear when you do a DESCRIBE ?
Also make sure that you are using the most recent JDBC driver, recent Hibernate and that the Hibernate dialect matches the database.


text:
Q: How to delete the label under pie chart in swift? enter image description here
As seen in the photo, I cannot delete the camel text below.
class ChartViewController: UIViewController {

    @IBOutlet weak var pieChartView: PieChartView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let entries = [
            PieChartDataEntry(value: 10, label: "Camel"),
            PieChartDataEntry(value: 20, label: "Cat"),
            PieChartDataEntry(value: 30, label: "Dog"),
            PieChartDataEntry(value: 40, label: "Fish")
        ]
        let set = PieChartDataSet(entries: entries, label: "")  // Set the label to an empty string
        let data = PieChartData(dataSet: set)

        // Customize the pie chart
        pieChartView.data = data
        pieChartView.holeRadiusPercent = 0.5
        pieChartView.transparentCircleRadiusPercent = 1
        pieChartView.chartDescription.text = ""  // Set the chart description to an empty string
        pieChartView.frame = CGRect(x: 20, y: 100, width: 400, height: 400)

        // Set the colors for the pie slices
        set.colors = [UIColor.red, UIColor.green, UIColor.blue, UIColor.orange]
    }
}

It's not enough to do this let set = PieChartDataSet(entries: entries, label: "")

A: i found the solution.
pieChartView.legend.enabled = false


text:
Q: How to assign multiple enum values to a property in Spring.NET configuration? .NET supports the FlagsAttribute for enum's, which indicates "that an enumeration can be treated as a bit field".
An example of an enum that makes use of this [Flags] attribute is System.Windows.Forms.Keys
Here is my Spring.NET object definition:
<object id="command.paste" type="MyNamespace.PasteClipboardCommand, MyProject">
  <property name="Title" value="Paste into Folder" />
  <property name="ShortcutKeys" value="P" />
</object>

This sets the property ShortcutKeys of type Keys to the key P. No problem there. However, since this is a shortcut, I'd like to assign something like Control+P as shortcut key.
If I would wire this up in code, it would be:
command.ShortcutKeys = Keys.Control | Keys.P;

So, maybe I was a little naive trying this:
<property name="ShortcutKeys" value="Control|P" />

This fails, because the EnumConverter can only parse/convert string representations of single enum's. A full stacktrace is available below.

*

*Is this possible by default Spring.NET ?

*Can I work around this by specifying/using another EnumConverter ?

*Should I create/use another Keys class to do the Spring.NET initialization ?

UPDATE:
Apparently the KeysConverter knows how to handle this like this:
(new KeysConverter()).ConvertFrom(null, null, "Control+P");

Unfortunately, the EnumConverter does not support this ?
Attached Stacktrace:
System.Configuration.ConfigurationErrorsException: Error creating context 'spring.root': PropertyAccessExceptionsException (1 errors); nested PropertyAccessExceptions are:
[Spring.Core.TypeMismatchException: Cannot convert property value of type [System.String] to required type [System.Windows.Forms.Keys] for property 'ShortcutKeys'., Inner Exception: System.FormatException: Control|P is not a valid value for Keys. ---> System.ArgumentException: Requested value 'Control|P' was not found.
    at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
    at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
    --- End of inner exception stack trace ---
    at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
    at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
    at Spring.Core.TypeConversion.TypeConversionUtils.ConvertValueIfNecessary(Type requiredType, Object newValue, String propertyName)] ---> Spring.Objects.Factory.ObjectCreationException: Error creating object with name 'command.builder.paste' defined in 'file [....\commands.xml] line 39' : Error setting property values: PropertyAccessExceptionsException (1 errors); nested PropertyAccessExceptions are:
[Spring.Core.TypeMismatchException: Cannot convert property value of type [System.String] to required type [System.Windows.Forms.Keys] for property 'ShortcutKeys'., Inner Exception: System.FormatException: Control|P is not a valid value for Keys. ---> System.ArgumentException: Requested value 'Control|P' was not found.
    at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
    at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
    --- End of inner exception stack trace ---
    at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
    at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
    at Spring.Core.TypeConversion.TypeConversionUtils.ConvertValueIfNecessary(Type requiredType, Object newValue, String propertyName)] ---> PropertyAccessExceptionsException (1 errors); nested PropertyAccessExceptions are:
[Spring.Core.TypeMismatchException: Cannot convert property value of type [System.String] to required type [System.Windows.Forms.Keys] for property 'ShortcutKeys'., Inner Exception: System.FormatException: Control|P is not a valid value for Keys. ---> System.ArgumentException: Requested value 'Control|P' was not found.
    at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
    at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
    --- End of inner exception stack trace ---
    at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
    at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
    at Spring.Core.TypeConversion.TypeConversionUtils.ConvertValueIfNecessary(Type requiredType, Object newValue, String propertyName)]

A: If you look at the Spring.NET documentation 5.11 Configuration of IApplicationContext, you can see an example of how to add a specific type converter for a given type.
Adding the KeysConverter for type Keys in app.config is sufficient:
<converter for="System.Windows.Forms.Keys, System.Windows.Forms" type="System.Windows.Forms.KeysConverter, System.Windows.Forms"/>

Now the enumvalue/shortcut can be specified like this:
<property name="ShortcutKeys" value="Control+P" />

A: Try using SpEL (Spring.NET Expression Language) :
http://www.springframework.net/doc-latest/reference/html/expressions.html
<property name="ShortcutKeys" expression="Keys.Control or Keys.P" />

or
<property name="ShortcutKeys" expression="T(System.Windows.Forms.Keys).Control or T(System.Windows.Forms.Keys).P" />

A: <property name="ShortcutKeys" value="Control, P" />