text:
Q: Elm Specify Different Value for Other Item in Model Just starting and playing around with Elm.
I have the following Elm Code:
import Html exposing (..)
import Html.Attributes
import Html.Events exposing (..)
import List
import Random
import Svg exposing (..)
import Svg.Attributes exposing (..)

main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

-- MODEL
type alias Model =
    { dieFace1 : Int
    , dieFace2: Int
    }

init : ( Model, Cmd Msg )
init =
    ( Model 2 5, Cmd.none )

-- UPDATE
type Msg
    = Roll
    | NewFace Int

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Roll ->
          ( model, Random.generate NewFace (Random.int 1 6) )

        NewFace newFace ->
            ( Model newFace newFace, Cmd.none )

-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
    Sub.none

-- VIEW
view : Model -> Html Msg
view model =
    div []
        [ h1 [] [ Html.text (toString (model.dieFace1 + model.dieFace2)) ]
        , svg
            [ width "120", height "120", viewBox "0 0 120 120", fill "white", stroke "black", strokeWidth "3", Html.Attributes.style [ ( "padding-left", "20px" ) ] ]
            (List.append
                [ rect [ x "1", y "1", width "100", height "100", rx "25", ry "25" ] [] ]
                (svgCirclesForDieFace model.dieFace1)
            )
        , svg
            [ width "120", height "120", viewBox "0 0 120 120", fill "white", stroke "black", strokeWidth "3", Html.Attributes.style [ ( "padding-left", "20px" ) ] ]
            (List.append
                [ rect [ x "1", y "1", width "100", height "100", rx "25", ry "25" ] [] ]
                (svgCirclesForDieFace model.dieFace2)
            )
        , br [] []
        , button [ onClick Roll ] [ Html.text "Roll" ]
        ]

svgCirclesForDieFace : Int -> List (Svg Msg)
svgCirclesForDieFace dieFace =
    case dieFace of
        1 ->
            [ circle [ cx "50", cy "50", r "10", fill "black" ] [] ]

        2 ->
            [ circle [ cx "25", cy "25", r "10", fill "black" ] []
            , circle [ cx "75", cy "75", r "10", fill "black" ] []
            ]

        3 ->
            [ circle [ cx "25", cy "25", r "10", fill "black" ] []
            , circle [ cx "50", cy "50", r "10", fill "black" ] []
            , circle [ cx "75", cy "75", r "10", fill "black" ] []
            ]

        4 ->
            [ circle [ cx "25", cy "25", r "10", fill "black" ] []
            , circle [ cx "75", cy "25", r "10", fill "black" ] []
            , circle [ cx "25", cy "75", r "10", fill "black" ] []
            , circle [ cx "75", cy "75", r "10", fill "black" ] []
            ]

        5 ->
            [ circle [ cx "25", cy "25", r "10", fill "black" ] []
            , circle [ cx "75", cy "25", r "10", fill "black" ] []
            , circle [ cx "25", cy "75", r "10", fill "black" ] []
            , circle [ cx "75", cy "75", r "10", fill "black" ] []
            , circle [ cx "50", cy "50", r "10", fill "black" ] []
            ]

        6 ->
            [ circle [ cx "25", cy "20", r "10", fill "black" ] []
            , circle [ cx "25", cy "50", r "10", fill "black" ] []
            , circle [ cx "25", cy "80", r "10", fill "black" ] []
            , circle [ cx "75", cy "20", r "10", fill "black" ] []
            , circle [ cx "75", cy "50", r "10", fill "black" ] []
            , circle [ cx "75", cy "80", r "10", fill "black" ] []
            ]

        _ ->
            [ circle [ cx "50", cy "50", r "50", fill "red", stroke "none" ] [] ]

It renders two dice SVG items, with values 2 and 5 displayed.
With the Roll function, I am trying to get a random number to display for each dice. Right now, what's happening is that both dice are getting the same value. I am not quite sure how to have different random number assigned to each dice.
Appreciate any ideas. Thanks.

A: You can use Random.pair to generate a 2-tuple of values. You'll need to update NewFace to store a 2-tuple of Int values:
| NewFace (Int, Int)

And then modify update like this:
    Roll ->
        ( model, Random.generate NewFace (Random.pair (Random.int 1 6) (Random.int 1 6))

    NewFace (a, b) ->
        ( Model a b, Cmd.none )


text:
Q: Responsive website and media queries I am using media queries as below
@media (min-width:100px) and (max-width:639px)
{
}
@media (min-width:640px) and (max-width:960px)
{
    .box  {background-color:red;}
}
@media (width:768px)
{
    .box  {background-color:green; }
}
@media (min-width:961px)
{
}

I want to specifically target some div element for screen 768 pixel so that it appears exactly as i want for example in general i want to overwrite css defined in  @media (min-width:640px) and (max-width:960px) by css which is targeted for screen 768 @media (min-width:768px)
At present it is still showing me box as red while it should be red, I am not sure how css is complied i defined it after the second media query so that it will over right it.
How can i target certain element using media queries for specific devices
example :http://jsfiddle.net/X43Et/
Update:
I am not sure what exactly was wrong with it put i copy pasted  @media (width:768px) { part from fiddle & it works in my actual page.
May be some invisible typo mistake..

A: This is just an example of media queries You would want to have your normal css before the media queries
#gallery-1 img {
    width:375px;
}
@media screen and (min-width: 1366px) {
    #gallery-1 img {width:375px;}
}
@media screen and (min-width: 1440px) {
    #gallery-1 img {width:428px;}
}
@media screen and (min-width: 1600px) {
    #gallery-1 img {width:434px;}
}
@media screen and (min-width: 1920px) {
    #gallery-1 img {width:540px;}
}

And when you're using media queries, you want to specify that you want the screen size so you use screen after @media. I hope this is what you were looking for and will help you!
Here is a small example script I made
<style>
#box {
    width: 500px;
    height: 200px;
    background: yellow;
    border: 1px solid #000;
}
@media screen and (max-width:1000px) {
    #box { background: red; }
}
@media screen and (min-width:1000px) and (max-width:1200px) {
    #box { background: green; }
}
@media screen and (min-width:1200px) and (max-width:1400px) {
    #box { background: blue; }
}
</style>
<div id="box">

</div>

On JSFiddle the screen size isn't the whole screen, it's the small box the preview is in so you would need to make the sizes smaller to see the effect, here is a DEMO resize your screen browser to see the preview.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change MySql Database in Model, Ruby on Rails I have model Stat:
class Stat < ActiveRecord::Base

  establish_connection(
    :adapter  => "mysql2",
    :database => @db
  )

end

I want change database name, using params[:id]
Example, if url
/stat/?id=db01

model Stat:
@db = "db01"


text:
Q: Referencing item in ForLoop within Pandas column rename I have two pandas.DataFrame's and I wish to rename a column named value, which exists in both, as the name of the dataframe:
#Debt level relative to currency strength
#preamble
import pandas as pd
import statsmodels.formula.api as sm #check that this is actually used
import os
import numpy as np

os.chdir('C:\\Users\\pineapple\\Desktop')

#function construction
def loader(y):
    return pd.read_csv(y, header='infer',  encoding="ISO-8859+-1")

def viewer(x):
    print(x.ix[:])

def delrow(x,y):
    return x[pd.notnull(x[y])]

#
names = ['currency', 'debt_ratio']

for i in names:
    i = loader(''+i+'.csv') #load data
    i = i.replace('..', np.NaN)

    for x in range(2007,2015):
        y = str(x)
        print(y)
        i=delrow(i, '' + y + ' [YR'+y+']') #deletes missing values
        i.rename(columns = {'' + y + ' [YR'+y+']': ''+ y +''}, inplace=True) #rename columns

    i = i.drop(['Series Name','Series Code', 'Country Name', \
         '1990 [YR1990]', '2000 [YR2000]' ], axis = 1)

    i = pd.melt(i, id_vars=['Country Code'],value_vars=['2007','2008','2009','2010','2011', \
    '2012','2013','2014']) #reshape

    i.rename(columns={'variable':'year', 'Country Code':'code'}, inplace=True)
    viewer(i)

    eval(i).rename(columns={'value':i}, inplace=True) #breaks here

    i['id'] = i['code'] + i['year']

    #output
    viewer(i)

This does not work - it fails to update the value column and messes up the format of the dataframe.

A: Change:
for i in names:
    i = loader(''+i+'.csv') #load data

To:
for name in names:
    i = loader(name + '.csv') #load data

Then do the rename with:
i.rename(columns={'value':name}, inplace=True)

A: You need to use eval:
MCVE
a = pd.DataFrame({'Value':[1,2,3,4]})
b = pd.DataFrame({'Value':[5,6,7,9]})

names = ['a','b']

for i in names:
    eval(i).rename(columns={'Value':i}, inplace=True)

print(a)

Output:
   a
0  1
1  2
2  3
3  4

print(b)

Output:
   b
0  5
1  6
2  7
3  9


text:
Q: PhoneGap session (cookies) on iOS On server we have a set of JSON APIs.
There's a login method that authenticates the user and creates user session. Subsequent calls to other methods on the API assume that the user is authenticated.
On client side we have PhoneGap and jQuery mobile.
We use ajax calls to communicate with server.
On Android session management is OK, but on iOS after login it seems like the session cookie is not sent back on next call (or is not accepted at all) and the calls fail on server as if the user is not authenticated.
When tested from Safari on the same device everything works fine.
Same behaviour is on iPad 2 with iOS 5.0 and iPhone 4S with iOS 5.1.
Any idea?

A: the problem was with UserAgent string. ASP.NET needs to be configured to accept Mozilla/iOS. See Asp.Net Forms Authentication when using iPhone UIWebView


text:
Q: ACF Repeater and Flexslider not working For some reason my images aren't showing and I can't seem to figure it out. I'm also getting this error when I inspect the page, $(...).onload is not a function.
Heres all the code to do with the slider maybe you can notice something wrong. Thanks

  <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/css/flexslider.css">

      <?php if(get_field('slider')): ?>

            <?php while(has_sub_field('slider')): ?>

<img class="img-responsive" src="<?php the_sub_field('image'); ?>" alt="Welcome to StairWorld" />

              <?php endwhile; ?>

        <?php endif; ?>

A: I figured it out I had to change $(window).onload to $(document).ready

A: I recommend taking a look at https://www.advancedcustomfields.com/resources/gallery/
It is an excellent tutorial how you build this.
<?php

$images = get_field('gallery');

if( $images ): ?>

        <?php foreach( $images as $image ): ?>

                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

<?php echo $image['caption']; ?>

        <?php endforeach; ?>

        <?php foreach( $images as $image ): ?>

                <img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />

        <?php endforeach; ?>

Please do not forget to download and connect the flexslider files.
https://woocommerce.com/flexslider/

<link rel="stylesheet" href="flexslider.css" type="text/css">

Also, include this in the header:


text:
Q: App runs fine in Xcode but crashes in ad-hoc distribution I've been developing an iOS app for years and publishing it with ad-hoc distribution method. I had no problem previously.
Now, when I publish and upload it on website for organisation to test it, members can install the app on their devices fine, but as soon as they launch the app, it crashes on splash screen while  it runs on Xcode fine!
I have no idea what is the problem, and I have been searching for a solution for 2 days and I have got nothing.

macOS version: 11.6 Xcode version : 13 iOS version: 15.0.1

Update:
Incident Identifier: 553C6AC8-ECA9-40D3-B433-5CC6304BFFFA
CrashReporter Key:   1d0c853c41e2477c3383142c94f5379de9c324b9
Hardware Model:      iPhone10,3
Process:             {{AppName}} [2208]
Path:                /private/var/containers/Bundle/Application/49A22310-6360-4684-99E1-48E2F646F54A/{{AppName}}.app/{{AppName}}
Identifier:          com.{{AppName}}
Version:             1.12.0 (1)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.{{AppName}} [969]

Date/Time:           2021-10-14 23:49:42.2495 +0330
Launch Time:         2021-10-14 23:49:40.9020 +0330
OS Version:          iPhone OS 15.0.2 (19A404)
Release Type:        User
Baseband Version:    7.02.00
Report Version:      104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001042f11fc
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: SIGNAL; [5]
Terminating Process: exc handler [2208]

Terminating Process: exc handler [2208]
Triggered by Thread:  0

Thread 0 name:   Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   {{AppName}}                                0x1042f11fc 0x1040d0000 + 2232828
1   {{AppName}}                                0x1042f0504 0x1040d0000 + 2229508
2   {{AppName}}                                0x1042ef694 0x1040d0000 + 2225812
3   UIKitCore                              0x18340334c -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 352
4   UIKitCore                              0x1835da624 -[UIApplication _callInitializationDelegatesWithActions:forCanvas:payload:fromOriginatingProcess:] + 3456
5   UIKitCore                              0x1835c380c -[UIApplication _runWithMainScene:transitionContext:completion:] + 1216
6   UIKitCore                              0x18342f9ec -[_UISceneLifecycleMultiplexer completeApplicationLaunchWithFBSScene:transitionContext:] + 148
7   UIKitCore                              0x183292b00 _UIScenePerformActionsWithLifecycleActionMask + 96
8   UIKitCore                              0x1833b79f4 __101-[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:]_block_invoke + 196
9   UIKitCore                              0x1834ce204 -[_UISceneLifecycleMultiplexer _performBlock:withApplicationOfDeactivationReasons:fromReasons:] + 240
10  UIKitCore                              0x1836fb064 -[_UISceneLifecycleMultiplexer _evalTransitionToSettings:fromSettings:forceExit:withTransitionStore:] + 732
11  UIKitCore                              0x18368adac -[_UISceneLifecycleMultiplexer uiScene:transitionedFromState:withTransitionContext:] + 336
12  UIKitCore                              0x1832939e8 __186-[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:]_block_invoke + 188
13  UIKitCore                              0x1833502f8 +[BSAnimationSettings(UIKit) tryAnimatingWithSettings:actions:completion:] + 812
14  UIKitCore                              0x183295778 _UISceneSettingsDiffActionPerformChangesWithTransitionContext + 248
15  UIKitCore                              0x18337b530 -[_UIWindowSceneFBSSceneTransitionContextDrivenLifecycleSettingsDiffAction _performActionsForUIScene:withUpdatedFBSScene:settingsDiff:fromSettings:transitionContext:lifecycleActionType:] + 356
16  UIKitCore                              0x1837d7bec __64-[UIScene scene:didUpdateWithDiff:transitionContext:completion:]_block_invoke.573 + 772
17  UIKitCore                              0x1832c3f80 -[UIScene _emitSceneSettingsUpdateResponseForCompletion:afterSceneUpdateWork:] + 248
18  UIKitCore                              0x1833063ec -[UIScene scene:didUpdateWithDiff:transitionContext:completion:] + 264
19  UIKitCore                              0x183434684 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 548
20  UIKitCore                              0x18337994c -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 360
21  FrontBoardServices                     0x191816fc4 -[FBSScene _callOutQueue_agent_didCreateWithTransitionContext:completion:] + 412
22  FrontBoardServices                     0x191839550 __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke.180 + 100
23  FrontBoardServices                     0x1917f9714 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 232
24  FrontBoardServices                     0x1917fab1c __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke + 312
25  libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
26  libdispatch.dylib                      0x180ac5f58 _dispatch_block_invoke_direct$VARIANT$armv81 + 212
27  FrontBoardServices                     0x1917fad7c __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40
28  FrontBoardServices                     0x1917fa300 -[FBSSerialQueue _targetQueue_performNextIfPossible] + 176
29  FrontBoardServices                     0x1917fe3f0 -[FBSSerialQueue _performNextFromRunLoopSource] + 24
30  CoreFoundation                         0x180e42220 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
31  CoreFoundation                         0x180e52248 __CFRunLoopDoSource0 + 204
32  CoreFoundation                         0x180d955e8 __CFRunLoopDoSources0 + 256
33  CoreFoundation                         0x180d9aa18 __CFRunLoopRun + 768
34  CoreFoundation                         0x180dadd8c CFRunLoopRunSpecific + 572
35  GraphicsServices                       0x19aeba9a0 GSEventRunModal + 160
36  UIKitCore                              0x1835e2fa8 -[UIApplication _run] + 1080
37  UIKitCore                              0x18337722c UIApplicationMain + 2060
38  {{AppName}}                                0x1040d782c 0x1040d0000 + 30764
39  dyld                                   0x1048d4190 start + 444

Thread 1 name:   Dispatch queue: com.apple.root.default-qos
Thread 1:
0   libsystem_kernel.dylib                 0x1ba2f13dc stat + 8
1   Foundation                             0x182548b80 _NSFrameworkPathFromLibraryPath + 416
2   Foundation                             0x1825dd29c __25+[NSBundle allFrameworks]_block_invoke + 332
3   libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
4   libdispatch.dylib                      0x180abeac0 _dispatch_once_callout + 28
5   Foundation                             0x1825dd14c +[NSBundle allFrameworks] + 64
6   AccessibilityUtilities                 0x1955961e0 __43-[AXBinaryMonitor evaluateExistingBinaries]_block_invoke + 112
7   libdispatch.dylib                      0x180aed2ec _dispatch_call_block_and_release + 24
8   libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
9   libdispatch.dylib                      0x180ac5698 _dispatch_queue_override_invoke + 712
10  libdispatch.dylib                      0x180ad2488 _dispatch_root_queue_drain + 320
11  libdispatch.dylib                      0x180ad2c5c _dispatch_worker_thread2 + 160
12  libsystem_pthread.dylib                0x1da70aefc _pthread_wqthread + 224
13  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 2:
0   libsystem_pthread.dylib                0x1da70aa9c start_wqthread + 0

Thread 3 name:   Dispatch queue: APMExperimentWorkerQueue
Thread 3:
0   libsystem_kernel.dylib                 0x1ba2f13dc stat + 8
1   libsqlite3.dylib                       0x1a37ebe80 0x1a37c6000 + 155264
2   libsqlite3.dylib                       0x1a37eab68 0x1a37c6000 + 150376
3   libsqlite3.dylib                       0x1a37ea1fc 0x1a37c6000 + 147964
4   libsqlite3.dylib                       0x1a38099d0 0x1a37c6000 + 276944
5   libsqlite3.dylib                       0x1a3807dc4 sqlite3_step + 308
6   {{AppName}}                                0x10440411c 0x1040d0000 + 3359004
7   {{AppName}}                                0x104403638 0x1040d0000 + 3356216
8   {{AppName}}                                0x1044028f8 0x1040d0000 + 3352824
9   {{AppName}}                                0x104403200 0x1040d0000 + 3355136
10  {{AppName}}                                0x1043886b8 0x1040d0000 + 2852536
11  {{AppName}}                                0x104388234 0x1040d0000 + 2851380
12  {{AppName}}                                0x104388110 0x1040d0000 + 2851088
13  {{AppName}}                                0x1043911cc 0x1040d0000 + 2888140
14  {{AppName}}                                0x104391174 0x1040d0000 + 2888052
15  {{AppName}}                                0x1043926e4 0x1040d0000 + 2893540
16  libdispatch.dylib                      0x180aed2ec _dispatch_call_block_and_release + 24
17  libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
18  libdispatch.dylib                      0x180ac9410 _dispatch_lane_serial_drain$VARIANT$armv81 + 596
19  libdispatch.dylib                      0x180ac9eb8 _dispatch_lane_invoke$VARIANT$armv81 + 388
20  libdispatch.dylib                      0x180ad376c _dispatch_workloop_worker_thread + 616
21  libsystem_pthread.dylib                0x1da70af38 _pthread_wqthread + 284
22  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 4 name:  com.apple.uikit.eventfetch-thread
Thread 4:
0   libsystem_kernel.dylib                 0x1ba2f0b70 mach_msg_trap + 8
1   libsystem_kernel.dylib                 0x1ba2f1194 mach_msg + 72
2   CoreFoundation                         0x180d96ad0 __CFRunLoopServiceMachPort + 368
3   CoreFoundation                         0x180d9abb8 __CFRunLoopRun + 1184
4   CoreFoundation                         0x180dadd8c CFRunLoopRunSpecific + 572
5   Foundation                             0x1824ecb6c -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 232
6   Foundation                             0x18252bd6c -[NSRunLoop(NSRunLoop) runUntilDate:] + 88
7   UIKitCore                              0x183560950 -[UIEventFetcher threadMain] + 512
8   Foundation                             0x18253964c __NSThread__start__ + 776
9   libsystem_pthread.dylib                0x1da70c458 _pthread_start + 116
10  libsystem_pthread.dylib                0x1da70aab0 thread_start + 8

Thread 5 name:   Dispatch queue: com.google.firebase.crashlytics.startup
Thread 5:
0   libsystem_kernel.dylib                 0x1ba2f0bc4 semaphore_timedwait_trap + 8
1   libdispatch.dylib                      0x180abda44 _dispatch_sema4_timedwait$VARIANT$armv81 + 60
2   libdispatch.dylib                      0x180abdfd4 _dispatch_semaphore_wait_slow + 72
3   FirebaseCrashlytics                    0x104fbb140 -[FIRCLSInstallIdentifierModel regenerateInstallIDIfNeeded] + 216
4   FirebaseCrashlytics                    0x104fc857c __91-[FIRCLSReportUploader prepareAndSubmitReport:dataCollectionToken:asUrgent:withProcessing:]_block_invoke_2 + 52
5   libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
6   libdispatch.dylib                      0x180abeac0 _dispatch_once_callout + 28
7   FirebaseCrashlytics                    0x104fc8544 __91-[FIRCLSReportUploader prepareAndSubmitReport:dataCollectionToken:asUrgent:withProcessing:]_block_invoke + 1156
8   FirebaseCrashlytics                    0x104faa980 FIRCLSApplicationActivity + 72
9   FirebaseCrashlytics                    0x104fc8078 -[FIRCLSReportUploader prepareAndSubmitReport:dataCollectionToken:asUrgent:withProcessing:] + 180
10  FirebaseCrashlytics                    0x104fb60e0 -[FIRCLSExistingReportManager processExistingActiveReportPath:dataCollectionToken:asUrgent:] + 192
11  FirebaseCrashlytics                    0x104fb5b64 -[FIRCLSExistingReportManager sendUnsentReportsWithToken:asUrgent:] + 220
12  FirebaseCrashlytics                    0x104fc770c -[FIRCLSReportManager beginReportUploadsWithToken:blockingSend:] + 144
13  FirebaseCrashlytics                    0x104fc70b4 __46-[FIRCLSReportManager startWithProfilingMark:]_block_invoke + 40
14  FBLPromises                            0x104f2f40c __56-[FBLPromise chainOnQueue:chainedFulfill:chainedReject:]_block_invoke.48 + 52
15  libdispatch.dylib                      0x180aed2ec _dispatch_call_block_and_release + 24
16  libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
17  libdispatch.dylib                      0x180ac94dc _dispatch_lane_serial_drain$VARIANT$armv81 + 800
18  libdispatch.dylib                      0x180ac9eb8 _dispatch_lane_invoke$VARIANT$armv81 + 388
19  libdispatch.dylib                      0x180ad376c _dispatch_workloop_worker_thread + 616
20  libsystem_pthread.dylib                0x1da70af38 _pthread_wqthread + 284
21  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 6 name:   Dispatch queue: com.apple.UIKit.KeyboardManagement
Thread 6:
0   libsystem_kernel.dylib                 0x1ba2f1754 __ulock_wait + 8
1   libdispatch.dylib                      0x180abdde0 _dlock_wait + 52
2   libdispatch.dylib                      0x180abdbb8 _dispatch_thread_event_wait_slow$VARIANT$armv81 + 52
3   libdispatch.dylib                      0x180ad0560 __DISPATCH_WAIT_FOR_QUEUE__ + 336
4   libdispatch.dylib                      0x180ad015c _dispatch_sync_f_slow + 136
5   UIKitCore                              0x18344a10c __37-[_UIRemoteKeyboards startConnection]_block_invoke_3 + 112
6   CoreFoundation                         0x180db08e0 __invoking___ + 144
7   CoreFoundation                         0x180dcc5b8 -[NSInvocation invoke] + 300
8   Foundation                             0x182508910 __NSXPCCONNECTION_IS_CALLING_OUT_TO_REPLY_BLOCK__ + 20
9   Foundation                             0x1825280fc -[NSXPCConnection _decodeAndInvokeReplyBlockWithEvent:sequence:replyInfo:] + 552
10  Foundation                             0x18250475c __88-[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:]_block_invoke_3 + 208
11  libxpc.dylib                           0x1da740cc8 _xpc_connection_reply_callout + 60
12  libxpc.dylib                           0x1da735004 _xpc_connection_call_reply_async + 76
13  libdispatch.dylib                      0x180aee368 _dispatch_client_callout3 + 16
14  libdispatch.dylib                      0x180ac2808 _dispatch_mach_msg_async_reply_invoke$VARIANT$armv81 + 344
15  libdispatch.dylib                      0x180ac92e8 _dispatch_lane_serial_drain$VARIANT$armv81 + 300
16  libdispatch.dylib                      0x180ac9eec _dispatch_lane_invoke$VARIANT$armv81 + 440
17  libdispatch.dylib                      0x180ad376c _dispatch_workloop_worker_thread + 616
18  libsystem_pthread.dylib                0x1da70af38 _pthread_wqthread + 284
19  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 7 name:   Dispatch queue: com.apple.network.connections
Thread 7:
0   libobjc.A.dylib                        0x197e812b8 objc_loadWeakRetained + 376
1   libnetwork.dylib                       0x181d680c4 __nw_resolver_create_dns_getaddrinfo_locked_block_invoke.165 + 80
2   libnetwork.dylib                       0x181d680c4 __nw_resolver_create_dns_getaddrinfo_locked_block_invoke.165 + 80
3   libdns_services.dylib                  0x1d9755f20 ___dnssd_getaddrinfo_activate_block_invoke + 168
4   libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
5   libdispatch.dylib                      0x180ac59f0 _dispatch_continuation_pop$VARIANT$armv81 + 436
6   libdispatch.dylib                      0x180ad6e3c _dispatch_source_invoke$VARIANT$armv81 + 1320
7   libdispatch.dylib                      0x180acb02c _dispatch_workloop_invoke$VARIANT$armv81 + 1640
8   libdispatch.dylib                      0x180ad376c _dispatch_workloop_worker_thread + 616
9   libsystem_pthread.dylib                0x1da70af38 _pthread_wqthread + 284
10  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 8 name:   Dispatch queue: com.google.perf.configUpdate
Thread 8:
0   libsystem_kernel.dylib                 0x1ba2f1754 __ulock_wait + 8
1   libsystem_platform.dylib               0x1da705110 _os_unfair_lock_lock_slow + 192
2   libobjc.A.dylib                        0x197e85ce8 objc_initWeak + 124
3   FirebaseRemoteConfig                   0x1051d14d4 -[RCNConfigExperiment loadExperimentFromTable] + 44
4   FirebaseRemoteConfig                   0x1051d1474 -[RCNConfigExperiment initWithDBManager:experimentController:] + 484
5   FirebaseRemoteConfig                   0x1051c70e4 -[FIRRemoteConfig initWithAppName:FIROptions:namespace:DBManager:configContent:analytics:] + 440
6   FirebaseRemoteConfig                   0x1051ca404 -[FIRRemoteConfigComponent remoteConfigForNamespace:] + 808
7   FirebaseRemoteConfig                   0x1051c6dd0 +[FIRRemoteConfig remoteConfigWithFIRNamespace:app:] + 148
8   FirebasePerformance                    0x10514a880 __38+[FPRRemoteConfigFlags sharedInstance]_block_invoke + 80
9   libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
10  libdispatch.dylib                      0x180abeac0 _dispatch_once_callout + 28
11  FirebasePerformance                    0x10514a82c +[FPRRemoteConfigFlags sharedInstance] + 60
12  FirebasePerformance                    0x105138b64 -[FPRConfigurations setupRemoteConfigFlags] + 148
13  FirebasePerformance                    0x105138a98 __27-[FPRConfigurations update]_block_invoke + 76
14  libdispatch.dylib                      0x180aed2ec _dispatch_call_block_and_release + 24
15  libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
16  libdispatch.dylib                      0x180ac9410 _dispatch_lane_serial_drain$VARIANT$armv81 + 596
17  libdispatch.dylib                      0x180ac9eb8 _dispatch_lane_invoke$VARIANT$armv81 + 388
18  libdispatch.dylib                      0x180ad376c _dispatch_workloop_worker_thread + 616
19  libsystem_pthread.dylib                0x1da70af38 _pthread_wqthread + 284
20  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 9 name:   Dispatch queue: com.google.firebase.crashlytics.ios.binary-images
Thread 9:
0   libsystem_kernel.dylib                 0x1ba2f2b38 access + 8
1   Foundation                             0x182512bdc -[NSBundle initWithPath:] + 372
2   Foundation                             0x182531588 +[NSBundle bundleWithPath:] + 36
3   FirebaseCrashlytics                    0x104fac24c __FIRCLSBinaryImageChanged_block_invoke + 696
4   libdispatch.dylib                      0x180aed2ec _dispatch_call_block_and_release + 24
5   libdispatch.dylib                      0x180aee2f0 _dispatch_client_callout + 16
6   libdispatch.dylib                      0x180ac9410 _dispatch_lane_serial_drain$VARIANT$armv81 + 596
7   libdispatch.dylib                      0x180ac9eb8 _dispatch_lane_invoke$VARIANT$armv81 + 388
8   libdispatch.dylib                      0x180ad376c _dispatch_workloop_worker_thread + 616
9   libsystem_pthread.dylib                0x1da70af38 _pthread_wqthread + 284
10  libsystem_pthread.dylib                0x1da70aaa4 start_wqthread + 8

Thread 10:
0   libsystem_pthread.dylib                0x1da70aa9c start_wqthread + 0

Thread 11 name:  com.google.firebase.crashlytics.MachExceptionServer
Thread 11:
0   libsystem_kernel.dylib                 0x1ba2f23e8 write + 8
1   FirebaseCrashlytics                    0x104fbb650 FIRCLSSDKFileLog + 316
2   FirebaseCrashlytics                    0x104fbd4c4 FIRCLSMachExceptionServer + 1004
3   libsystem_pthread.dylib                0x1da70c458 _pthread_start + 116
4   libsystem_pthread.dylib                0x1da70aab0 thread_start + 8

Thread 12:
0   libsystem_pthread.dylib                0x1da70aa9c start_wqthread + 0

Thread 13:
0   libsystem_pthread.dylib                0x1da70aa9c start_wqthread + 0

Thread 14:
0   libsystem_pthread.dylib                0x1da70aa9c start_wqthread + 0

No thread state (register information) available

Binary Images:
       0x1040d0000 -        0x10451ffff {{AppName}} arm64  <3ae785ec3f5d36919fb7c01330e5b80d> /private/var/containers/Bundle/Application/49A22310-6360-4684-99E1-48E2F646F54A/{{AppName}}.app/{{AppName}}
       0x1830f5000 -        0x18487cfff UIKitCore arm64  <4c9b5192c562355cbfca71961f92935e> /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
       0x1917f0000 -        0x19188efff FrontBoardServices arm64  <0d3af6437c5b34afac62d438b1d74315> /System/Library/PrivateFrameworks/FrontBoardServices.framework/FrontBoardServices
       0x180a8a000 -        0x180b0cfff libdispatch.dylib arm64  <5d722afcfb8c3769bf66167bb94a6133> /usr/lib/system/libdispatch.dylib
       0x180d90000 -        0x1811cafff CoreFoundation arm64  <fe94d75f5f1d3127ba500161d8817ee6> /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
       0x19aeb9000 -        0x19aec1fff GraphicsServices arm64  <87b24bb5a3dd358d9abba1f70544a383> /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices
       0x1048bc000 -        0x10490ffff dyld arm64  <d7a0282e93de3a1e981327e84517cc96> /usr/lib/dyld
       0x1ba2f0000 -        0x1ba321fff libsystem_kernel.dylib arm64  <83a7e9554c943d9d9c1163fe9c36fbd7> /usr/lib/system/libsystem_kernel.dylib
       0x1824d5000 -        0x1827b3fff Foundation arm64  <b17c0d3bcabb321290560791b2521900> /System/Library/Frameworks/Foundation.framework/Foundation
       0x19554d000 -        0x195665fff AccessibilityUtilities arm64  <ca01cc924b7b3328b02bc17837fbbbb4> /System/Library/PrivateFrameworks/AccessibilityUtilities.framework/AccessibilityUtilities
       0x1da70a000 -        0x1da719fff libsystem_pthread.dylib arm64  <c685b49359ff3f13a9b33d3bb868ccd5> /usr/lib/system/libsystem_pthread.dylib
       0x1a37c6000 -        0x1a3951fff libsqlite3.dylib arm64  <7301a6c6c94335029598d1e1a2fbab71> /usr/lib/libsqlite3.dylib
       0x104fa4000 -        0x104fe3fff FirebaseCrashlytics arm64  <911707c79bfb3abcbbdafbb1893a35b3> /private/var/containers/Bundle/Application/49A22310-6360-4684-99E1-48E2F646F54A/{{AppName}}.app/Frameworks/FirebaseCrashlytics.framework/FirebaseCrashlytics
       0x104f28000 -        0x104f37fff FBLPromises arm64  <c416500f6a1a350c8f8edb5696eeaeda> /private/var/containers/Bundle/Application/49A22310-6360-4684-99E1-48E2F646F54A/{{AppName}}.app/Frameworks/FBLPromises.framework/FBLPromises
       0x1da728000 -        0x1da75afff libxpc.dylib arm64  <fbe92a1095e630599061c21ef625fbd5> /usr/lib/system/libxpc.dylib
       0x197e7c000 -        0x197eb1fff libobjc.A.dylib arm64  <aaf2058b0b5d35aca9b881383e71814b> /usr/lib/libobjc.A.dylib
       0x1819f8000 -        0x18245dfff libnetwork.dylib arm64  <ee6d55995b6e3aacabc705f56b4ee2fb> /usr/lib/libnetwork.dylib
       0x1d9754000 -        0x1d975cfff libdns_services.dylib arm64  <8384989ee1b535a79501d7c856fce4d7> /usr/lib/libdns_services.dylib
       0x1da6fd000 -        0x1da708fff libsystem_platform.dylib arm64  <4bdfc54acdcb3b799ffc3d9e226fd47d> /usr/lib/system/libsystem_platform.dylib
       0x1051c0000 -        0x1051dffff FirebaseRemoteConfig arm64  <8971dc73d9b533ea9977ed8fb425049d> /private/var/containers/Bundle/Application/49A22310-6360-4684-99E1-48E2F646F54A/{{AppName}}.app/Frameworks/FirebaseRemoteConfig.framework/FirebaseRemoteConfig
       0x10512c000 -        0x10515bfff FirebasePerformance arm64  <53e1cd2d04413ceabe13595d9df8d665> /private/var/containers/Bundle/Application/49A22310-6360-4684-99E1-48E2F646F54A/{{AppName}}.app/Frameworks/FirebasePerformance.framework/FirebasePerformance

Error Formulating Crash Report:thread_get_state(PAGEIN) returned 0x10000003: (ipc/send) invalid destination port
thread_get_state(EXCEPTION) returned 0x10000003: (ipc/send) invalid destination port
thread_get_state(FLAVOR) returned 0x10000003: (ipc/send) invalid destination port

EOF

A: As I investigated deeply, I found out that the reason my app is crashing is because of the custom font that I'm using is not included in my arcchive file but it is available in the project and in the info.plist and in Copy Bundle Resources.
⚠This is just a solution for now until I figure out why the Font is not in the archive file!

*

*I selected the archive and then "show in finder".

the extension of archive should be : .xcarchive

*Right clicked my archive in finder and selected "show package contents".

*Right clicked my App and selected "show package contents" in Products>Applications>{{AppName}}.App

*Dropped my fonts here and distributed the archive and it worked fine without any crash.


text:
Q: Javascript if statement does not meet other condition when the correct number is entered I'm having an issue with my if statement. When I enter a number less than 16 it will still redirect to the lottery website. I'm not sure what I've missed or done wrong in my javascript code so any help is appreciated!
Javascript:
const button = document.querySelector(".image-button");
const age = 16;

function checkAge() {
    button.addEventListener('click', function() {
        prompt("What is your age?");
        if (age >= 16) {
            window.location.assign("https://www.national-lottery.co.uk/")
            alert("You are eligible to play");
        } else if (age < 16) {
            alert("You are not eligible to play");
        }
    });
}

checkAge();

Html:

Are you eligible to play the national lottery?

          <button>Check</button>

A: You need to capture the user input in the age variable, and then check that value:
function checkAge() {
    button.addEventListener('click', function() {
        var age = prompt("What is your age?");
        if (age >= 16) {
            window.location.assign("https://www.national-lottery.co.uk/")
            alert("You are eligible to play");
        }
        else {
            alert("You are not eligible to play");
        }
    });
}


text:
Q: Javascript natural sort array/object and maintain index association I have an array of items as follows in Javascript:
var users = Array();

users[562] = 'testuser3';
users[16] = 'testuser6';
users[834] = 'testuser1';
users[823] = 'testuser4';
users[23] = 'testuser2';
users[917] = 'testuser5';

I need to sort that array to get the following output:
users[834] = 'testuser1';
users[23] = 'testuser2';
users[562] = 'testuser3';
users[823] = 'testuser4';
users[917] = 'testuser5';
users[16] = 'testuser6';

Notice how it is sorted by the value of the array and the value-to-index association is maintained after the array is sorted (that is critical). I have looked for a solution to this, tried making it, but have hit a wall.
By the way, I am aware that this is technically not an array since that would mean the indices are always iterating 0 through n where n+1 is the counting number proceeding n. However you define it, the requirement for the project is still the same. Also, if it makes a difference, I am NOT using jquery.

A: If I understand the question correctly, you're using arrays in a way they are not intended to be used. In fact, the initialization style
// Don't do this!
var array = new Array();
array[0] = 'value';
array[1] = 'value';
array[2] = 'value';

teaches wrong things about the nature and purpose of arrays. An array is an ordered list of items, indexed from zero up. The right way to create an array is with an array literal:
var array = [
    'value',
    'value',
    'value'
]

The indexes are implied based on the order the items are specified. Creating an array and setting users[562] = 'testuser3' implies that there are at least 562 other users in the list, and that you have a reason for only knowing the 563rd at this time.
In your case, the index is data, and is does not represent the order of the items in the set. What you're looking for is a map or dictionary, represented in JavaScript by a plain object:
var users = {
    562: 'testuser3',
    16:  'testuser6',
    834: 'testuser1',
    823: 'testuser4',
    23:  'testuser2',
    917: 'testuser5'
}

Now your set does not have an order, but does have meaningful keys. From here, you can follow galambalazs's advice to create an array of the object's keys:
var userOrder;
if (typeof Object.keys === 'function') {
    userOrder = Object.keys(users);
} else {
    for (var key in users) {
        userOrder.push(key);
    }
}

…then sort it:
userOrder.sort(function(a, b){
    return users[a].localeCompare(users[b]);
});

Here's a demo

A: You can't order arrays like this in Javascript. Your best bet is to make a map for order.
order = new Array();
order[0] = 562;
order[1] = 16;
order[2] = 834;
order[3] = 823;
order[4] = 23;
order[5] = 917;

In this way, you can have any order you want independently of the keys in the original array.
To sort your array use a custom sorting function.
order.sort( function(a, b) {
  if ( users[a] < users[b] ) return -1;
  else if ( users[a] > users[b] ) return 1;
  else return 0;
});

for ( var i = 0; i < order.length; i++ ) {
  // users[ order[i] ]
}

[Demo]

A: The order of the elements of an array is defined by the index. So even if you specify the values in a different order, the values will always be stored in the order of their indices and undefined indices are undefined:
> var arr = [];
> arr[2] = 2;
> arr[0] = 0;
> arr
[0, undefined, 2]

Now if you want to store the pair of index and value, you will need a different data structure, maybe an array of array like this:
var arr = [
    [562, 'testuser3'],
    [16, 'testuser6'],
    [834, 'testuser1'],
    [823, 'testuser4'],
    [23, 'testuser2'],
    [917, 'testuser5']
];

This can be sorted with this comparison function:
function cmp(a, b) {
    return a[1].localeCompare(b[1]);
}
arr.sort(cmp);

The result is this array:
[
    [834, 'testuser1'],
    [23, 'testuser2'],
    [562, 'testuser3'],
    [823, 'testuser4'],
    [917, 'testuser5'],
    [16, 'testuser6']
]

A: Using the ideas from the comments, I came up with the following solution. The naturalSort function is something I found on google and I modified it to sort a multidimensional array. Basically, I made the users array a multidimensional array with the first index being the user id and the second index being the user name. So:
users[0][0] = 72;
users[0][1] = 'testuser4';
users[1][0] = 91;
users[1][1] = 'testuser2';
users[2][0] = 12;
users[2][1] = 'testuser8';
users[3][0] = 3;
users[3][1] = 'testuser1';
users[4][0] = 18;
users[4][1] = 'testuser7';
users[5][0] = 47;
users[5][1] = 'testuser3';
users[6][0] = 16;
users[6][1] = 'testuser6';
users[7][0] = 20;
users[7][1] = 'testuser5';

I then sorted the array to get the following output:
users_sorted[0][0] = 3;
users_sorted[0][1] = 'testuser1';
users_sorted[1][0] = 91;
users_sorted[1][1] = 'testuser2';
users_sorted[2][0] = 47;
users_sorted[2][1] = 'testuser3';
users_sorted[3][0] = 72;
users_sorted[3][1] = 'testuser4';
users_sorted[4][0] = 20;
users_sorted[4][1] = 'testuser5';
users_sorted[5][0] = 16;
users_sorted[5][1] = 'testuser6';
users_sorted[6][0] = 18;
users_sorted[6][1] = 'testuser7';
users_sorted[7][0] = 12;
users_sorted[7][1] = 'testuser8';

The code to do this is below:
function naturalSort(a, b) // Function to natural-case insensitive sort multidimensional arrays by second index
{

    // setup temp-scope variables for comparison evauluation
    var re = /(-?[0-9\.]+)/g,
        x = a[1].toString().toLowerCase() || '',
        y = b[1].toString().toLowerCase() || '',
        nC = String.fromCharCode(0),
        xN = x.replace( re, nC + '$1' + nC ).split(nC),
        yN = y.replace( re, nC + '$1' + nC ).split(nC),
        xD = (new Date(x)).getTime(),
        yD = xD ? (new Date(y)).getTime() : null;
    // natural sorting of dates
    if ( yD )
        if ( xD < yD ) return -1;
        else if ( xD > yD ) return 1;
    // natural sorting through split numeric strings and default strings
    for( var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++ ) {
        oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc];
        oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc];
        if (oFxNcL < oFyNcL) return -1;
        else if (oFxNcL > oFyNcL) return 1;
    }
    return 0;
}

// Set values for index
    var users = Array();
    var temp = Array();

    users.push(Array('72', 'testuser4'));
    users.push(Array('91', 'testuser2'));
    users.push(Array('12', 'testuser8'));
    users.push(Array('3', 'testuser1'));
    users.push(Array('18', 'testuser7'));
    users.push(Array('47', 'testuser3'));
    users.push(Array('16', 'testuser6'));
    users.push(Array('20', 'testuser5'));

// Sort the array
    var users_sorted = Array();
    users_sorted = users.sort(naturalSort);

A: I'd use map once to make a new array of users,
then a second time to return the string you want from the new array.
var users= [];
users[562]= 'testuser3';
users[16]= 'testuser6';
users[834]= 'testuser1';
users[823]= 'testuser4';
users[23]= 'testuser2';
users[917]= 'testuser5';

var u2= [];
users.map(function(itm, i){
    if(itm){
        var n= parseInt(itm.substring(8), 10);
        u2[n]= i;
    }
});
u2.map(function(itm, i){
    return 'users['+itm+']= testuser'+i;
}).join('\n');

/*returned value: (String)
users[834]= testuser1
users[23]= testuser2
users[562]= testuser3
users[823]= testuser4
users[917]= testuser5
users[16]= testuser6
*/

If you want to avoid any gaps. use a simple filter on the output-
u2.map(function(itm, i){
    return 'users['+itm+']= testuser'+i;
}).filter(function(itm){return itm}).join('\n');

A: Sparse arrays usually spell trouble.  You're better off saving key-value pairs in an array as objects (this technique is also valid JSON):
users = [{
    "562": "testuser3"
},{
    "16": "testuser6"
}, {
    "834": "testuser1"
}, {
    "823": "testuser4"
}, {
    "23": "testuser2"
}, {
    "917": "testuser5"
}];

As suggested, you can use a for loop to map the sorting function onto the array.

A: Array.prototype.sort() takes an optional custom comparison function -- so if you dump all of your users into an array in this manner [ [562, "testuser3"], [16, "testuser6"] ... etc.]
Then sort this array with the following function:
function(comparatorA, comparatorB) {
    var userA = comparatorA[1], userB = comparatorB[1]
    if (userA > userB)     return 1;
    if (userA < userB)     return -1;
    if (userA === userB)   return 0;
}

Then rebuild your users object.  (Which will loose you your sorting.)  Or, keep the data in the newly sorted array of arrays, if that will work for your application.

A: A oneliner with array of array as a result:
For sorting by Key.
let usersMap = users.map((item, i) => [i, item]).sort((a, b) => a[0] - b[0]);

For sorting by Value. (works with primitive types)
let usersMap = users.map((item, i) => [i, item]).sort((a, b) => a[1] - b[1]);


text:
Q: Proving that lines $(-1+4t,3+t,1)$ and $(-13+12t,1+6t,2+3t)$ intersect
Prove that these lines intersect each other:
  $$\begin{align}
L_1 &= \{(x,y,z) = (-1\phantom{3}+\phantom{1}4t,3+t,1)\} \\
L_2 &=\{(x,y,z) = (-13+12t,1+6t,2+3t)\}
\end{align}$$

I thought that what I had to do was to solve
$$\begin{align}-1+4t&=-13+12t \\
3+t &=1+6t \\
1 &=2+3t
\end{align}$$
But I guess that is not the correct way to do it since it does not give me a consistency. How should I do it then?

A: You want to show that there exist $t$ and $t'$ such that $(−1+4t, 3+t, 1) = (−13+12t', 1+6t', 2+3t')$.

A: A bit more geometrically, the direction vector for $L_1$ is $v_1=(4,1,0)$ and the direction vector for $L_2$ is $(12,6,3)$, or, rescaling, $v_2=(4,2,1)$. Let's find a vector orthogonal to both: This will be the normal vector to parallel planes containing the lines. Well, $n = v_1\times v_2 = (1,-4,4)$. The first line goes through the point $P_1=(-1,3,1)$ and the second line goes through the point $P_2=(-13,1,2)$. The planes with normal vector $n$ passing through these respective points are
$$x-4y+4z = (-1)-4(3)+4(1) = -9 \qquad\text{and}\qquad x-4y+4z=(-13)-4(1)+4(2)=-9.$$
Aha — the planes are identical. So we have two non-parallel (why?) lines both contained in a plane. Thus, they intersect.


text:
Q: gmpy2 qdiv() returns mpq where mpz would be possible I wonder if I don't get something here... Why does qdiv(8,2) return an mpq instead of an mpz?
See here:
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gmpy2 import qdiv
>>> help(qdiv)
Help on built-in function qdiv in module gmpy2:

qdiv(...)
    qdiv(x[, y=1]) -> number

    Return x/y as 'mpz' if possible, or as 'mpq' if x is not exactly
    divisible by y.
>>> qdiv(8,2)
mpq(4,1)
>>> qdiv(4,1)
mpz(4)

I thought the whole idea was to return an mpz if possible?

A: I believe that is a bug that was fixed in version 2.0.5. Your example works with 2.0.8. What version of gmpy2 are you using?
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import gmpy2
>>> gmpy2.qdiv(8,2)
mpz(4)
>>> gmpy2.qdiv(4,1)
mpz(4)
>>> gmpy2.version()
'2.0.8'
>>>

Edit
This is a bug in gmpy2 2.1.0 alpha release. A fix has been committed to the master trunk at the main repository - gmpy2. It will be included in version 2.1.0a5.


text:
Q: How to perform a while loop with a callback function so i'm trying to reproduce a simpler version of the lodash function takeWhile. To do so i need to use a callback function and i assume i'm going to have to use a while loop which i'm not sure how to implement inside of my function.
Here is what i thought made the most sense but it doesn't seem to be working.
const data1 = [1, 2, 5, 7, 2, -1, 2, 4, 5];

const takeUntil = function(array, callback) {
  let result = [];
  for (let i = 0; i < array.length; i++) {
    while (callback(array[i]) === false) {
      result.push(array[i]);
    }
  }
  return result;
}

const testOne = takeUntil(data1, x => x < 0);
console.log(testOne);

the expected result is to make a string identical to the original one but only until the callback evaluates to true, so in the example it would be as soon as one of the numbers is smaller than 0.

A: Your break conditional needs to be on the for, not an inner while.

const data1 = [1, 2, 5, 7, 2, -1, 2, 4, 5];

const takeUntil = function(array, callback) {
  let result = [];
  for (let i = 0; i < array.length && callback(array[i]) === false; i++) {
      result.push(array[i]);
  }
  return result;
}

const testOne = takeUntil(data1, x => x < 0);
console.log(testOne);


text:
Q: Is there a way to get time and day in C++ without using the system clock? The question may sound stupid, but here's my case: I have a C++ program on Jetson Nano (a Single Board Computer) and want to get current time and date. In my application however, I can't always connect the internet cable to the device. Although in the Ubuntu settings I told it to automatically get the time from the internet, when it powers on after a longer time period (when it was not connected to power), the system clock gets confused and has a completely wrong time and date. This is what my C++ program (using std::chrono::system_clock()) then picks up.
Is there a way to get around this issue? Somehow, make does know when system time and date are set incorrect even if the device is not connected to the internet. I can tell because it fails when trying to compile with "Clock skew detected". How can I get the correct time and date when not connected to the internet?

A:
Somehow, make does know when system time and date are set incorrect even if the device is not connected to the internet.

'Fraid not.
It merely spots that the time has gone backwards since the last time it checked, and knows that this is not naturally how time works. It's guessing. The clock could be wrong now, it could have been wrong before, or it could be wrong both times.
A clock is where you get the time from. If you don't have a clock, you don't have the time. ♂ And if you do have a clock (as most computers do, including yours), but it's not traceable (e.g. by a NTP server connected to a local time server, or one on the internet), you'll never be able to trust it.
You have a clock that's not traceable, and already unreliable because apparently no battery is present to let it keep time over the long term. If you want to know the time, you'll need to fix at least one, ideally both, of these problems.
Fortunately, it seems to be possible to install a backup battery for your Real-Time Clock, which solves the reliability. Without traceability you'd still be relying on the clock's own properties, and it may gradually lose or gain time, but if you manually set it once then you'll at least be in the ballpark for a good while. You can look up the clock's specs to find out how large that ballpark is, and thus how often you may need to update the time from another source (e.g. wristwatch!).


text:
Q: Displaying bitmaps rapidly I have a WPF application where I need to add a feature that will display a series of full screen bitmaps very fast.  In most cases it will be only two images, essentially toggling the two images.  The rate they are displayed should be constant, around 10-20ms per image.  I tried doing this directly in WPF using a timer, but the display rate appeared to vary quit a bit.  I also tried using SharpGL (a .Net wrapper on OpenGL), but it was very slow when using large images (I may not have been doing the best way).  I will have all the bitmaps upfront, before compile time, so the format could be changed as long as the pixels are not altered.
What would be the best way to do this?
I'm already behind schedule so I don't have time to learn lots of APIs or experiment with lots of options.

A: "I tried doing this directly in WPF using a timer, but the display rate appeared to vary quit a bit."
Instead of using a Timer, use Thread.Sleep(20) as it wont hog as many system resources. This should give you an immediate improvement.
It also sounds as though there will be user interaction with the application while the images are rapidly toggling, in this case put the code that toggles the images in a background thread. Remember though that the UI- is not thread safe.
These are just quick wins, but you might need to use DirectX for Hardware Acceleration to get around HAL:

The Windows' Hardware Abstraction Layer (HAL) is implemented in
  Hal.dll. The HAL implements a number of functions that are
  implemented in different ways by different hardware platforms, which
  in this context, refers mostly to the Chipset. Other components in the
  operating system can then call these functions in the same way on all
  platforms, without regard for the actual implementation.


text:
Q: How to separate multiple-character values inside row? I have this dummy input dataframe. (Input dataframe cannot be changed)
data <- data.frame(c('c(a1, a10)'),
                   c('c(b1, b10)'),
                   stringsAsFactors = FALSE)

colnames(data) <- c('A', 'B')
head(data)
#           A          B
#1 c(a1, a10) c(b1, b10)

And I would like to turn this dataframe to below dataframe. Tidyverse, dplyr approach will be helpful.
#    A            B
#1  a1           b1
#2 a10          b10

A: You can remove additional text around the character and use separate_rows.
library(dplyr)
library(tidyr)

data %>%
  mutate(across(.fns = ~gsub('c\\(|\\)', '', .))) %>%
  separate_rows(A:B, sep = ',\\s*')

#  A     B
#  <chr> <chr>
#1 a1    b1
#2 a10   b10

A: Use the tidyr library's function named separate_rows:
library(tidyr)
as.data.frame(t(apply(data, 1, function(x) gsub("c\\(|\\)", "", x)))) %>%
  separate_rows(colnames(.), sep=',\\s*')

Output:
# A tibble: 2 x 2
  A     B
  <chr> <chr>
1 a1    b1
2 a10   b10

This only requires the tidyr library, and it doesn't need the dplyr package.
Explanation:
It applies on every a function with removes the c( in the beginning and ) at the end with regex in the function gsub. Then applies the tidyr::separate_rows function on all the column names (with colnames(.)), and specified the separator as a regex ,\\s*, which is a comma and a space.

A: You can first str_extract the relevant strings using lookbehind and lookahead and then separate_rows:
library(tidyr)
library(stringr)
data %>%
  mutate(across(c(1:2),
                ~str_extract_all(., "(?<=\\()[^,\\s]+|[^,\\s]+(?=\\))"))) %>%
  separate_rows(., sep = ",\\s*") %>%
  unnest(cols = c(1:2))
# A tibble: 2 x 2
  A     B
  <chr> <chr>
1 a1    b1
2 a10   b10


text:
Q: How to test sharing social media link preview on local environment? I want to set social media share options with preview, but it doesn't work for me on my local environment. The meta tags are present in the link that i'm sharing but because the site is in development stage the social media platforms can't reach it, and the preview doesn't show.
Is there a way to test the preview before deployment to production?

A: You can use a google chrome extension to test your page previews from a local environment.
It is called Social Share Preview
https://chrome.google.com/webstore/detail/social-share-preview/ggnikicjfklimmffbkhknndafpdlabib/related?hl=en


text:
Q: Where does git store information about the origin of a repository I have a repository that I cloned from someplace a few months back and I'd really like to know where it came from. A 'git pull' returns successfully and tells me everything is up to date, but I'd really like to know where its checking.
I've looked in the usual suspects in the .git folder, but can't see anything obvious. Anyone know where this upstream information is kept?

A: Try git remote:
git remote -v

This information is actually stored in the .git/config file.


text:
Q: Trying to display "trade options" to a user based on the games they have in their library. Is there a faster way to do this? I'm trying to build a platform where each user is able to add games to their library, under either the "owned" or "wanted" categories, and then it is the platform's responsibility to find possible trade options.
For example, if user A has game A in their owned list, and user B wants game A, and owns games C and D, then user A will see games C and D under their possible trade options, in return for game A.
Currently, I've implemented this somewhat crudely using too many nested DB queries and I feel like there's a faster way to do this.
The following is what happens every time a user wants to see all of their trade options.
let foundUser = await User.findById({_id: req.session.user_id})

let gamesList = []
    //for each game in the users have library, search it up in the game DB and add wantedBy users to an array
    for (let i = 0; i < foundUser.library.have.length; i++){
        let foundGame = await Game.findById({_id: foundUser.library.have[i].gameID})
        //for this game, add each user in the WantedBy List to a local array
        for (let j = 0; j < foundGame.wantedBy.length; j++){
            //for each of these users, use their have list to build the trade object
            let newFoundUser = await User.findById({_id: foundGame.wantedBy[j]})

            //check if the other user wants the game for the same platform as foundUser.library.have[i].platform
            console.log(newFoundUser)
            console.log(foundGame.wantedBy)
            let platformMatch = newFoundUser.library.want.find(game => (game.platform === foundUser.library.have[i].platform) && (game.gameID == foundUser.library.have[i].gameID))

            if (platformMatch){

                for (let k = 0; k < newFoundUser.library.have.length; k++){
                    //for each of these games in the other users have list, make a trade object
                    let newFoundGame = await Game.findById({_id: newFoundUser.library.have[k].gameID})
                    let tradeObject = {
                        gameOffered: newFoundUser.library.have[k].gameID,
                        gameOfferedBackImg: newFoundGame.backImg,
                        gameOfferedPlatform: newFoundUser.library.have[k].platform,
                        gameOfferedTitle: newFoundGame.title,
                        inReturnForTitle: foundGame.title,
                        inReturnForPlatform: foundUser.library.have[i].platform,
                        inReturnFor: foundGame._id,
                        otherUserID: newFoundUser._id
                    }
                    gamesList.push(tradeObject)
                }
            }
        }

    }

res.render('trade', {gamesList: gamesList, mainUser: foundUser._id})

The nested loops and DB queries make this really slow, especially if the no. of users and the no. games in their library increases.
The following are the DB schemas:
The User Schema:
username: {
    type: String,
    required: ['true', 'Username cannot be blank'],
},
email: {
    type: String,
    required: ['true', 'Email cannot be blank']
},
password: {
    type: String,
    required: ['true', 'Password cannot be blank'],
},
phoneNum: {
    type: String,
    required: true,
    unique: true
},
isVerified: false,
address: {
    city: String,
    area: String,
    street: String,
    nearestLandmark: String
},
verificationCode: String,
library: {
    have: [{
        gameID: String,
        platform: String
    }],
    want: [{
        gameID: String,
        platform: String
    }]
},
notifications: [
    {
        dateTime: Date,
        message: String
    }
]

})
The Game Schema:
const gameSchema = new mongoose.Schema({
title: String,
backImg: String,
wantedBy: [String]

})
Any help optimising this would be greatly appreciated. Thank you!


text:
Q: How can I put a pyblock in a box? I'm learning using PythonTeX and I have a problem. I would like to put a pyblock inside a box on my document, I tried this two things, but TeXMaker never ends compiling
Option 1:
\documentclass{article}

\input{settings/packages}

\begin{document}

\frame{
\begin{pyblock}
import numpy
import matplotlib.pyplot as plt
import sympy
import pandas
import scipy
print(6)
a = numpy.array([9])
plt.plot([1,2,3,4],[1,4,5,6])
\end{pyblock}
}

\end{document}

Option 2:
\documentclass{article}

\input{settings/packages}

\begin{document}

\begin{tabular}{|c|}
\hline
\begin{pyblock}
import numpy
import matplotlib.pyplot as plt
import sympy
import pandas
import scipy
print(6)
a = numpy.array([9])
plt.plot([1,2,3,4],[1,4,5,6])
\end{pyblock} \\
\hline
\end{tabular}

\end{document}

where settings/packages is a file with all packages are imported (\usepackage{pythontex})

A: The manual of PythonTeX recommends to use mdframed in Section 3.1 Installing PythonTeX:

The mdframed package is recommended for enclosing typeset code in
  boxes with fancy borders and/or background colors

It also works for not-so-fancy borders, see the following MWE:
\documentclass{article}

\usepackage{pythontex}
\usepackage{mdframed}

\begin{document}

\begin{mdframed}
\begin{pyblock}
import numpy
import matplotlib.pyplot as plt
import sympy
import pandas
import scipy
print(6)
a = numpy.array([9])
plt.plot([1,2,3,4],[1,4,5,6])
\end{pyblock}
\end{mdframed}

\end{document}

Result:

A: I'm sorry to say I don't have an answer for you but when I wanted to do this and couldn't get it to work I used the listings package instead. I simply made a listing that have python color coding and used the frame option to make a box around my listing.


text:
Q: Receive Packet Acknowledgement from NDIS to Miniport Layer When developing a PCIe - Ethernet driver in Wince 7 .
Send packet is working fine but on receive when we dump buffer at miniport layer we are receiving the packet but once sent to NDIS we don't get any flags or acknowledgement from NDIS to Miniport .
Is there any API or OID or function helping on this cause ?


text:
Q: How to store value in a variable on Client click in a Grid View? I want to store data in a variable on client click in a grid view.
I have a Stored Procedure which returns Service Id depending on Department code passed and we are binding these details to a Grid View.How do we bind Service Id to a variable which can be used anywhere in the code to pass the same to different Stored Procedure.Currently i am hard coding data for testing purpose.
While binding to grid view,we are not showing Service Id anywhere but we are returning the same in data table.I am doing RowDataBound but unable to store clicked element in variable
.
C# part
protected void gvServiceCount_RowDataBound(object sender, GridViewRowEventArgs e)
{   int serviceId = Convert.ToInt32(e.Row.Cells[2].Text);
    Session["serviceId"] = serviceId;
}

ASP.NET part
<asp:GridView ID="gvServiceCount" runat="server" AutoGenerateColumns="false" EmptyDataText="No Data Found"
                    Width="100%" HeaderStyle-BackColor="#facf5a" OnSelectedIndexChanged="gvServiceCount_SelectedIndexChanged" OnRowDataBound="gvServiceCount_RowDataBound"
                    HeaderStyle-ForeColor="Black" RowStyle-BackColor="White"
                    RowStyle-ForeColor="Black">
                    <Columns>
                         <asp:TemplateField HeaderText="Closed">
                            <ItemTemplate>
                                <asp:LinkButton ID="lblClosedCount" Text='<%#Eval("SUMOFAPPROVEREJECTED") %>' runat="server" OnClick="lblClosedCount_Click"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                         </Columns>
                </asp:GridView>

Data should be stored in a variable on client click.

A: Try below code:
<asp:TemplateField HeaderText="Closed">
    <ItemTemplate>
    <asp:LinkButton ID="lblClosedCount" Text='<%#Eval("SUMOFAPPROVEREJECTED") %>' runat="server" data-serviceid='<%#Eval("ServiceId")' OnClick="lblClosedCount_Click"></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

Code:
protected void lblClosedCount_Click(object sender,EventArgs e)
{
    string serviceId = lblClosedCount.Attributes["data-serviceid"].toString();
    // your coding here ----
}


text:
Q: Running my work webapp locally but cant access the correct site I have been trying to get a Django webapp run in local. What I have done was set my debug = True and basically carried my settings.py file over from my test server. I finally got my  python manage.py runserver [::]:8000 to run smoothly without errors. The problem that I am now having is that I cant access the correct idea.
Sorry for any incorrect terms but lets say my application is at three links www.webapp.com, www.buying.webapp.com and www.selling.webapp.com where the SITE_IDs are 1,2,3. I have learned to use localhost:8000 to access webapps before but that was with my simpler webapps.
Any help would be appreciated! Thank you.
EDIT:
I followed DOMAINS_URLCONF and found this
class SubdomainMiddleware:
    """ Make the subdomain publicly available to classes """

    def process_request(self, request):
        domain_parts = request.get_host().split('.')
        if (len(domain_parts) > 2):
            subdomain = domain_parts[0]
            if (subdomain.lower() == 'www'):
                subdomain = None
            domain = '.'.join(domain_parts[1:])
        else:
            subdomain = None
            domain = request.get_host()
#         if subdomain in settings.DOMAINS_URLCONF:
#             request.__setattr__('urlconf',settings.DOMAINS_URLCONF[subdomain])
        try:
            current_site = Site.objects.get(domain=request.get_host())
        except Site.DoesNotExist:
            current_site = Site.objects.get(id=settings.SITE_ID)

        request.current_site = current_site
        #settings.SITE_ID = current_site.id
        request.subdomain = subdomain
        request.domain = domain

A: For that to work, you simply need different domains on your local machine. That can be simply achieved by editing your local /etc/hosts file (on windows it is C:\Windows\System32\drivers\etc\hosts). Simply add this line in it:
127.0.0.1     buying.x.localhost selling.x.localhost

Update:
After seeing your middleware code, there is one more caveat: local domains for buying and selling should have at least 3 parts. I've just added .x in the middle of domains above, so it should be parsed correctly by this middleware. You can structure those urls as you wish, but they have to have at least 3 parts and the first part has to match one of the subdomains of your project.
After doing this, if you type just localhost:8000 in the address bar of your browser, you should see the main page, by entering buying.x.localhost:8000 you will see the content of buying. subdomain and by entering selling.x.localhost:8000 you will see content of selling. subdomain.


text:
Q: Is it posssible to preinstall the files downloaded by graalvm nativeCompile to avoid using internet on build Spring (native) Boot 3? Error downloading component catalog from https://www.graalvm.org/component-catalog/v2/graal-updater-component-catalog-java17.properties: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.

Is there a way to preinstall this file to avoid using Internet in build ?


text:
Q: Use wildcard in when groups statements I would like to execute a task only when host is in group *beat, like this.
when:
  - (groups['*beat'] is defined and inventory_hostname in groups['*beat'])

Which does not work. The task is skipped all the time.
Anyone has an idea how I can achive the desired behavior?

A: Looking at the problem at hand the other way around could maybe help: instead of trying to find if the current host you are looping on is indeed in a specific group pattern, you could list the groups that the host is in, with the variable group_names, and then select only the groups that match your pattern.
From there on, if the list is empty, then it means your host is not in a group respecting the pattern.
Given the inventory:
all:
  hosts:
    localhost:

  vars:
    ansible_connection: local

  children:
    heartbeat:
      hosts:
        rate:
        diastole:
        systole:

    filebeat:
      hosts:
        syslog:
        file:
        stdout:

    fox:
      hosts:
        brown:
        jump:
        over:
        lazy:
        dog:

And the playbook:
- hosts: all
  gather_facts: no

  tasks:
    - debug:
        msg: "I am in a group named *beat"
      when:
        - group_names | select('match', '^(.*)beat$') | list | length > 0

It gives the output:
PLAY [all] ********************************************************************************************************

TASK [debug] ******************************************************************************************************
skipping: [localhost]
ok: [rate] => {
    "msg": "I am in a group named *beat"
}
ok: [diastole] => {
    "msg": "I am in a group named *beat"
}
ok: [systole] => {
    "msg": "I am in a group named *beat"
}
ok: [syslog] => {
    "msg": "I am in a group named *beat"
}
ok: [file] => {
    "msg": "I am in a group named *beat"
}
ok: [stdout] => {
    "msg": "I am in a group named *beat"
}
skipping: [brown]
skipping: [jump]
skipping: [over]
skipping: [lazy]
skipping: [dog]

PLAY RECAP ********************************************************************************************************
brown                      : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
diastole                   : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
dog                        : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
file                       : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
jump                       : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
lazy                       : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
localhost                  : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
over                       : ok=0    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
rate                       : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
stdout                     : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
syslog                     : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
systole                    : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


text:
Q: Show splash screen only once IOS I understand, Its a HIG violation to play around with the default launch icons and splash screens, but I have requirement such that, I need to display the splash screen only for the first time, Is it possible to implement it ?
One simple solution, I can think of is : displaying  as an imageView on top of UIwindow and then removing it based on a timer. Am looking for other options.

A: My advice is to rework your view hierarchy so that the first view mimics the splash screen you wish to show (A view controller with a uiimage embedded should work fine for what you've described). Then push the "main screen" over top of that view after your specific period of time. A little code to ensure that this happens only on the first run with some persistent storage and you should be good to go.
I do not advise working with UIWindow directly. Doing so can lead to all sorts of headaches.

A: That is to simple.
But you aren't need to manipulate the launch image, but an image loaded by your app.
To prevent to launch the second time you can set a flag in the internal storage.
Make sure to use a lazy load / initalization technique and display the image fast as much is possible, than do the initializations.
I hope it helps!

A: So you know its a HIG violation but looking for some workaround.
You have to have a launch image while uploading the app and showing on first launch.
I assume you dont care about app review in appstore.
Lets think
Launch image has to be in main bundle. And the main bundle is readonly for your code.
I have some workaround but it may work only for second time launch to show the launch image and then no again.

*

*Add your launch image with any name

*Add a symlink to your app bundle with name Default.png, which shows the file in 3. step

*Copy that launch image to your app directory folder (your symlink in app bundle shows the file) on first launch.

*Launch second time the app and see the launch image

*Delete the copied image.
When your app can not find a png file which showed by your symlink it can not show launch image
PS: Personally I did not try that but may work.

A: If you use iOS6, you can use restoration feature.
At first run your app will show launch image. All other runs it'll show last state screenshot.


text:
Q: How to skip elements in python for loop? In Java/C++/etc. we can change the value of the for-loop control variable, but how can we accomplish the same in Python?
For example, let's say I have list nums[5, 1, 2, 4, 3, 3], and in a for loop I want to add the current element and the one immediately after it, then skip to the third index and repeat. So list[0] + list[1], list[2] + list[3]...
In Java/C++/etc. we can do this by:
for (int i = 0; i < list.size(); i += 2) {
 some variable = list[i] + list[i + 1];
 // whatever else
}

How can I accomplish the equivalent in Python?

A: You can use zip in conjunction with some judicious slicing like this:
list_ = [5, 1, 2, 4, 3, 3]

for x, y in zip(list_[::2], list_[1::2]):
    print(x + y)

Output:
6
6
6

A: You can write it this way, setting the step of 2 in the iteration:
list_ = [5, 1, 2, 4, 3, 3]
for i in range(0, len(list_), 2):
    print(list_[i] + list_[i+1])

Output:
6
6
6

A: first and second arguments in python built-in function range() declare start and stop and third argument declares step.
so you can use range and iterate your list like the code below(equivalent to your code):
for i in range(0, len(sample_list), 2):
   some_variable = sample_list[i] + sample_list[i+1]
   # whatever else


text:
Q: Laravel: how to access a file in the local disk? - File does not exist I'm trying to edit an excel file after uploading it in laravel.
the file is uploaded to local disk, so no one can access it from the public.
Filesystems.php
'local' => [
        'driver' => 'local',
        'root' => storage_path('app')

Routes.php
Route::get('test',function()
{

    // Create new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objPHPExcel = PHPExcel_IOFactory::load(Storage::disk('local')->url('margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx'));
    $objPHPExcel->setActiveSheetIndex(0);
    echo $objPHPExcel->getActiveSheet()->getHighestRow();
})->middleware('admin');

I keep getting error:
Could not open /storage/margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx for reading! File does not exist.

this works
     $objPHPExcel = PHPExcel_IOFactory::load('..'.Storage::disk('local')->url('app/margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx'));

but it is annoying. I thought specifying 'root' => storage_path('app') in the filesystems.php means that Storage::disk('local') will be in the app directly

A: The URL method is used to get URL for the file (ie: something to access it from the browser). What you want to use id the get() method.
$contents = Storage::get(''margin/analyser/0IGkQQgmGXkHrV9ISnBTrGyZFUPfjz3cWJbLGbDN.xlsx'');

That being said, there is still easier way to manipulate uploaded files with Laravel.
// this will take the uploaded file from the request
// and store it into `/storage/someFolder`
$path = $request->file('file')->store('someFolder');

You can then use the value returned to $path to access the file.
EDIT
After discussion below, it was decided by OP that, even if it's not the the perfect solution, he would use $objPHPExcel = PHPExcel_IOFactory::load('..'.Storage::disk('local')->url($fileLocation));.


text:
Q: check if an element from a list exists in a strings of a txt file (not working) Python I have tried many ways but I do not get any output at all. I have a list containing different types of strings:
lst=['ATCGG','GTAACGCT','AATCGAT',...]

and I have a text file as below:
>seq1
NNNGTAACGCTNNN
>seq2
NNNNNAATCGATNNNN
>seq3
NNNNNNNN
.
.
.

I want to print lines of the text file if any item in the list exists in the line. Based on the examples above, the desired output should be:
NNNGTAACGCTNNN
NNNNNAATCGATNNNN

I used the command below but nothing is getting printed out:
main_file =  open('test_file.txt', 'r')
contn = main_file.read()
#print(contn)

for dna in contn:
    if any(i in dna for i in lst):
        print(dna)

A: You need readlines instead of read, read will be creating a single string so when you iterate, dna is actually just individual characters
contn = main_file.read()

should be
contn = main_file.readlines()

A: An explicit loop version for intuitiveness:
def find_lines_containing_any(filename, wanted_list):
    with open(filename, 'r') as dna_file:
       for dna_line in dna_file:
            for wanted in wanted_list:
                if wanted in dna_line:
                    yield dna_line

for dna in find_lines_containing_any('test_file.txt', lst):
    print(dna)

A: With for dna in contn, you are iterating over the characters as read() returns a str object, you can simply do:
main_file =  open('test_file.txt', 'r')
for line in main_file:
    if any(i in line for i in lst):
        print(line)


text:
Q: Curl - Retrieve headers - empty response Using php when working with curl.
I'm attempting to only recive the headers.
I request from the following url: http://halens.se/kvinna-klader-bad-strand-baddrakter-93/baddrakt-074209/
My settings look like this:
  CURLOPT_AUTOREFERER     => true,
  CURLOPT_CERTINFO        => false,
  CURLOPT_CRLF            => true,
  CURLOPT_CONNECTTIMEOUT  => 15,
  CURLOPT_FAILONERROR     => true,
  CURLOPT_FOLLOWLOCATION  => true,
  CURLOPT_FORBID_REUSE    => true,
  CURLOPT_FRESH_CONNECT   => true,
  CURLOPT_HEADER          => true,
  CURLOPT_MAXREDIRS       => 15,
  CURLOPT_PROTOCOLS       => CURLPROTO_HTTP,
  CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP,
  CURLOPT_RETURNTRANSFER  => true,
  CURLOPT_SSL_VERIFYPEER  => false,
  CURLOPT_TIMEOUT         => 15,
  CURLOPT_HEADER          => true,
  CURLOPT_NOBODY          => true

But the response is empty.. What did I do wrong? or How can we solve this in an alternative way?

If I instead change the last setting to:
  CURLOPT_NOBODY          => false

Then I get the headers:
HTTP/1.1 301 Moved Permanently
Content-Length: 199
Content-Type: text/html; charset=UTF-8
Location: http://www.halens.se/kvinna-klader-bad-strand-baddrakter-93/baddrakt-074209/
Server: Microsoft-IIS/7.5
X-Powered-By: ARR/2.5
X-Powered-By: ASP.NET
Date: Sun, 06 Oct 2013 19:26:31 GMT

HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 123009
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=wsp1hsdq1huvdnmr0jf42m1o; path=/; HttpOnly
Set-Cookie: ASP.NET_SessionId=wsp1hsdq1huvdnmr0jf42m1o; path=/; HttpOnly
Set-Cookie: FavoriteList=Id=593cd25e-3508-46a8-9596-66bd45caa335&Hash=PRHTFWRFDX; expires=Sat, 04-Jan-2014 20:26:32 GMT; path=/
Set-Cookie: InteractorId=wsp1hsdq1huvdnmr0jf42m1o_162_13_85_148; path=/
Set-Cookie: ClickTrail=074209; expires=Thu, 05-Dec-2013 20:26:32 GMT; path=/
X-Powered-By: ARR/2.5
X-Powered-By: ASP.NET
Date: Sun, 06 Oct 2013 19:26:32 GMT

A: Not an answer to the specific : It seems a little bit weird and googling around I can see other people have struggling with this issue also (without getting closer to an explanation) - but are you aware of the get_headers function?
$header = get_headers('http://halens.se/kvinna-klader-bad-strand-baddrakter-93/baddrakt-074209/');
echo '<pre>';
print_r($header);
echo '</pre>';

outputs
Array
(
    [0] => HTTP/1.1 301 Moved Permanently
    [1] => Content-Length: 199
    [2] => Content-Type: text/html; charset=UTF-8
    [3] => Location: http://www.halens.se/kvinna-klader-bad-strand-baddrakter-93/baddrakt-074209/
    [4] => Server: Microsoft-IIS/7.5
    [5] => X-Powered-By: ARR/2.5
    [6] => X-Powered-By: ASP.NET
    [7] => Date: Sun, 06 Oct 2013 21:17:44 GMT
    [8] => Connection: close
    [9] => HTTP/1.1 200 OK
    [10] => Cache-Control: private
    [11] => Content-Length: 123078
    [12] => Content-Type: text/html; charset=utf-8
    [13] => Server: Microsoft-IIS/7.5
    [14] => Set-Cookie: ASP.NET_SessionId=i5nrsl55e1shp4alanw3dlzu; path=/; HttpOnly
    [15] => Set-Cookie: ASP.NET_SessionId=i5nrsl55e1shp4alanw3dlzu; path=/; HttpOnly
    [16] => Set-Cookie: FavoriteList=Id=51b514b9-21e8-4ed3-9ec9-38ef8a2df113&Hash=VKSZPIUFZX; expires=Sat, 04-Jan-2014 22:17:44 GMT; path=/
    [17] => Set-Cookie: InteractorId=i5nrsl55e1shp4alanw3dlzu_80_163_1_60; path=/
    [18] => Set-Cookie: ClickTrail=074209; expires=Thu, 05-Dec-2013 22:17:44 GMT; path=/
    [19] => X-Powered-By: ARR/2.5
    [20] => X-Powered-By: ASP.NET
    [21] => Date: Sun, 06 Oct 2013 21:17:44 GMT
    [22] => Connection: close
)


text:
Q: How do I return a trait object with generic methods? I am using yup_oauth2 and attempting to create a Token source that implements the GetToken trait for use on Google Compute Engine.
pub trait GetToken {
    fn token<'b, I, T>(&mut self, scopes: I) -> Result<Token, Box<Error>>
    where
        T: AsRef<str> + Ord + 'b,
        I: IntoIterator<Item = &'b T>;

    fn api_key(&mut self) -> Option<String>;
}

Depending on where the application is running, I want to resolve to different types that implement the above trait but the compiler is not happy because apparently traits with generics are not trait-object safe.
What is the idiomatic way of solving such a problem?


text:
Q: How to get values from matching column in a different sheet I have two worksheets (Variáveis and Indicadores). In Variáveis there are 14 columns (col A-Codes, col B-Description, cols C:N-months from January to December) and in Indicadores there are 17 columns (col A-ID, col B-Description, col C-Formula, col D-Measurement Unit, col E- Info, cols F:Q- months from January to December).
Variáveis contains the int monthly values for each code.
Indicadores has a text formula (column C) composed by the codes stored in Variáveis (e.g. (dAA11b+dAA12b)/dAA13b*100) that is converted (with the code below that was developed with the help of @tigeravatar) into a excel formula by replacing the codes for his correspondent int monthly value (e.g. (742+764)/125*100).
Portion of Sheet Variáveis

Portion of Sheet Indicadores with formula already converted and result in the first month

Note: this is just an example and values vary because I used the =RANDBETWEEN() formula to populate the worksheet with int values

    Dim wb As Workbook
    Dim wsLookup As Worksheet
    Dim wsData As Worksheet
    Dim aLookup() As Variant
    Dim aData() As Variant
    Dim lCodesLookupCol As Long
    Dim lCodesConvertCol As Long
    Dim i As Long

    Set wb = ActiveWorkbook
    Set wsData = wb.Worksheets("Indicadores")
    Set wsLookup = wb.Worksheets("Variáveis")

    'This line loads the codes we need to lookup and their associated Int Value into an array
    aLookup = wsLookup.Range("A2:C1309")

    lCodesLookupCol = LBound(aLookup, 2)
    lCodesConvertCol = UBound(aLookup, 2)

    'This is the range containing the Formulas stored as text in data worksheet
    With wsData.Range("C2", wsData.Cells(wsData.Rows.Count, "C").End(xlUp))

        'Loop through the lookup array and convert all codes into their associated Int Values using the Range.Replace method
        For i = 1 To UBound(aLookup, 1)
            .Replace aLookup(i, lCodesLookupCol), aLookup(i, lCodesConvertCol), xlPart, , False
        Next i

        'Now all of the Codes should have been replaced with their associated Int Values, but the formulas are still just text
        'This block will load the formulas as text into an array
        If .Cells.Count = 1 Then
            ReDim aData(1 To 1, 1 To 1)
            aData(1, 1) = .Formula
        Else
            aData = .Formula
        End If

        'Loop through the aData array to prepend an = sign to convert them into formulas
        For i = 1 To UBound(aData, 1)
            'Verifies if the cell isn't blank and that it's not already a formula
            If Len(aData(i, 1)) > 0 And Left(aData(i, 1), 1) <> "=" Then aData(i, 1) = "=" & aData(i, 1)
            wsData.Cells(i + 1, 6) = aData(i, 1)
            If Left(aData(i, 1), 1) <> "=" Then
                MsgBox "Error @ row " & Str(i + 1)
            End If
            'On Error Resume Next
        Next i

    End With

End Sub

Right now the code converts the text formulas in Indicadores into excel formulas by replacing the codes with their values (stored in Variáveis) and placing the result in the column desired (in this case it was col F- Jan)
At the moment the macro can only do the job for one month at a time. What I'm trying to do now is to do the same thing but for all months simultaneously. All help is appreciated, thank you.

A: It's a little obfuscated and over-engineered, but I think this is the line that actually writes your values to the output sheet:
wsData.Cells(i + 1, 6) = aData(i, 1)

In which case the number "6" is the column being written to, which makes sense since that is the "January" column in your output sheet.
What I would do is enclose the entire sub in a For Loop that runs 12 times (once for each month), and have it increment that number on each loop. Something like this:
Sub Looper()

For x = 6 To 18

    LookupMachine x

Next x

End Sub

Sub LookupMachine(MonthNum As Integer)

    Dim wb As Workbook
    Dim wsLookup As Worksheet
    Dim wsData As Worksheet
    Dim aLookup() As Variant
    Dim aData() As Variant
    Dim lCodesLookupCol As Long
    Dim lCodesConvertCol As Long
    Dim i As Long

    Set wb = ActiveWorkbook
    Set wsData = wb.Worksheets("Indicadores")
    Set wsLookup = wb.Worksheets("Variáveis")

    'This line loads the codes we need to lookup and their associated Int Value into an array
    aLookup = wsLookup.Range("A2:N1309")

    lCodesLookupCol = LBound(aLookup, MonthNum - 4)
    lCodesConvertCol = UBound(aLookup, MonthNum - 4)

    'This is the range containing the Formulas stored as text in data worksheet
    With wsData.Range("C2", wsData.Cells(wsData.Rows.Count, "C").End(xlUp))

        'Loop through the lookup array and convert all codes into their associated Int Values using the Range.Replace method
        For i = 1 To UBound(aLookup, 1)
            .Replace aLookup(i, lCodesLookupCol), aLookup(i, lCodesConvertCol), xlPart, , False
        Next i

        'Now all of the Codes should have been replaced with their associated Int Values, but the formulas are still just text
        'This block will load the formulas as text into an array
        If .Cells.Count = 1 Then
            ReDim aData(1 To 1, 1 To 1)
            aData(1, 1) = .Formula
        Else
            aData = .Formula
        End If

        'Loop through the aData array to prepend an = sign to convert them into formulas
        For i = 1 To UBound(aData, 1)
            'Verifies if the cell isn't blank and that it's not already a formula
            If Len(aData(i, 1)) > 0 And Left(aData(i, 1), 1) <> "=" Then aData(i, 1) = "=" & aData(i, 1)
            wsData.Cells(i + 1, MonthNum) = aData(i, 1)
            If Left(aData(i, 1), 1) <> "=" Then
                MsgBox "Error @ row " & Str(i + 1)
            End If
            'On Error Resume Next
        Next i

    End With

End Sub

Note that I extended the aLookup array to cover up to column N, and changed the column number in the Array lookup from a hardcoded "2", to "MonthNum - 4", which should increment the column of data it's working with in the way that you want.


text:
Q: Strange redirect issue This is my code from my function from controller:
public function step3Action(){
     $redirectUrl = Mage::getUrl('returns/rma_new/step2', array('m'=>'-1'));
     $this->_redirectUrl($redirectUrl);
     $redirectUrl2 = Mage::getUrl('returns/rma_new/step2', array('m'=>'-2'));
     $this->_redirectUrl($redirectUrl2);
     $redirectUrl3 = Mage::getUrl('returns/rma_new/step2', array('m'=>'-3'));
     $this->_redirectUrl($redirectUrl3);
}

Why am I redirect always to returns/rma_new/step2 with the -3 parameter  ?
instead of returns/rma_new/step2 with the -1 parameter
I am confused. thx

A: Actually I forgot the add the return type:
public function step3Action(){
     $redirectUrl = Mage::getUrl('returns/rma_new/step2', array('m'=>'-1'));
     $this->_redirectUrl($redirectUrl);
     return $this;
}

If I add the return after my first redirect, the rest of them are ignored.


text:
Q: Unable to locate and click an element using Selenium Webdriver I've been trying to automate a download process, but I am unable to find an element that needs clicking. The element has no ID, and is embedded in a tableau table. I've tried xPath, and it didn't work.
This is the html code of the element I'm trying to click-
image xlink:href="somerandomlink" class="tab-button-zone-image" width="30" height="9"></image

The element also has a outerwidget code, under which the above code for the actual element I want to click can be found-
<div class="tab-zone tab-widget tabSuppressVizTooltipsAndOverlays tabZone-dashboard-object fade-bg" id="tabZoneId26" style="z-index: 35; width: 30px; height: 22px; top: 78px; left: 1315px;">

Code that I've been using is this:
elem1= driver.find_element_by_id('tabZoneId26')
elem1.click()

and
elem= driver.find_element_by_id('//*[@id="tabZoneId26"]/div/div/div/div/div/div/svg/image')
elem.click()

Both didn't work. Can't share link to the page, I'm afraid.
Any help would be greatly appreciated, stuck on this for some time now. Thanks.

A: You use wrong method find_element_by_id for xpath. Right one is find_element_by_xpath
driver.find_element_by_xpath('//*[@id="tabZoneId26"]/div/div/div/div/div/div/svg/image')

Also your xpath is untrustworthy: try to do better xpath like
driver.find_element_by_xpath('//div[contains(@id,"tabZoneId2")]//svg/image[@class="tab-button-zone-image"]')

Also make sure that web element is in DOM before click it. for example
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By

timeout = 5
wait = WebDriverWait(browser, timeout, poll_frequency=1)
wait.until(
  method=ec.presence_of_element_located((By.XPATH, "YOUR XPATH")))

A: elem1= driver.find_element_by_xpath('//div[@id="tabZoneId26"]//image')
elem1.click()

or
from selenium.webdriver.common.action_chains import ActionChains

elem1 = driver.find_element_by_xpath('//div[@id="tabZoneId26"]//image')
actions = ActionChains(driver)
actions.click(elem1).perform()


text:
Q: Google App Engine as part of a load balanced service I have a set of servers that are currently using a single domain name with multiple DNS A records to round robin load balance. I have ported my service to run on the Google App Engine and I would like to add the google hosted service to the round robin list on the domain name. However GAE apps do not get assigned a static IP address. All I get from google is a domain name for the service.
The organization I work for requires that the service not be hosted by a single company to provide a sufficient level of fail over redundancy. I would like to host part of this service on GAE but I don't see any way to do it and still have it accessed by the same domain name as the rest of the servers.
Any suggestions?

A: I don't think it's possible.
Google App Engine uses CNAME records to "point" a domain to their GAE infrastructure. Due to the way how CNAME works, CNAME must be the only record for a FQDN.
One of the solutions is to use DNSMadeEasy's ANAME service which resolves the CNAME record into an A record. HTTP-level forwarding/balancing may also get the job done.

A: If you add a top level custom domain to App Engine, Google will give you a list of multicast IPs to use instead of the CNAME, as mostly you can't use a CNAME for the root DNS record.
Since they expect people to have to put them in as A records, I expect they won't change, although can't say if they are different per region.


text:
Q: Angular scanner autosubmit I am new to angular.js but I am trying to learn. I created a form that allows me to search using a barcode scanner and I can then press a button to submit. This step seems redundant. I would like the scanner to search and then submit the information in one action but I am not sure how to do this. Here is the current code.

        {{trans('sale.search_item')}} <input ng-model="searchKeyword" class="form-control">

                @{{item.item_name}}
                <button class="btn btn-success btn-xs" type="button" ng-click="addSaleTemp(item, newsaletemp)"></button>

A: Does your scanner send a return after the string?  I know some scanners have this ability, you could then likely add a ngKeyPress or ngChange attribute to detect the new line command to "auto submit".  If the scanner is not able to do this, another option (assuming all UPC codes will have the same length) is to check for the length of the text and auto submit when it reaches the appropriate number of characters for the UPC.


text:
Q: 100% viewport height working on large monitor but not laptop? I'd like to make my hero image to fit 100% height of the viewport. I achieved this by adding height: 100vh; to the class="video-hero" (stretches the image gradient) and added to increase the image size added a class to the image video-hero-placeholder-small.jpg with  height: 100vh;.
However this is resulting in an odd grey section to the right of the image (when on my laptop) but appears to not be an issue on my large side monitor.
I have a min-width of 100% if when removed centers the image on my laptop but not on my large side monitor. Could this be related to the issue?
.video-hero__media-wrapper
{
min-width : 100%
}

Video demonstration: https://www.screencast.com/t/Oftl68noHO
Video demonstration explained: On the right side of the video (my laptop screen) the hero image doesn't stretch full width (instead shows the odd grey section), I then bring it onto my large side monitor and it mysteriously works?
HTML

    ::before

    <picture>

    </picture>

CSS
.video-hero {
    height: 100vh;
    padding-top: 420px;
    position: relative;
    overflow: hidden;
    z-index: 1;
}

Screen resolution of large monitor:
1920x1200
Screen resolution of laptop:
1366x768
URL of website:
https://workbooks.com - Live site so I've not applied the changes to the viewport height.

A: There are a few typos in this code, but when I set the hero img width to 100% and the video-hero wrapper class to 100vh, it looked right on a laptop and desktop monitor.