text:
Q: Auto focus Input within React Native Viewpager I'm using a React Native Viewpager to take in user entry, and move to the next page on button press. Important to note that moving to the next page happens on button press, and not by normal scrolling, which is disabled.
The best way I could think to handle this was to have a state on the ViewPager, which would propagate into the child Entries.
ViewPager.tsx:
export default function ViewPager({ route, navigation }) {

    const ref: React.RefObject<ViewPager> = React.createRef();
    const [currentPage, setCurrentPage] = useState(0);

    let setEntryPage = (page: number) => {
        ref.current?.setPage(page);
        setCurrentPage(page);
    }

    return (
        <View style={{flex: 1}}>
            <ViewPager
                style={styles.viewPager}
                initialPage={0}
                ref={ref}
                scrollEnabled={false}
            >
                {
                    GlobalStuff.map((entry, index) => {
                        return (
                            <Entry
                                key={index}
                                index={index}
                                pagerFocusIndex={currentPage}
                                pagerLength={quizDeck?.litems.length!}
                                setEntryPage={setEntryPage}
                            />
                        )
                    })
                }
            </ViewPager>
        </View>
    );
};

Entry.tsx:
export function Entry(props: EntryProps) {

    const inputRef: React.RefObject<Input> = React.createRef();
    if (props.pagerFocusIndex === props.index) {
        inputRef.current?.focus();
    }

    return (
        <View>
            <Input
                // ...
                ref={inputRef}
            />
            <IconButton
                icon="arrow-right-thick"
                color={colorTheme.green}
                onPress={() => {
                    props.index !== props.pagerLength - 1 ?
                        props.setEntryPage(props.index + 1) :
                        props.navigation!.reset({ index: 0, routes: [{ name: recapScreenName as any }] });
                }}
            />
// ...

Unfortunately, inputRef appears to be null, and there is probably a better way of achieving what I'm trying to achieve anyway.

A: Anything in your render loop will be called every time the component renders.
    // This is called on every render
    const inputRef: React.RefObject<Input> = React.createRef();

    // So is this, it's always null
    if (props.pagerFocusIndex === props.index) {
        inputRef.current?.focus();
    }

Put side effects in effects.
    // Untested
    const inputRef = useRef();

    useEffect(() => {
        if (props.pagerFocusIndex === props.index) {
            inputRef.current?.focus();
        }
    }, [inputRef.current, props.pagerFocusIndex, props.index]);


text:
Q: How to get the Language ID of Word dynamically I want to get the language id of Word dynamically and assign it to Custom Dictionaries language id. I can do this when I know the language the Word is using Word.WdLanguageID.wdEnglishUS;. But how to get this dynamically. I tried as below but get a casting error. I can do this easily in VB6 but need a solution in c#.

Cannot implicitly convert type 'Microsoft.Office.Core.MsoLanguageID' to 'Microsoft.Office.Interop.Word.WdLanguageID'

C#
oCustDict.LanguageSpecific = true;
oCustDict.LanguageID = WordApp.Language;

VB6 - Works
Dim lCurrentLanguage As Long
CurrentLanguage = WordApp.Language
oCustDict.LanguageSpecific = True
oCustDict.LanguageID = lCurrentLanguage

A: VB6 was notoriously bad at enforcing variable types - it would jump through invisible hoops to try to stuff data of one type into a variable of a different type, often incorrectly.
C# is much stricter about type conversions, and in 99.9% of cases that's a good thing. In this particular case, it looks like the two enums have the same values, so you just need to add an explicit cast:
oCustDict.LanguageID = (Microsoft.Office.Interop.Word.WdLanguageID)WordApp.Language;

redpajama_set_name: RedPajamaStackExchange


text:
Q: what should I do to resolve warning from third party in flutter Today when I start debbuging the flutter(v3.0.4) project, shows warning like this:
Launching lib/main.dart on iPod touch (7th generation) in debug mode...
Running Xcode build...
Xcode build done.                                           13.3s
Debug service listening on ws://127.0.0.1:56272/SE55zaOahPg=/ws
Syncing files to device iPod touch (7th generation)...
../../../../.pub-cache/hosted/pub.dartlang.org/overlay_support-1.2.1/lib/src/overlay_entry.dart:101:24: Warning: Operand of null-aware operation '?.' has type 'WidgetsBinding' which excludes null.
 - 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('../../../../fvm/versions/3.0.4/packages/flutter/lib/src/widgets/binding.dart').
        WidgetsBinding.instance?.scheduleFrameCallback((_) => animateRemove());
                       ^
../../../../.pub-cache/hosted/pub.dartlang.org/scrollable_positioned_list-0.2.3/lib/src/scrollable_positioned_list.dart:439:24: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
 - 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('../../../../fvm/versions/3.0.4/packages/flutter/lib/src/scheduler/binding.dart').
      SchedulerBinding.instance!.addPostFrameCallback((_) {
                       ^
../../../../.pub-cache/hosted/pub.dartlang.org/scrollable_positioned_list-0.2.3/lib/src/scrollable_positioned_list.dart:486:26: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
 - 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('../../../../fvm/versions/3.0.4/packages/flutter/lib/src/scheduler/binding.dart').
        SchedulerBinding.instance!.addPostFrameCallback((_) {
                         ^
../../../../.pub-cache/hosted/pub.dartlang.org/scrollable_positioned_list-0.2.3/lib/src/positioned_list.dart:312:24: Warning: Operand of null-aware operation '!' has type 'SchedulerBinding' which excludes null.
 - 'SchedulerBinding' is from 'package:flutter/src/scheduler/binding.dart' ('../../../../fvm/versions/3.0.4/packages/flutter/lib/src/scheduler/binding.dart').
      SchedulerBinding.instance!.addPostFrameCallback((_) {

this warning was come from the third party dependencies, it it possible to resolve the warnings? I did not any warning in my flutter project. what should I do to make the warning disappeared?

A: This is normal, since the Flutter 3 update, the instance property has been made non-nullable. Not all packages have been updated to accommodate this yet, which is why you're seeing all these warnings.
The only thing to do is check the packages for updates regularly, and if there are, updating your pubspec.yaml to use the latest version.

A: Both of the packages causing warnings have newer versions that support null safety, so update overlay_support and scrollable_positioned_list.


text:
Q: Yii2 Advanced Template on Nginx Elastic Beanstalk I'm trying to launch my Yii2-advanced project on AWS' Elastic Beanstalk stack running an nginx server. I have been unable figure out a configuration that allows me to access the backend of the site. I have tried extending the nginx configuration via the AWS documentation:
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html
Which does not work. So I modify the configuration manually via vim from the command line.
While using combinations of the following configuration settings:
https://www.yiiframework.com/wiki/799/yii2-app-advanced-on-single-domain-apache-nginx
To no avail. I have tried alias and root for the backend folder and each variation I get either a 404  (file not found) or 502 (bad gateway) error.
At bare minimum, this is what I've tried to add to my nginx configuration:
root /var/www/html/frontend/web;

index index.php index.html index.htm;

location /backend/ {
    root ../../backend/web;
}

What am I doing wrong?

A: Here you can see a fully working yii2 advanced app example nginx configuration. You can change it to match your needs.
App server:

*

*mycoolapp.com

*nginx

*php7.4-fpm

Routes:

*

*http://mycoolapp.com -- frontend

*http://mycoolapp.com/admin -- backend

*http://mycoolapp.com/api -- api

Nginx configuration:
server {
    ## Listen ports config
    listen *:80 http2;
    #listen *:443 ssl http2;

    ## Site name config
    server_name mycoolapp.com;

    ## SSL config (uncomment if necessary)
    #include /etc/nginx/ssl-snippets/ssl-snippet.conf;

    ## Access and error log files path
    access_log /var/log/nginx/mycoolapp.com.access.log;
    error_log /var/log/nginx/mycoolapp.com.error.log;

    ## Max upload size config
    client_max_body_size 32m;
    client_body_buffer_size 32m;

    charset utf-8;

    ## Gzip config
    gzip on;
    gzip_types
        text/plain
        text/css
        application/json
        application/x-javascript
        text/xml
        application/xml
        application/xml+rss
        text/javascript
        application/javascript;

    ## Path to app root (folder that contains frontend and backend folders)
    set $base_root /var/www/html/mycoolapp;

    root $base_root;
    index index.php index.html;

    ## Frontend app config
    ## Entry point: https://mycoolapp.com
    location / {
        # Path to frontend web folder
        root $base_root/frontend/web;

        try_files $uri $uri/ /frontend/web/index.php$is_args$args;

        ## Omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
        location ~ ^/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
            expires 365d;
            log_not_found off;
            access_log off;
            try_files $uri =404;
        }

        ## Deny any php file in assets folder (security)
        location ~ ^/assets/.+\.php(/|$) {
            deny all;
        }
    }

    ## Backend app config
    ## Entry point: https://mycoolapp.com/admin
    location /admin {
        ## Path to backend web folder
        root $base_root/backend/web/;

        ## Redirect to the URL without a trailing slash (uncomment if necessary)
        #location = /admin/ {
        #    return 301 /admin;
        #}

        ## Prevent the directory redirect to the URL with a trailing slash
        location = /admin {
            try_files $uri /backend/web/index.php$is_args$args;
        }

        ## Omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
        location ~ ^/admin/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
            rewrite ^/admin(/.+)$ $1 break;
            log_not_found off;
            access_log off;
            try_files $uri =404;
        }

        ## Deny any php file in assets folder (security)
        location ~ ^/admin/assets/.+\.php(/|$) {
            deny all;
        }

        try_files $uri $uri/ /backend/web/index.php$is_args$args;
    }

    ## API app config
    ## Entry point: https://mycoolapp.com/api
    location /api {
        root $base_root/api/web/;

        ## Redirect to the URL without a trailing slash (uncomment if necessary)
        #location = /api/ {
        #    return 301 /api;
        #}

        location = /api {
            try_files $uri /api/web/index.php$is_args$args;
        }

        ## Omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
        location ~ ^/api/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
            rewrite ^/api(/.+)$ $1 break;
            log_not_found off;
            access_log off;
            try_files $uri =404;
        }

        ## Deny any php file in assets folder (security)
        location ~ ^/api/assets/.+\.php(/|$) {
            deny all;
        }

        try_files $uri $uri/ /api/web/index.php$is_args$args;
    }

    ## PHP configuration
    location ~ ^/.+\.php(/|$) {
        ## Rewrites
        rewrite (?!^/((frontend|api|backend)/web|api|admin))^ /frontend/web$uri break;
        rewrite (?!^/api/web)^/api(/.+)$ /api/web$1 break;
        rewrite (?!^/backend/web)^/admin(/.+)$ /backend/web$1 break;

        ## FPM config
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        try_files $fastcgi_script_name =404;
    }

    ## Logging and access of restricted folders
    location =  /robots.txt     { access_log off; log_not_found off; }
    location =  /favicon.ico    { access_log off; log_not_found off; }
    location ~* /CHANGELOG      { access_log off; log_not_found off; deny all; }
    location ~* /LICENSE        { access_log off; log_not_found off; deny all; }
    location ~* /README         { access_log off; log_not_found off; deny all; }
    location ~* /\.             { access_log off; log_not_found off; deny all; }

}


text:
Q: Remote Desktop Connection keeps timing out I use RDP to connect to a server, and I leave it connected while I work, but it always keeps disconnecting me - I have other servers that don't do this... is there a setting somewhere that I need to set? What is this setting?

A: This is probably best suited for ServerFault, but I would check the RDP Idle disconnect and other timers.  See http://technet.microsoft.com/en-us/library/cc754272.


text:
Q: Android Jetpack Navigation nested tab backward navigation strange behaviour So I'm trying Jetpack navigation component with BottomNavigationView. I created two layer of BottomNavigationView, and the structure looks like this:

*

*MainActivity (with nav_host_fragment, navigation_graph, bottom_navigation)

*

*FragmentA

*FragmentB

*FragmentC (with nested_nav_host_fragment, nested_navigation_graph, nested_bottom_navigation)

*

*FragmentCA

*FragmentCB

*FragmentCC

I have no problem navigating forward, but I couldn't navigate backward properly.
For example, when I navigation from A -> B -> C, and in C navigate CA -> CB -> CC, then clicking back button or calling navControler back, it should go from CC -> CB -> CA -> B -> A, but it straightly went to A instead.
The minimum demo project can be found here, hope someone can help, thanks.

A: By default, Fragments do not pop anything added to the back stack of child fragments.
To get the system back button to pop child Fragments of your Fragment C, you must specifically opt into that behavior by calling setPrimaryNavigationFragment().
This can be done anywhere in your Fragment after your Fragment is attached. For example, you can update your FragmentC to do it in onActivityCreated():
override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    NavigationUI.setupWithNavController(nested_bottom_navigation,
            activity?.findNavController(R.id.nested_nav_host_fragment)?:return)

    // This routes the system back button to this Fragment
    requireFragmentManager().beginTransaction()
            .setPrimaryNavigationFragment(this)
            .commit()
}

This is actually the same technique that the app:defaultNavHost="true" attribute on NavHostFragment is using under the hood.


text:
Q: Prove that $||x|-|y|| \leq |x-y|$ $||x|-|y|| \leq |x-y|$  when $(x,y \in R^k)$
In Principles of MA(Rudin), the author said one sees easily that

$||x|-|y|| \leq |x-y|$  when $(x,y \in R^k)$ (p.88, Rudin)

from the triangle inequality.
But I'm not sure how to use the triangle inequality to show this.
Can you help me show this?

A: Using the triangle inequality, you obtain:
$$|x - y| \geq |x| - |y|$$
and
$$|y - x| \geq |y| - |x|.$$
Since $|x-y| = |y-x|$, you have that
$$-|x-y| \leq |x| - |y| \leq |x-y|$$
which gives the result.

A: $$|a|+|b|\ge |a+b|$$
Take $a=x-y, b=y$.  Then take $a=y-x, b=x$.

A: $|x|=|(x-y)+y|\le|x-y|+|y|$ so $|x|-|y|\le|x-y|$.
$|y|=|(y-x)+x|\le|x-y|+|x|$ so $|y|-|x|\le|x-y|$.
Altogether,
$||x|-|y||\le|x-y|$

A: Hint: You can write $|x| = |x-0|$


text:
Q: Powershell code Telnet website or ping website If there is no connection Works restart iis Please Help
I have a server win 2012
I have a There is website    www.forme.com.ph
I have a problem stopping iis sometimes
I want code Powershell
Do the following
Telnet website or ping website.
If there is a connection Nothing works .
If there is no connection Works restart  iis

A: Test if you can "ping" a website:
#basic test to see if you can connect to the port
$tcp = [System.Net.Sockets.TcpClient]::new()
try {
    $tcp.Connect('example.com', 443)
    $tcp.Dispose()
} catch {
    #put code to restart IIS here
}

Or:
#more thorough test to see if you can get a response from the web server
try {
    $response = Invoke-WebRequest -Uri 'https://example.com' -UseBasicParsing -Method Head
} catch {
    #put code to restart IIS here
}

Restart IIS:
& {iisreset}


text:
Q: how to resolve the error in the face detection project face detection Error  File "C:\Users\Mahesh_1\Desktop\face_Recognition\face_detector.py", line 7, in
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-o3uk2uiw\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
added snapshot of code install the required openCV package

A: put valid image name. look at your imp_img variable which .jpg loaded file. Which is not valid file name.


text:
Q: How do you wait until multiple onReady/services are ready until executing method I have a onReady (to wait for google maps to be ready) and an onConnected (to wait for the Google Api Client/Service to be connected). I want to run some code after both of those services are ready/connected (wait for the google map to be ready so I can display the user's last location on the map. The last location needs to be gotten from the Google Api Client). I am unsure how to do this in Java/Android and I am just starting out.
Thanks!


text:
Q: AngularJS Website looks different on different servers It's a problem that's been bugging me for a while and I can't find a solution online.
I have two identical angularJs sites.  They're basically copies of each other.  The only difference is that they are on different servers.
I create a site, it looks great on one server.  I make a copy of it...upload it...on a different server.  It looks drastically different.   The images and text are smaller.  It's as if the screen has been zoomed out by 300%.   Also the Button's are out of place.  On the original server...it was in the middle where I wanted it to be.  On the new one...it's retreated to the bottom left?
The first image is the screenshot of the original site.

The second Image is the screenshot of the copy site.  As you can see it looks different.

There's been no css changes and I'm viewing it on the same browser.
If it was a different browser...then I could understand the problem.
Does anyone know why?  Thanks.

A: CTRL F5 did the job!  Thanks everyone.


text:
Q: PrimeFaces commandButton actionListener not firing I am having trouble getting my actionListener in a
 to fire inside of a dialog. I've tried changing it to action, removing the (), adding the (), changing the scope of the managed bean, moving around the ajax statements and nothing has helped so far. Everything worked until I updated Netbeans, everything broke, somehow a library was removed, it was the commons-fileupload jar.
This happened with no changes to the code, only after netbeans updated. Netbeans 7.3, JSF2.2, Tomcat 7, jdk1.7, primefaces 4.0. There is a working version of this inside of my tomcat manager application, if I could possibly retrieve that hopefully everything would be back in working order but I can't find anything about getting the files back from tomcat. So my question is, why is this not firing? Is it the order of my calls in the button? I can't wrap my head around why this is not working.
EDIT Error I recieve after switching form and dialog positions -
    Jul 10, 2014 11:50:48 AM     com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
    SEVERE: Error Rendering View[/sampleExport.xhtml]
    javax.faces.FacesException: Cannot find component with expression ":searchDialogID" referenced from "mainForm:j_idt22".
    at   org.primefaces.expression.SearchExpressionFacade.resolveComponentInternal(SearchExpressionFacade.java:271)

EDIT 3 Revised
Bean
@ManagedBean
@ViewScoped
public class SampleExportController implements Serializable {

//Variables used to show or hide panels on the webpage
private boolean _addTill = false;
private boolean _allowAddingExport;
private boolean _allowDelExport;
private boolean _allowModExport;
private boolean _allowReading;
private boolean _previousCrop;
private boolean _spreadSelected;
//Variables Used For Whole Form
private ArrayList<Account> _agronomers;

private StreamedContent _file;
private ArrayList<String> _growers;
private SampleSearch _search;
private LabSampleHelper _labHelper;
private ArrayList<AdminLabNumber> _labNumbers;
private NutrientsGuide _nutriGuide;
private SampleAdminHelper _saHelper;
private List<String> _sampleTypes;
private SampleAlter _selectedSample;
private AdminLabNumber _selectedLab;
private QueryHelper _qHelper;
private List<String> _years;

public SampleExportController() {
    AllowedRights awdRight = AllowedRights.getAllowedRights();
    Access rights = awdRight.getAccessRigths("exportSample");
    if (rights != null) {
        _allowAddingExport = rights.getOperationAdd();
        _allowDelExport = rights.getOperationDel();
        _allowModExport = rights.getOperationMod();
        _allowReading = rights.getReadAccess();
    } else {
        _allowAddingExport = false;
        _allowDelExport = false;
        _allowModExport = false;
        _allowReading = false;
    }
    _search = new SampleSearch();
    _saHelper = new SampleAdminHelper();
    _qHelper = new QueryHelper();
    _years = _saHelper.getYears();
    if (_years != null && !_years.isEmpty()) {
        _search.setYear(_years.get(0));
    }
    _sampleTypes = _saHelper.getSampleTypes();
    _labHelper = new LabSampleHelper();
}

public void initSearch() {
    AccountHelper acHelper = new AccountHelper();
    _agronomers = acHelper.getAllAgronomers();
    SampleAdminHelper saHelper = new SampleAdminHelper();
    _growers = saHelper.getAllGrowers();
}

public void loadSearch() {
    UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":mainForm:DTsamples");
    table.setValueExpression("sortBy", null);
    _search.setStage("Completed");
    _labNumbers = _saHelper.exportSampleSearch(_search);
    ExportFormatHelper efHelper = new ExportFormatHelper();
    for (int i = 0; i < _labNumbers.size(); i++) {
        _labNumbers.get(i).addExportSettings(efHelper.getFormats(_labNumbers.get(i).getAccountNumber(), _labNumbers.get(i).getSampleType()));
    }
    //loadExportSettings from account
    _agronomers.clear();
    _growers.clear();
}

/**
 * @return the _search
 */
public SampleSearch getSearch() {
    return _search;
}

/**
 * @return the _labNumbers
 */
public ArrayList<AdminLabNumber> getLabNumbers() {
    return _labNumbers;
}

/**
 * @return the _agronomers
 */
public ArrayList<Account> getAgronomers() {
    return _agronomers;
}

/**
 * @return the _growers
 */
public ArrayList<String> getGrowers() {
    return _growers;
}

/**
 * @return the _selectedSample
 */
public SampleAlter getSelectedSample() {
    return _selectedSample;
}

/**
 * @param selectedSample the _selectedSample to set
 */
public void setSelectedSample(SampleAlter selectedSample) {
    this._selectedSample = selectedSample;
    //This gets the value of the initial till level from the sample
    _initialTill = _selectedSample.getTilled();
    _initialPreviousCrop = _selectedSample.getPreviousCrop();
    if (selectedSample.getSampleType().equalsIgnoreCase("Soil")) {

        if (_crop1 == null | _crop2 == null || _crop3 == null) {
            _crop1 = new CropGuide(_qHelper, _selectedSample);
            _crop2 = new CropGuide(_qHelper, _selectedSample);

            _crop3 = new CropGuide(_qHelper, _selectedSample);
        }
        _nutriGuide = new NutrientsGuide(_crop1.getRec(),_selectedSample);
        boolean flag1, flag2, flag3;
        flag1 = _crop1.refresh();
        flag2 = _crop2.refresh();
        flag3 = _crop3.refresh();
        if (flag1 || flag2 || flag3) {
            RequestContext.getCurrentInstance().update("nutrientguides");
        }
    }
}

/**
 * @return the _file
 */
public StreamedContent getFile() {
    return _file;
}

/**
 * @return the _selectedLab
 */
public AdminLabNumber getSelectedLab() {
    return _selectedLab;
}

/**
 * @param selectedLab the _selectedLab to set
 */
public void setSelectedLab(AdminLabNumber selectedLab) {
    this._selectedLab = selectedLab;
}

/**
 * @return the _years
 */
public List<String> getYears() {
    return _years;
}

/**
 * @return the _sampleTypes
 */
public List<String> getSampleTypes() {
    return _sampleTypes;
}

public void setPreviousCrop(boolean _previousCrop) {
    this._previousCrop = _previousCrop;
}

}

xhtml mostly full
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:body>
    <ui:composition template="template/desktop_viewer.xhtml">
        <ui:define name="PageName">
            <title>Sample Export</title>
        </ui:define>

        <ui:define name="PageHeader">
            Sample Export
        </ui:define>

        <ui:define name="PageLocation">
            Viewer
        </ui:define>

        <ui:define name="Body" >

            <h:form id="mainForm" rendered="#{sampleExportController.allowReading eq true}">

                    <f:facet name="start">
                        <h:graphicImage value="./resources/images/ajaxloading.gif" />
                    </f:facet>
                    <f:facet name="complete">
                        <h:outputText value="" />
                    </f:facet>

                        #{labNumbers.number}

                        #{labNumbers.sampleType}

                            <f:facet name="header">

                                        Submitter

                                        Lab Number Report Export

                                        Lab Number CSV Export

                            </f:facet>

                                    <h:panelGrid columns="1" styleClass="Ignore" >
                                        <h:outputText value=" #{''.concat(labNumbers.getSamples().get(0).agronomer.accountNumber).concat(' - ').concat(labNumbers.getSamples().get(0).agronomer.lastName ).concat(' , ').concat(labNumbers.getSamples().get(0).agronomer.firstName)}"/>

                                        <h:outputText value=" #{'Email: '.concat(labNumbers.getSamples().get(0).agronomer.primaryEmail)}"/>
                                        <h:outputText value=" #{'Email 2: '.concat(labNumbers.getSamples().get(0).agronomer.email2)}"/>
                                        <h:outputText value=" #{'Email 3: '.concat(labNumbers.getSamples().get(0).agronomer.email3)}"/>
                                    </h:panelGrid>

                                    <h:panelGrid styleClass="Ignore">

                                    </h:panelGrid>

                                        <f:selectItem itemLabel="Select One" itemValue="" />
                                        <f:selectItems value="#{labNumbers.exportSettings}" var="export" itemLabel="#{export}" itemValue="#{export}" />

                                #{sampleheader.containerID}

                                #{sampleheader.sampleID}

                                #{sampleheader.fieldID}

                                #{sampleheader.grower}

                                #{sampleheader.sampleType}

                                #{sampleheader.note}

                                    <f:setPropertyActionListener value="#{sampleheader}" target="#{sampleExportController.selectedSample}" />

            </h:form>
            <h:outputText value="Nice Try" rendered="#{sampleExportController.allowReading eq false}"/>
            <h:form id="innerSearch">

                    <h:panelGrid columns="4">
                        <h:outputText value="Starting Lab Number:"/>

                        <h:outputText value="Ending Lab Number:"/>

                        <h:outputText value="Starting Container ID:"/>

                        <h:outputText value="Ending Container ID:"/>

                        <h:outputText value="Season:"/>

                            <f:selectItem itemLabel="Select One" itemValue="" />
                            <f:selectItems value="#{sampleExportController.years}" var="year" itemLabel="#{year}" itemValue="#{year}"/>

                    </h:panelGrid>
                    <h:panelGrid columns="2">

                            <f:selectItem itemLabel="Select One" itemValue="" />
                            <f:selectItems value="#{sampleExportController.agronomers}" var="agronomer" itemLabel="#{agronomer.lastName} #{agronomer.company} #{agronomer.firstName} #{agronomer.accountNumber}" itemValue="#{agronomer}"/>

                                Base Ac. #: #{p.account.accountNumber}

                                Company Name: #{p.company}
First Name:#{p.firstName}
Last Name:#{p.lastName}

                        <h:outputText value="Sample Type:"/>

                            <f:selectItem itemLabel="Select One" itemValue="" />
                            <f:selectItems value="#{sampleExportController.sampleTypes}" var="stype" itemLabel="#{stype}" itemValue="#{stype}"/>

                            <f:selectItem itemLabel="Select One" itemValue="" />
                            <f:selectItems value="#{sampleExportController.growers}" var="grower" itemLabel="#{grower}" itemValue="#{grower}"/>

                    </h:panelGrid>

            </h:form>

                <h:form id="innerView">
                    <h:panelGrid columns="2" width="100%">
                        <h:panelGrid>

                                <f:facet name="header">

                                            CSV Single Sample Report

                                            Single Sample Report Export

                                            Lab Number Report Export

                                </f:facet>

+ random ending tags

A: The problem resides in your dialog. There's p:commandButton that contains the following:

`

It should be update=":mainForm:DTsamples" since you need to reference the id and not the widgetVar. Have a nice day!


text:
Q: CSS Inheritance not working as expected So I have html and css that looks like the following..

 Foo text

 Bar text

And then I have some css that looks like the following...
    #foo p {
    text-align:left;
    font-family: helvetica, verdana, sans;
    font-size: 14px;
    color: #000000;
    padding: 10px 10px 10px 10px;
    margin: 0px 0px 0px 0px;
    }
    #bar p {
    font-size: 12px;
    color: #ffffff;
    padding: 0px 0px 0px 0px;
    }

So isn't the point of CSS to override the styles applied to the child from the parent foo? It's not doing this, I just get the child styles overridden by the parent. I'm clearly missing something big here, any help would be great.

A: I think you're confused, or have coded yourself blind. :) What you have works perfectly well, it is your intentions that I suspect is off. What you're thinking is that the first set of styles should be inherited and then overwritten by the second, but if you look to your HTML, that's not the structure you've put in place.
You're saying #foo's
's should have the first style, but the second set of styles are in a
, and hence not applied. The second p is in a
, and hence will not have the first rules which are for elements under a
.
If you want the styles to inherit, wrap your
 into your
 (even though structurally not good, nor valid in a number of schemas);

 Foo text

 Bar text

I'm not sure what you're trying to do, though, so it's a bit hard to come up with good examples to solve your problem. :)

A: Look Chris you're misunderstanding CSS selectors and their inheritance ...
Nothing will explain it better than this presentation by Russ Weakly
CSS Cascade


text:
Q: Haskell do notation vs (>>) operator, happstack routing with 'method' I am learning Haskell, and I'm trying to learn the happstack server as well.
I am following the guide at http://happstack.com/docs/crashcourse/index.html#matching-on-request-method-get-post-etc , and their usage of the 'dir' and 'method' functions isn't working in my case.
I am trying to split up the routing sections into helper functions for my sanity, by I am having a hard time understanding how to properly handle the return types in regards to do blocks, the unit ('()') type, and monads.
The repository for my learner project isn't public yet, so I will paste the relevant code in it's entirety here.
EDIT: the below code is using tabs for indentation
main :: IO ()
--main = simpleHTTP nullConf $ ok "Hello, Haskell!!!"
main = simpleHTTP nullConf $ msum
    [
    dir "signup" $ serveFile (asContentType "text/html") "static/index.html",
    dir "static" $ serveDirectory DisableBrowsing [] "static",
    dir "api" api
    --do dir "account" $ ok $ toResponse "account page",
    --do dir "welcome" $ ok $ toResponse "welcome page",
    ----dir "api" $ ok $ toResponse "api endpoint",
    ----do dir "api" $ dir "person" (do method PUT
    ----                ok $ toResponse "api/person"),
    --(do dir "api" $ apiRouting),
    --do dir "static" $ serveDirectory DisableBrowsing [] "static"
    ----seeOther "welcome" ""
    ]

--apiRouting :: (ToMessage a) => ServerPartT IO a
--apiRouting = do
--  dir "person" (do method PUT ok $ toResponse "api/person")

--personHandler :: ServerPartT IO String
--personHandler = return (method PUT (return ok $ toResponse "api/person"))

api :: ServerPartT IO Response
api = msum
    [
        dir "person" person
    ]

person :: ServerPartT IO Response
-- this works
-- person = ok $ toResponse "api/person"
--so does this
--person = msum
--  [
--      ok $ toResponse "api/person"
--  ]
person = msum
    [
        --so, method PUT does nothing besides control which code branch is ran, based on the request
        --that is why the happstack tutorial was using do notation
        --but for some reason, do notation did not work when I tried it
        --if it was because of whitespace or indentation, that's just silly
        --this is the same as the happstack guide, doesn't work because "Couldn't match type '()' with 'Response -> ServerPartT IO Response'"
        (do method PUT
            ok $ toResponse "api/person put")
        --this works and I think this syntax is nicer, but why does the do block not work?
        --the thing1 >> thing2 operator does thing1, ignores any return value it might have had, and then returns the result of thing2
        --method PUT >> (ok $ toResponse "api/person put")
    ]

for some reason, the do method PUT way does not work, but the '>>' way does.
I was afraid that the do block wasn't returning what I wanted it to, so I tried to use the 'return' statement, but to no avail.
In the Happstack guide, it looks like this:
main :: IO ()
main = simpleHTTP nullConf $ msum
       [ do dir "foo" $ do method GET
                           ok $ "You did a GET request on /foo\n"
       , do method GET
            ok $ "You did a GET request.\n"
       , do method POST
            ok $ "You did a POST request.\n"
       ]

I've tried things like below, but it doesn't work.
person = msum
    [
        --so, method PUT does nothing besides control which code branch is ran, based on the request
        --that is why the happstack tutorial was using do notation
        --but for some reason, do notation did not work when I tried it
        --if it was because of whitespace or indentation, that's just silly
        --this is the same as the happstack guide, doesn't work because "Couldn't match type '()' with 'Response -> ServerPartT IO Response'"
        do method PUT
            (return (ok $ toResponse "api/person put"))
        --this works and I think this syntax is nicer, but why does the do block not work?
        --the thing1 >> thing2 operator does thing1, ignores any return value it might have had, and then returns the result of thing2
        --method PUT >> (ok $ toResponse "api/person put")
    ]

I thought that do blocks return the result of their last statement, but from the error message it looks like the 'do method PUT' part is just returning '()', which I understand to be similar to the void or unit types in other languages.
I am working my way through Learn You A Haskell, but when I try and do some hands-on learning like this I run into a bunch of gotchas.
EDIT: entire compiler error
web/app/Main.hs:72:20: error:
    • Couldn't match type '()' with 'ServerPartT IO Response'
      Expected: m0 (m1 Response) -> ServerPartT IO Response
        Actual: m0 (m1 Response) -> ()
    • In the result of a function call
      In a stmt of a 'do' block:
        method PUT (return (ok $ toResponse "api/person put"))
      In the expression:
        do method PUT (return (ok $ toResponse "api/person put"))
   |
72 |                 do method PUT

A: person = msum
    [
        do method PUT
            (return (ok $ toResponse "api/person put"))
    ]

Causes the error:
    • Couldn't match type '()' with 'ServerPartT IO Response'
      Expected: m0 (m1 Response) -> ServerPartT IO Response
        Actual: m0 (m1 Response) -> ()

because the indentation in the do block is incorrect. The 'return' keyword here is incorrect, as well.
The alignment rules of a 'do' block are such that the first character of the first word after the 'do' block becomes the column value that all subsequent lines of the do block must be aligned with.
Because the 'm' in 'method' did not line up with the second statement in the do block, the do block actually only contained the contents do method PUT. EDIT: The too indented line was actually being interpreted as a continuation of the method PUT expression, becoming do method PUT (return (ok $ toResponse "api/person put")) Thanks, Ben!
The Happstack 'method' function has the return type
ghci> :t method
method
  :: (Happstack.Server.Internal.Monads.ServerMonad m, MonadPlus m,
      Happstack.Server.Routing.MatchMethod method) =>
     method -> m ()

, so the value that the do block "returned" ended up just being m (), causing the error.
If you use tabs instead of spaces, it is necessary to place the first keyword after a statement that creates a block, like 'do', on a new line.
person :: ServerPartT IO Response
person = msum
    [
        do
            method PUT
            ok $ toResponse "api/person put",
        do
            method GET
            ok $ toResponse "api/person get",
        do
            method DELETE
            ok $ toResponse "api/person delete"
    ]

EDIT: read this too
An example from the wikibook is as follows, and an alternative way of solving these white-space related issues would be to use the curly bracket and semicolon syntax:
do { putStr "Hello"
   ; putStr " "
   ; putStr "world!"
   ; putStr "\n" }


text:
Q: How To Navigate Between Pages with PageView and NavigationBar Together- Flutter I want to navigate different pages with pageview and navigationbar together. These pages will have different Scaffolds because some pages include appbar some don't. I see different examples but all of them use the same scaffold but different body widgets. How can I do that?
I am thinking of using PageView as a parent widget and all of the other pages will be in the list. Also, I will add these pages parameter for the navigation bar index. So when I go to another page by swiping, a new page will come and at this new page, because of the index that I am getting as a parameter, navigationbar item will be seen as selected. Is it a viable solution? I don't want to cripple my app performance

A: If I got your problem right, You Could use the main screen to have another screen under as using the bottom navigation to the main screen and give the other screens to the bottom navigation and make the main Scaffold to take the screens by making the screen you want to use in the body of the main Scaffold and change its index with the bottom navigation and the page view and then you can have a scaffold for each page like the example below:
PageView(
  physics: const BouncingScrollPhysics(),
  controller: _pageViewController,
  children: cubit.screens,
  onPageChanged: (index) {
    cubit.changeIndex(index);
  },
),
bottomNavigationBar: BottomNavigationBar(
  currentIndex: cubit.currentIndex,
  onTap: (index) {
    if (index == 2) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => NewPostScreen(),
        ),
      );
    } else {
      _pageViewController.animateToPage(
        index,
        duration: const Duration(milliseconds: 500),
        curve: Curves.fastLinearToSlowEaseIn
      );
      cubit.changeIndex(index);
    }
  },
  items: const[
    BottomNavigationBarItem(
      icon: Icon(Iconsax.home_11),
      label: 'News Feed',
    ),
    BottomNavigationBarItem(
      icon: Icon(Iconsax.notification5),
      label:  'Notifications',
    ),
    BottomNavigationBarItem(
      icon: Icon(Iconsax.add),
      label: 'New Post',
    ),
    BottomNavigationBarItem(
      icon: Icon(Iconsax.people5),
      label:  'Users',
    ),
    BottomNavigationBarItem(
      icon: Icon(Iconsax.profile_2user5),
      label: 'Profile',
    ),
  ],
),

A: my solution is adding setstate indexNumber into each of the button that is not includes in the appbar, for example if i have 3 items menu in the appbar, then it containt indexNumber = 0, 1, 2. the other button outside of appbar, you can add like indexNumber = 3, 4 and so on as you need.


text:
Q: Sharding existing postgresql database with PostgresXL We want to shard our PostgreSQL DB, due to high disk load. Firstly, we looked at django-sharding library, but:

*

*Very much rewriting in our backend

*Migrating all tables to 64-bit primary keys is hard work on 300-400gb tables

*Generating ids with Postgres Specific algorithm makes it impossible to move data from shard to shard. More than that, we have a large database with old ids. Updating all of them is a big problem too.

*Generating ids with special tables makes us do a special SELECT query to main database every time we insert data. We have high write load, so it's not good.

Considring all these, we decided too look on Postgres database sharding solutions. We found 2 opportunities - Citus and PostgresXL. Citus makes us change data format too much and rewrite a big bunch of backend at the same time, so we are about to try PostgresXL as more transparent solution. But reading the docs, I can't understand some things and will be greatfull for recomendations:

*

*Are there any other sharding workarounds except for Citus and PostgresXL? It would be good not to change much in our database on migrating.

*Some questions about PostgresXL:

*

*Do I understand correctly, that it's not Postgres extension, it's a standalone fork? So I should build all its parts from sources and than move data in some way?

*How are Postgres and PostgresXL versions compatible? We have PostgreSQL 9.4. I don't see such a version in PostgresXL (9.2 or 9.5 no middle?). So can I use, for example, streaming replication for migration?

*If yes/no, what is the best solution to migrate data? If I have 2Tb database with heavy write, can I migrate it somehow without stopping for a long period of time?

Thanks.

A: First off to save your self a LOT of headache have you looked at options Like Amazon's Auora, Dynomo, Red Shift, etc services?  They are VERY cost effective at scale, as well as optimized and managed for you.
Actually Amazon's straight Postgress databases can handle MASSIVE amounts of reads or writes.  We can go into 2,000- 6,000 IOPS on reads and another 2,000 to 6,000 IOPS in writes without issue.  I would really look into this as the option.  Azure, Oracle, and Google also have competing services.
Also be aware that Postgres-XL beyond all reason has no HA support.   If you lose a single node you lose everything.   The nodes can not fail over.

it's a standalone fork?

Yes,   They are very different apps and developed separate from each other.

How are Postgres and PostgresXL versions compatible?

They arn't compatible.  You can not just migration Postgres to Postgresl-XL.  They work VERY differently.

Generating ids with Postgres Specific algorithm makes it impossible to >move data from shard to shard

Not following this, but with sharing you are not supposed to move data from one shard to another.   The key being used generally needs to be something specific and unique to split/segregate your data on.   Like a date, or a "type" field, or some other (hopefully ordered) field(s)/column(s).  This breaks things up but has obvious pain in the a$$ limitations.

Are there any other sharding workarounds except for Citus and
    PostgresXL? It would be good not to change much in our database on >>migrating.

Tons of options, but right off the bat going from a standard RDS, to a NoSql, or MPP database is going to be a major migration, a lot of effort, and have a LOT of limitations no matter what you do.
Next Postress-XL and Citus are MPP (massive parallel processing) clustering apps, not sharing specifically.  That is part of what they can do, but it is not their focus.
Other options for MPP
pgPool -- (not great for heavy writes )
haProxy -- ( have not done it but read about it.   Lost of work to setup and maintain. )
MySql Cluster -- (Huge pain to use the OSS version and major $$$ for the commercial version)
Green Plumb
Teradata
Vertica

what is the best solution to migrate data?

Very unlikely to find a simple migration for this kind of switch.  You can expect to likely need to export the data your self from the existing RDS and import it to the new DB and will likely have to write something your self to get it the way you want it.


text:
Q: T-SQL Regex range in XML method nodes() I have a table T with two columns. Column A is a varchar column and Column B is a XML column.
Somewhere inside Column B there is always the following parent tag: <Documents> ... </Documents>. Inside there are some <Document>...</Document> children.
I would like to get a result set with two columns:
Column 1 should contain the same values of Column A;
Column 2 should contain the content of one <Document>...</Document> only.
Also, in column 2 there should only be <Document>s with attribute equal to 1, 2 or 3.
E.g. Starting table T:
Column A | Column B
--------------------------------------------------------------------------
abc      | <Documents><Document ID="1">Doc Foo</Document><Document ID="4">Doc Bar</Document></Documents>
def      | <Documents><Document ID="2">Doc Foo2</Document><Document ID="3">Doc Bar2</Document></Documents>

Expected result:
Column 1 | Column 2
-------------------------------------
abc      |<Document ID="1">Doc Foo</Document>
def      |<Document ID="2">Doc Foo2</Document>
def      |<Document ID="3">Doc Bar2</Document>

I can get the expected result like this:
SELECT
     [Column A]     AS [Column 1]
    ,T2.c.query('.') AS [Column 2]
FROM T AS tbl
    CROSS APPLY T.nodes('*/Documents/Document[@ID="1" or @ID="2" or @ID="3"]') AS T2(c)

But when filter conditions are more complex it can get out of control without regex.
This does not work:
SELECT
     [Column A]      AS [Column 1]
    ,T2.c.query('.') AS [Column 2]
FROM T AS tbl
    CROSS APPLY T.nodes('*/Documents/Document[@ID="[1-3]"]') AS T2(c)

How to make it work?

A: To expand on what @JeroenMostert suggests, and if he's correct, then perhaps what you are after is:
WITH YourTable AS(
    SELECT *
    FROM (VALUES('abc',CONVERT(xml,'<Documents><Document ID="1">Doc Foo</Document><Document ID="4">Doc Bar</Document></Documents>')),
                ('def',CONVERT(xml,'<Documents><Document ID="2">Doc Foo2</Document><Document ID="3">Doc Bar2</Document></Documents>')))V(Col1,Col2))
SELECT YT.Col1,
       Ds.D.query('.')
FROM YourTable YT
     CROSS APPLY YT.Col2.nodes('Documents/Document') Ds(D)
WHERE Ds.D.value('@ID','int') IN (1,2,3);

A: You could filter on the attribute to appear in a sequence of values:
Document[@ID = (1,2,3)]

A: You were very close. XQuery is based on the notion of sequences. So you need to check if the @ID attribute value is a member of the sequence.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID CHAR(3), xmldata XML);;
INSERT INTO @tbl (ID, xmldata)
VALUES
('abc', '<Documents><Document ID="1">Doc Foo</Document><Document ID="4">Doc Bar</Document></Documents>')
, ('def', '<Documents><Document ID="2">Doc Foo2</Document><Document ID="3">Doc Bar2</Document></Documents>');
-- DDL and sample data population, end

SELECT ID
    , c.query('.') AS [Column 2]
FROM @tbl AS tbl
    CROSS APPLY tbl.xmldata.nodes('/Documents/Document[@ID=("1","2","3")]') AS t(c);

Output

+-----+--------------------------------------+
| ID  |               Column 2               |
+-----+--------------------------------------+
| abc | <Document ID="1">Doc Foo</Document>  |
| def | <Document ID="2">Doc Foo2</Document> |
| def | <Document ID="3">Doc Bar2</Document> |
+-----+--------------------------------------+


text:
Q: What is best option for dealing with date types in Android? What is at the moment best option for dealing with date in time in Android development, since Android studio doesn't yet support Java 8 (and new java.time package) (if I am correct)?

A: tl;dr

*

*ThreeTenABP

*

*How to use…
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Java 6 & 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android: ThreeTenABP
That back-port is further adapted to Android in ThreeTenABP (see How to use…).
You should definitely avoid the troublesome confusing mess that is the legacy date-time classes.

A: *

*Support for Java 8 language features requires a new compiler called
Jack. Jack is supported only on Android Studio 2.1 and higher. So if
you want to use Java 8 language features, you need to use Android
Studio 2.1 to build your app. Source: developer.android.com/guide/platform/j8-jack.html

*For date's and Timestamp you can see the links given below: using [java.util.Date]https://developer.android.com/reference/java/util/Date.html Or By using [java.text.SimpleDateFormat] https://developer.android.com/reference/java/text/SimpleDateFormat.html


text:
Q: Proof for triangle inequality for case $x+y<0$ Here's the attempt in case $x+y<0$:
In case $$x+y<0,$$ it must be true that $$(x<0\wedge y<0)$$
$$x\in \mathbb{R}\text{ is negative IFF }-x\in \mathbb{R}^+$$
$$x + y < 0 < -(x + y) = (-x)+(-y) = x + y < |x| + y < |x| + |y| \ (\forall x\land \forall y)\in \mathbb{R}$$
Does this looks right?

A: Note that $x+y < 0$ does not imply that $x < 0 \land y<0$. (For example: $x=-10$, $y=9$.)
Your remark that $x\in\mathbb{R}$ is negative iff $-x \in \mathbb{R}^+$ is correct.
Your equality $(-x)+(-y) = x + y$ is mistaken. Note that you have $x + y < 0 < \ldots x + y < \ldots$. That doesn't work.
Finally, note that $x < |x|$ is not necessarily true. You want $x \leq |x|$.

A: $-|x| \leq x \leq |x|$
and $-|y| \leq y \leq |y|$ $\implies$ $-|x|-|y| \leq x+y \leq |x|+|y|$ $\implies$ $|x+y| \leq |x| +|y|$ for any real $x,y$
The last implication comes from the fact:
$|x| \leq a \leftrightarrow -a \leq x \leq a$ for some $a \geq 0$


text:
Q: Is the Transpose of a Representation an Equivalent Representation? Suppose we are working over $\mathbf{Z}[G]$ where $G$ is finite. Suppose further we have two representations $\rho$ and $\rho^\prime$ such that $\rho^\prime=(\rho)^T$. Can we say that these two representations are equivalent?
I know that if we were working over $\mathbf{C}$ then we could consider characters since these two representations have the same character and are therefore equivalent, but does this method survive the transition to integral representation?


text:
Q: R Shiny: Removing item from renderPlot and referring to it again I have code inside the renderPlot option of a shiny app that I would like the pull into a separate reactive context. However, I'm having trouble figuring out how to do so and still be able to refer to the table.
What I want is to be able to pull the first section into it's own reactive context and then refer to it in the renderPlot, but I'm not sure how to do that considering the data source for the matrix is conditional on one of the inputs. Thanks in advance!
Current code:
output$distPlot <- renderPlot({
if (input$predictor == "bin") {matrix(0,ncol=1, nrow=input$n) -> predictor; predictor[1:input$pos] <- 1}
if (input$predictor == "norm") {predictor <- matrix(rnorm(input$n,input$pred_mean, input$pred_sd),ncol=1,nrow=input$n)}
if (input$predictor == "user") {inFile <- input$predictor2; predictor <- as.matrix(read.delim2(inFile$datapath, header=F), ncol=1)}
....
data <- sim(input$n,input$coverage[1], input$coverage[2], predictor)
....
})

Desired Code (conceptual)
predictor <- reactive({
if (input$predictor == "bin") {matrix(0,ncol=1, nrow=input$n) -> predictor; predictor[1:input$pos] <- 1}
if (input$predictor == "norm") {predictor <- matrix(rnorm(input$n,input$pred_mean, input$pred_sd),ncol=1,nrow=input$n)}
if (input$predictor == "user") {inFile <- input$predictor2; predictor <- as.matrix(read.delim2(inFile$datapath, header=F), ncol=1)}
})

output$distPlot <- renderPlot({
data <- sim(input$n,input$coverage[1], input$coverage[2], predictor)
....
})


text:
Q: Variables are "lost" somewhere, then reappear... all with no error thrown I'm probably going to make myself look like a fool with my horrible scripting but here we go.
I have a form that I am collecting a bunch of checkbox info from using a binary method.  ON/SET=1  !ISSET=0
Anyway, all seems to be going as planned except for the query bit.  When I run the script, it runs through and throws no errors, but it's not doing what I think I am telling it tom which is updating the specified fields within the DB.
I've hard coded the desired values into the query and it DOES update the DB.  Relying on the variables I believe I've established and am then calling upon in the query does NOT update the DB.
I've also tried echoing all the needed variables after the script runs and exiting right after so I can audit them... and they're all there.  Here's an example.
  ####FEATURES RECORD UPDATE
### HERE I DECIDE TO RUN THE SCRIPT BASED ON WHETHER AN IMAGE BUTTON WAS USED
if (isset($_POST["button_x"])) {

### HERE I AM ASSIGNING 1 OR 0 TO A VAR BASED ON WHTER THE CHECKBOX WAS SET
if (isset($_POST["pool"])) $pool=1;
if (!isset($_POST["pool"])) $pool=0;
if (isset($_POST["darts"])) $darts=1;
if (!isset($_POST["darts"])) $darts=0;
if (isset($_POST["karaoke"])) $karaoke=1;
if (!isset($_POST["karaoke"])) $karaoke=0;
if (isset($_POST["trivia"])) $trivia=1;
if (!isset($_POST["trivia"])) $trivia=0;
if (isset($_POST["wii"])) $wii=1;
if (!isset($_POST["wii"])) $wii=0;
if (isset($_POST["guitarhero"])) $guitarhero=1;
if (!isset($_POST["guitarhero"])) $guitarhero=0;
if (isset($_POST["megatouch"])) $megatouch=1;
if (!isset($_POST["megatouch"])) $megatouch=0;
if (isset($_POST["arcade"])) $arcade=1;
if (!isset($_POST["arcade"])) $arcade=0;
if (isset($_POST["jukebox"])) $jukebox=1;
if (!isset($_POST["jukebox"])) $jukebox=0;
if (isset($_POST["dancefloor"])) $dancefloor=1;
if (!isset($_POST["dancefloor"])) $dancefloor=0;

### I'VE DONE LOADS OF PERMUTATIONS HERE... HARD SET THE 1/0 VARS AND LEFT THE $estab_id TO BE PICKED UP.  SET THE $estab_id AND LEFT THE COLUMN DATA TO BE PICKED UP.  ALL NO GOOD.  IT _DOES_ WORK IF I HARD SET ALL VARS THOUGH

mysql_query("UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'");

 ###WEIRD THING HERE IS IF I ECHO THE VARS AT THIS POINT AND THEN EXIT(); they all show up as intended.

header("location:theadminfilething.php");
exit();

THANKS ALL!!!

A: I recommend you to use something like:
$fields = array('pool', 'darts', 'karaoke', 'trivia', ...);
foreach ( $fields as $field ) {
    $$field = isset($_POST[$field]) ? 1 : 0;
}

instead of 20 lines of ifs.
Your columns are ENUM or int type ? If int - drop apostrophes.

A: Your code could really use some error checking. Make sure you have activated the displaying of errors in your script.
In your testing environment add this at the top of your main script for instance (if you haven't done something equivalent already):
error_reporting( E_ALL | E_STRICT );
ini_set( 'display_errors', 1 );

Then (although not dependant on the above) make sure you probe the result of the query with something like:
if( false === mysql_query( 'UPDATE ...etc' ) )
{
   echo 'query failed with error:' . mysql_error();
}

My guess is it will fail with the error that your column name karaoke is mispelled. But there may be more errors.
Also, hsz' suggestions are spot on (though probably not the root of your problem). Makes for easier to maintain code, and significantly reduces code.

A: Firstly, construct the sql query string in a variable and then pass it to mysql_query(), comment out the header() line and print out the query for debugging. For example:
...
$sql="UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'";
print("$sql");
mysql_query($sql);
//header("location:theadminfilething.php");
exit();
...

Secondly, even tho you are exiting the script, its good practice to always match your braces. You are missing the end brace for the if statement at the end of your code.
The value of the $sql variable output you can see if it works by executing it 'manually' thru phpmyadmin or the command line. What happens?


text:
Q: Exclude Logback logging My log4j.properties file is not used but configured correctly (VM args: -Dlog4j.debug=true) Instead it seems to me, that one required lib (via ivy) is using logback and now some logback default layout pattern is used.
How can I prevent, that my app uses logback instead of log4j? Any ideas? Or how can I use sth. like -Dlog4j.debug=true for logback?
At the moment I just exclude the logback lib in one loaded ivy lib with logback dependency. Is there a better way?

A: Remove any logback-classic.jar and  logback-core.jar from your classpath (files may contain version numbers). If you have dependencies in Maven, exclude logback (example for log4j).

A: <exclude org="log4j"/>
<exclude org="logback-classic"/>
<exclude org="logback-core"/>

if these dependencies are coming with another dependency then you need to exclude like below
 <dependency org="...." name=".." rev="..." conf="...">
      <exclude org="logback-classic"/>
      <exclude org="logback-core"/>
</dependency>


text:
Q: Invalidate an element forming a path if it is surrounded I'm building a 2D grid game composed of cells in which players have to put tokens and try to contain (encircle) the opponent's tokens. Now each cell can have 3 states: empty, contains a red token or contains a blue token.
All cells that can form a "path" are in a list, and along that path I can draw lines (polygons) passing by the center of cells.
Also there is a list of contained tokens, the one being encircled,
Now I want to find a way to "invalidate" an encircled token so it can be ignored by path calculations
See examples below:

*

*Blue tokens are encircled first, they cannot be apart of any further path calculation.

*This cannot be allowed. First to contain, first to win.

All codes below are from the path class:
class Path extends Stack<int[]>{

    private Token[][] grid;

    //a path shorter than min can not surround any cell
    private static final int MIN_PATH_LEGTH = 3;

    //a collection of cells that has been tested
    private ArrayList<int[]>checked;

    //represents the cell where the search starts from
    int[] origin;
    //represents the token of the origin
    Token originToken;

    private int rows;
    private int cols;

    //represents the path bounds: min/max row/col in path
    private int minPathRow, maxPathRow, minPathCol, maxPathCol;

    Path(Token[][] grid){

        this.grid = grid;
        rows = grid.length;
        cols = grid[0].length;
    }

    //search for a path
    boolean findPath(int[] origin) {

        this.origin = origin;

        int row = origin[0] , col =  origin[1];

        //represents the token of the origin
        originToken = grid[row][col];

        //initialize list of checked items
        checked = new  CellsList();

        boolean found = findPath(row, col);

        if(found) {
            printPath();
        } else {
            System.out.println("No path found");
        }

        return found;
    }

    //recursive method to find path. a cell is represented by its row, col
    //returns true when path was found
    private boolean findPath(int row, int col) {

        //check if cell has the same token as origin
        if(grid[row][col] != originToken) {
            return false;
        }

        int[] cell = new int[] {row, col};

        //check if this cell was tested before to avoid checking again
        if(checked.contains(cell)) {
            return false;
        }

        //get cells neighbors
        CellsList neighbors = getNeighbors(row, col);

        //check if solution found. If path size > min and cell
        //neighbors contain the origin it means that path was found
        if((size() >= MIN_PATH_LEGTH) && neighbors.contains(origin)  ) {

            add(cell);
            return true;
        }

        //add cell to checked
        checked.add(cell);

        //add cell to path
        add(cell);

        //if path was not found check cell neighbors
        for(int[] neighbor : neighbors ) {

            boolean found = findPath(neighbor[0],neighbor[1]);
            if(found) {
                return true;
            }
        }

        //path not found
        pop(); //remove last element from stack
        return false;
    }

    //use for testing
    private void printPath() {

        System.out.print("Path : " );
        for(int[] cell : this) {
            System.out.print(Arrays.toString(cell));
        }
        System.out.println("");

        List<int[]> containedCells = getContainedWithin();

        System.out.print(containedCells.size() +" cell contained : " );
        for(int[] cell : containedCells) {
            System.out.print(Arrays.toString(cell));
        }
        System.out.println("");
    }

    CellsList getPath() {

        CellsList cl = new CellsList();
        cl.addAll(this);
        return cl;
    }
}

The code below finds the neighbors of a cell (path.java):
//return a list of all neighbors of cell row, col
        private CellsList getNeighbors(int  row, int col) {

            CellsList neighbors = new CellsList();

            for (int colNum = col - 1 ; colNum <= (col + 1) ; colNum +=1  ) {

                for (int rowNum = row - 1 ; rowNum <= (row + 1) ; rowNum +=1  ) {

                    if(!((colNum == col) && (rowNum == row))) {

                        if(isWithinGrid (rowNum, colNum )  ) {

                            neighbors.add( new int[] {rowNum, colNum});

                        }
                    }
                }
            }

            return neighbors;
        }

        private boolean isWithinGrid(int colNum, int rowNum) {

            if((colNum < 0) || (rowNum <0) ) {
                return false;
            }
            if((colNum >= cols) || (rowNum >= rows)) {
                return false;
            }
            return true;
        }
    }

The below code finds all bounded cell by a path (all contained or encircled tokens) and their token is of the opposite color of the path:
List<int[]> getContainedWithin() {

        //find path max and min X values, max and min Y values
        minPathRow = grid[0].length; //set min to the largest possible value
        maxPathCol = grid.length;
        maxPathRow = 0;              //set max to the largest possible value
        maxPathCol = 0;

        //find the actual min max x y values of the path
        for (int[] cell : this) {
            minPathRow = Math.min(minPathRow, cell[0]);
            minPathCol = Math.min(minPathCol, cell[1]);
            maxPathRow = Math.max(maxPathRow, cell[0]);
            maxPathCol = Math.max(maxPathCol, cell[1]);
        }

        List<int[]> block = new ArrayList<>(25);
        int[] cell = get(0);//get an arbitrary cell in the path
        Token pathToken = grid[cell[0]][cell[1]]; //keep a reference to its token

        //iterate over all cells within path x, y limits
        for (int col = minPathCol; col < (maxPathCol); col++) {

            for (int row = minPathRow; row < (maxPathRow); row++) {

                //check cell color
                Token token = grid[row][col];
                if ((token == pathToken) || (token == Token.VIDE)) {
                    continue;
                }
                if (isWithinLoop(row,col)) {
                    block.add(new int[] {row, col});
                }
            }
        }

        return block;
    }

    //check if row, col represent a cell within path by checking if it has a
    //path-cell to its left, right, top and bottom
    private boolean isWithinLoop(int row, int col) {

        if(  isPathCellOnLeft(row, col)
             &&
             isPathCellOnRight(row, col)
             &&
             isPathCellOnTop(row, col)
             &&
             isPathCellOnBottom(row, col)
          ) {
            return true;
        }

        return false;
    }
}

If you need more elements, just let me now, I'll update with the necessary.

A: This requirement means that previous paths, affect current path calculations. It can be achieved in many ways. The easiest, within current program structure could be adding a static collection of contained cells in all paths.
See allContainedWithin and the way it is used in the code.
Also note that I refactored getContainedWithin() to be a getter, and moved its functionality to a new method findContainedWithin().
All changes have no effect on other classes.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

//a stack representing cells in the path
//each cell represented by [row,col]
class Path extends Stack<int[]>{

    private Token[][] grid;

    //a path shorter than min can not surround any cell
    private static final int MIN_PATH_LEGTH = 3;

    //a collection of cells that has been tested
    private ArrayList<int[]>checked;

    //represents the cell where the search starts from
    int[] origin;
    //represents the token of the origin
    Token originToken;

    private int rows;
    private int cols;

    //represents the path bounds: min/max row/col in path
    private int minPathRow, maxPathRow, minPathCol, maxPathCol;

    //a collection of all cells that are bounded by the path
    //and their token is of the opposite color of the path
    private List<int[]> containedWithin;

    //a STATIC collection that holds all containedWithin cells, of
    //current and previous paths
    private static CellsList allContainedWithin = new CellsList();

    Path(Token[][] grid){

        this.grid = grid;
        rows = grid.length;
        cols = grid[0].length;
    }

    //search for a path
    boolean findPath(int[] origin) {

        this.origin = origin;

        int row = origin[0] , col =  origin[1];

        //represents the token of the origin
        originToken = grid[row][col];

        //initialize list of checked items
        checked = new  CellsList();

        boolean found = findPath(row, col);

        if(found) {

            //find bounded cells
            findContainedWithin();
            //update the collection all
            allContainedWithin.addAll(containedWithin);

            printPath();
        } else {
            System.out.println("No path found");
        }

        return found;
    }

    //recursive method to find path. a cell is represented by its row, col
    //returns true when path was found
    private boolean findPath(int row, int col) {

        //check if cell has the same token as origin
        if(grid[row][col] != originToken) {
            return false;
        }

        int[] cell = new int[] {row, col};

        //check if this cell was tested before to avoid checking again
        if(checked.contains(cell)) {
            return false;
        }

        //check if this cell was contained in previously calculated paths
        if(allContainedWithin.contains(cell)) {
            return false;
        }

        //get cells neighbors
        CellsList neighbors = getNeighbors(row, col);

        //check if solution found. If path size > min and cell
        //neighbors contain the origin it means that path was found
        if((size() >= MIN_PATH_LEGTH) && neighbors.contains(origin)  ) {

            add(cell);
            return true;
        }

        //add cell to checked
        checked.add(cell);

        //add cell to path
        add(cell);

        //if path was not found check cell neighbors
        for(int[] neighbor : neighbors ) {

            boolean found = findPath(neighbor[0],neighbor[1]);
            if(found) {
                return true;
            }
        }

        //path not found
        pop(); //remove last element from stack
        return false;
    }

    //return a list of all neighbors of cell row, col
    private CellsList getNeighbors(int  row, int col) {

        CellsList neighbors = new CellsList();

        for (int colNum = col - 1 ; colNum <= (col + 1) ; colNum +=1  ) {

            for (int rowNum = row - 1 ; rowNum <= (row + 1) ; rowNum +=1  ) {

                if(!((colNum == col) && (rowNum == row))) {

                    if(isWithinGrid (rowNum, colNum )  ) {

                        neighbors.add( new int[] {rowNum, colNum});
                    }
                }
            }
        }

        return neighbors;
    }

    private boolean isWithinGrid(int colNum, int rowNum) {

        if((colNum < 0) || (rowNum <0) ) {
            return false;
        }
        if((colNum >= cols) || (rowNum >= rows)) {
            return false;
        }
        return true;
    }

    //use for testing
    private void printPath() {

        System.out.print("Path : " );
        for(int[] cell : this) {
            System.out.print(Arrays.toString(cell));
        }
        System.out.println("");

        List<int[]> containedCells = getContainedWithin();

        System.out.print(containedCells.size()+" cell contained : " );
        for(int[] cell : containedCells) {
            System.out.print(Arrays.toString(cell));
        }
        System.out.println("");
    }

    CellsList getPath() {

        CellsList cl = new CellsList();
        cl.addAll(this);
        return cl;
    }

    //finds all cells that are bounded by the path
    //and their token is of the opposite color of the path
    private void findContainedWithin() {

        containedWithin = new ArrayList<>();

        //find path max and min X values, max and min Y values
        minPathRow = grid[0].length; //set min to the largest possible value
        maxPathCol = grid.length;
        maxPathRow = 0;              //set max to the largest possible value
        maxPathCol = 0;

        //find the actual min max x y values of the path
        for (int[] cell : this) {
            minPathRow = Math.min(minPathRow, cell[0]);
            minPathCol = Math.min(minPathCol, cell[1]);
            maxPathRow = Math.max(maxPathRow, cell[0]);
            maxPathCol = Math.max(maxPathCol, cell[1]);
        }

        //todo remove after testing
        System.out.println("x range: "+minPathRow + "-"
        + maxPathRow + " y range: " + minPathCol + "-" + maxPathCol);

        int[] cell = get(0);//get an arbitrary cell in the path
        Token pathToken = grid[cell[0]][cell[1]]; //keep a reference to its token

        //iterate over all cells within path x, y limits
        for (int col = minPathCol; col < (maxPathCol); col++) {

            for (int row = minPathRow; row < (maxPathRow); row++) {

                //check cell color
                Token token = grid[row][col];
                if ((token == pathToken) || (token == Token.VIDE)) {
                    continue;
                }
                if (isWithinLoop(row,col)) {
                    containedWithin.add(new int[] {row, col});
                }
            }
        }
    }

    //returns a collection of all cells that are bounded by the path
    //and their token is of the opposite color of the path
    List<int[]> getContainedWithin() {

        return containedWithin;
    }

    //check if row, col represent a cell with in path by checking if it has a
    //path-cell to its left, right, top and bottom
    private boolean isWithinLoop(int row, int col) {

        if(  isPathCellOnLeft(row, col)
             &&
             isPathCellOnRight(row, col)
             &&
             isPathCellOnTop(row, col)
             &&
             isPathCellOnBottom(row, col)
          ) {
            return true;
        }

        return false;
    }

    private boolean isPathCellOnLeft(int cellRow, int cellCol) {

        for ( int col = minPathCol; col < cellCol ; col++) {

            if(getPath().contains(new int[] {cellRow, col})) {
                return true;
            }
        }

        return false;
    }

    private boolean isPathCellOnRight(int cellRow, int cellCol) {

        for ( int col = cellCol; col <= maxPathCol ; col++) {

            if(getPath().contains(new int[] {cellRow, col})) {
                return true;
            }
        }

        return false;
    }

    private boolean isPathCellOnTop(int cellRow, int cellCol) {

        for ( int row =minPathRow; row < cellRow ; row++) {

            if(getPath().contains(new int[] {row, cellCol})) {
                return true;
            }
        }

        return false;
    }

    private boolean isPathCellOnBottom(int cellRow, int cellCol) {

        for ( int row = cellRow; row <= maxPathRow; row++) {

            if(getPath().contains(new int[] {row, cellCol})) {
                return true;
            }
        }

        return false;
    }
}

Note that I only run some basic testing like :

A: In addition to the previous answer, I would like to add an alternative which requires a deeper change in the program.
A better way to handle the requirement would be to change the representation of a cell. Instead of using int[]{row, col} , consider representing it by a Cell class which has attributes like row, col,token, contained etc.
 A simple implementation of Cell could be :
public class Cell {

    private int row, col;
    private Token token;
    private boolean isContained;

    Cell(int row, int col) {

        this(row, col, Token.VIDE);
    }

    Cell(int row, int col, Token token) {

        this.row = Math.abs(row); //to allow only positve addresses
        this.col = Math.abs(col);
        this.token = (token == null) ? Token.VIDE : token;
    }

    int getRow() {
        return row;
    }

    int getCol() {
        return col;
    }

    Token getToken() {
        return token;
    }

    boolean isContained() {
        return isContained;
    }

    void setRow(int row) {
        this.row = row;
    }

    void setCol(int col) {
        this.col = col;
    }

    void setToken(Token token) {
        this.token = token;
    }

    void setContained(boolean isContained) {
        this.isContained = isContained;
    }

    int[] getAddress() {
        return new int[] {row, col};
    }

    @Override
    public String toString() {
        return Arrays.toString(getAddress()) +"-"+ token;
    }

    @Override
    public boolean equals(Object cell) {

        if ((cell == null) || !(cell instanceof Cell)) {
            return false;
        }

        return Arrays.equals(getAddress(), ((Cell)cell).getAddress());
    }

    @Override
    public int hashCode() {

        return 31*row + 17*col;
    }
}

Note: This representation should be changed all across the program.
    (Not tested)


text:
Q: Ошибка компилятора при stdexcept Необходимо объявить исключение при введении юзером отрицательного числа.
В коде подключен #include <stdexcept>, но компилятор выдаёт ошибку "идентификатор invalid_argument не определен". Не могу понять причину.
    #include "jar.h"
#include <stdexcept>
#include <iostream>
#include <string>

void JarType::unitToEmpty()
{
    numUnits = 0;
}
void JarType::add(int n)
{
    if (n >= 0) {
        numUnits += n;
    }

    else {
        throw invalid_argument("Invalid value to add");
    }
}

void JarType::subtract(int n)
{
    if (n >= 0)
        numUnits -= n;
}


text:
Q: Is it a good idea to put "try...except..." at the first line of the code to catch unknown error? I've already handled some exceptions in my code, but I'm afraid of some unexpected errors that may occur. Let's say the code needs to finish three tasks. Is it okay to write it like this?
#Python 3.x

try:
    try:
        Task1()
    except KnownError1:
        Handler1()
    Task2()        # The second task is safe
    try:
        Task3()
    except KnownError2:
        Handler2()
except Exception:
    Handler3()

or should I catch the unknown error every time when I catch other errors:
try:
    Task1()
except KnownError1:
    Handler1()
except Exception:
    Handler3()
Task2()
try:
    Task3()
except KnownError2:
    Handler2()
except Exception:
    Handler3()

and why?

A: In general it's never a good practice to except every exception.
But, if it make sense, in my opinion the first one is cleaner.


text:
Q: CountDown Timer to release date Hi I am trying to handle this code and my problem is on part of code:
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: (Any).self, selector: #selector(updateTime), userInfo: nil, repeats: true)

is this error message in Xcode

Argument of '#selector' cannot refer to global function 'updateTime()'

And I am unable to handle this.
what could be wrong ? thank you
import UIKit
import Foundation
var releaseDate: NSDate?
var countdownTimer = Timer()

func startTimer() {

    let releaseDateString = "2019-02-23 08:00:00"
    let releaseDateFormatter = DateFormatter()
    releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    releaseDate = releaseDateFormatter.date(from: releaseDateString)! as NSDate

    countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: (Any).self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}

func updateTime() {

    let currentDate = Date()
    let calendar = Calendar.current

    let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: releaseDate! as Date)

    let countdown = "Days \(diffDateComponents.day ?? 0), Hours \(diffDateComponents.hour ?? 0), Minutes \(diffDateComponents.minute ?? 0), Seconds \(diffDateComponents.second ?? 0)"

    print(countdown)
}

A: You can't use global function in #selector. So move this into a class. Plus, if you're going to use selector-based timer, updateTime must be marked as @objc.
Alternatively, if you really want to use global functions, just use the block-based timer:
var releaseDate: Date?
var countdownTimer = Timer()

func startTimer() {
    let releaseDateString = "2019-02-23 08:00:00"
    let releaseDateFormatter = DateFormatter()
    releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    releaseDate = releaseDateFormatter.date(from: releaseDateString)

    countdownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
        updateTime()
    }
}

func updateTime() {
    let currentDate = Date()
    let calendar = Calendar.current

    let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: releaseDate!)

    let countdown = "Days \(diffDateComponents.day ?? 0), Hours \(diffDateComponents.hour ?? 0), Minutes \(diffDateComponents.minute ?? 0), Seconds \(diffDateComponents.second ?? 0)"

    print(countdown)
}

But it would be better to put this in a struct or class to avoid polluting your global namespace.
(Plus, I'm not sure why you use NSDate ... I'd suggest staying with Date objects.)

Personally, I'd do something like:
class TimerManager {
    var releaseDate: Date?

    private weak var countdownTimer: Timer?

    private let formatter: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .full
        formatter.allowedUnits = [.day, .hour, .minute, .second]
        return formatter
    }()

    deinit {
        countdownTimer?.invalidate()
    }

    func startTimer() {
        releaseDate = DateComponents(calendar: .current, year: 2019, month: 2, day: 23, hour: 8).date

        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            self?.updateTime()
        }
    }

    private func updateTime() {
        guard let releaseDate = releaseDate,
            let string = formatter.string(from: Date(), to: releaseDate) else { return }
        print(string)
    }
}

This not only takes care of the Timer issues, but also gets you out of the business of manually building those formatted strings of the components of the date difference.


text:
Q: Google Analytics - Logging Campaign Information? I have created a unique URL (http://www.example.com/uniqueurl) and used the Google Link Builder to create a campaign for this page.
So basically, people see this unique URL at trade shows and on print ads, they can visit that URL and they will be redirected to www.example.com/uniqueurl+campaign-characters-medium-etc which will take them to my home page, but also log the source, medium etc.
The home page has a Google Analytics code on it, however I'm not seeing any information regarding these campaign settings inside analytics.... am I missing something? Am I looking in the wrong place? Does the 302 redirect page need an Analytics code on it as well?
Thanks in advance.
Code as follows:
On the PHP redirect page (www.example.com/uniqueurl):
<?

    Header( "HTTP/1.1 301 Moved Permanently" );

    Header( "Location: http://example.com/more-example.php?utm_source=WA15&utm_medium=offline&utm_campaign=WA15" );

?>

And on the actual page (the Google Analytics code):
<script type="text/javascript">

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-1234567-1']);
      _gaq.push(['_trackPageview']);

     (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();

</script>


text:
Q: How to generate consecutive integers in Azure SQL? I am interested in generating a series of consecutive integers from 1 to 1000 (for example) and storing these numbers in each row of some table. I would like to do this in Microsoft Azure SQL but I am not sure if arrays are even supported.

A: One relatively simple method is a recursive CTE:
with n as (
      select 1 as n
      union all
      select n + 1
      from n
      where n < 1000
     )
select n.n
from n
options (maxrecursion 0);

A: Another mechanism to solve something like this could be to use a SEQUENCE on the table. It's similar to an IDENTITY column (they actually have the same behavior under the covers) without some of the restrictions. Just reset it to a new seed value as you add data to the table.


text:
Q: vba excel - custom format for strings, limit viewable text I am trying to use a custom format to restrict the amount of text that is displayed in a cell.
For instance, the following custom format will hide the entire cell's contents...
";;;"

But i want to limit the amount of text that is displayed, like only show the first 8 characters.
I have tried various variations of @, but nothing has worked so far.

A: I don't believe there is practical way of doing this using custom number format.  Here is an impractical way:  It is impractical because it requires a separate format for each entry and, eventually, you could run out of available number formats. Any difference in format -- whether it is the numberformat, or other things such as font, colors, borders, etc counts as a different format.  In Excel 2003 and earlier, there were 4,000 different formats allowed.  In 2007+, the number increased to 64,000.  In any event, the following Event code will format anything you enter in column A to show only the first 8 characters of text displayed, but will have all of the characters in the cell.  Enter the code by right-clicking on the worksheet tab, select View Code, and entering it into the window that opens.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim R As Range
    Dim C As Range
Set R = Range("a:a")
If Not Intersect(Target, R) Is Nothing Then
    Application.EnableEvents = False
    For Each C In Intersect(Target, R)
        C.NumberFormat = ";;;""" & Left(C, 8) & """"
    Next C
    Application.EnableEvents = True
End If

End Sub

Another solution would be to use a separate display column containing only the first 8 characters.


text:
Q: How to add a new product type on woocommerce product types? I want to add a new custom "product type" to woocommerce plugin:

Tried to duplicate one of currently exist product type files (woocommerce template structure) as a new file (file name and inside commented name) but not worked!

A: The add to cart template is only 1 of the many things you'll need to do. Each product type has it's own class in the /includes/ folder. Each one extends the WC_Product class.
To add items to the list you've screencapped (which is on the admin side and not the front-end, unlike the add-to-cart.php template, you will need to filter product_type_selector.
add_filter( 'product_type_selector', 'wpa_120215_add_product_type' );
function wpa_120215_add_product_type( $types ){
    $types[ 'your_type' ] = __( 'Your Product Type' );
    return $types;
}

then you'll need to declare your product class. The standard naming system is WC_Product_Type_Class so in this example it would be:
class WC_Product_Your_Type extends WC_Product{
    /**
     * __construct function.
     *
     * @access public
     * @param mixed $product
     */
    public function __construct( $product ) {
        $this->product_type = 'your_type'; // Deprecated as of WC3.0 see get_type() method
        parent::__construct( $product );
    }

     /**
     * Get internal type.
     * Needed for WooCommerce 3.0 Compatibility
     * @return string
     */
    public function get_type() {
        return 'your_type';
    }
}

You are asking a very complicated question and I can't provide a more complete answer. Hopefully this sets you on the right path.  I highly encourage you to read the code in WooCommerce. It is very well commented and you can see how they are handling the different product types.
Edit Added WC3.0 compatibility to product type class.


text:
Q: Updating iPhone application from 3.0 to iOS4 I was just wondering if anyone knows of any articles relating to upgrading an iPhone application from 3.0 to iOS4. (Thanks for this iWasRobbed).
While the application still runs on iOS4, it will not run on the iPhone 4, but does on my iPhone 3G.
When I deploy the app on the iPhone 4, the Default screen loads and it will sit there hanging. The only inclination towards a problem I get is this warning:
warning: UUID mismatch detected with the loaded library - on disk is:
 /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/System/Library/Frameworks/UIKit.framework/UIKit
warning: UUID mismatch detected with the loaded library - on disk is:
 /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/System/Library/PrivateFrameworks/DataAccessExpress.framework/DataAccessExpress

Thanks
James

A: James,
Apple has provided this checklist:  http://developer.apple.com/iphone/checklist/
It generally should not be that big of an issue.  Typically, you just set the baseline SDK as 4.0 and the deployment target as either 4.0 or something 3.0+.
If it is not running on an iPhone 4, you may wish to explain further what specifically it is doing or not doing when you attempt to run it on that device.  Keep in mind that all apps (for the most part) that were designed to run on 3.0 and above will typically run well on an iPhone 4.
There might be some issues with deprecated methods, so make sure you resolve those prior to installing and running the app.  You should get a compiler warning for any of those, if not check your target settings and there should be a checkbox for it.
Other than that, I'm not sure what else would prevent you without understanding further details of your project.
As additional information, you should really look into the WWDC 2010 video called "Future Proofing Your Applications" (watching it now :)

A: That is most likely a mismatch between what iOS your iPhone 4 is running and what SDK you're using in Xcode. The UUIDs are mismatched because the iPhone 4 is using a different version SDK to what you've coded in.
Solution, install the latest SDK and make sure your iPhone matches this. The latest out is 4.1

A: I had the same problem and think I have solved it because the problem has gone away.
Firstly I deleted the build folder. Then I Installed the latest version of ios (4.1 in this case) onto my iphone through itunes. Afterwards i installed the latest xcode and iphone sdk package from the apple devlopers site.
This in itself probably fixed the problem but just to be sure I added a new provisioning profile for the phone on my computer and everything worked great afterwards.
Hope that helps


text:
Q: Can i use another type of de valuset in code property distinct to type indicate in the Group resource definition? It is correct to use the Group resource code, with a valueset different from the Kind of Group members GroupKind. For example to use a valueset of programs with which a group of patients is served.

A: Group.code has a binding strength of example.  You're welcome to use any valueset you like there.  (On the other hand Group.type has a 'required' binding, so you are limited to only the specified codes.)


text:
Q: Possible raw SQL statement detected Magento 2. Custom module.
I have to run some raw SQLs. It works and doesn't show any error. But when I'm trying to upload module to Magento 2 Market Place (developer.magento.com/extension) it shows in technical report a dozen of such errors:

Possible raw SQL statement 'UPDATE `' detected.
Possible raw SQL statement 'SELECT MAX(entity_id) AS MaxOrderId FROM ' detected.
Possible raw SQL statement 'SELECT COUNT(entity_id) AS CountNewOrder FROM ' detected.

What is the correct way to run this statement?

$sql = 'SELECT COUNT(entity_id) AS CountNewOrder FROM ' . $this->getDbPrefix() . 'sales_order WHERE entity_id > ' . $order_id;
$result = \Magento\Framework\App\ObjectManager::getInstance()->getConnection()->fetchAll($sql);*

A: The idea is to never run  raw queries in your modules. Magento EcgM2 coding standards does not like that.
You can use the ORM to do that.
If you want the number of orders with Id over a certain value you can do this in your class.
class MyClassNameHere extends WhateverYouNeed
{
    protected $collectionFactory;
    public function __construct(
        //add a dependency to your class, don't use object manager directly
        \Magento\Sales\Model\ResourceModel\Order\Collectionfactory $collectionFactory,
         //other dependencies here if needed
    )
    {
       $this->collectionFactory = $collectionFactory;
       //rest of constructor here
    }
    public function getOrdersWithIdEqualOrOver($id)
    {
        $collection = $this->collectionFactory->create();
        $collection->addFieldToFilter('entity_id', ['gteq' => $id]);
        return $collection->getSize();
    }
}

then just call the method getOrdersWithIdEqualOrOver where you need.
Side note: I would think twice before using a module that has raw queries in it.

A: Here is solution:
$om = \Magento\Framework\App\ObjectManager::getInstance();
$adapter = $om->get('Magento\Framework\App\ResourceConnection')->getConnection()->select()->getAdapter();
$sql = 'SELECT COUNT(entity_id) AS CountNewOrder FROM sales_order WHERE entity_id > :order_id';
$binding = ['order_id' => 1];

$data = $adapter->query($sql, $binding)->fetch();

But still no success with Magento 2 Code Validator...


text:
Q: Down-sampling with numpy I have an 1D array A that represents categorical data (where each entry is the number of element of a certain category):
A = array([ 1, 8, 2, 5, 10, 32, 0, 0, 1, 0])

and I am trying to write a function sample(A, N) to generate an array B that contains N elements generated by randomly drawing elements from A (keeping the categories):
>>> sample(A, 20)
array([ 1, 3, 0, 1, 4, 11, 0, 0, 0, 0])

I wrote this:
def sample(A, N):
    AA = A.astype(float).copy()
    Z = zeros(A.shape)
    for _ in xrange(N):
        drawn = random.multinomial(1, AA/AA.sum())
        Z = Z + drawn
        AA = AA - drawn
    return Z.astype(int)

Probably it is quite naive, is there a better/faster way to do it? Maybe using some fast numpy function?
Edit: It was not clear: it has to be without replacement!!!

A: This may not be the most elegant solution, but it's about 3x as fast. It uses numpy.random.choice, which has a Boolean replace option (in this case set to False - i.e. without replacement). The rest of the code is to:

*

*Set up the array of choices, which contains A[n] counts of the index n, e.g. for A=[2,0,3,1] you'd get choices=[0,0,2,2,2,3]. Note that each of these will have equal probability so no need to create a probability array.

*Convert the values chosen by the numpy function call into the output array required. Each element of the vals array will be an index picked from the choices array, so you need to add 1 to the appropriate element of B for each of these chosen indices.

I hope that makes sense! Here is the code:
def sample_2(A, N):
    # Create array of choices (indicies)
    choices = []
    for n in xrange(len(A)):
        for _ in xrange(A[n]):
            choices.append(n)
    # Randomly choose from these indicies
    vals = numpy.random.choice(choices, N, False)
    # Count up the chosen indicies
    B = numpy.zeros(len(A), dtype=int)
    for index in xrange(N):
        B[vals[index]] += 1
    return B

Speed test results for 10000 calls of each function:
Original: 3.0517 s
Method_2: 0.9968 s

A: faster than the other's as far as i can see. But probably uses more memory.
import random
from collections import Counter

def sample2(A,N):
    distribution = [i for i, j in enumerate(A) for _ in xrange(j)]
    sample = Counter(random.sample(distribution, N))
    return [sample[i] for i in xrange(len(A))]

In [52]: A = np.random.randint(0, 100, 500)

In [53]: %timeit sample(A, 100) #Original
100 loops, best of 3: 2.71 ms per loop

In [54]: %timeit sample2(A, 100) #my function
1000 loops, best of 3: 914 µs per loop

In [55]: %timeit sample3(A, 100) #sftd function
100 loops, best of 3: 8.33 ms per loop

A: Here's how I would do it:
def sample(A, N):
        population = np.zeros(sum(A))
        counter = 0
        for i, x in enumerate(A):
                for j in range(x):
                        population[counter] = i
                        counter += 1

        sampling = population[np.random.randint(0, len(population), N)]
        return np.histogram(sampling, bins = np.arange(len(A)+1))[0]

What we're doing is building a population defined by the histogram A and then randomly sampling from it. If the real-world case has N large and sum(A) small, and/or you need to sample A many times for a fixed A, this should be better. What you'd do is to build the population corresponding to A outside of the function call and define sample(population, N) as just the last two lines of the above.


text:
Q: Passing arguments values to shell script I'm using the following script to purge cache from cdn,
#!/bin/bash

##  API keys ##
zone_id=""
api_key=""
login_id=""
akamai_crd=""

## URL ##

urls="$1"
[ "$urls" == "" ] && { echo "Usage: $0 url"; exit 1; }

echo "Purging $urls..."

curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${zone_id}/purge_cache" \
     -H "X-Auth-Email: ${login_id}" \
     -H "X-Auth-Key: ${api_key}" \
     -H "Content-Type: application/json" \
     --data "{\"files\":[\"${urls}\"]}"

#echo "CF is done now purging from Akamai ..."

echo  "..."

curl -v -s https://api.ccu.akamai.com/ccu/v2/queues/default -H "Content-Type:application/json" -d '{"objects":["$urls"]}' -u $akamai_crd

The 1st part for cloudflare is working fine the 2nd part when I pass it to Akamai
["$urls"]

I keep getting an error and it's passing the url as an argument it returns the variable itself ($urls) not the arg value.
I ran the script as following:
sh +x  script.sh  url

Any advise here?

A: First i would change this:
SCRIPTNAME=$(basename "$0")
...
if [ $# != 1 ] then
    echo "Usage: $SCRIPTNAME url"
    exit
fi

$urls="$1"

Change your second curl command as the following (you need to escape the quotes):
--data "{\"files\":[\"${urls}\"]}"

A: Avoid creating JSON by hand like this; you can't guarantee that the resulting JSON is properly escaped. Use a tool like jq instead.
#!/bin/bash

##  API keys ##
zone_id=""
api_key=""
login_id=""
akamai_crd=""

## URL ##

url=${1:?Usage: $0 url}

headers=(
  -H "X-Auth-Email: $login_id"
  -H "X-Auth-Key: $api_key"
  -H "Content-Type: application/json"
)

purge_endpoint="https://api.cloudflare.com/client/v4/zones/${zone_id}/purge_cache"

echo "Purging $url..."

jq -n --arg url "$url" '{files: [$url]}' |
  curl -X DELETE "$purge_endpoing" "${headers[@]}" --data @-

#echo "CF is done now purging from Akamai ..."

echo  "..."

jq -n --arg url "$url" '{objects: [$url]}' |
  curl -v -s -H "Content-Type:application/json" -d @- -u "$akamai_crd"