text:
Q: Formula for length of the diagonal of a parallelepiped Let $a,b,c$ and  $\alpha, \beta, \gamma $ are sides and angles ($\alpha$ is the angle between the sides $b$ and $c$ and so on)  of a parallelepiped. By using the vector algebra it is easу to prove the formula for  the length of the diagonal $d$ of this  parallelepiped
$$
d=\sqrt{a^2+b^2+c^2+2ab\cos \gamma+2ac\cos \beta+2bc \cos \alpha}
$$
Question. How to prove the formula without vectors?
It is clear that we have to use two times the cosine theoren but what is the angle between one side and the diagonal of parallelogram formed by two other sides?

A: This solution is from SPHERICAL TRIGONOMETRY
For the Use of Colleges and Schools.
by I. TODHUNTER, FIFTH EDITION.
London, 1886
(p.125, ex.157)
(I post the links since for my reputation this site still does not allow to embed images..)
here is the first part;
second
Hope this helps!

A: At last, I have found a solution in the book
Casey, John (1889). A Treatise on Spherical Trigonometry: And Its Application to Geodesy and Astronomy with Numerous Examples. London: Longmans, Green, & Company. p. 134.  Problem 125

A: The formula can be derived from two geometric results/theorems:

*

*Parallelogram law

In a parallelogram $ABCD$ with $AB = CD = a, BC = DA = b$, one has $$AC^2 + BD^2 = 2(AB^2 + BC^2) = 2(a^2+b^2)$$

Since in a parallelogram, $\angle A = \angle C$ and $\angle B = \angle D = \pi - \angle A$, one can easily derive this result from law of cosines.

*The second result concerns parallel lines in space.
Two lines in space are parallel if either they are the same line or they lie in a common plane and didn't intersect. The results we need is "parallel-ness"  among lines is transitive:

Given any three lines $a, b, c$; if $a$ is parallel to $b$ and $b$ is parallel to $c$, then $a$ is parallel to $c$.
  $$a \parallel b\quad\text{ and }\quad b \parallel c\quad\implies\quad a \parallel c
$$

This can be proved from first principle using Hilbert's axioms.
For a proof, see this answer.
Back to the original problem.
Let $\mathcal{P}$ be a parallelepiped with sides $a,b,c$. Let $O$ be a vertex of $\mathcal{P}$. Let $A,B,C$ be the three vertices adjacent to $O$ such that
$$|OA| = a, |OB| = b, |OC| = c, \angle BOC = \alpha, \angle COA = \beta, \angle AOB = \gamma$$
Let $A_1,B_1,C_1,D$ be the remaining 4 vertices of $\mathcal{P}$ oppositie to $A, B, C$ and $O$ respectively.
Being a parallelepiped, it faces are parallelograms. In particular,
$OAB_1C$ and $AC_1DC$ are parallelograms. This implies
$$OC \parallel AB_1, |OC| = |AB_1| \quad\text{ and }\quad AB_1 \parallel CD_1, |AB_1| = |C_1D|$$
By second result, $OC \parallel CD_1, |OC| = |CD_1|$ and $OC_1DC$ is a parallelogram. By a similiar arguments, $OA_1DA$ and $AC_1A_1C$ are parallelograms too.
Apply parallelogram law to parallelograms $OC_1DC, OA_1DA, AC_1A_1C, OAB_1C$, we obtain
$$\begin{align}
OD^2 + CC_1^2 &= 2(OC^2 + OC_1^2)\\
OD^2 + AA_1^2 &= 2(OA^2 + OA_1^2)\\
AA_1^2 + CC_1^2 &= 2(AC^2 + AC_1^2) = 2(AC^2 + OB^2)\\
AC^2 + OB_1^2 &= 2(OA^2 + OC^2)\\
\end{align}$$
Sum the $1^{st}$ and $2^{nd}$ equation and subtract $3^{rd}$ equation from it, we obtain
$$\begin{align}
OD^2 &=  OC^2 + OC_1^2 + OA^2 + OA_1^2 - AC^2 - OB^2\\
&= OC^2 + OC_1^2 + OA^2 + OA_1^2 - (2OA^2 + 2OC^2 - OB_1^2) - OB^2\\
&= OA_1^2 + OB_1^2 + OC_1^2 - OA^2 - OB^2 - OC^2
\end{align}\tag{*1}
$$
Apply parallelogram law and law of cosines to faces $OAB_1C$, $OBC_1A$ and $OCA_1B$, we find
$$\begin{align}
OA_1^2 &= b^2 + c^2 + 2bc\cos\alpha\\
OB_1^2 &= c^2 + a^2 + 2ca\cos\beta\\
OC_1^2 &= a^2 + b^2 + 2ab\cos\gamma
\end{align}$$
Substitute this back into $(*1)$, the desired formula follows:
$$d^2 \stackrel{def}{=} OD^2 = a^2 + b^2 + c^2 +  2bc\cos\alpha + 2ca\cos\beta + 2ab\cos\gamma$$


text:
Q: Transform.LookAt() changes object's Y rotation to 180 or -180 I'm trying to make a charge meter rotate around a pivot to face away from the mouse.
When I use Transform.LookAt(), the pivot's rotation is changed to 180 or -180.
What is the issue here and is there any way to solve this?
Code:
        public void Rotate(Vector3 direction)
        {
            if (direction.magnitude > 0)
            {
                var targetPosition = _pivot.position + direction;
                _pivot.LookAt(targetPosition, Vector3.up);
            }
        }

EDIT:
This is where I call the method mentioned above:
        private void UpdateMousePosition()
        {
            _currentMousePosition = Input.mousePosition;

            _direction = _initialMousePosition - _currentMousePosition;
            _direction.Normalize();
            _indicator.Rotate(_direction);
        }

UpdateMousePosition() is called once per frame when proper conditions are met. _initialMousePosition is the cached Input.mousePosition when player clicks on the object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Instance does not appear in shell I'm currently learning Python and I'm very confused with its behaviour. I'm creating an instance of a class and calling it directly. It is not appearing on the shell when I'm executing the script, only when I'm calling it directly in the shell. Why does Python behave like that or is it a problem with IDLE?
Here's the code of foo.py:
class Foo:
    def __init__(self, _data=None):
        self.data = _data

    def __repr__(self):
        return "repr[%s]" % self.data

    def __str__(self):
        return "str[%s]" % self.data

if __name__ == "__main__":

    print "Begin"

    f = Foo(1234)

    print "direct"
    f

    print "print"
    print f

    print "End"

Here's the shell output:
Begin
direct
print
str[1234]
End
>>> f
repr[1234]
>>>

Btw. I'm on linux (ubuntu 16.04 LTS) using IDLE 2.7.12 with Python 2.7.12

A: As Mr. Gordon pointed out in his comment the REPL will print the object, but in the script it won't print it out unless you tell it to do so. If you want the same type of behavior as the REPL you can do:
print(repr(f))

That should give you:
repr[1234]

Is that what you are looking for?

A: You can't just type in an object an expect it to print. You need to tell python to print it. The shell is different and is designed to always print the output.


text:
Q: Create stack space within a struct in C I have:
  typedef struct{
   int *stack;
   int *stack_ptr;
  }MyStruct;

then somewhere else I do:
MyStruct *temp = malloc(sizeof(MyStruct));
temp->stack = malloc(1024) //allocate 1024 bytes
temp->stack_ptr = temp->stack;  //stack_ptr points to beginning of stack
temp->stack_ptr += 800;  //move stack_ptr down towards bottom of stack

I'm trying to make sense of the debugger output and I don't think this is right, but I can't tell for sure.  I just want to have a stack within my struct and then a stack pointer within this stack that I can manipulate.
EDIT:  Okay, the part about adding 800 makes sense.  I guess what I'm having trouble understanding is after I allocate 1024 bytes for temp->stack, how do I go about inserting something down towards the bottom of that stack?  Do I even need to have the stack_ptr or is there a way to offset stack variable.

A: Your problem is likely that you think
temp->stack_ptr += 800;  //move stack_ptr down towards bottom of stack

would advance your stack pointer to the 800th stack entry. It doesn't, it moves the stack pointer to 800 * sizeof(int) bytes (likely 3200), while you allocated only 1024 bytes.
If you need to dynamically allocate n items of something, the idiomatic C code is
sometype *foo;
/* ... */
foo = malloc (n * sizeof (*foo));

The sizeof multiplication is usually omitted for pointers-to-char since sizeof(char) is 1 by definition of the C Language Standard.

A: temp->stack = malloc(1024) //allocate 1024 bytes

Should be:
temp->stack = malloc(1024 * sizeof(int)); //allocate 1024 bytes

What exactly is your problem ??
Edit
Let me explain what i meant by that:
Your are trying to move your pointer of 800 blocks (800 * sizeof(int)) but you only allocate 1024 = 1024 / sizeof(int) blocks


text:
Q: 'value' must be a single Unicode code point     def Check():
            afile = open("test.txt", "r")
            lines = afile.readlines()
            afile.close()

            for line in lines:
                test = line.split("\n")

                actions = ActionChains(driver)
                actions.send_keys(test)
                actions.perform()
                time.sleep(1)
                actions = ActionChains(driver)
                actions.send_keys(Keys.ENTER)
                actions.perform()
                time.sleep(1)
                actions = ActionChains(driver)
                actions.send_keys(Keys.LEFT_CONTROL).send_keys('z')
                actions.perform()
                time.sleep(1)
                actions = ActionChains(driver)
                actions.send_keys(Keys.LEFT_CONTROL).send_keys('z')
                actions.perform()
                time.sleep(1)
                actions = ActionChains(driver)
                actions.send_keys(Keys.LEFT_CONTROL).send_keys('z')
                actions.perform()
                Check()
Check()

Everytime i run this i get this error:

selenium.common.exceptions.InvalidArgumentException: Message: invalid
argument from invalid argument: 'value' must be a single Unicode code
point

A: in that row you're setting list to test variable:
test = line.split("\n")

and pass to send_keys action:
actions.send_keys(test)

instead, try to put string value. And remove '\n' by rstrip function:
test = line.rstrip("\n")

Moreover, where are you attaching webdriver element to interact with?
I would suggest first moving to the element and then send_keys action, like that:
def Check():
    menu = driver.find_element(By.XPATH, '//input[@name="q"]')
    with open("test.csv", "r") as afile:
        lines = afile.readlines()

    for line in lines:
        actions = ActionChains(driver)
        actions.move_to_element(menu).send_keys(line)
        actions.perform()


text:
Q: Nested for loop in bash not iterating properly? I am new to scripting/programming/everything and can't seem to figure out this bash script/loop I am trying to iterate.
I have a directory called "folder", in which there are many subdirectories which each contain files that I would like to echo (for now)
I have this, but it doesn't seem to print the files within the subdirectories but instead prints the subdirectories themselves. How would I alter the script to make this work?
for directory in *;
do
        for thing in $directory
        do
                echo $thing
        done
done

A: The for loop itself doesn't traverse a file system; it only iterates over a sequence of strings. You need to iterate over the result of a pathname expansion for the second loop.
for directory in *;
do
    for thing in "$directory"/*
    do
        echo "$thing"
    done
done

You can do this with one loop with a more complex pattern:
for thing in */*; do
    echo "$thing"
done

A: Bash version 4.0 adds a new globbing option called globstar which treats the pattern ** differently when it's set.
#!/bin/bash
shopt -s globstar
for file in folder/** # with '**'  bash recurses all the directories
do
  echo "$file"
done


text:
Q: Azure IOT Device Provisioning - How to get the IOT Device Primary Connection String from the Device/Provisoning Client SDK? I'm testing IOT Device Provisioning using a C# sample code quickstart "Provision a simulated TPM device" MS Docs reference Quickstart: Provision a simulated TPM device
I can successfully provision the device, but I want the device provisioning service to some how return the IOT Device Primary (or Secondary) Connection string on completion of the registration in order that the next time I connect to Azure, I can simply connect directly to the IOT Hub and not have to keep re-provisoning the device as a means of simply getting connected to Azure.
I would store the connection string in an encrypted local database so the connection string information remains secure. Only if the connection string is no longer valid after a period of time when re-connecting to the IOT Hub, would I then call a method to re-provision the device and repeat the above process.
The MS Docs says "We recommend not provisioning on every reboot of the device, as this could hit the service throttling limits especially when reprovisioning several thousands or millions of devices at once. Instead you should attempt to use the Device Registration Status Lookup API and try to connect with that information to IoT Hub" see Runtime Registration - Device Registration Status Lookup
I really don't understand the documentation for the "Device Registration Status Lookup" API and hoping there is another way to obtain the connecton string without calling this service?
If there is no other option, then from reading the docs on this API, I cant find anything that explains how to construct the IOT Device connection string from the information returned from this API service? ( i dont see any json properties returned mentioned in the docs that resmebles a connection string)
Secondly I dont see any code samples for calling this service using C#, the MS docs only gives the HTTP Uri reference which is unhelpful considering I'd be calling the code in C# using HTTP Client class, not using postman.
Sample code below shows two lines of commented out text where I'm looking for some kind of solution to retrieve the IOT Device Primary Connection string, straight after the device had been provisioned:
public async Task RunSampleAsync()
{
    Console.WriteLine("Initializing security using the local TPM...");
    using SecurityProviderTpm security = new SecurityProviderTpmHsm("MyRegistraton123456"); // Registration Id

    Console.WriteLine($"Initializing the device provisioning client...");

    using var transport = GetTransportHandler();
    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(
        "global.azure-devices-provisioning.net", // GlobalDeviceEndpoint
        "MyIdScope", // IdScope
        security,
        transport);

    Console.WriteLine($"Initialized for registration Id {security.GetRegistrationID()}.");

    Console.WriteLine("Registering with the device provisioning service... ");
    DeviceRegistrationResult result = await provClient.RegisterAsync();

    // ------------------------------------------------------------------------------
    // Is it possible to get the connection string from the DeviceRegistrationResult?
    // ------------------------------------------------------------------------------

    Console.WriteLine($"Registration status: {result.Status}.");
    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
    {
        Console.WriteLine($"Registration status did not assign a hub, so exiting this sample.");
        return;
    }

    Console.WriteLine($"Device {result.DeviceId} registered to {result.AssignedHub}.");

    Console.WriteLine("Creating TPM authentication for IoT Hub...");
    IAuthenticationMethod auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

    Console.WriteLine($"Testing the provisioned device with IoT Hub...");
    Console.WriteLine("Assigned Hub" + result.AssignedHub);
    using DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp_WebSocket_Only);

    // ------------------------------------------------------------------------------------
    // Is it possible to get the connection string from the active DeviceClient connection?
    // ------------------------------------------------------------------------------------

    Console.WriteLine("Sending a telemetry message...");
    using var message = new Message(Encoding.UTF8.GetBytes("TestMessage"));
    await iotClient.SendEventAsync(message);

    await iotClient.CloseAsync();
    Console.WriteLine("Finished.");
}

Just to confirm, the primary/secondary connection string I'm tryin to obtain is the one that is unique to that particular IOT Device, which allows it to connect with the IOT Hub using the Microsoft.Azure.Devices.Client SDK i.e. like the screenshot below:

A: Well, the answer was staring at me, within the code sample shown in my question!
So it seems my approach was wrong in that we dont use the IOT Device connection string for subsequent calls after registration. In my environment and the code sample shown in my question, we're using the TPM as our means of authentication, so we keep using this as it will always produce the same output as long as we're feeding in the same "RegistrationId".
Using my original code sample, for testing purposes we allow the IOT device to complete the registration, it then sends a test message "TestMessage" and we then close the client connection.
I then since added a new method "SendMessageAfterRegistration" call and placed this at the end of this sequence, as shown below:

Bearing in mind that once the we have first registered, we'd store the details of the DeviceId and the Assigned Hub somehwere locally, database or something.
Then I added the following test method underneath the code sample from my question:
private async Task SendMessageAfterRegistration(string deviceId, string assignedHub)
{
    Console.WriteLine("Initializing security using the local TPM...");
    using SecurityProviderTpm security = new SecurityProviderTpmHsm("MyRegistraton150820221815"); // Registration Id

    Console.WriteLine("Creating TPM authentication for IoT Hub...");
    IAuthenticationMethod auth = new DeviceAuthenticationWithTpm(deviceId, security);

    // Create an instance of the Device Client
    using DeviceClient iotClient = DeviceClient.Create(assignedHub, auth, TransportType.Amqp_WebSocket_Only);

    Console.WriteLine("Sending a telemetry message...");
    using var message = new Message(Encoding.UTF8.GetBytes("TestMessage-WithNewConnection"));
    await iotClient.SendEventAsync(message);
}

In the new method "SendMessageAfterRegistration" you'll see that we call up the SecurityProviderTpm class and feed in the same orignal Registration Id as a string. Using the security value returned we then call up the IAuthenticationMethod class (these ar both baked into the device provisioning SDK)
So the "auth" result returned from IAuthenticationMethod is then used to create the DeviceClient, from there we can send the second test message "TestMessage-WithNewConnection"
I have a seperate project that recieves the Device To Cloud messages so I used this to confirm we have the result we're looking for.


text:
Q: Porting Android i want to have some knowledge on porting android on linux devices. I am a web and android developer but now i want to port android on some hardware which you could suggest is easy for the beginners to start with.
I don't feel like buying a mobile phone this time i want to make a mobile phone :)
Please help me achieve this goal.
regards
Abhishek Talwar

A: Well, what you're asking is pretty complex.
Do you want to BUILD your own cellphone from scratch?
This would take a lot of knowledge and development time. You could get some GSM development boards to experiment with that. Something like these:
http://www.sparkfun.com/search/results?term=gsm&what=products
You could get an Arduino and use one of the arduino linux ports. The arduino could handle the gsm module and an lcd screen.
This is extremely complicated though.
If its android porting you're interested in, I suggest just getting a mobile phone and then porting android to it.  It WILL be complicated and you better get something you can easily develop for. Windows Mobile phones would be my suggestion as there are a lot of active programs to port android to those.


text:
Q: Configure Angular 4 to generate web components For a project I need to provide my code as a web component.
I read that you can configure Angular to generate web components. Plain and simple question: How can that be done?


text:
Q: Unable to run react native IOS application on device due to codesign errors I have a react native application (that I deploy with expo). I am trying to run on ios.

*

*I had a app under a different account  under the build identifier com.bcc.quickpass. There, the build was working fine. I transferred the app along with the build identifier to my current account.

*I then tried to run the app under my current account account using automated signing. The app builds but the following comes up:

Here is the XCode Log:
Could not launch "QuickPass"
Domain: IDEDebugSessionErrorDomain
Code: 3
Failure Reason: The operation couldn't be completed. Unable to launch com.bcc.quickpass because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user.
User Info: {
    DVTErrorCreationDateKey = "2022-12-06 06:01:22 +0000";
    DVTRadarComponentKey = 855031;
    IDERunOperationFailingWorker = DBGLLDBLauncher;
    RawUnderlyingErrorMessage = "The operation couldn\U2019t be completed. Unable to launch com.bcc.quickpass because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user.";
}
--

Analytics Event: com.apple.dt.IDERunOperationWorkerFinished : {
    "device_model" = "iPhone10,1";
    "device_osBuild" = "14.6 (18F72)";
    "device_platform" = "com.apple.platform.iphoneos";
    "launchSession_schemeCommand" = Run;
    "launchSession_state" = 1;
    "launchSession_targetArch" = arm64;
    "operation_duration_ms" = 32442;
    "operation_errorCode" = 3;
    "operation_errorDomain" = IDEDebugSessionErrorDomain;
    "operation_errorWorker" = DBGLLDBLauncher;
    "operation_name" = IDEiPhoneRunOperationWorkerGroup;
    "param_consoleMode" = 0;
    "param_debugger_attachToExtensions" = 0;
    "param_debugger_attachToXPC" = 1;
    "param_debugger_type" = 5;
    "param_destination_isProxy" = 0;
    "param_destination_platform" = "com.apple.platform.iphoneos";
    "param_diag_MainThreadChecker_stopOnIssue" = 0;
    "param_diag_MallocStackLogging_enableDuringAttach" = 0;
    "param_diag_MallocStackLogging_enableForXPC" = 1;
    "param_diag_allowLocationSimulation" = 1;
    "param_diag_gpu_frameCapture_enable" = 0;
    "param_diag_gpu_shaderValidation_enable" = 0;
    "param_diag_gpu_validation_enable" = 0;
    "param_diag_memoryGraphOnResourceException" = 0;
    "param_diag_queueDebugging_enable" = 1;
    "param_diag_runtimeProfile_generate" = 0;
    "param_diag_sanitizer_asan_enable" = 0;
    "param_diag_sanitizer_tsan_enable" = 0;
    "param_diag_sanitizer_tsan_stopOnIssue" = 0;
    "param_diag_sanitizer_ubsan_stopOnIssue" = 0;
    "param_diag_showNonLocalizedStrings" = 0;
    "param_diag_viewDebugging_enabled" = 1;
    "param_diag_viewDebugging_insertDylibOnLaunch" = 1;
    "param_install_style" = 0;
    "param_launcher_UID" = 2;
    "param_launcher_allowDeviceSensorReplayData" = 0;
    "param_launcher_kind" = 0;
    "param_launcher_style" = 0;
    "param_launcher_substyle" = 0;
    "param_runnable_appExtensionHostRunMode" = 0;
    "param_runnable_productType" = "com.apple.product-type.application";
    "param_runnable_swiftVersion" = "5.5.2";
    "param_runnable_type" = 2;
    "param_testing_launchedForTesting" = 0;
    "param_testing_suppressSimulatorApp" = 0;
    "param_testing_usingCLI" = 0;
    "sdk_canonicalName" = "iphoneos15.2";
    "sdk_osVersion" = "15.2";
    "sdk_variant" = iphoneos;
}
--

System Information

macOS Version 11.4 (Build 20F71)
Xcode 13.2.1 (19586) (Build 13C100)
Timestamp: 2022-12-06T12:01:22+06:00

I also tried to build the app using expo. But codesign error occurs.
SQTCs-Mac-mini:ekyc-native-app sqtc$ expo run:ios --device 68f18c4f36c2943dff92345ae21bc58887477c55
...
...
CodeSign /Users/sqtc/Library/Developer/Xcode/DerivedData/QuickPass-faybjdvqxbotkeajwmmcoupclnpg/Build/Products/Debug-iphoneos/QuickPass.app (in target 'QuickPass' from project 'QuickPass')
    cd /Users/sqtc/Desktop/ekyc-native-app/ios
    export CODESIGN_ALLOCATE\=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate

    Signing Identity:     "Apple Development: Samidhya Sarker (66DM5N2A46)"
    Provisioning Profile: "iOS Team Provisioning Profile: com.bcc.quickpass"
                          (50d1bff7-a77b-4ecb-88d2-a0b7620625c6)

    /usr/bin/codesign --force --sign BF6FCB75B17E29CD93717001359BB14881C0ED50 --entitlements /Users/sqtc/Library/Developer/Xcode/DerivedData/QuickPass-faybjdvqxbotkeajwmmcoupclnpg/Build/Intermediates.noindex/QuickPass.build/Debug-iphoneos/QuickPass.build/QuickPass.app.xcent --timestamp\=none --generate-entitlement-der /Users/sqtc/Library/Developer/Xcode/DerivedData/QuickPass-faybjdvqxbotkeajwmmcoupclnpg/Build/Products/Debug-iphoneos/QuickPass.app
/Users/sqtc/Library/Developer/Xcode/DerivedData/QuickPass-faybjdvqxbotkeajwmmcoupclnpg/Build/Products/Debug-iphoneos/QuickPass.app: errSecInternalComponent
Command CodeSign failed with a nonzero exit code

** BUILD FAILED **

The following build commands failed:
        CodeSign /Users/sqtc/Library/Developer/Xcode/DerivedData/QuickPass-faybjdvqxbotkeajwmmcoupclnpg/Build/Products/Debug-iphoneos/QuickPass.app (in target 'QuickPass' from project 'QuickPass')
(1 failure)
Build logs written to /Users/sqtc/Desktop/ekyc-native-app/.expo/xcodebuild.log

react-native also gives the same errors:
SQTCs-Mac-mini:ekyc-native-app sqtc$ npx react-native run-ios --device "SQTC's iPhone"
^C
SQTCs-Mac-mini:ekyc-native-app sqtc$ npx react-native run-ios --device "SQTCs iPhone"
info Found Xcode workspace "QuickPass.xcworkspace"
info Building (using "xcodebuild -workspace QuickPass.xcworkspace -configuration Debug -scheme QuickPass -destination id=68f18c4f36c2943dff92345ae21bc58887477c55")
▸ Running script 'Create Symlinks to Header Folders'
▸ Running script 'Create Symlinks to Header Folders'
▸ Running script '[CP-User] Generate Specs'
▸ Copying /Users/sqtc/Desktop/ekyc-native-app/ios/build/generated/ios/FBReactNativeSpec/FBReactNativeSpec.h
▸ Compiling FBReactNativeSpec-generated.mm
▸ Running script '[CP-User] Generate app.manifest for expo-updates'
▸ Running script '[CP-User] Generate app.config for prebuilt Constants.manifest'
▸ Running script 'Create Symlinks to Header Folders'
▸ Compiling RCTVibration.mm
▸ Compiling RCTSettingsManager.mm
▸ Compiling RCTNetworking.mm
▸ Compiling RCTLinkingManager.mm
▸ Compiling RCTImageStoreManager.mm
▸ Compiling RCTFileReaderModule.mm
▸ Compiling RCTNativeAnimatedTurboModule.mm
▸ Compiling RCTAccessibilityManager.mm
▸ Compiling RCTBlobManager.mm
▸ Compiling RCTImageLoader.mm
▸ Compiling RCTImageEditingManager.mm
▸ Compiling RCTNativeAnimatedModule.mm
▸ Compiling RCTWebSocketModule.mm
▸ Compiling RCTTiming.mm
▸ Compiling RCTStatusBarManager.mm
▸ Compiling RCTSourceCode.mm
▸ Compiling RCTRedBox.mm
▸ Compiling RCTPlatform.mm
▸ Compiling RCTLogBox.mm
▸ Compiling RCTKeyboardObserver.mm
▸ Compiling RCTI18nManager.mm
▸ Compiling RCTExceptionsManager.mm
▸ Compiling RCTDeviceInfo.mm
▸ Compiling RCTDevSplitBundleLoader.mm
▸ Compiling RCTDevSettings.mm
▸ Compiling RCTDevMenu.mm
▸ Compiling RCTDevLoadingView.mm
▸ Compiling RCTClipboard.mm
▸ Compiling RCTAsyncLocalStorage.mm
▸ Compiling RCTAppearance.mm
▸ Compiling RCTAppState.mm
▸ Compiling RCTAlertManager.mm
▸ Compiling RCTActionSheetManager.mm
▸ Running script 'Start Packager'
▸ Linking QuickPass
⚠  ld: method '+UIDatePickerMode:' in category from /Users/sqtc/Library/Developer/Xcode/DerivedData/QuickPass-faybjdvqxbotkeajwmmcoupclnpg/Build/Products/Debug-iphoneos/React-Core/React.framework/React(RCTDatePickerManager.o) conflicts with same method from another category
▸ Running script 'Bundle React Native code and images'
    the transform cache was reset.
▸ Processing Info.plist
▸ Running script '[CP] Copy Pods Resources'
▸ Running script '[CP-User] [RNFB] Core Configuration'
      A firebase.json file was not found, whilst this file is optional it is recommended to include it to configure firebase services in React Native Firebase.
▸ Generating 'QuickPass.app.dSYM'
error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening QuickPass.xcworkspace.
info Run CLI with --verbose flag for more details.

I then tried to create new signing profiles. Created new CSRs in my device and uploaded them to developer.apple.com and created new development certificates. But the same error occurs.
My device informations:

*

*Development machine: macOS Big Sur (11.4)

*XCode: 13.2.1 (13C100)

*Device: iOS 14.1


text:
Q: Getting value as undefined when trying to retrieve from Observable I have an Observable declared as data$ in which I could see the values (array of objects) in the console. But when I try to subscribe and get the value from data$, it returns undefined. Here is my code:
data$ = this.feedValue.feedValues$; \\This returns some values as array of objects.Could see the values under actionObserver
I am trying to get the values inside this observable by doing this,
dataResponse: any;
this.data$.subscribe(resp => (this.dataResponse = resp));
dataResponse is shown as undefined.


text:
Q: Google Maps JavaScript API error: ExpiredKeyMapError I'm getting the error on the website Google API, so why happening is api not free or whats wrong even I enable the google javascript. Google Maps JavaScript API error: ExpiredKeyMapError
https://developers.google.com/maps/documentation/javascript/error-messages#expired-key-map-error

A: Based on the doc given on the error message, you usually get ExpiredKeyMapError when the API key you are using is not recognized by the system or already expired.
I suggest generating a new API key and using that new API key in your implementation instead. You can check the youtube tutorial - How to generate and restrict API keys for Google Maps Platform
If the error still persists, I suggest that you file a support case to Google Maps Support for further assistance.


text:
Q: jquery accordion - separate validation for each tab I am using jquery accordion with 4 tabs. Each tab has different number of textfields and a button to submit the values (only in the particular div). In this case, i have 4buttons inside 4 tabs. Each button click should validate the textfields in the inner div only.
validation needed :
1st and 2nd tab : userid should be minimum 5characters
3rd tab : userid should be minimum 5 characters and password should not be a part of userid
4th tab : all fields are mandatory. Password should not be a part of userid, firstname or lastname
js fiddle link http://jsfiddle.net/7R3wX/2/
below is my html code

Changes in User Setup

<form>

Check User

 User ID : <input type="text" id="userid1">

<input type="button" value="Submit" onclick="onAjaxPost()" id="checkButton">

Deletion of users

 User ID : <input type="text" id="userid2">

<input type="button" value="Submit" onclick="onAjaxPost()"id="deleteButton">

Password Reset

 User ID : <input type="text" id="userid3">

 New Password : <input type="text" id="password1">

<input type="button" value="Submit" onclick="onAjaxPost()" id="resetButton">

Create User

 First Name : <input type="text" id="fName" >

 Last Name : <input type="text" id="lName">

 User ID : <input type="text" id="userid4">

 Password : <input type="text" id="password2">

<input type="button" value="Submit" onclick="onAjaxPost()" id="createButton">

</form>

below is my onajaxpost function
var user,pwd,id,fname,lname;
var urlCalled,dataPassed,divID,userTextID,pwdTextID,fnameTextID,lnameTextID,errorMsg,ifcheck;
function onAjaxPost() {
id = event.target.id;
$('#check').html("");
$('#delete').html("");
$('#create').html("");
$('#reset').html("");
if (id == "checkButton") {
divID="#check";
userTextID="#userid1";
user = $(userTextID).val();
ifcheck=user;
urlCalled="/SecuritySetup/UserCheckingConsole.service";
dataPassed="userid=" + user;
errorMsg="Input field is empty....";
}
else if (id == "deleteButton") {
divID="#delete";
userTextID="#userid2";
user = $(userTextID).val();
ifcheck=user;
urlCalled="/SecuritySetup/UserDeletionConsole.service";
dataPassed="userid=" + user;
errorMsg="Input field is empty....";
}
else if (id == "resetButton") {
divID="#reset";
userTextID="#userid3";
pwdTextID="#password1";
user = $(userTextID).val();
pwd = $(pwdTextID).val();
ifcheck=user&&pwd;
urlCalled="/SecuritySetup/UserPasswordChange.service";
dataPassed="userid=" + user+ "&password=" + pwd;
errorMsg="Please enter all fields....";
}
else if (id == "createButton") {
divID="#create";
userTextID="#userid4";
pwdTextID="#password2";
fnameTextID="#fName";
lnameTextID="#lName";
user = $(userTextID).val();
pwd = $(pwdTextID).val();
fname=$(fnameTextID).val();
lname=$(lnameTextID).val();
ifcheck=user&&pwd&&fname&&lname;
urlCalled="/SecuritySetup/UserCreationConsole.service";
dataPassed="firstName=" + fname + "&lastName=" + lname +"&userid=" + user + "&password=" + pwd;
errorMsg="Please enter all fields....";
}
if(ifcheck){
$(divID).css({
'color' : 'grey',
'font-style' : 'italic',
'font-size': '12px'
});
$(divID).html("Processing Request....");
$.ajax({
type : "POST",
url : urlCalled,
data : dataPassed,
dataType : "json",
success : function(response) {
$(divID).css({
'color' : 'green',
'font-style' : 'normal'
});
$(divID).html(response);
$(userTextID).val('');
$(pwdTextID).val('');
$(fnameTextID).val('');
$(lnameTextID).val('');
},
error : function(e) {
alert('Error: ' + e);
}
});
}
else{
$(divID).css({
'color' : 'red',
'font-style' : 'normal'
});
$(divID).html(errorMsg);
}}

How can i achieve that? Any help please?
I have updated the onAjaxpost() function code also. please see above
Thanks,
Suriya

A: You could do something like this...
The onClick would not be required in the inputtags.
$(document).on('click','#accordion input[type=button]',function(){
    onAjaxPost($(this).attr('id'));
});

This way, you send the value of your id button to onAjaxPost().
In this function, you could get the values of the form fields according to the id value, for instance by using a switch(). You can then build a string of data to be sent to the distant page, together with the id value.
On the distant page, you get the id value, and you can therefore proceed to the according validation processes.
You can send back data including the validation outcome.

A more usable option would be to validate your forms on a field by field basis using onBlur :
$(document).on('blur','#accordion input[type=text]',function(){
    onAjaxPost($(this).attr('id'));
});

This time you can send the field's id and its value to your distant validation page, and your user gets a feedback as soon as he leaves an input.


text:
Q: find difference between lists and append difference to lists, but for 40 different lists - python Hi so it's difficult to explain this properly in the title, but firstly let me start by explaining my data. I have 40 lists stored within a list with a form such as this:
data[0] = [[value1 value2 value3,80],[value1,90],[value1 value3,60],[value2 value3,70]]
data[1] = [[value2,40],[value1 value2 value3,90]]
data[2] = [[value1 value2,80],[value1,50],[value1 value3,20]]
   .
   .
   .

Now I am expecting an output such as this:
data[0] = [[value1 value2 value3,80],[value1,90],[value1 value3,60],[value2 value3,70],[value2,0],[value1 value2,0]]
data[1] = [[value2,40],[value1 value2 value3,90],[value1,0],[value1 value3,0],[value2 value3,0],[value1 value2,0]]
data[2] = [[value1 value2,80],[value1,50],[value1 value3,20],[value1 value2 value3,0],[value2 value3,0],[value2,0]]

I know this is a bit complicated to read, but I wanted to make sure a good demo of the data is there. So basically all lists need to have all possible combinations of the values present in all the lists, if the combination isn't present in that list as standard then it's frequency (the second field) is 0.
Thanks for any help, please bear in mind this is the intersection of 40 different lists and thus needs to be fast and efficient. I'm not sure how best to do this...
EDIT: I also don't know all the 'values', I have just written 3 different values here (value1, value2, value3) for simplicity. In my project I have no idea what the values are or how many different ones there are (I know there are at least a few thousand)
EDIT 2: Here is some real input data, I don't have real output data but I will try and work it out:
data[0] = [['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP syslog_priority:Info', '39.7769'], ['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP', '39.7769'], ['destination_ip:10.32.0.100 destination_service:http destination_port:80 syslog_priority:Info', '39.7769'], ['destination_ip:10.32.0.100 destination_service:http destination_port:80', '39.7769'], ['destination_ip:10.32.0.100 destination_service:http protocol:TCP syslog_priority:Info', '39.7769']]

data[1] = [['syslog_priority:Info', '100'], ['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80 protocol:TCP', '43.8362'], ['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80', '43.8362'], ['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http protocol:TCP', '43.8362'], ['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http', '43.8362']]

data[2] = [['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info protocol:TCP', '43.9506'], ['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info', '43.9506'], ['destination_ip:10.32.0.100 destination_port:80 destination_service:http protocol:TCP', '43.9506'], ['destination_ip:10.32.0.100 destination_port:80 destination_service:http', '43.9506'], ['destination_ip:10.32.0.100 destination_port:80 syslog_priority:Info protocol:TCP', '43.9506']]

A: Sounds like you could use sets:
>>> {1, 2, 3, 4, 5} & {2, 3, 4, 5, 6, 7} & {3, 4, 5}
{3, 4, 5}

& is the intersection operator for sets. Get a set of a list (this will remove duplicate elements with set(mylist).
Edit: In the light of your comments, it seems what you need is some sort of union (the union operator being |), not an intersection.
Here is a function that does what you wanted in your comment for 2 lists of lists:
def function(first, second):
    first_set = {tuple(i) for i in first}
    second_set = {tuple(i) for i in second}
    return (first_set | {(i[0], 0) for i in second_set},
            second_set | {(i[0], 0) for i in first_set})

>>> a = [(1,60),(3,90)]
>>> b = [(2,30),(4,50)]
>>> x, y = function(a, b)
>>> print(x)
{(2, 0), (3, 90), (1, 60), (4, 0)}
>>> print(y)
{(3, 0), (4, 50), (1, 0), (2, 30)}

A: Well given your comments I would use sets as already suggested
first loop through your list to build a set of each possible string
possible_strings = set()
for row in mydata:
   for item in row:
       possible_string.add(item[0])

So possible_strings has all possible strings in your data
Now you need to inspect each row for a string, if it does not exist you need to append it to the row with a frequency of 0
my_new_data = []
for row in mydata:
    row_strings = set(item[0] for item in row)
    missing_strings = possible_strings - row_strings
    for item in list(missing_strings):
         new_item = []
         new_item.append(item)
         new_item.append(0)
         row.append(new_item)
     row.sort()
     my_new_data.append(row)

The reason I would use sets is that you do not have to do any lookup and the items are strings so they can be members of a set.  There are ways to speed this up (condense the code) but I like to lay things out so I can see clearly what I am doing.  Unless I made a typo (and I have already corrected 3) this code worked on my computer
Here are the unsorted results
newrow*************
['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP syslog_priority:Info', '39.7769']
['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP', '39.7769']
['destination_ip:10.32.0.100 destination_service:http destination_port:80 syslog_priority:Info', '39.7769']
['destination_ip:10.32.0.100 destination_service:http destination_port:80', '39.7769']
['destination_ip:10.32.0.100 destination_service:http protocol:TCP syslog_priority:Info', '39.7769']
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80', 0]
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http', 0]
['destination_ip:10.32.0.100 destination_port:80 syslog_priority:Info protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info', 0]
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80 protocol:TCP', 0]
['syslog_priority:Info', 0]
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http', 0]
newrow*************
['syslog_priority:Info', '100']
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80 protocol:TCP', '43.8362']
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80', '43.8362']
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http protocol:TCP', '43.8362']
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http', '43.8362']
['destination_ip:10.32.0.100 destination_port:80 syslog_priority:Info protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP syslog_priority:Info', 0]
['destination_ip:10.32.0.100 destination_service:http protocol:TCP syslog_priority:Info', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_port:80 destination_service:http', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80 syslog_priority:Info', 0]
newrow*************
['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info protocol:TCP', '43.9506']
['destination_ip:10.32.0.100 destination_port:80 destination_service:http syslog_priority:Info', '43.9506']
['destination_ip:10.32.0.100 destination_port:80 destination_service:http protocol:TCP', '43.9506']
['destination_ip:10.32.0.100 destination_port:80 destination_service:http', '43.9506']
['destination_ip:10.32.0.100 destination_port:80 syslog_priority:Info protocol:TCP', '43.9506']
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80', 0]
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80 protocol:TCP syslog_priority:Info', 0]
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http destination_port:80 protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_service:http protocol:TCP syslog_priority:Info', 0]
['syslog_priority:Info', 0]
['destination_ip:10.32.0.100 syslog_priority:Info destination_service:http protocol:TCP', 0]
['destination_ip:10.32.0.100 destination_service:http destination_port:80 syslog_priority:Info', 0]

A: It sounds like you want dictionaries, and then you want to compare the keys, which are lists of "values" as you have them, but not the dictionary values, which are frequencies. Restructuring your data as dictionaries isn't necessary, of course, but it might make more sense.
Now, for an actual answer: make a new list/dictionary just to put together one full list of all the keys/"lists of values". Then, go through a second time and add the elements that are missing to the lists that are missing them. The outer loops go through 40 times. The first outer loop is O(n*2), where n is the total number of unique keys, although I imagine the average case will be less than n*2. The second outer loop is O(n**2), as well.
I hope that's not too brute forcey. At least it's better than comparing data[n] to data[n+m] for n 0-40... That'd be 40**2 for the outer loops... which is still a constant, but, obviously a bigger one than 80.

A: Correct me if I'm wrong, but I think the best solution to this involves a dictionary for each desired output, and a master set of keys. A set will basically store every value without allowing for duplicates. With your above example I would do this:
master_set = set()
for current_list in list_of_lists:
    master_set |= [entry[0] for entry in current_list]

Where |= is effectively the union operator for sets.
Once you have that set, you're looking to construct a dictionary for each entry that either contains the relevant value, or a zero. First I would construct a dictionary, then I would just add results for absent items.
full_dictionary = {}
for entry in master_set:
    full_dictionary[entry] = [thing[1] for thing in current_list if thing[0] == entry]

And then just generate the full dictionary for each list you've got.
Alternately, if you have choice over how your data is coming in, or just want to restructure it reasonably I would suggest using a dictionary comprehension, which would just make this whole thing simpler:
new_dict = {value[0]: value[1] for value in current_list}

I'm also having a little trouble interpreting the question, but let me know if that's not accurate and I can revise it.


text:
Q: java...based on Collections import java.util.ArrayList;
import java.util.*;

class Employee1 implements Comparable<Employee1> {
    int empno;

    String name;
    Employee1(int i,String j) {
        empno=i;
        name=j;
    }

    public int compareTo(Employee1 e1) {
        Employee1 e2=this;
        Integer i1=e1.empno;
        Integer i2=e2.empno;
        return i1.compareTo(i2);
    }
}

public class Employee {
    public static void display(ArrayList<Employee1> i) {
        for(Employee1 o:i){
            System.out.println(o.empno);
        }
    }

    public static void main(String[] args) {
        ArrayList<Employee1> ob=new ArrayList<Employee1>();
        Employee1 e1=new Employee1(1001,"A");
        Employee1 e2=new Employee1(1002,"B");
        ob.add(e2);
        ob.add(e1);
        Collections.sort(ob);
        display(ob);
    }
}

The output should be 1001 1002 but instead the output is 1002 1001.
First I passed the e2 object with empno to the List and then
e1 with empno of 1001
Due to the compareTo method in Employee1 - e1.compareTo(e2); should be the same as 1001.compareTo(1002); So why are they showing in the wrong order?

A: change
  return i1.compareTo(i2);

to
  return -i1.compareTo(i2);

or
  return i2.compareTo(i1);

A: I think your code is just badly written.
Here's how the method should be coded:
public int compareTo(Employee1 other) {
    return this.empno.compareTo(other.empno);
}


text:
Q: Firebase .indexOn how it works? If I for example have:
users: {
    userId1: {
        email: "email1"
    },
    userId2: {
        email: "email2"
    }
}

If I want to figure out if a new certain email I want to add to my users tree exists or not.
I would expect the complexity to be linear to the amount of data in the users tree. Like O(n)?
If I have the rule:
"users": {
    ".indexOn": ["email"]
}

What is it Firebase is doing exactly? Does it turn into something like O(1)?


text:
Q: targetframeworks conflict in asp net core project I am trying to change target frameworks in csproj file from <TargetFrameworks>netcoreapp3.1</TargetFrameworks>
to <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> because I am trying reference to library that used net framework. After changing the program not compiling with message

"Severity Code    Description Project File    Line    Suppression State
  Error CS0234  The type or namespace name 'AspNetCore' does not exist in
  the namespace 'Microsoft' (are you missing an assembly reference?)"

What am I doing wrong?
enter image description here

A: ASP.NET Core 3.0 requires .NET Core 3.0 or higher. It will not run on (nor compile for) any version of the .NET Framework.
Likewise, ASP.NET Core 3.1 requires .NET Core 3.1 or higher.
You can find more details and links on the announcement.


text:
Q: Android game, options about storing user data I'm developing a little game for android and i'm at the point where i want to save data of the progress the user has made so far.
I read about sharedpreferences, SQLlite... i have used some XML parsers aswell but my question is, if i want this:

*

*Fast performance.

*Secure or encryptable.

I want to point out that the data to save is not very long, profile name, levels completed, faction selected...
Thanks in advance!

A: Any solution will be "fast enough" for loading/saving the data...  and any of them will be encryptable (as in they can all store string data).
SharedPreferences would probably be the simplest way to go.  Perhaps store your data as JSON, then store the entire JSON string in SharedPreferences.  Then you can easily add encryption to it later.


text:
Q: Ms Access create procedure to insert one row after inserting multiple rows I have 3 tables: purchase, purchaseDetails and supplierAccount. When purchase inserted and purchaseDetails are added, one record will be inserted to the supplierAccount based on the sum in purchaseDetails. How to create procedure to add to supplierAccount after inserting multiple rows not at every single row in purchaesDetails table

A: Well... with the lack of details, this questions could have multiple answers.
But one of the easiest ways to control this is to create a Form that adds the new "purchase" record that has a "Purchase Id" field to link to the other tables.
In this Purchase Form, you can add a subform that links to the "purchaseDetails" table.  You can then add as many records to the subform for each of your line items.  And each of these records will have a Purchase ID that links them back to the Header Purchase record.
Then when you are finished adding these "purchaseDetail" records, you can place a button on your Purchase Form called "Commit" (or something like that) which calls a "Supplier Account Summary" query.
You can then create the "Supplier Account Summary" query to sum up the multiple rows in the "purchaseDetails" table for the records with the current Purchase ID.
After doing so, you might want to create VBA code behind the button to set a "Lock" field so someone can't hit the button multiple times for the same Purchase ID.  This kind of VBA code can get complicated if you want to add more details after the first commit has been done.  You would have to undo a lot stuff and recommit.  Even though the VBA can get very complicated, it's all very do-able.
Anyway, I hope this answers your question.
If you are not using Forms, you just have to create and run the "Supplier Account Summary" query making sure you supply the correct Purchase ID.
Best of luck!


text:
Q: Diferencias entre use y require , require_once , include , include_once La pregunta viene a ser eso, que diferencia existen entre principalmente use en php y los demás, pero tampoco tengo muy clara la diferencia. Hasta donde yo llego es a esto :

*

*use, por lo que entiendo es una forma de invocar clases en php desde otra clase , cuando se trabaja con namespaces.

*require, llamas a un fichero en concreto que invocas su contenido, si no lo encuentra da un E_COMPILE_ERROR y para la ejecución del programa.

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR

PHP : require

*

*require_once, lo mismo de require, pero solo lo pide una vez.

*includees lo mismo que require.

*include_oncees lo mismo que require_once.
Si me lo podéis explicar la diferencias entre use y los demás lo agradecería, por si se me escapa algo.

A: Los espacios de nombre o namespaces en PHP son y cito de la documentación oficial

Los espacios de nombres de PHP proporcionan una manera para agrupar clases, interfaces, funciones y constantes relacionadas. Un ejemplo de la sintaxis de los espacios de nombres de PHP:

Ejemplo: Declaramos una clase con un namespace llamado App, es decir la clase Person esta declarada y ahora solo existe bajo el contexto de esta declaración
archivo: Person.php
<?php

namespace App;

class Person
{
    public function sayHi()
    {
        return "Hello World";
    }
}

Ahora si queremos utilizarla dentro de otro archivo, por medio por ejemplo de la instanciación hacemos lo siguiente
archivo: People.php
<?php

use App\Person as Usuario;

$nuevoUsuario = new Usuario();

echo $nuevoUsuario->sayHi();

Hacemos uso de use para invocar el nombre del namespace principal que engloba a Person que en este caso es App posterior con la contrabarra invocamos el nombre de la clase que deseamos obtener que es Person; opcionalmente podemos darle un alias a la invocación hecha por ejemplo Usuario.
Ya con lo anterior hecho podemos hacer el proceso de instanciación asignando al objeto $nuevoUsuario acceso a la clase Person con el alias Usuario
Ahora si ejecutamos este desde el navegador o la consola, obtendremos esto

C:\Users\user>php People.php PHP Warning:  include(Persons.php):
  failed to open stream: No such file or directory in
  C:\Users\user\People.php on line 3

Lo anterior ocurre precisamente por que necesitamos incluir o requerir dicho archivo; entonces hacemos lo siguiente
<?php

require_once 'Person.php';

use App\Person as Usuario;

$nuevoUsuario = new Usuario();

echo $nuevoUsuario->sayHi();

Y si ejecutamos desde consola o navegador veremos lo siguiente

Hello World

Otro ejemplo
Mencioné mas arriba que Person solo existe dentro del contexto del namespace App por lo que si ahora creamos otro archivo mas llamado Demo.php y le agregamos lo siguiente
<?php

require_once 'Person.php';

$nuevoObjeto = new Person();

echo $nuevoObjeto->sayHi();

¿Qué va a pasar si ejecutamos este código?
En teoría debería funcionar pues estamos creando una instancia de esa clase y aparte al inicio estamos requiriendo dicho archivo; sin embargo al ejecutar el resultado sería este:

PHP Fatal Error: Uncaught Error: Class Person Not Found

Lo anterior se debe a que aunque estemos invocando al archivo, nos hace falta hacer uso use del namespace que la contiene o engloba dentro de si mismo; por lo que al no hacerlo no estamos accediendo a dicho contenido; caso contrario si hacemos lo siguiente justo después del require_once el problema queda resuelto
use App\Person;

Cabe destacar que desde PHP 7.0 y superior puedes importar múltiples nombres de clases de este modo
use App\Person\{ People1, People2, People3 };

Es decir dentro de la misma línea del use puedes mandar llamar entre llaves todos los nombres de clases que estan bajo el mismo namespace en este caso Person
Como punto final te comento que existe una práctica llamada la autocarga de clases a través de PSR-4 te dejo un enlace para que consultes
Fuentes:

*

*namespaces en PHP

*psr-4

*namespaces agrupados


text:
Q: How can restrict a user from accessing the admin panel in django? I have created a web app but I want to prevent a user from accessing the admin panel in Django web app.The user will only be allow to access the custom created site but not Django's default admin site.

A: I don't think I understood what is your issue really well, but I'm going to list some things related to what you asked.
1 - If you want to log in as the admin user, and as another user in the site, that is not possible, if you are logged in as the admin in the admin panel you are going to be logged in as the admin in the site. So if you want to log in as a different user in the site, just logout of the admin panel, and login as the user that you want to use.
2 - If you want to separate the project in two different folders, one for the admin part, and one for the rest of the application, you can create an app using the command: django-admin startapp name_of_the_app. This will create a folder with some default python files that you can use to separate the project.
Hope I've helped, if I wasn't able to solve your issue, feel free to contact me.


text:
Q: Break out of a qx.data.Array forEach loop? Is there a way to break out of the Qooxdoo qx.data.Array forEach loop?
For example,
 myarray.forEach(function(obj){
   if(obj.match(/ra/i)){
       //break out of the loop
   }
 }

A: No, thats not possible. If you need that, you could think about using a regular for loop and break on the condition.

A: Not sure about the version that existed in 2013 but currently there is the array method some. If you return a Boolean true from the function passed in, the loop will terminate.
myarray.some(function(obj) {
    if(obj.match(/ra/i))
    {
        // do something
        return true;
    }
}, this);


text:
Q: Error: no suitable constructor found for ArrayAdapter(activity, int, int, string) I have been wanted to display multiple data retrieve in a list view. However when i used array adapter, i have been facing this problem. How should i solve it? This is the class where i get my data and i store it in an array list. The array list will later be call in another class to put it in array adapter.
public class connect2 extends AsyncTask<String, Void, String>{
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
View view;
Activity activity;
public static final String SEARCH = "product_img1";
ArrayList<String> list = new ArrayList<String>();

ContactObjects co = new ContactObjects();

Bitmap bitmap;

public connect2(Activity activity, View v) {
    this.activity = activity;
    view = v;
}

String convertStreamToString(InputStream is) {
    try {
        return new java.util.Scanner(is).useDelimiter("\\A").next();
    } catch (java.util.NoSuchElementException e) {
        return "";
    }
}
protected String doInBackground(String... arg0) {
    String ipAddress = "http://192.168.43.214/apexStore2/";
    try {
        URL url = new URL(ipAddress +"image1.php");
        String urlParameters =
                URLEncoder.encode("cat_id", "UTF-8") + "=" +
 URLEncoder.encode(arg0[0], "UTF-8") + "&" +
                      URLEncoder.encode("product_img1", "UTF-8") + "=" +
 URLEncoder.encode("???", "UTF-8");

        HttpURLConnection connection = (HttpURLConnection)
 url.openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" +
                Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        //System.out.println(response.toString());

        JSONObject mainObject = new JSONObject(response.toString());
        JSONArray uniObject = mainObject.getJSONArray("result");
        for(int i = 0; i < uniObject.length(); i++) {
            JSONObject rowObject = uniObject.getJSONObject(i);
            //EventObject co = new EventObject();
            co.img1 = ipAddress +"img/products/" +
  rowObject.getString("product_img1");
            //mContentItems.add(co);
            System.out.println("hi" +co.title);
            list.add(co.img1);
        }

        //To further break down JSON
        //JSONObject oneObject = mainObject.getJSONObject("1");
        //String id = oneObject.getJSONObject("id");
        try{

        }
        finally{
            connection.disconnect();
        }
    } catch (Exception e){
        System.out.println(e.toString());
    }
    return "";
}

protected void onPreExecute(){

}

@Override
protected void onPostExecute(String result){
    Intent intent = new Intent(view.getContext(), CatalogActivity.class);
    intent.putExtra(SEARCH, list);
    activity.startActivity(intent);
}

private class LoadImage extends AsyncTask<String, String, Bitmap> {
    ImageView img;
    public LoadImage(ImageView img){
        this.img = img;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
    protected Bitmap doInBackground(String... args) {
        try {
            bitmap = BitmapFactory.decodeStream((InputStream) new
  URL(args[0]).getContent());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    protected void onPostExecute(Bitmap image) {

        if(image != null){
            img.setImageBitmap(image);
        }else{
        }
    }
}
}

This is the class where i call the data and put it in array adapter.
public class CatalogActivity extends Activity {
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.catalog);

    // Create the list
    ListView listViewCatalog = (ListView)
findViewById(R.id.ListViewCatalog);
    setContentView(R.layout.item);
    new connect2 (this,
this.findViewById(android.R.id.content)).execute("3");
    Intent intent = getIntent();
    String search = intent.getStringExtra(connect2.SEARCH);
    adapter = new ArrayAdapter<String>(this, R.layout.item,
R.id.ImageViewItem, search);
    listViewCatalog.setAdapter(adapter);
}
}

A: The problem seems to be that you're using an ImageView's resource ID while ArrayAdapter takes only TextView as resource ID.
EDIT- Since your string is nothing but text, the container can't be an ImageView.
Another EDIT- You need to pass a List of strings as a parameter as the 4th parameter. Add this as the 4th parameter instead:- new String[]{search}


text:
Q: How to testing the equality of variables in Assembler? I have problem with testing the equality of variables. In this case it works, it skip this "do something", it go to next like i want:
b dw 5

mov eax, [b]
 cmp eax, 5
 je next
 ;do something
 next:

But , if i set for example 6 instead of 5 it won't skip "do something":
b dw 6

mov eax, [b]
 cmp eax, 6
 je next
 ;do something
 next:

(Using NASM)

A: The size of your variable relative to how you're using it is wrong:
b dw 6

mov eax, [b]
cmp eax, 6

When you use dw you declare a word-sized variable, which is 16 bits on x86. The eax register is 32 bits (a doubleword), so with mov eax,[b] you're loading the word at b and the word direcly following b in memory, whatever that may contain.
Either change your declaration of b to b dd 6, or use a zero-extending mov (movzx eax, word [b]).

A: I found the error. I just jump over "b dd 6" and it work


text:
Q: When is a string built / created / compiled? When will these string get their value and should they all produce the same value?
class StringFactory{
    companion object{
        val str1 = App.shared.userSettings.getString(key, "")

        val str2: String
        get(){
            return App.shared.userSettings.getString(key, "")
        }

        val str3 = getUserKey()
        fun getUserKey():String {
            return App.shared.userSettings.getString(key, "")
        }
    }
}

When will these change their value?
When the code compiles, when I read them or at some other time?

A: The str1 and str3 properties are assigned on creation of StringFactory.Companion and never change their value.
In str2 the property will get the value from userSettings anytime you access it. There's no field for storing that value. It basically behaves the same as getUserKey().


text:
Q: Peculiar behavior of Classes in Python I'm learning Python, but have no OOP experience. I'm entering the following lines in IDLE (Python 3.3), and the behavior of the objects is confusing me:
>>> class IBAN:
    ISOcode = '  '
    checkDigits = '00'
    class CCC:
        bankCode = '0000'
        branchCode = '0000'
        checkBank = '0'
        checkAccount = '0'
        account = '0000000000'

>>> >>> numberOne = IBAN()
>>> numberOne.CCC
<class '__main__.IBAN.CCC'>
>>> numberOne.CCC.bankCode
'0000'
>>> numberOne.ISOcode = 'ES'
>>> IBAN.ISOcode
'  '
>>> numberOne.ISOcode
'ES'
>>> IBAN.ISOcode = 'FR'
>>> numberOne.ISOcode
'ES'
>>> IBAN.ISOcode = 'FR'
>>> IBAN.ISOcode
'FR'
>>> numberTwo = IBAN()
>>> numberTwo.ISOcode
'FR'
>>> IBAN.ISOcode = 'IT'
>>> IBAN.ISOcode
'IT'
>>> numberOne.ISOcode
'ES'
>>> numberTwo.ISOcode
'IT'
>>> IBAN.ISOcode is numberTwo.ISOcode
True
>>>

Why is the ISOcode attribute of object numberTwo the same as the ISOcode of IBAN, but not the same as the ISOcode of objectnumberOne?
I expected something like this:
>>> numberOne.ISOcode
'ES'
>>> numberTwo.ISOcode
'FR'

This, however, doesn't match my results.
I found a similar question on StackOverflow, that made me think the results should be:
>>> numberOne.ISOcode
'IT'
>>> numberTwo.ISOcode
'IT'

But that doesn't match my results either.
Can anybody explain or link to resources that explain the behavior of Classes in Python? I tried to study the Python Tutorial and "Unifying types and classes in Python 2.2" by Guido van Rossum, but I wasn't able to understand what they were saying.
Thank you!

A: The class is a different object than instances of the class.  Classes have attributes, and instances have attributes.  Every time you try to access an attribute of an instance, if the instance does not have the attribute, it is looked up on the class.  If you set an attribute on an instance, it is always set on the instance, even if that means it shadows an attribute of the same name on the class.
In your class IBAN, you defined an attribute ISOcode on the class.  When you do numberOne.ISOcode = 'ES', you set a new attribute on the instance.  You have decoupled the value of numberOne.ISOcode from the value of IBAN.ISOcode.  But any new instances you create (like numberTwo) will still not have their own instance ISOcode.  When you then set IBAN.ISOcode, you are changing the class attribute.
You can think of the class attribute as like a "default".  When you do obj.attr, if obj does not have its own attribute attr, it takes the value that the class has at that moment.  If you change the value of class's attribute, you change the default; if you later try to access the attribute on an instance that doesn't have its own attribute, they will see the new default that you created.
Here is a somewhat more streamlined example:
>>> class Foo(object):
...     attr = "Something"
>>> one = Foo()
>>> two = Foo()

At first, all have the same value, because I didn't specify any instance-specific values, so one and two both get their value from the class.
>>> Foo.attr
'Something'
>>> one.attr
'Something'
>>> two.attr
'Something'

Now I will set a new value just for one.  This does not affect Foo, and two is still gettings its value from Foo, so two is also not affected.
>>> one.attr = "This is only for #1"
>>> Foo.attr
'Something'
>>> one.attr
'This is only for #1'
>>> two.attr
'Something'

Now I will set a new value on the class Foo.  This doesn't affect one, because one has its own value.  But since two doesn't have its own value, it is getting its value from the class, and since I changed the class's value, this changes what value I get from two:
>>> Foo.attr = "This is the class value"
>>> Foo.attr
'This is the class value'
>>> one.attr
'This is only for #1'
>>> two.attr
'This is the class value'

The thing to remember is that every attribute lookup is always dynamically computed right when you do it.  Creating an instance does not automatically copy class attributes from the class to the instance.  When you access an attribute on an instance, the instances says to itself "Do I have my own attribute with this name?  If so, return that value.  If not, return the class's value."  It asks itself this every time you try to access an attribute; there is no moment at which the instance becomes "independent" of the class.

A: ISOcode as defined in your example is what's known as a class attribute, not an instance attribute
You should set self.ISOcode inside your class's __init__ method to make it unique to each instance. Otherwise the attribute is stored in the class.
class IBAN:
    def __init__(self):
        self.ISOcode = '  '

A: You are doing some confusing name shadowing by setting instance attributes over class attributes.
>>> class A():
    stuff = ''

>>> a = A()
>>> a.stuff
''
>>> a.stuff = 'thing' # sets an instance attribute
>>> a.stuff
'thing'
>>> a.__class__.stuff
''
>>> a.__class__.stuff = 'blah'
>>> a.stuff # instance attributes are checked FIRST
'thing'
>>> aa = A()
>>> aa.stuff
'blah'

Basically, don't do this.  If you intend for attributes to be instance attributes, set them up in __init__.

A: Python has class attributes and instance attributes. When you assign a value like
x.ISOcode = 'b'

It creates a member attribute for the instance. When you access an attribute in an object first it searches in member attributes, if not found it searches in class attributes.
Consider the following example
class IBAN(object):
    ISOcode = 'a'

print IBAN.ISOcode // outputs a

x = new IBAN()
print x.ISOcode // outputs "a"
x.ISOcode = 'b' // creates a member variable for instance x instead of modifying class variable

print IBAN.ISOcode // outputs "a"
print x.ISOcode // outputs "b"
print x.__class__.ISOcode // outputs "a"

y = new IBAN()
print y.ISOcode // outputs "a"

IBAN.ISOcode = 'c'

print IBAN.ISOcode // outputs "c"
print x.ISOcode // outputs "b" because member variable is set
print x.__class__.ISOcode // outputs "c"
print y.ISOcode // outputs "c" because it still uses class variable. no instance variable set for this instance

A: The behavior you're seeing is because of the fallback behavior of member access on python objects. numberOne is an instance of the IBAN class, and when you try to access a member of it, such as with numberOne.ISOCode, it will check to see if the object itself has a member named ISOCode. If it does, it will use that. If not, then it will fallback to the object's type, and check to see if the type has a member of that name, and use that.
However, when you set a member on an object, for instance when numberOne.ISOCode = 'ES', it doesn't do the fallback behavior, it either uses the existing member of that object, or if there is no such member it will create it.
It probably doesn't matter because you've never done OOP before, but Python does things a bit different than other language. You don't declare instance members inside a python class, so when you set ISOCode directly under the IBAN class, you're making it a member of the IBAN class object, not individual instances of that class. If you want all instances of the class to have a field, assign it in the __init__ constructor function for that class. For instance:
#!/bin/python

class IBAN:
    def __init__(self):
        self.ISOCode = '   '

This will ensure that when an instance is created, it will have it's own ISOCode member.


text:
Q: Runtime error when creating a constructor for my viewModel I have designed a simple UI that displays connection strings read from a web.config file.  I have followed the MVVM light framework fairly close and when I instantiate my ConnectionStringViewModel, I get the error.  If I take it out, things work but then I can't reach the data I need to display.  Here is some code:
Connection String ViewModel:
public string SqlConnectionString
{
    get { return _sqlConnString; }
    set
    {
        if (_sqlConnString == value)
            return;
        _sqlConnString = value;
        RaisePropertyChanged(SqlConnString);
    }
}

public ConnectionStringViewModel(*IValidationService validationService*)
{
    _validationService = validationService;
    _validationService.SqlConnectionStringService(
        (item, error) =>
        {
            if (error != null)
            {
                // Report error here
                return;
            }
            SqlConnectionString = item.ConnString;
        });
}

ValidationService:
public class ValidationService : IValidationService
{
    private readonly Configuration _webConfig = WebConfigurationManager.OpenWebConfiguration(@"C:\Source\web.config");

    public void SqlConnectionStringService(Action<ConnectionString, Exception> callback)
    {
        var connString = new ConnectionString(_webConfig.ConnectionStrings.ConnectionStrings["SomeConnectionString"].ConnectionString);
        callback(connString, null);
    }
}

IValidationService:
public interface IValidationService
{
    void SqlConnectionStringService(Action<ConnectionString, Exception> callback);
}

A: With DI you want to avoid executing methods in your constructors. This is because it's possible the DI bootstrapper hasn't finished mapping yet and could cause NullReference exceptions.
You don't say what the exception is so hard to say.


text:
Q: Getting feature coordinates from dynamically loaded layer using OpenLayers? i want to load the coordinates of a point that is stored inside a vector layer and the vector layer is stored inside a layergroup.
I do load the vector layers dynamically to the layergroup "Runs". So i can't just do:
var source = layer.getSource();
source.forEachFeature(function(feature){
  var coord = feature.getGeometry().getCoordinates();
  // ...
});

At the moment it is totally unclear how to filter for the layer and then for the point by name to get the coordinates.
So what i have available is the layer name, layergroup name and the feature name. I tried different approaches like:
My layergroup is called 'runs' so to get the layers inside runs i did:
i tried also:
runs.getLayers().getSource();

But i get:

Uncaught TypeError: runs.getLayers(...).getSource is not a function.

I'm having a hard time to get my head around this.

So i made it a little furhter:
      function getActiveLayer(layerName,picID) {
            // get layerGroups
            var layers = map.getLayers();
            var length = layers.getLength(), l;
            for (var i = 0; i < length; i++) {
                l = layers.item(i);
                var lt = l.get('title');
                // check for layers within groups
                if (lt === 'Runs') { // Title of Group
                  // get layers from Runs
                  var layers = l.getLayers();
                  //get length
                  var length = layers.getLength(), l;
                  if (length > 0) {
                    for (var i = 0; i < length; i++) {

                      l = layers.item(i);
                      var lt = l.get('title');
                      // check for Layer Title
                      if (lt === layerName) { // Title if Layer
                        var innerLayers = l.getSource().getFeatureById(picID).getGeometry().getCoordinates();
                        return innerLayers;
                      }
                    }
            }
                }
            }

      };

With this function i get the LayerGroup list that i can parse and identify the Group "Runs" i want. Until this point it is working.
The Problem starts at the second Point. The layers.getLength() is always zero for the layers that are inside the "Runs" Group.

The Upper one is the getLayers from map.
The lower one is the getLauers from "Runs".
Why is length 0 if there are Layers inside the array?
EDIT
      function getActiveLayer(layerName,picID) {
        var layers = map.getLayers();
        console.log(layers);
            var length = layers.getLength(), l;
            console.log(length);
            for (var i = 0; i < length; i++) {
                l = layers.item(i);
                var lt = l.get('title');
                // check for layers within groups
                if (lt === 'Runs') { // Title of Group
                  var layers = l.getLayers().getArray();
                  console.log(layers);
                  //if (length > 0) {
                    for (var i = 0; i < 99; i++) {

                      l = layers[i];
                      console.log(l);
                      console.log(layerName);
                      var lt = l.get('title');
                      console.log(lt);
                      // check for Layer Title
                      if (lt === layerName) { // Title if Layer
                        var innerLayers = l.getSource().getFeatureById(picID).getGeometry().getCoordinates();
                        return innerLayers;
                      }
                    }
                }
            }

      };

This function works. The only Problem i have that i can not figure out how the get the length of the object to config the second for loop.

A: Just in case someone else is starting with openlayes. This is a working function i came up with:
 function setActivePicMarker(layerName,layerTitle, featureName) {
   var layers = map.getLayers();
   var length = layers.getLength();
   for (var i = 0; i < length; i++) {
       l = layers.item(i);
       var lt = l.get('title');

       // check for layers within groups
       if (lt === layerTitle) { // Title of Group
         var layers = l.getLayers().getArray();
         var length = l.getLayers().getArray().length;

           // loop over layers
           for (var i = 0; i < length; i++) {
             l = layers[i];
             var lt = l.get('title');

             // check for Layer Title
             if (lt === layerName) { // Title if Layer
               var coords = l.getSource().forEachFeature(function (feature){

                    // check for feature and get coordinates
                    if (feature.get('Name') == featureName{
                       var Coords = feature.getGeometry().getCoordinates();
                       console.log(Coords);
                    }
               })
               return Coords;
             }
           }
       }
   }
}; // end

The function searches for a specified feature inside a specified layer inside a specified layer group and returns the features coordinates.

A: I was spacing out at work today... So here is a way of doing what you described above. There are for sure other ways of doing this.
// OpenLayers V4.6.5
// demo data
const feature = new ol.Feature({
  geometry: new ol.geom.Point([3,5]),
  name: 'myFeatureName'
});
feature.setId(5);

const map = new ol.Map({
  view: new ol.View({}),
  layers: [
    new ol.layer.Group({
      title: 'Runs',
      layers: [
        new ol.layer.Vector({
          title: 'layerName',
          source: new ol.source.Vector({
            features: [feature]
          })
        })
      ]
    })
  ]
});

//// Return data by Feature ID
// Internal function for returning coordinates from a layer, from a feature by featureID
const byFeatureId = (layer, layerName, picID) => {
  if(layer.get('title') === layerName) {
    return layer.getSource().getFeatureById(picID).getGeometry().getCoordinates();
  }
};

// Public function for returning coordinates from a feature by featureID
// layerName: string, the name of the layer that will be querried
// picID: string/number, the featureID of the feature that will be querried
// groupLayerName: string, 'Runs'
function getCoordinatesByFeatureID(layerName, picID, groupLayerName) {
  var result = [];

  map.getLayers().forEach(groupLayer => {
    if (groupLayer.get('title') === groupLayerName) {
      groupLayer.getLayers().getArray().forEach(innerLayer => {
        result = byFeatureId(innerLayer, layerName, picID);
      });
    }
  });

  return result;
}

console.log('coodinatesById', getCoordinatesByFeatureID('layerName', 5, 'Runs'));

//// Return data by Feature NAME
// Internal function for returning coordinates from a layer, from a feature by featureName
const byFeatureName = (layer, layerName, featureName) => {
  var result = new ol.Feature();

  if(layer.get('title') === layerName) {
    layer.getSource().getFeatures().forEach(feature => {
      if (feature.get('name') === featureName) {
        result = feature.getGeometry().getCoordinates();
      }
    });
  }

  return result;
};

// Public function for returning coordinates from a feature by featureName
// layerName: string, the name of the layer that will be querried
// featureName: string, the featureName of the feature that will be querried
// groupLayerName: string, 'Runs'
function getCoordinatesByFeatureName(layerName, featureName, groupLayerName) {
  var coordinates = [];

  map.getLayers().forEach(groupLayer => {
    if (groupLayer.get('title') === groupLayerName) {
      groupLayer.getLayers().getArray().forEach(innerLayer => {
        coordinates = byFeatureName(innerLayer, layerName, featureName);
      });
    }
  });

  return coordinates;
}

console.log('coodinatesByName', getCoordinatesByFeatureName('layerName', 'myFeatureName', 'Runs'));


text:
Q: Allow user to configure Tampermonkey @match value for domain, without editing the script I'd like to make a Tampermonkey script that's currently in a secret gist publicly available. However, the script needs to be restricted to run within a particular site of interest to the user, but the domain name cannot be known in advance. And leaving in the domain name I'm currently using means I can't make the gist public. But taking it out means any users who want to use the script have to manually edit the @match header for their use case.
Are there any good patterns for this? I'm reluctant to make the script run on just any site. Anyone considering a Tampermonkey script who sees that it does not have a @match (or @include) header is less likely to even review the code to see if it is useful.

A: As far as I know, there is no user friendly API for parametrizing userscripts. Your users simple need to replace the domain name. For making your script public, just use www.example.net which is a designated example domain.
If you want to help your users altering the domain, the best way would be to make a website for it (easily on github pages from the script's repository). Then write a simple JS code that produces script based on what domain the user enters in some form.


text:
Q: Is an injective morphism from a Lie group to itself surjective? I have a question about Lie groups. Let $G$ be a finite dimensional (real or complex) Lie group and $f:G \rightarrow G$ an homomorphism of Lie groups. Edit : in the view of some counter-examples let's also suppose $G$ connected.
Q1 : Suppose that $f$ is injective, is it then surjective ?
Here are my attempts so far to adress this question. It is known that an injective Lie homomorphism is an immersion so the differential $df_g$ of $f$ in any point $g\in G$ is injective. For reasons of dimension, $df_g$ is then bijective. Thus, by the inversion theorem, $f$ is a diffeormorphism from $G$ to $f(G)\leq G$.
Moreover, it is also well known that $f(G) \simeq G/Ker(f) \simeq G/\lbrace e \rbrace \simeq G$. So we have a subgroup $f(G)$ of $G$ isomorphic to $G$. Then, we can reduce the question to :
Q2 : Let $H$ be a Lie subgroup of $G$. If $H \simeq G$, do we have $H=G$ ?
Now, maybe we can progress with some topological argument. Typically, I think of the fundamental group, that is useful to link the classification of Lie groups to the classification of Lie algebras. As $H$ is diffeomorphic to $G$, we have $\pi(H)=\pi(G)$. Hence a third question :
Q3 : Let $H$ be a Lie subgroup of $G$. If $Lie(H)=Lie(G)$ and $\pi(H)=\pi(G)$, do we have $H=G$ ?
After that, I have to admit that I don't have ideas about where to look. So if someone as an answer, a hint or a reference, that would be awesome.
In addition, I have a few "bonus" questions around this subject :
B1 : If the answer to the questions above is no, what is a counterexample ? Is there a simple hypothesis we can add so that it becomes true ?
B2 : What are the possible generalisations to all this discussion ? For example with infinite dimensional Lie groups ? With topological groups ?
B3 : In the other way around, if $f\in Hom(G,G)$ is surjective, is it injective ?
Thanks a lot to all who have read till the end and to the ones who will answer.

A: For the sake of having an answer, and to summarize some discussion in both the question and the comments:
If $G$ is connected and $f : G \to G$ is injective, then it is an immersion, hence a local diffeomorphism, hence open. But the only open subgroup of a connected topological group $G$ is $G$ itself, since any open neighborhood of the identity in $G$ generates $G$. Hence $f$ is surjective.
So with connectivity, the answers to Q1, Q2, Q3 are all yes, and in Q3 the extra hypothesis on fundamental groups is unnecessary.
The answer to a slightly different version of Q3 is no: you might ask whether two connected Lie groups are isomorphic if their Lie algebras and fundamental groups are isomorphic. As a counterexample, $SL_2(\mathbb{R})$ has fundamental group $\mathbb{Z}$, and hence it admits a unique connected double cover whose fundamental group is also $\mathbb{Z}$ (and which also has Lie algebra $\mathfrak{sl}_2(\mathbb{R})$), the metaplectic group $Mp_2(\mathbb{R})$. These two Lie groups are not isomorphic: the metaplectic group has no faithful finite-dimensional representations.
It's a bit trickier to find a compact counterexample, but it can still be done: $SU(2) \times SU(2)$ double covers three Lie groups, namely $SU(2) \times SO(3), SO(3) \times SU(2)$, and $SO(4)$. All of these have the same Lie algebra (namely $\mathfrak{su}(2) \times \mathfrak{su}(2)$) and fundamental group (namely $\mathbb{Z}_2$) but $SO(4)$ is not isomorphic to $SU(2) \times SO(3)$: their representation theory is different.
The answer to another slightly different version of Q3 is yes: you might ask whether a map $f : G \to H$ of connected Lie groups is an isomorphism if it induces an isomorphism on Lie algebras and on $\pi_1$. This is true and follows from covering space theory, since the first hypothesis implies that $f$ induces an isomorphism on universal covers.


text:
Q: Armstrong Number Error Here's a code I wrote for Oracle PL/SQL Armstrong Number
declare
num number;
sum number;
temp number;
val number;
begin
num:=#
temp:=num;
while temp<>0 loop
val:=trunc(temp mod 10);
sum:=sum +(val*val*val);
temp:=temp/10;
end loop;
if sum=num then
dbms_output.put_line('number is Armstrong');
else
dbms_output.put_line('number is not Armstrong');
end if;
end;

I get the following error:

ERROR at line 11: ORA-06550: line 11, column 10: PLS-00103:
  Encountered the symbol "+" when expecting one of the following: ( The
  symbol "(" was substituted for "+" to continue. ORA-06550: line 11,
  column 24: PLS-00103: Encountered the symbol ";" when expecting one of
  the following: ) * & - + / at mod remainder rem  ||
  year day The symbol ")" was substituted for ";" to continue.
  ORA-06550: line 14, column 7: PLS-00103: Encountered the symbol "="
  when expecting one of the following: (

What have I done wrong?
Thanks.

A: sum is a reserved word in most databases (including Oracle). It's an aggregate function, which is why Oracle's telling you that it's expecting a left parenthesis. Change the name of that variable and the block will work.


text:
Q: Invoke-Command on remote target with specific Powershell Version possible? I'm trying to write a small PowerShell script which will use a specific PowerShell module on a remote machine to do some things. This module requires the use of a PowerShell Version >= to work.
I tried using Invoke-Command to execute the script on the remote machine, but I can't figure out how to use the latest PowerShell Version available on the remote target:
$SessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$Session = New-PSSession -ComputerName "TARGETHOST" -Authentication Negotiate -SessionOption $SessionOption
Invoke-Command -Session $Session -ScriptBlock {
    (Get-Host).Version
}

Will result in Version 1 used. After some tinkering I found a way to do what I want:
$SessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$Session = New-PSSession -ComputerName "TARGETHOST" -Authentication Negotiate -SessionOption $SessionOption
Invoke-Command -Session $Session -ScriptBlock{
    C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe -Command {
        (Get-Host).Version
    }
}

But I don't think this is a nice solution, because I'm spawning another PS session inside the remote session. Now I'm wondering if there are nicer ways to accomplish the same thing.

A: Back when PowerShell was created, the original idea was that the version would be differentiated by script extension.
That idea was not implemented to preserve backward compatibility and to avoid confusion, so now only have .ps1 files (and not .ps2, .ps3, etc.).
As backwards compatibility was preserved, they didn't need to keep old versions of powershell around either, and so PowerShell v2 installed into the C:\Windows\System32\WindowsPowerShell\v1.0 directory... over the top of the original v1.0 and keeping the same directory name.
So even though you think you are running the PS v1 from that directory, you are actually running the latest Powershell version. You can confirm this by running powershell.exe from that location and checking version with $PSVersionTable
In my case:
PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.15063.608
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.608
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

A: I had the same issue with my Invoke-Command script, it would return version 1.0.0.0 when checking with (Get-Host).Version as well as $host.version. However $PSVersionTable.PSVersion successfully output 5.1. So I modified the script that is asking for the version to use $PSVersionTable.PSVersion and now it runs without complaining.


text:
Q: mysql insert code produced following error: Not all parameters were used in the SQL statement Below is my code for loading data in a mysql table (7 column of information):
#!/usr/bin/env python
import mysql.connector, csv, sys

csv.field_size_limit(sys.maxsize)

cnx = mysql.connector.connect(user='testuser', password= 'testuser', database='database')

cursor = cnx.cursor()

table=csv.reader(file("logs.txt"), delimiter='\t')

for row in table:

      cursor.execute("INSERT INTO first_table (column1, column2, column3, column4 , column5, column6, column7) VALUES (%s, %s, %s, %s, %s, %s, %s)", row)

cnx.commit()

cnx.close()

Below is truncated content of what logs.txt file consist of, 7 columns (tab-delimited) and the last column (mouse_phene_id) may be empty or has single or multiple items delimited by space:
human_gene_symbol       entrez_id       homolog_id      hgnc_assoc      mouse_gene_symbol       mouse_mgi_id    mouse_phene_id
A1BG      1     11167   yes     A1bg      MGI:2152878
A1CF      29974 16363   yes     A1cf      MGI:1917115     MP:0005387 MP:0005386 MP:0005388 MP:0005385 MP:0002873 MP:0010768 MP:0005369 MP:0005376 MP:0005384 MP:0005378
A2M       2     37248   yes     A2m       MGI:2449119
A3GALT2   127550        16326   yes     A3galt2   MGI:2685279
A4GALT    53947 9690    yes     A4galt    MGI:3512453     MP:0005386 MP:0010768 MP:0005376
A4GNT     51146 87446   yes     A4gnt     MGI:2143261     MP:0005384 MP:0002006 MP:0005385 MP:0005381 MP:0005387
AAAS      8086  9232    yes     Aaas      MGI:2443767     MP:0005389 MP:0005386 MP:0005378
AACS      65985 11322   yes     Aacs      MGI:1926144
AADAC     13    37436   yes     Aadac     MGI:1915008

I get the following error and since this is a common error, I tried everything that was posted on stackoverflow related to this error and still unfixed and stuck:
Traceback (most recent call last):
  File "insert_mysql.py", line 23, in <module>
    cursor.execute("INSERT INTO first_table (column1, column2, column3, column4 , column5, column6, column7) VALUES (%s, %s, %s, %s, %s, %s, %s)", row)
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 551, in execute "Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

first_table:

Greatly appreciate any help, advice. Thank you in advance.

A: The error you are seeing is likely being caused by a row in the logs.txt file which does not have the same number of items (7) which your insert prepared statement is expecting.  The error

Not all parameters were used in the SQL statement

means that you had one or more positional parameters which could not be assigned values, and hence were not used.
I can make two suggestions about where in the file the problem might be.  First, you log file may have one or more header lines, which might not have the same number of columns or types of values the script expects.  You may skip any number of initial lines via this:
skip_first_line = next(table)
skip_second_line = next(table)
# etc.

In other words, just call next() to consume any number of initial lines in the log file which do not contain the actual data you want to insert.
If not, then perhaps the problematic line is somewhere in the middle of the file.  You can try printing each row in your script, to see where it dies:
for row in table:
    cursor.execute("INSERT INTO first_table (column1, column2, column3, column4 , column5, column6, column7) VALUES (%s, %s, %s, %s, %s, %s, %s)", row)
    print row


text:
Q: Javascript Top Down Movement Issues I have a question about player movement in a top down game.
The player should be able to smoothly move up, down, left, right, and diagonally. The code I have written works at first, but when you hold down two keys for a long time to make the player move diagonally it immediately transitions from smooth to jittery after about one second of holding down both keys.
Here is the code: I would greatly appreciate any help. Thanks!
gameCanvas = document.getElementById("gameCanvas");
gameCanvasContext = gameCanvas.getContext("2d");

gameCanvas.width = window.innerWidth;
gameCanvas.height = window.innerHeight;

window.addEventListener("keydown", handleKeyAction);
window.addEventListener("keyup", handleKeyAction);

playerPosition = {xPosition: gameCanvas.width / 2, yPosition: gameCanvas.height / 2};

var keys = [];

function handleKeyAction(event) {
  if(event.type === "keydown" && !keys.includes(event.keyCode)) {
    keys.push(event.keyCode);
  } else {
    for(var index = 0; index < keys.length; index++) {
      if(keys[index] === event.keyCode) {
        keys.splice(index, 1);
        break;
      }
    }
  }
}

function movePlayer() {
  if(keys.includes(87)) {
    playerPosition.yPosition -= 5;
  } if(keys.includes(65)) {
    playerPosition.xPosition -= 5;
  } if(keys.includes(83)) {
    playerPosition.yPosition += 5;
  } if(keys.includes(68)) {
    playerPosition.xPosition += 5;
  }
}

function drawPlayer() {
  gameCanvasContext.beginPath();
  gameCanvasContext.fillStyle = "#000000";
  gameCanvasContext.arc(playerPosition.xPosition, playerPosition.yPosition, 15, 0, Math.PI * 2);
  gameCanvasContext.fill();
  gameCanvasContext.closePath();
}

function animate() {
  gameCanvasContext.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
  movePlayer();
  drawPlayer();
  requestAnimationFrame(animate);
}

animate();

A: Because your else in handleKeyAction. It fired the else even in situations that should not.
Try this (JSFiddle):
function handleKeyAction(event) {
  if(event.type === "keydown" && !keys.includes(event.keyCode)) {
    keys.push(event.keyCode);
  }
  if(event.type === "keyup") {
    for(var index = 0; index < keys.length; index++) {
      if(keys[index] === event.keyCode) {
        keys.splice(index, 1);
        break;
      }
    }
  }
}


text:
Q: How should I clone listView.item of one form to listView of another form? mainform main = new mainform();
            main.ShowDialog();
            ListViewItem itemClone;
            ListView.ListViewItemCollection coll = main.listView2.Items;
            foreach (ListViewItem item in coll)
            {
                itemClone = item.Clone() as ListViewItem;
                main.listView2.Items.Remove(item);
                listView2.Items.Add(itemClone);
            }

how should I do this one??
the codes in not cloning my listView to another listView of another form?

A: You dont get the value from your mainform Listview because you declare the mainform as new instance.
Put all this code to your mainform.Listview2 and rather declare a new instance of your destination listview.


text:
Q: How to find the uncommon rows between two Pyspark DataFrames? I have 2 pyspark dataframes each containing 1 column. I want to find the uncommon elements between these 2 dataframes and put them in a seperate dataframe.
Kindly help.