text:
Q: Migrating from Google calendar V3 (1.5.0.56-beta) version to latest Dlls i.e Version 3(1.8.1.820) I am using Google calendar version 3(1.5.0.56-beta) beta for my asp.net application, now I want to upgrade these DLL to version 3(1.8.1.820). I have downloaded the new DLLs but not it is showing that NativeApplicationClient, GoogleAuthenticationServer are not in these DLLs. Please check the below code that I am using for V3 beta version
private CalendarService CreateService(string token)
{
    KeyValuePair<string, string> credentials = Common.Get3LOCredentials();
    var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
    provider.ClientIdentifier = credentials.Key;
    provider.ClientSecret = credentials.Value;
    var auth = new Google.Apis.Authentication.OAuth2.OAuth2Authenticator<NativeApplicationClient>(provider, (p) => GetAuthorization(provider, token, credentials.Key, credentials.Value));
    CalendarService service = new CalendarService(new BaseClientService.Initializer()
    {
        Authenticator = auth,
        ApiKey = ConfigurationManager.AppSettings["APIkey"].ToString(),
        GZipEnabled = false
    });
    provider = null;
    return service;
}
 private IAuthorizationState GetAuthorization(NativeApplicationClient arg, String Refreshtoken, string clientid, string clientsecret)
{
    int retrycount = 0;
    IAuthorizationState state = null;
    string accesstoken = string.Empty;

    while (retrycount < 7)
    {
        accesstoken = string.Empty;
        try
        {
            state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);// NativeApplicationClient.OutOfBandCallbackUrl);
            ProfileSettingsBL bl = BLFactory.CurrentInstance.ProfileSettingsBLObj;
            ProfileSettingsDS.SOUserCalendarAccountRow row = bl.RetrieveSOUserCalendarAccountByToken(Refreshtoken);
            if (row != null)
            {
                string[] splitter = new string[1];
                splitter[0] = Constants.EQUAL_REPLACE_STRING;
                string[] arr = row.Token.Split(splitter, StringSplitOptions.None);
                if (arr.Length == 1)
                {
                    accesstoken = ExchangeCodeWithAccessAndRefreshToken(Refreshtoken, clientid, clientsecret, retrycount);
                    if (!string.IsNullOrEmpty(accesstoken))
                    {
                        string[] arr1 = accesstoken.Split(splitter, StringSplitOptions.None);
                        if (arr1.Length > 1)
                        {
                            bl.updateAccessToken(Refreshtoken, arr1[0], arr1[1]);
                            accesstoken = arr1[0];
                        }
                    }
                }
                else
                {
                    if (arr.Length >= 1)
                        accesstoken = arr[1];
                }
            }
            else
            {
                string[] splitter = new string[1];
                splitter[0] = Constants.EQUAL_REPLACE_STRING;
                accesstoken = ExchangeCodeWithAccessAndRefreshToken(Refreshtoken, clientid, clientsecret, retrycount);
                if (!string.IsNullOrEmpty(accesstoken))
                {
                    string[] arr1 = accesstoken.Split(splitter, StringSplitOptions.None);
                    if (arr1.Length >= 1)
                        accesstoken = arr1[0];
                }
            }
            if (!string.IsNullOrEmpty(accesstoken))
                state.AccessToken = accesstoken;
            state.RefreshToken = Refreshtoken;
            return state;
        }
        catch (Exception ex)
        {

        }
    }
    return state;
}

can anyone please help me in this regards, unable to find good documentation for .NET developers. Thanks in advance.

A: Now I have converted the old application to new one, here you just need to use UserCredential class that is inside the Google.Apis.Auth.OAuth2. Kindly check the below code for this.
private CalendarService CreateService(string token)
{
    KeyValuePair<string, string> credentials = Common.Get3LOCredentials();
    String AccessToken = GetAuthorization(RefreshToken, credentials.Key, credentials.Value);
    var tokenCode = new TokenResponse() { RefreshToken = RefreshToken, AccessToken = AccessToken };
    var secreat = new ClientSecrets() { ClientId = credentials.Key, ClientSecret = credentials.Value };
    UserCredential credential = new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = secreat
    }), "user", tokenCode);
    var service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "Google Calendar API Sample",
    });
    return service;
}

It is really very easy than before code that Google was having in Beta versions.


text:
Q: Grabbing local hostname and creating link with images Javascript I am trying to create an image link based on the location of the server it is hosted on. If the server is server1. I want the image to be linked to http://server1/dod" I'm trying to get two images with this shot. However, nothing is loading. I am missing a piece and I don't know where. I'm also hosting this on an IIS server.
<!DOCTYPE html>

redpajama_set_name: RedPajamaStackExchange


text:
Q: cannot get rid of duplicate values I have following table in my database:

All I need is to load Country list for User with ID=5:

*

*USA

*Canada

*Germany

Then, when I will click for example on USA, it will load the cities for that country:

*

*Washington DC

*Miami

I can display country field for every row where User ID=5 but I will have the following result which is not acceptable.

*

*USA

*Canada

*USA

*Germany

*Canada

*Germany

Are there any tricks which can help me not to duplicate country values?

A: You should be able to use DISTINCT to remove duplicate values from your resultset:
SELECT DISTINCT Country FROM <table> WHERE UserID = 5;

Reference: How to Use MySQL DISTINCT to Eliminate Duplicate Rows

A: As Krister says, part 1 is
SELECT DISTINCT COUNTRY FROM TABLE WHERE USERID =5
Then to get cities for that user in USA:
SELECT  CITY FROM TABLE WHERE USERID =5 AND COUNTRY = 'USA'


text:
Q: Cannot find module 'application-settings' I'am getting an error when trying to include "application-settings module".
*Cannot find module 'application-settings'  <----- Error
the error is in my storage.driver.ts which is in nativescript sdk which is built using loopback sdk builder
storage.driver.ts
import * as AppSettings from 'application-settings'; <---- Error here
export class StorageDriver {
static set(key: string, value: any) {
AppSettings.setString(key, String(value));
}
static get(key: string): any {
return AppSettings.getString(key);
}
static remove(key: string): any {
if (AppSettings.hasKey(key)) {
  AppSettings.remove(key);
} else {
  console.log('Trying to remove unexisting key: ', key);
}
}
}

*

*https://github.com/m-expert-official/loopback-sdk-builder/wikiean
what should i do to resolve this issue? I am new to nativescript.

A: 'application-settings' was moved to 'tns-core-modules', which is now deprecated as 'application-settings' and other core nativescript modules are now a part of '@nativescript/core'.
Now we use '@nativescript/core' instead of 'tns-core-modules'.
@deprecated
import * as AppSettings from 'tns-core-modules/application-settings';

Use this instead :
import * as AppSettings from '@nativescript/core/application-settings';

A: This is how you would import it
const applicationSettings = require('tns-core-modules/application-settings')

// or if you are using webpack for example
import * as applicationSettings from 'tns-core-modules/application-settings'


text:
Q: React-Bootstrap Grid layout not applying I am having issues getting grid (and row) to work in React-Bootstrap. All other
components are functioning fine, but trying to get my items to display as a row
has been a pain. My code:
PARENT COMPONENT
        <Grid>
        <Row className="show-grid">
                {this.state.results.map((movie, index) => (
                    <EachResult key={index} id={index} movie={movie} results={this.state.results} index={index} userInfo={this.props.userInfo} />
                ))}
        </Row>
        </Grid>

CHILD COMPONENT
    <Col>

{props.movie.title}

    <Image src={url} width="125" height="220" thumbnail />

Summary: {props.movie.overview}

Rating: {props.movie.vote_average}

    <Button id={props.index} onClick={addGame}>Add</Button>
    </Col>

I have installed React-bootstrap and I am importing each Component as such:
import { Grid, Row } from "react-bootstrap";

and
import {Button, Image, Col} from "react-bootstrap"

Sorry for the messy code! Any help would be greatly appreciated
EDIT: I am importing the the stylesheet in my Index.html!

A: Try add Col size parameter eg.
 <Grid>
    <Row className="show-grid">
      <Col md={3}>
        ...
      </Col>
    </Row>
  </Grid>

Vid office doc
Check output DOM in browser, in most browsers F12,
in chrome check specific element with Ctrl+Shift+C.
Hope it will help


text:
Q: Android Dialog not showing at all if called from a Timer Task timer = new Timer("Timer Thread");

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
                showDialog(0);
                timeBar.setProgress(time);
            }
        }
    }, INTERVAL, INTERVAL);`

My onCreateDialog method is working fine, so when I use showDialog(0) from a Button it works fine. But not if the method is called by a Scheduler.

A: Using a handler:
protected static final int DIALOG_OK= 0;

timer = new Timer("Timer Thread");

timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
            mDialogHandler.sendEmptyMessage(DIALOG_OK);
            timeBar.setProgress(time);
        }
    }
}, INTERVAL, INTERVAL);

 private Handler mDialogHandler = new Handler(){
            public void handleMessage(android.os.Message msg) {
                    switch (msg.what) {
                    case DIALOG_OK:
                            // We are now back in the UI thread
                            showDialog(0);
                    }

            };
    };

This allows you to call method's on the UI thread from other threads. Need more explanation, just ask.

A: You need to call these methods on the UI thread.
One way to do this is via AsyncTask, as in this answer.
Another way is to create a Handler and send messages to it from your TimerTask.
You can read more about AsyncTasc and the UI thread in Painless Threading.


text:
Q: I had follow someone code samples and try apply to my HighChart program but I can't get it work at all I had follow someone code samples, but I'm new to javascript and highcharts. In fact
this program worked but only shows one month at a time, I want show all the months' data. Sorry for my English. Could you give me some advice thanks.
$(document).ready(function () {
    var options = {
        chart : {
            renderTo : 'container',
            defaultSeriesType : 'column',
            rightMargin : 80
        },
        title : {
            text : 'the scholls'
        },
        subtitle : {
            text : 'data for 2012 years'
        },
        xAxis : {
            title : 'months',
            categories : []
        },
        yAxis : [{
                min : 0,
                title : {
                    text : 'students'
                }
            }, {
                linkedTo : 0,
                opposite : true
            }
        ],
        tooltip : {
            formatter : function () {
                return '' + this.series.name + '
' + this.x + 'Months: ' + this.y + ' students:';
            }
        },
        legend : {
            layout : 'vertical',
            align : 'right',
            verticalAlign : 'top',
            x : -10,
            y : 100,
            borderWidth : 0
        },
        series : [{
                name : "students total",
                data : []
            }
        ]
    };

    //get the json files
    $.getJSON('http://localhost:3000/students/givemechart.json', function (data) {

        yData = options.series[0].data; //Array to store data for y column
        xData = options.xAxis.categories; //Array to store data for x column
        xDataObj = data[3]; //only can show one months
        yDataObj = data[3]; //only can show one totals

        // [[5, 2], [6, 3], [8, 2]]
        for (var key in xDataObj) {
            xData.push((xDataObj[key].month));
            console.dir(xData); //chrome console only
        }

        for (var key in yDataObj) {
            yData.push((yDataObj[key].total));
            console.dir(yData); //chrome console only
        }

        var chart = new Highcharts.Chart(options);

    });
});

This is one of my json files.
[
    {
        "student" : {
            "month" : 1,
            "total" : 24
        }
    }, {
        "student" : {
            "month" : 2,
            "total" : 27
        }
    }, {
        "student" : {
            "month" : 10,
            "total" : 96
        }
    }, {
        "student" : {
            "month" : 11,
            "total" : 1088
        }
    }, {
        "student" : {
            "month" : 12,
            "total" : 125
        }
    }

]

A: Set Min and Max for Xaxis like this :
 xAxis : {
            title : 'months',
            categories : [],
min: 1,
max: 12
        }


text:
Q: How to change Display Name of Safari Extension for iOS devices? Can you please help me change the Display Name of the Safari Extensions(iOS v15) for the iPhone/iPad?
I did try (in Xcode) all combinations of updating Build and Bundle Ids and display names, but nothing worked.  I tried updating the CBBundleDisplayName property in the project file and also in plist file, but didn't make any difference.
My app/extension ID is: "ABC.MNO.XYZ", and accordingly, there are four targets generated in Xcode, mainly App, Test, UITest, Extension.
The last target (Extension) one is already set to "ABC MNO XYZ Extension" by default, and there I tried to change its Display Name without suffix of Extension, but nothing worked, causing either build issues or no change in the app.
In sum, the app name and extension name, both in Settings > Safari > Extensions and also in the Safari Browser Extension's popup menu, should be set to "ABC MNO".
How to resolve this issue?

A: Change the "name" attribute in the manifest.json file, within the Targets projects, that(last folder) ends with the suffix "Extension", like "ProjectName Extension".
Then, remove the existing (installed) extension on the device, and rebuild the project, to see the new custom name.


text:
Q: Cannot open OGR file I have already tried re-writing this code using dsn=path.expand and shapefile. However, this keeps giving me an error.
mapfile <-readOGR("/Users/kajoribanerjee/Documents/PhD/bayesian geoadditive model/india_2011.shp")

Error in ogrListLayers(dsn = dsn) : Cannot open data source}

A: In rgdal you have to name a layer destination (dsn) and a layer name (layer).
In case of a shapefile located at /home/user/folder/shapefile.shp that would be dsn = "/home/user/folder" and layer = "shapefile"
So you should use it like this:
mapfile <- readOGR("/Users/kajoribanerjee/Documents/PhD/bayesian geoadditive model",
                   "india_2011")

You should also have a look at ?readOGR where it is stated that:

If reading a shapefile, the data source name (dsn= argument) is the folder (directory) where the shapefile is, and the layer is the name of the shapefile (without the .shp extension)

Another way is shown here by using raster::shapefile.


text:
Q: What is the proper way to execute a batchfile with multiple params? I have a batchfile which I use for managing the translation of various programs.
Now I want a delphi application to call this batchfile and pass on the parameter it needs for further processing. Unfortunately the parameters contain spaces which leads to a splitup. Is there a way to keep all parameters tied up as intended?
this is how my batchfile looks:
ECHO Scan for new ressources
%MLDIR%\Ml7Build.exe s %1%

ECHO Import glossary for new translation
%MLDIR%\MlBuild.exe i %2%

ECHO Create translated application
%MLDIR%\Ml7Build.exe b %3%

I tried to use the ShellExecute-Command from ShellApi because I found several similar questions on SO, but none of them could help me in solving my problem. My delphi code looks like this:
 param1 := ExtractFileName(hMLProj);
 param2 := '-f: '+MLWorkDir+'Prev_'+ExtractFileName(hMLProj)+' -settings:Auftrag_Test.importsettings-method:2 -overwri:3 -error:2 '+ExtractFileName(hMLProj)+' ';
 param3 := ExtractFileName(hMLProj);
 ShellExecute(0,'open',PCHAR(MLWorkDir+'__AutomatedTranslationFUBAR.bat'),PChar(param1 +param2 +param3),nil,SW_SHOWDEFAULT);

A: ECHO Scan for new resources
%MLDIR%\Ml7Build.exe s %~1

ECHO Import glossary for new translation
%MLDIR%\MlBuild.exe i %~2
REM is 7 ^ omitted here?

ECHO Create translated application
%MLDIR%\Ml7Build.exe b %~3

Note that %n not %n% (n=1..9) refers to the parameter n supplied to the batch. The tilde removes "any enclosing quotes."
Parameters require to be "enclosed in quotes" (and they must be double-quotes) if they contain separators such as spaces.


text:
Q: Differing CPUID usage from high-level languages I'm attempting to utilize an x86 ASM function that requires certain processor architecture. I understand that I need to check a specific bit after calling "CPUID standard function 01H". Below is a C implementation from the CPUID Wikipedia page for calling CPUID:
#include <stdio.h>

int main() {
    int i;
    unsigned int index = 0;
    unsigned int regs[4];
    int sum;
    __asm__ __volatile__(
#if defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
        "pushq %%rbx     \n\t" /* save %rbx */
#else
        "pushl %%ebx     \n\t" /* save %ebx */
#endif
        "cpuid            \n\t"
        "movl %%ebx ,%[ebx]  \n\t" /* write the result into output var */
#if defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
        "popq %%rbx \n\t"
#else
        "popl %%ebx \n\t"
#endif
        : "=a"(regs[0]), [ebx] "=r"(regs[1]), "=c"(regs[2]), "=d"(regs[3])
        : "a"(index));
    for (i=4; i<8; i++) {
        printf("%c" ,((char *)regs)[i]);
    }
    for (i=12; i<16; i++) {
        printf("%c" ,((char *)regs)[i]);
    }
    for (i=8; i<12; i++) {
        printf("%c" ,((char *)regs)[i]);
    }
    printf("\n");
}

Though the Linux kernel uses the function below:
static inline void native_cpuid(unsigned int *eax, unsigned int *ebx,
                                unsigned int *ecx, unsigned int *edx)
{
        /* ecx is often an input as well as an output. */
        asm volatile("cpuid"
            : "=a" (*eax),
              "=b" (*ebx),
              "=c" (*ecx),
              "=d" (*edx)
            : "0" (*eax), "2" (*ecx));
}

Which one is better? Other they essentually equivalent?

A: As Jester says, in GNU C the cpuid.h wrapper intrinsic is probably your best bet.

There's also __builtin_cpu_supports("popcnt") or "avx" or whatever, which works after you call __builtin_cpu_init().  Only the really major feature-bits are supported, though.  For example, the docs don't mention the feature-bit for rdrand, so __builtin_cpu_supports("rdrand") probably doesn't work.

Custom inline-assembly versions:
The implementation from Linux can inline with no wasted instructions, and it looks well-written, so there's no reason to use anything else.  It's remotely possible that you might get a complaint about not being able to satisfy the "=b" constraint; if so see below for what clang's cpuid.h does.  (But I think that's never necessary and the result of a documentation mistake).
It doesn't actually need volatile, though, if you're using it for the values produced rather than the serializing effect on the pipeline: Running CPUID with the same inputs will give the same result, so we can let the optimizer move it around or hoist it out of loops.  (So it runs fewer times).  This is probably not helpful because normal code won't use it in a loop in the first place, though.

The source for clang's implementation of cpuid.h does some weird stuff, like preserving %rbx because apparently some x86-64 environments might not be able to satisfy a constraint that uses %rbx as an output operand?   The comment is /* x86-64 uses %rbx as the base register, so preserve it. */, but I have no idea what they're talking about.  If anything x86-32 PIC code in the SysV ABI uses %ebx for a fixed purpose (as a pointer to the GOT), but I don't know about anything like that for x86-64.  Perhaps that code is motivated by a mistake in the ABI documentation?  See HJ Lu's mailing list post about it.

Most importantly, the first version in the question (inside main()) is broken because it clobbers the red-zone with push.
To fix it, just tell the compiler the result will be in ebx (with "=b"), and let it worry about saving/restoring ebx/rbx at the start/end of the function.


text:
Q: Chef hostname will not set I have read the docs on chef hostname resource and I also have found the community cookbook which has examples of how it works since the hostname resource used to be a community cookbook but is no longer.
Different variations I have tried:
hostname node.name
hostname 'myhostname '
hostname 'set_hostname' do
  hostname 'myhostname'
  action :set
end

None have worked and I can't seem to find anything recent for how to get this to work.

A: As stated in https://docs.chef.io/resource_hostname.html doc
hostname resource works in "New in Chef Client 14.0.
Also, after giving it a try, it seems work for me at least. See the following logs:
vagrant@ubuntu-xenial:~$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
vagrant@ubuntu-xenial:~$ hostname
ubuntu-xenial
vagrant@ubuntu-xenial:~$ curl -O https://packages.chef.io/files/stable/chef/14.5.33/ubuntu/18.04/chef_14.5.33-1_amd64.deb && sudo dpkg -i chef_14.5.33-1_amd64.deb
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 51.6M  100 51.6M    0     0  3431k      0  0:00:15  0:00:15 --:--:-- 3016k
Selecting previously unselected package chef.
(Reading database ... 54150 files and directories currently installed.)
Preparing to unpack chef_14.5.33-1_amd64.deb ...
Unpacking chef (14.5.33-1) ...
Setting up chef (14.5.33-1) ...
Thank you for installing Chef!
vagrant@ubuntu-xenial:~$ mkdir -p cookbooks/sethostname/recipes
vagrant@ubuntu-xenial:~$ vim cookbooks/sethostname/recipes/default.rb
vagrant@ubuntu-xenial:~$ echo "hostname 'example'" > cookbooks/sethostname/recipes/default.rb
vagrant@ubuntu-xenial:~$ cat cookbooks/sethostname/recipes/default.rb
hostname 'example'
vagrant@ubuntu-xenial:~$ sudo chef-client -z -o sethostname
[2018-10-22T04:31:22+00:00] WARN: No config file found or specified on command line, using command line options.
Starting Chef Client, version 14.5.33
[2018-10-22T04:31:24+00:00] WARN: Run List override has been provided.
[2018-10-22T04:31:24+00:00] WARN: Run List override has been provided.
[2018-10-22T04:31:24+00:00] WARN: Original Run List: []
[2018-10-22T04:31:24+00:00] WARN: Original Run List: []
[2018-10-22T04:31:24+00:00] WARN: Overridden Run List: [recipe[sethostname]]
[2018-10-22T04:31:24+00:00] WARN: Overridden Run List: [recipe[sethostname]]
resolving cookbooks for run list: ["sethostname"]
Synchronizing Cookbooks:
  - sethostname (0.0.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Recipe: sethostname::default
  * hostname[example] action set
    * ohai[reload hostname] action nothing (skipped due to action :nothing)
    * execute[set hostname to example] action run
      - execute /bin/hostname example
    * file[/etc/hosts] action create
      - update content in file /etc/hosts from 7ea6de to fb5e96
      --- /etc/hosts    2018-10-22 04:27:39.004000000 +0000
      +++ /etc/.chef-hosts20181022-1725-1ghvofd 2018-10-22 04:31:24.503686000 +0000
      @@ -8,5 +8,5 @@
       ff02::2  ip6-allrouters
       ff02::3  ip6-allhosts
       127.0.1.1    ubuntu-xenial   ubuntu-xenial
      -
      +10.0.2.15 example example
    * execute[hostnamectl set-hostname example] action run
      - execute hostnamectl set-hostname example
    * ohai[reload hostname] action reload/opt/chef/embedded/lib/ruby/gems/2.5.0/gems/ohai-14.5.4/lib/ohai/plugins/windows/filesystem.rb:26: warning: already initialized constant CONVERSION_STATUS
/opt/chef/embedded/lib/ruby/gems/2.5.0/gems/ohai-14.5.4/lib/ohai/plugins/windows/filesystem.rb:26: warning: previous definition of CONVERSION_STATUS was here

      - re-run ohai and merge results into node attributes

  Converging 1 resources
  * hostname[example] action set
    * ohai[reload hostname] action nothing (skipped due to action :nothing)
    * execute[set hostname to example] action run (skipped due to not_if)
    * file[/etc/hosts] action create (skipped due to not_if)
    * execute[hostnamectl set-hostname example] action run (skipped due to not_if)
     (up to date)
[2018-10-22T04:31:24+00:00] WARN: Skipping final node save because override_runlist was given
[2018-10-22T04:31:24+00:00] WARN: Skipping final node save because override_runlist was given

Running handlers:
Running handlers complete
Chef Client finished, 5/11 resources updated in 01 seconds
vagrant@ubuntu-xenial:~$ hostname
example

If you are using older version, please check this cookbook https://github.com/kigster/set-hostname-cookbook


text:
Q: PHP SQL Select From Where I am having some difficulty running some SQL code.
What I am trying to do is, find a row that contains the correct username, and then get a value from that correct row.
This is my SQL in the php:
mysql_query("SELECT * FROM users WHERE joined='$username' GET name")

As you can see, it looks for a username in users and then once found, it must GET a value from the correct row.
How do I do that?

A: mysql_query("SELECT `name` FROM users WHERE joined='$username' ")

Just select the right column in your 'select clause' like above.
Edit: If you are just starting out though, you might want to follow a tutorial like this one which should take you through a nice step by step (and more importantly up to date functions) that will get you started.

A: mysql_query("SELECT name FROM users WHERE joined='$username'")

A: You need some additional PHP code (a call to mysql_fetch_array) to process the result resource returned by MySQL.
$result = mysql_query("SELECT name FROM users WHERE joined='$username'");

$row = mysql_fetch_array($result);

echo $row['name'];

A: $q = mysql_query("SELECT * FROM users WHERE joined='$username'");

$r = mysql_fetch_array($q);

$name = $r['user_name']; // replace user_name with the column name of your table

A: mysql_query("SELECT name FROM users WHERE joined='$username' ")

Read documentation : http://dev.mysql.com/doc/refman/5.0/en/select.html


text:
Q: Хранение изображений и тег img Добрый день.
Существует вид хранения изображений в теге img (строчки вида "base64/JPEG...").
Как мне лучше хранить изображения-просто в отдельной таблице базе данных,или в поле с текстом статьи например записывать весь тег img с этой строчкой?
A: Лучше всего хранить изображения в файловой системе, а в поле с текстом схранять только URL-картинок.
Не насилуйте БД. Зачем каждый раз забирать из БД в память BLOB картинки, если можно взять только ее URL?
A: base64 нужен для маленьких изображений, спрайтов. Для больших его лучше не использовать.
Если используете base64 - то можно хранить и в базе. Лучше в отдельной таблице или в отдельной ячейке хотя бы. Мешать текст с тегами - плохая практика.
Если base64 не используете и не нужно шифрование - в базе изображения не храните. Храните на сервере. А в базу пишите только ссылку.


text:
Q: How to do nested routing with api response In our current project, my leads want to control everything from admin panel. They want to add/change content of layouts from panel and i have to send request to get layout info to change ui accordingly. And also routes will change dynamically with this response.
I have an api response similar to the following below. I need to get react components with "component" and routes with "url" by using it.
[
  {
    "__typename": "Layout",
    "order": 2,
    "title": "{\"en\":\"our services\",\"tr\":\"servislerimiz\"}",
    "is_hidden_from_footer": false,
    "is_hidden_from_header": false,
    "meta_data": null,
    "private_meta_data": null,
    "seo_meta_data": null,
    "category_path": "-",
    "parent_uuid": "-",
    "url": "/our-services",
    "component": "OurServices",
    "children": [
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"digital transformation\",\"tr\":\"dijital dönüşüm\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "digital-transformation",
        "component": "DigitalTransformation"
      },
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"Managed IT Services\",\"tr\":\"managed it services\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "managed-it-services",
        "component": "ManagedItServices"
      },
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"sap consulting\",\"tr\":\"sap consulting\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "sap-consulting",
        "component": "SapConsulting"
      },
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"Devops\",\"tr\":\"Devops\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "devops",
        "component": "Devops"
      },
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"application managemenet\",\"tr\":\"application management tr\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "application-management",
        "component": "ApplicationManagement"
      },
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"QA\",\"tr\":\"QA tr\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "qa-testing-services",
        "component": "QATestingServices"
      }
    ]
  },
  {
    "__typename": "Layout",
    "order": 3,
    "title": "{\"en\":\"insight\",\"tr\":\"insight tr\"}",
    "is_hidden_from_footer": false,
    "is_hidden_from_header": false,
    "meta_data": null,
    "private_meta_data": null,
    "seo_meta_data": null,
    "category_path": "-",
    "parent_uuid": "-",
    "url": "/insight",
    "component": "Insight",
    "children": [
      {
        "__typename": "Layout",
        "order": 3,
        "title": "{\"en\":\"digital transformation\",\"tr\":\"dijital dönüşüm\"}",
        "is_hidden_from_footer": false,
        "is_hidden_from_header": false,
        "meta_data": null,
        "private_meta_data": null,
        "seo_meta_data": null,
        "category_path": "-",
        "parent_uuid": "-",
        "url": "digital-transformation",
        "component": "DigitalTransformation"
      }
    ]
  }
]

I write this render method but there are warnings.
export const RenderRoutes = ({ routes = [] }) => {
  return (
    <Suspense fallback={
loading
}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Layout headerData={routes} />}>
            {routes.length &&
              routes.map((item, index) => {
                let Comp = lazy(() => import(`../pages/${item.component}`));

                return (
                  <Route
                    key={index}
                    path={item.url}
                    render={() => {
                      return <Comp />;
                    }}
                  >
                    {item.children.map((child, i) => {
                      let ChildComponent = lazy(() =>
                        import(`../pages/${item.component}/${child.component}`)
                      );

                      return (
                        <Route
                          key={index}
                          path={child.url}
                          render={() => {
                            return <ChildComponent />;
                          }}
                        />
                      );
                    })}
                  </Route>
                );
              })}
          </Route>
        </Routes>
      </BrowserRouter>
    </Suspense>
  );
};

So how can I handle this? Thank you for your help.

A: I think you've a few issues:

*

*In react-router-dom v6 the Route components no longer have a component prop or render and children prop functions. They were replaced by a single element prop taking a ReactElement, a.k.a. JSX.

*The nested inner (children) routes are incorrectly using the parent route's index as their React keys. Don't use the mapped index, instead use the url property as this needs to be unique among sibling routes anyway.

*Remove the BrowserRouter and render only a single router higher in the ReactTree so any links in the app elsewhere can work correctly.

Code:
export const RenderRoutes = ({ routes = [] }) => {
  return (
    <Suspense fallback={
loading
}>
      <Routes>
        <Route path="/" element={<Layout headerData={routes} />}>
          {routes.map((item) => {
            let Comp = lazy(() => import(`../pages/${item.component}`));

            return (
              <Route key={item.url} path={item.url} element={<Comp />}>
                {item.children.map((child) => {
                  let ChildComponent = lazy(() =>
                    import(`../pages/${item.component}/${child.component}`)
                  );

                  return (
                    <Route
                      key={child.url}
                      path={child.url}
                      element={<ChildComponent />}
                    />
                  );
                })}
              </Route>
            );
          })}
        </Route>
      </Routes>
    </Suspense>
  );
};


text:
Q: How to get server path of physical path ?  I want to convert this physical path "C:\bla\bla\Content\Upload\image.jpg" to server path like "/Content/Upload/image.jpg".
How can i do that ?

A: You can do the following to get the relative path.
String filePath = @"C:\bla\bla\Content\Upload\image.jpg";

String serverPath = Request.PhysicalPath;
String relativePath = filePath.Substring(serverPath.Length, filePath.Length - serverPath.Length);

A: you can use something like that :
 public static class Extensions        {
        public static string RelativePath(this HttpServerUtility utility, string path, HttpRequest context)
        {
            return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "/").Replace(@"\", "/");
        }
    }

and you call
Server.RelativePath(path, Request);


text:
Q: Fallo Ejercicio Basico PHP Hola buenas me gustaría saber que fallo tiene...Se que es un ejercicio básico de PHP, no me acaba de ejecutar bien la linea del for...
Debería crear una fila de tabla con sus tr y dos th internos en uno un numero (euros) , y en otro esa cifra multiplicada por pesetas...

<!DOCTYPE html>

   <TITLE>PHP y HTML</TITLE>
   <LINK REL="stylesheet" TYPE="text/css" HREF="estilo.css">

PHP y HTML

             EUROS
             Pesetas

<?PHP

  $n = 166.338;

   for ($i=1; $i<=10; $i++){
    print ("
$i	$n*$i
");

   }
?>

A: Puedes solucionarlo concatenando los valores asi:
<!DOCTYPE html>

   <TITLE>PHP y HTML</TITLE>
   <LINK REL="stylesheet" TYPE="text/css" HREF="estilo.css">

PHP y HTML

             EUROS
             Pesetas

<?PHP

  $n = 166.338;

   for ($i=1; $i<=10; $i++){
    print ("
$i	".$n*$i."
");

   }
?>


text:
Q: Performance cost of comparing two C++ iterators In general, what is the performance cost of an equality comparison between two STL container iterators?  I'm only talking about defined operations; that is, comparing two iterators referring to the same object.
My specific use-case is that I have a std::map that could potentially have very large elements, lots of elements, or both.  If an equality comparison between two iterators over such a map have hidden penalties that I'm not aware of, it could impact the performance of my code.

A: Generally, the performance of comparing two iterators depends on the implementation of the STL.
However, concerning the time complexity, the C++ standard imposes the restriction that comparison of input iterators (and thus forward iterators, bidirectional iterators and random access iterators) takes amortized constant time. Particularly, this means for an std::map<std::string, int>, that its iterators cannot be compared by comparing the keys for equality, because that would be linear with respect to the length of the key.

A: Most of STL containers operator==() is just raw pointer comparison. Which is meaningless unless it's for boundaries checking. More over, if you are comparing iterators from different containers - it's undefined behaviour.
If you override this operator or use external comparison function, perfomance depends on how large are object you are comparing.
Probably I got your question wrong, it's not 100% clear what do you mean by "iterator comparison" and what's your use case.

A: The draft Standard states that iterator operations are amortized constant time
24.2.1 In general [iterator.requirements.general]

8 All the categories of iterators require only those functions that
  are realizable for a given category in constant time (amortized).
  Therefore, requirement tables for the iterators do not have a
  complexity column.

If you look at the signatures of iterator operations, there are no parameters or return types that correspond to the underlying elements T themselves, only T* and T& are required. Even operator== does not have to directly compare two arbitrarily large elements T themselves.
However, this does not give a hard real-time upper-bound for iterator operations. In particular, iterators can do very costly bounds checking, but these Debug mode security guards can usually be left out in Release builds.


text:
Q: getting the index of a Seq / Vector while in a map function I have a Seq[Article]
I want to map over them but somehow get access to the position of the Article in the Sequence.
So if the Seq contains (Article1, Article2, Article3, Article4) I want to do something like this:
mySeq.map { article =>

   val index = article.getPositionInSeq  // <- obviously this is not defined

   //if index odd {}
   //if index even {}

}

I know that Vector is indexed, and has a indices function defined on it which gives the range of the Vector (in my case, 0..3) but how could I get the actual place for each Article in the Sequence? Thanks

A: Use zipWithIndex to transform sequence of elements into sequence of pairs (element, index):
mySeq.zipWithIndex.map { e =>
  val (element, idx) = (e._1, e._2)
}


text:
Q: WordPress Multisite for multi-language I want to make a WordPress with multiple languages. I have two WordPress sites and I want them to use the same domain name.
Site 1: http://example.com/en
Site 2: http://example.com/de
Is this possible? What information do I need to search for to find a tutorial.
I don't want to use a plugin like WPML to translate content, I have to use multiple WordPress sites.

A: Just create a standard multisite using the sub-directories option and name your site with the appropriate language slug.
Normally it would be : mysite.com/subsitename
You could just do : mysite.com/en


text:
Q: Formulating Transformation Matrix? How to formulate a transformation matrix for the following operation? Like all the examples I found are different and I can't understand how to solve this problem:
y=A.X
y = (y1 y2)'
x = (x1 'x2)
(y1 y2)' = (x1 x2)'
(-x1, x2)' = (-x1, -x2)'

A: For X gives the vector $(1,0)$ (as column)  calculate corresponding $t$ vector using the given formula. That would be the first column of $A$. Now repeat the same with $X=(0,1)$ to get the second column of $A$.


text:
Q: Build custom files w/o 'Custom Tool' in MSVS2012 What I like to do is compile a custom file to generate a C# file. I only need it to compile when its been changed but compiling everytime is ok.
When I looked around I kept finding reference to Custom Tool and found this pretty good article. I remember pre2010 I was able to have a build rule for extensions but it looks like that doesn't exist anymore? It allowed me to specify an extension and bin+args to run against when the file changed. Whats the closest thing to that? It looks like it no longer supported which is exactly what I want
Custom Tool requires me to mess around with registry, create a dll and requires VS SDK. Its way overkill for something I done with ease in the past.
How do I have visual studios run my exe to build a custom extension source file without going into overkill like custom tool above? Must work for C# project, C++ projects would be nice but not required.


text:
Q: Fiding $g$ such that $\int_0^1 g(y)\int_{y/2}^{1-y/2} \frac{1}{g(x)x^2} \ \mathrm{d}x\ \mathrm{d}y <\infty.$ I am trying to prove that there exists a measurable function $g:(0,1) \to (0,\infty)$ such that
$$\int_0^1 g(y)\int_{y/2}^{1-y/2} \frac{1}{g(x)x^2} \ \mathrm{d}x\ \mathrm{d}y <\infty,$$
(I do not know if such a function exists). But up to now, I have failed miserably. Any suggestions?

Brief comment
I noticed that choosing $f(x)=1/ \sqrt{x}$ we have that
$$\int_{0}^1 \sqrt{y} \int_{y/2}^{1-y/2} \frac{1}{x\sqrt x} \ \mathrm{d} x\ \mathrm{d} y = \frac{\pi}{2} <\infty,  $$
however I have not being able to adapt this proof to $1/x^2.$


text:
Q: osx change file encoding (iconv) recursive I know I can convert a single file encoding under OSX using:
iconv -f ISO-8859-1 -t UTF-8 myfilename.xxx > myfilename-utf8.xxx
I have to convert a bunch of files with a specific extension,
so I want to convert file encoding from ISO-8859-1 to UTF-8
for all *.ext files in folder /mydisk/myfolder
perhaps someobe know the syntax how to do this
thanks
ekke

A: if your shell is bash, something like this
for files in /mydisk/myfolder/*.xxx
do
  iconv -f ISO-8859-1 -t UTF-8 "$files" "${files%.xxx}-utf8.xxx"
done

A: Adam' comment showed me the way how to resolve it,
but this was the only syntax I made it work:
find /mydisk/myfolder -name \*.xxx -type f | \
    (while read file; do
        iconv -f ISO-8859-1 -t UTF-8 "$file" > "${file%.xxx}-utf8.xxx";
    done);

-i ... -o ... doesnt work, but >
thx again
ekke

A: Here is example Tested in mac 10.10.
Find file by name,convert encode ,then replace original file.work perfect.
Thanks for Roman Truba's example,COPY the full code below to your shell script.
   #!/bin/bash
        find ./ -name *.java -type f | \
        (while read file;
            do if [[ "$file" != *.DS_Store* ]]; then
            if [[ "$file" != *-utf8* ]]; then
                iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file-utf8";
                rm $file;
                echo mv "$file-utf8" "$file";
                mv "$file-utf8" "$file";
            fi
        fi
        done);

A: try this ... it´s tested and workin:
First step (ICONV):
find /var/www/ -name *.php -type f | (while read file; do iconv -f ISO-8859-2 -t UTF-8 "$file" > "${file%.php}.phpnew"; done)
Second step (REWRITE - MV):
find /var/www/ -name "*.phpnew" -type f | (while read file; do mv $file echo $file | sed 's/\(.*\.\)phpnew/\1php/' ; done)
It´s just conclusion on my research :)
Hope it helps
Jakub Rulec

A: I extended Albert.Qings script:

*

*autodetect the current file encoding

*added a command parameter to do a dry/exec-run

*added a parameter for the directory and filename pattern
#!/bin/bash
command=${1-"usage"}
searchPattern=${2-"*.java"}
searchDirectory=${3-"."}
if [[ "$command" == "usage" ]]; then
    echo "convert-file-to-utf8.sh [usage|dry|exec] [searchPattern=$searchPattern] [searchDirectory=$searchDirectory]"
    exit
fi
find $searchDirectory -type f -name "$searchPattern" | \
(while read file;
    do if [[ "$file" != *.DS_Store* ]]; then
    if [[ "$file" != *-utf8* ]]; then
        currentEncoding="$(file --brief --mime-encoding $file)"
        if [[ "$currentEncoding" != "utf-8" ]]; then
           echo "command:$command / iconv -f $currentEncoding -t UTF-8 $file"
           if [[ "$command" == "exec" ]]; then
             iconv -f $currentEncoding -t UTF-8 "$file" > "$file-utf8";
             rm $file;
             echo mv "$file-utf8" "$file";
             mv "$file-utf8" "$file";
          fi
        fi
    fi
fi
done);

Tested on MacOS X 10.12.6 / Sierra.

A: You could write a script in any scripting language to iterate over every file in /mydisk/myfolder, check the extension with the regex [.(.*)$], and if it's "ext", run the following (or equivalent) from a system call.
"iconv -f ISO-8859-1 -t UTF-8" + file.getName() + ">" + file.getName() + "-utf8.xxx"
This would only be a few lines in Python, but I leave it as an exercise to the reader to go through the specifics of looking up directory iteration and regular expressions.

A: If you want to do it recursively, you can use find(1):
find /mydisk/myfolder -name \*.xxx -type f | \
    (while read file; do
        iconv -f ISO-8859-1 -t UTF-8 -i "$file" -o "${file%.xxx}-utf8.xxx
    done)

Note that I've used | while read instead of the -exec option of find (or piping into xargs) because of the manipulations we need to do with the filename, namely, chopping off the .xxx extension (using ${file%.xxx}) and adding -utf8.xxx.


text:
Q: How do I (continue to, post-Kotlin Android Extensions) access widgets as array elements (which are doubly-included)? I am "modernizing" some 15-month-old code to take advantage of
Kotlin Extension View Binding (migrating away from the deprecated
Kotlin Android Extensions compiler plugin).
The issue I'm having is related to the practice of using vars of
type Array<ConstraintLayout> throughout my code. This is
exemplified by charKeys throughout this posting.
I'm using nested includes within the XML.
I am struggling to figure the correct new syntax or approach. I
cannot get this code to compile yet.
NOTE: All Kotlin & XML has been reduced to relevant sections only.
First, the "old" way - which is working perfectly.
PuzzleFragment.kt
import kotlinx.android.synthetic.main.fragment_puzzle.*
import kotlinx.android.synthetic.main.item_keyboard.*
import kotlinx.android.synthetic.main.item_keyboard.view.*
import kotlinx.android.synthetic.main.item_kkey.view.*
 :

class PuzzleFragment : Fragment() {

    lateinit var charKeys: Array<ConstraintLayout>

    charKeys = arrayOf(
        kbd_char_0,
        kbd_char_1
         :
        )

fragment_puzzle.xml
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/puzzle_fragment"
    >
    <include layout="@layout/item_keyboard" />
</androidx.constraintlayout.widget.ConstraintLayout>

item_keyboard.xml
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/keyboard"
    >
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/kbd_char_0"
        >
        <include layout="@layout/item_kkey" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/kbd_char_1"
        >
        <include layout="@layout/item_kkey" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

item_kkey.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <TextView
        android:id="@+id/kkey"
        />
</merge>

Again, all of that is (was) working (using Kotlin Android
Extensions). And this code allows (allowed) me to do things
like:
PuzzleFragment.kt
    for (x in 0 until someNumber) {
        val shape = charKeys[x].background as GradientDrawable
        shape.setStroke(...)
        charKeys[x].kkey.setTextColor(...)

    for (key in charKeys)
        key.isEnabled = false

    for ((kx, key) in charKeys.withIndex())
        key.elevation = ... //using kx

    for (cx in 0 until maxGuessLength)
        makeKeyRed(charKeys[cx], true)

    private fun makeKeyRed(key: ConstraintLayout, doRed: Boolean) {
        when {
            doRed -> key.kkey.setTextColor(...)
            key.kkey.text != "#" -> key.kkey.setTextColor(...)
            else -> key.kkey.setTextColor(...)
        }
    }

So - that's the old way. Everything's cool. Now I'm converting this code. I have:
PuzzleFragment.kt
import com.zazzem.thats.databinding.FragmentPuzzleBinding

class PuzzleFragment : Fragment(R.layout.fragment_puzzle) {

    private var _binding: FragmentPuzzleBinding? = null
    private val binding get() = _binding!!

The following code seems ok (no "highlighted" errors in the IDE):
    lateinit var charKeys: Array<ConstraintLayout>

    charKeys = arrayOf(
        binding.item_keyboard.kbd_char_0,
        binding.item_keyboard.kbd_char_1,
         :
    )

    for (x in 0 until someNumber) {
        val shape = charKeys[x].background as GradientDrawable
        shape.setStroke(...)

But it "falls apart" with the next line of code:
        charKeys[x].kkey.setTextColor(...)

It doesn't like "kkey" here ("Unresolved reference"). And, in fact,
Basic code completion (Ctrl + Space) shows none of the widgets which
are part of item_kkey.
I don't know if I'm simply missing something obvious? Or if this
whole "array of 'vaguely-typed' ConstraintLayouts" approach isn't
valid (any longer)? Or if it's something in between?

A: Your .kkey is another use of a synthetic property, so you can't do that without Kotlin Android Extensions. The synthetic property is under the hood using findViewById on whatever ConstraintLayout you call it on to find the child view.
With view binding, no such properties of Views exist. But the generated class does have properties for include blocks. These properties return the generated binding classes of the layout files that you're including. However, you have not used android:id elements on your include elements, so they won't be accessible via your binding class.
Even if you did, that wouldn't be compatible with your ConstraintLayout Array strategy here.
I suggest for ease of converting your code, you create a direct replacement for the synthetic property, like this:
val ConstraintLayout.kkey: TextView get() = findViewById(R.id.kkey)

One downside to this compared to the synthetic property is that it has to find the view every time you use it, which is slightly slower than synthetic properties when they are repeatedly used. But I don't think it will be very significant here, since this particular view is always the sole child of the layout you are searching in.
Note, this strategy has the same weakness that they deprecated Android Extensions for. It's not safe to call this on any arbitrary ConstraintLayout.


text:
Q: Reordering elements both visually and in the DOM I am creating a filtering function that will animate the reordering of a set of elements (projects in this case) as well as update their position within the DOM. Please see comments in js for the basic idea.
The function works the first time a category filter is clicked. Repeat use of the category filters breaks the function however.
The issue seems to be the elements using their original onload position for the animation rather than their updated current position.
I have tried various things to fix but nothing seems to work so any help is greatly appreciated.
I have tried to simplify my code as much as possible:

$('#filterNav').find('a').click(function() {
  var navItem = $(this);
  slideSwap(navItem);
  return false;
});

function slideSwap(navItem) {

  var projContainer = $('#projectContainer');
  var projects = projContainer.find('li');
  var category = navItem.data('sort');

  // 1. Record each project's current positioning
  projects.each(function() {

    $(this).attr('data-latpos', $(this).position().left)
      .attr('data-vertpos', $(this).position().top);

  });

  // 2. Reorder the project list based on selected category
  projects.each(function() {

    if ($(this).data('cat').indexOf(category) != -1) {
      $(this).prependTo(projContainer);
    }
  });

  // 3. Record new project positions
  projects.each(function() {

    $(this).attr('data-newlatpos', $(this).position().left)
      .attr('data-newvertpos', $(this).position().top);

  });

  // 4. Reset to original position with absolute positioning
  projects.each(function() {

    $(this).css({
      position: 'absolute',
      left: $(this).data('latpos'),
      top: $(this).data('vertpos')
    });

  });

  // 5. Animate from original position to new position
  projects.each(function() {

    var project = $(this);

    $(this).animate({
      left: $(this).data('newlatpos'),
      top: $(this).data('newvertpos')
    }, 1000, function() {
      $(this).css('position', 'static');
    });

  });

}

Cat 1

Cat 2

Cat 3

Cat 1

Cat 3

  ...

Cat 2

A: Answering my own question.. the issue was I didn't fully understand how data attributes affect their elements.
The data attributes need to be removed at the end of step 5 via removeData(). Now the animation seems to work correctly:

$('#filterNav').find('a').click(function() {
  var navItem = $(this);
  slideSwap(navItem);
  return false;
});

function slideSwap(navItem) {

  var projContainer = $('#projectContainer');
  var projects = projContainer.find('li');
  var category = navItem.data('sort');

  // 1. Record each project's current positioning
  projects.each(function() {

    $(this).attr('data-latpos', $(this).position().left)
      .attr('data-vertpos', $(this).position().top);

  });

  // 2. Reorder the project list based on selected category
  projects.each(function() {

    if ($(this).data('cat').indexOf(category) != -1) {
      $(this).prependTo(projContainer);
    }
  });

  // 3. Record new project positions
  projects.each(function() {

    $(this).attr('data-newlatpos', $(this).position().left)
      .attr('data-newvertpos', $(this).position().top);

  });

  // 4. Reset to original position with absolute positioning
  projects.each(function() {

    $(this).css({
      position: 'absolute',
      left: $(this).data('latpos'),
      top: $(this).data('vertpos')
    });

  });

  // 5. Animate from original position to new position
  projects.each(function() {

    var project = $(this);

    $(this).animate({
      left: $(this).data('newlatpos'),
      top: $(this).data('newvertpos')
    }, 1000, function() {
      $(this).css('position', 'static');

      // Remove data attributes
      $(this).removeData('latpos').removeData('vertpos').removeData('newlatpos').removeData('newvertpos');
    });

  });

}

Cat 1

Cat 2

Cat 3

Cat 1

Cat 3

  ...

Cat 2


text:
Q: How do you solve the 15-puzzle with A-Star or Dijkstra's Algorithm? I've read in one of my AI books that popular algorithms (A-Star, Dijkstra) for path-finding in simulation or games is also used to solve the well-known "15-puzzle".
Can anyone give me some pointers on how I would reduce the 15-puzzle to a graph of nodes and edges so that I could apply one of these algorithms?
If I were to treat each node in the graph as a game state then wouldn't that tree become quite large?  Or is that just the way to do it?

A: A good heuristic for A-Star with the 15 puzzle is the number of squares that are in the wrong location. Because you need at least 1 move per square that is out of place, the number of squares out of place is guaranteed to be less than or equal to the number of moves required to solve the puzzle, making it an appropriate heuristic for A-Star.

A: A quick Google search turns up a couple papers that cover this in some detail: one on Parallel Combinatorial Search, and one on External-Memory Graph Search
General rule of thumb when it comes to algorithmic problems: someone has likely done it before you, and published their findings.

A: This is an assignment for the 8-puzzle problem talked about using the A* algorithm in some detail, but also fairly straightforward:
http://www.cs.princeton.edu/courses/archive/spring09/cos226/assignments/8puzzle.html

A: The graph theoretic way to solve the problem is to imagine every configuration of the board as a vertex of the graph and then use a breath-first search with pruning based on something like the Manhatten Distance of the board to derive a shortest path from the starting configuration to the solution.
One problem with this approach is that for any n x n board where n > 3 the game space becomes so large that it is not clear how you can efficiently mark the visited vertices. In other words there is no obvious way to assess if the current configuration of the board is identical to one that has previously been discovered through traversing some other path. Another problem is that the graph size grows so quickly with n (it's approximately (n^2)!) that it is just not suitable for a brue-force attack as the number of paths becomes computationally infeasible to traverse.
This paper by Ian Parberry A Real-Time Algorithm for the (n^2 − 1) - Puzzle describes a simple greedy algorithm that iteritively arrives at a solution by completing the first row, then the first column, then the second row... It arrives at a solution almost immediately, however the solution is far from optimal; essentially it solves the problem the way a human would without leveraging any computational muscle.
This problem is closely related to that of solving the Rubik's cube. The graph of all game states it too large to solve by brue force, but there is a fairly simple 7 step method that can be used to solve any cube in about 1 ~ 2 minutes by a dextrous human. This path is of course non-optimal. By learning to recognise patterns that define sequences of moves the speed can be brought down to 17 seconds. However, this feat by Jiri is somewhat superhuman!
The method Parberry describes moves only one tile at a time; one imagines that the algorithm could be made better up by employing Jiri's dexterity and moving multiple tiles at one time. This would not, as Parberry proves, reduce the path length from n^3, but it would reduce the coefficient of the leading term.

A: Remember that A* will search through the problem space proceeding down the most likely path to goal as defined by your heurestic.
Only in the worst case will it end up having to flood fill the entire problem space, this tends to happen when there is no actual solution to your problem.

A: Just use the game tree.  Remember that a tree is a special form of graph.
In your case the leaves of each node will be the game position after you make one of the moves that is available at the current node.

A: Here you go http://www.heyes-jones.com/astar.html

A: Also. be mindful that with the A-Star algorithm, at least, you will need to figure out a admissible heuristic to determine whether a possible next step is closer to the finished route than another step.

A: For my current experience, on how to solve an 8 puzzle.
it is required to create nodes. keep track of each step taken
and get the manhattan distance from each following steps, taking/going to the one with the shortest distance.
update the nodes, and continue until reaches the goal


text:
Q: Proving combinatoric identity I am struggling with this identity :
$$\sum_{k=0}^n\binom{2n+1}{k}=2^{2n}$$
Thanks for your help

A: Let
$$S=\sum_{k=0}^{n} {2n+1 \choose k}.$$
By binomial expansion
$$(1+1)^{2n+1}=\sum_{j=0}^{n} {2n+1 \choose k}=1+{2n+1 \choose 1}+{2n+1 \choose 2}+{2n+1 \choose 3}+......+{2n+1 \choose n}+ {2n+1 \choose n+1}+{2n+1 \choose n+2}+.....+{2n+1 \choose 2n+1}=2^{2n+1}$$
Using the redlection propert of binomial cofficientafter $(n+1)$th term, we get
$$(1+1)^{2n+1}=\sum_{j=0}^{n} {2n+1 \choose k}=1+{2n+1 \choose 1}+{2n+1 \choose 2}+{2n+1 \choose 3}+......+{2n+1 \choose n}+ {2n+1 \choose n-1}+{2n+1 \choose n-2}+.....+{2n+1 \choose 0}=2^{2n+1}$$
$$\implies 2S=2^{2n+1}\implies S=2^{2n}$$

A: Consider the expansion of the binomial
$$(x+1)^{2n+1}$$
And subsitute $x = 1$


text:
Q: Automation Problem - Recursion I am dealing with an automation problem which I don't know how to solve and I hope to get some pointers from you. The task I want to achieve is that a certain field is filled with a code generated by an Apex-script. This should be done when the record type of a contact is changed.
Below I am describing two criteria nodes in a Process Builder. The first changes the record type and fills some fields (which are required for the filling of the field with the apex script).
In the screenshot below you can see two criteria nodes.

In the upper node there is a check to see if the recordtype of the record has changed
OR(
    AND(
        [Contact].RecordType.DeveloperName = 'Medewerker',
        ISCHANGED([Contact].RecordTypeId )
    ),
    AND(
        ISNEW(),
        [Contact].RecordType.DeveloperName = 'Medewerker'
    )
)

This is the part that works ;) The second criteria node checks whether certain fields are filled. What I thought the problem was, was that these fields are filled as an action after the first criteria node. However, when I turned on recursion this did not solve the problem. In fact, this resulted in executing the first node more than once.
Do you have any pointers as to where the problem could lie?
If any extra info/context is needed, let me know!


text:
Q: Wifi - wireless network not working after installing Ubuntu 12.04 I had installed ubuntu 12.04 in my Dell Vostro 3460. Initially wired as well wireless both are not working.
After installing compat-wireless-2012-07-03-pc.tar.bz2 wired network fine but wireless is not working. Previously both were working fine with ubuntu 11.10. Also presently both network are working fine in Win7.
lspci:
00:00.0 Host bridge: Intel Corporation Ivy Bridge DRAM Controller (rev 09)
00:01.0 PCI bridge: Intel Corporation Ivy Bridge PCI Express Root Port (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Ivy Bridge Graphics Controller (rev 09)
00:14.0 USB controller: Intel Corporation Panther Point USB xHCI Host Controller (rev 04)
00:16.0 Communication controller: Intel Corporation Panther Point MEI Controller #1 (rev 04)
00:1a.0 USB controller: Intel Corporation Panther Point USB Enhanced Host Controller #2 (rev 04)
00:1b.0 Audio device: Intel Corporation Panther Point High Definition Audio Controller (rev 04)
00:1c.0 PCI bridge: Intel Corporation Panther Point PCI Express Root Port 1 (rev c4)
00:1c.4 PCI bridge: Intel Corporation Panther Point PCI Express Root Port 5 (rev c4)
00:1d.0 USB controller: Intel Corporation Panther Point USB Enhanced Host Controller #1 (rev 04)
00:1f.0 ISA bridge: Intel Corporation Panther Point LPC Controller (rev 04)
00:1f.2 SATA controller: Intel Corporation Panther Point 6 port SATA Controller [AHCI mode] (rev 04)
00:1f.3 SMBus: Intel Corporation Panther Point SMBus Controller (rev 04)
01:00.0 VGA compatible controller: NVIDIA Corporation Device 0de9 (rev a1)
02:00.0 Network controller: Broadcom Corporation Device 4365 (rev 01)
03:00.0 Ethernet controller: Atheros Communications Inc. AR8161 Gigabit Ethernet (rev 10)

iwconfig:
lo        no wireless extensions.
eth0      no wireless extensions.

ifconfig:
eth0      Link encap:Ethernet  HWaddr 84:8f:69:d4:35:9b
          inet addr:10.24.22.72  Bcast:10.24.31.255  Mask:255.255.224.0
          inet6 addr: fe80::868f:69ff:fed4:359b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:15332 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10425 errors:0 dropped:0 overruns:0 carrier:1
          collisions:0 txqueuelen:1000
          RX bytes:9262594 (9.2 MB)  TX bytes:1572030 (1.5 MB)
          Interrupt:16

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:1432 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1432 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:145656 (145.6 KB)  TX bytes:145656 (145.6 KB)

A: I have a Vostro 1500 that I just set up recently and I had to do a bios update in order to get my wireless to work.

A: Maybe wifi driver problem.
Try like this
First we have to remove the bcmwl kernel source:
    sudo apt-get remove bcmwl-kernel-source
Then again install :
    sudo apt-get install bcmwl-kernel-source

A: Another reason for not detecting Wifi after new installations or such issues might be a problem with Wireless Network Adapter Drivers.
You can first check which Wifi Network Adapter is there in your PC.
lshw -C network

Mine Wireless N/W adapter was Realtek rtl8723be. So I installed the drivers from :
https://github.com/lwfinger/rtlwifi_new
Thanks.


text:
Q: UIProgressView, Theading, performSelectorOnMainThread while using ASIHTTPRequest Kinda stuck on this problem and I'm not sure, where I've gone wrong. Heres what I'm doing:
Class calls:
- (void)updateApplicationDataInBackground {

updateView = [[UpdatingView alloc] init];
[self.view addSubview:updateView.view];

DataSynchronizer *dataSynchronizer = [[DataSynchronizer alloc] init];

[NSThread detachNewThreadSelector:@selector(initWithDataRequest:) toTarget:dataSynchronizer withObject:self];

[dataSynchronizer release];

This creates a thread to retrieve data from the server and parse it. In DataSynchronizer this is the method being called:
- (void)initWithDataRequest:(id)parent {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

controller = parent;

NSLog(@"DataSynchronizer initWithDataRequest called");

NSURL *url = [NSURL URLWithString: ApiUrl];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:ApiKey forKey:@"key"];
[request setPostValue:ApiPass forKey:@"password"];
[request setPostValue:@"somevalue" forKey:@"framework"];
[request setPostValue:@"somevalue" forKey:@"method"];
[request setDidFinishSelector:@selector(parseResult:)];
[request setDidFailSelector:@selector(requestError:)];
[request setTimeOutSeconds:60];
[request setDelegate:self];
[request startAsynchronous];

[pool release];

After my data is received I parse the contents and do my data synch. This is all working as expected. I've decided to throw in a UIProgressView so the user can see what is going on with this request, this progress view lives in updateView which is created in the updateApplicationDataInBackground.
I'm not trying to show progress for the web service call but simply when milestones are reached in the data processing. In the DidFinishSelector its calling parseResult
There are five method its calls with the response data:
[self parseData:[data objectForKey:@"types"] forObject:[Types class] andParent:nil];
        [controller performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:.4] waitUntilDone:YES];

After each process I'm trying to update the UIProgressView, it will never update. Now if I simply call performSelectorOnMainThread from outside the ASIHTTPRequest it works as expected, but not within the DidFinishSelector. I've tried many variations on this where it calls a local method which updates the mainThread, where I simply use performSelector. Nothing works, how do I update the the UIProgessView?
Is the problem a thread spawning a thread?
Thanks
EDIT:
Looks like the DidFinishSelector is being called on the main thread already. I've updated my code to simply call:
[controller updateProgress:[NSNumber numberWithFloat:.8]]

Still no luck....
Realized it might be helpful to see the UIProgessView update method.
- (void)updateProgress:(NSNumber *)progress {

float newProgess = [progress floatValue];

[updateView.myProgress setProgress: newProgess];

A: Ok so it looks like I found my own answer after changing somethings around. Because ASIHttpRequest performs SetDidFinish selector on the main thread my calls performSelectorOnMainThread weren't doing anything. I changed my initial call for the DataSynchronizer to the main thread and added changed the DidFinish method to:
- (void)parseDataInBackground:(ASIHTTPRequest *)request {

[NSThread detachNewThreadSelector:@selector(parseResult:) toTarget:self withObject:request];

Which then makes the parse method run on separate thread (since its the bulk of the processing and now performOnMainThread works without issue.


text:
Q: Selecting on Sub Queries in NHibernate with Critieria API So I have a SQL query with the following structure:
select p.* from
(
    select max([price]) as Max_Price,
    [childId] as childNodeId
    from [Items] group by [childId]
) as q inner join [Items] as p on p.[price] = q.[Max_Price] and p.[childId] = q.[childNodeId]

I need to recreate this query in NHibernate, using the Criteria API.  I tried using the Subqueries API, but it seems to require that the inner query returns a single column to check equality with a property in the outer query.  However, I return two.  I've read that this can be accomplished via the HQL API, but I need to do it with Criteria API, as we're going to be dynamically generating queries like this on the fly.  Can anyone steer me in the correct direction here?

A: I've managed to resolve a similar problem by slightly adapting the original sql query. I've ended up with something like this (pseudo sql code):
SELECT p.* FROM [Items] as p
WHERE EXISTS
(
    SELECT [childId] as childNodeId FROM [Items] as q
    WHERE p.[childId] = q.[childNodeId]
    GROUP BY q.[childId]
    HAVING p.[price] = MAX(q.[price])
)

And this is the QueryOver implementation:
var subquery = QueryOver.Of(() => q)
  .SelectList(list => list.SelectGroup(() => q.ChildId))
      .Where(Restrictions.EqProperty(
          Projections.Property(() => p.Price),
          Projections.Max(() => q.Price)))
      .And(Restrictions.EqProperty(
          Projections.Property(() => p.ChildId),
          Projections.Property(() => q.ChildId)));

From here you only need to pass the aliases so that NHibernate can resolve entities correctly (pseudo code):
var filter = QueryOver.Of(() => p)
    .WithSubquery.WhereExists(GetSubQuery(p, criteria...));

I hope this helps in your particular case.
UPDATE: Criteria API
var subquery = DetachedCriteria.For<Items>("q")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.GroupProperty("q.ChildId")))
    .Add(Restrictions.EqProperty("p.Price", Projections.Max("q.Price")))
    .Add(Restrictions.EqProperty("p.ChildId", "q.ChildId"));

var query = DetachedCriteria.For<Items>("p")
    .Add(Subqueries.Exists(subquery));

Nevertheless I would recommend sticking to the QueryOver version, it's much more intuitive and you avoid magic strings (especially that you don't have to upgrade the NH version).
Please let me know if this is working for you.


text:
Q: Server and client checking in with one another I would like to set up an Apache Mina process where clients and servers communicate using a callback mechanism that the server could call when it detects when a new file has appeared along with a simple function that lets me know whether all systems are up and running or not.
Any help would be much appreciated, I have created a simple TimeServer and TimeHandler program in netbeans which compiles and runs.


text:
Q: Testing for significant difference between coefficients from 2 different IV regressions (Stata or in general) I'm running two different IV models in Stata that share the same DV and controls but have different instruments for the independent variable of interest.
ivregress 2sls energy householdsize sqmeters nondetached (investment= built1978), robust

and
ivregress 2sls energy householdsize sqmeters nondetached (investment= age60), robust

What I want to know is whether the two resulting coefficients for investment are significantly different from one another.
My first thought would be to use something along the lines of sureg or suest combined with lincom, but I can't quite figure out a way to make it work. sureg and suest do not work with ivregress(as far as I'm concerned), and with lincom I can't find a way to access the coefficients and their standard errors.
Any help would be greatly appreciated - both towards a general (non-Stata) solution but of course also towards a Stata-implementation.
Since I'm not accustomed to posting on these forums, please do let me know if there are obvious ways to improve my question.

A: I think you can do this by recasting the 2SLS problem as a GMM one, though I am now somewhat uncertain about the winitial() option. Perhaps others can chime in on this point.
Toy example:
. sysuse auto, clear
(1978 Automobile Data)

. ivregress 2sls mpg gear_ratio (turn = weight), robust

Instrumental variables (2SLS) regression          Number of obs   =         74
                                                  Wald chi2(2)    =      85.55
                                                  Prob > chi2     =     0.0000
                                                  R-squared       =     0.4483
                                                  Root MSE        =      4.268

------------------------------------------------------------------------------
             |               Robust
         mpg |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        turn |  -1.297417   .2285046    -5.68   0.000    -1.745278   -.8495566
  gear_ratio |  -.6471477   2.053764    -0.32   0.753    -4.672451    3.378156
       _cons |    74.6892   14.55076     5.13   0.000     46.17024    103.2082
------------------------------------------------------------------------------
Instrumented:  turn
Instruments:   gear_ratio weight

. ivregress 2sls mpg gear_ratio (turn = length), robust

Instrumental variables (2SLS) regression          Number of obs   =         74
                                                  Wald chi2(2)    =      93.27
                                                  Prob > chi2     =     0.0000
                                                  R-squared       =     0.4720
                                                  Root MSE        =     4.1754

------------------------------------------------------------------------------
             |               Robust
         mpg |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        turn |  -1.226092   .1904174    -6.44   0.000    -1.599303   -.8528803
  gear_ratio |  -.1820588   1.819862    -0.10   0.920    -3.748923    3.384806
       _cons |   70.45905   12.29022     5.73   0.000     46.37067    94.54744
------------------------------------------------------------------------------
Instrumented:  turn
Instruments:   gear_ratio length

.
. gmm ///
> (eq1: mpg - {xb: turn gear_ratio _cons}) ///
> (eq2: mpg - {xc: turn gear_ratio _cons}), ///
> instruments(eq1: gear_ratio weight) ///
> instruments(eq2: gear_ratio length) ///
> onestep winitial(unadjusted, indep)

Step 1
Iteration 0:   GMM criterion Q(b) =  949.82073
Iteration 1:   GMM criterion Q(b) =  5.552e-21
Iteration 2:   GMM criterion Q(b) =  5.159e-28

note: model is exactly identified

GMM estimation

Number of parameters =   6
Number of moments    =   6
Initial weight matrix: Unadjusted                 Number of obs   =         74

------------------------------------------------------------------------------
             |               Robust
             |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
xb           |
        turn |  -1.297417   .2285025    -5.68   0.000    -1.745274   -.8495606
  gear_ratio |  -.6471477   2.053753    -0.32   0.753    -4.672429    3.378134
       _cons |    74.6892   14.55064     5.13   0.000     46.17047    103.2079
-------------+----------------------------------------------------------------
xc           |
        turn |  -1.226092   .1904174    -6.44   0.000    -1.599303   -.8528802
  gear_ratio |  -.1820588   1.819862    -0.10   0.920    -3.748923    3.384806
       _cons |   70.45905   12.29022     5.73   0.000     46.37066    94.54745
------------------------------------------------------------------------------
Instruments for equation eq1: gear_ratio weight _cons
Instruments for equation eq2: gear_ratio length _cons

.
. test _b[xb:turn] = _b[xc:turn]

 ( 1)  [xb]turn - [xc]turn = 0

           chi2(  1) =    0.48
         Prob > chi2 =    0.4904

Stata Code:
cls
sysuse auto, clear
ivregress 2sls mpg gear_ratio (turn = weight), robust
ivregress 2sls mpg gear_ratio (turn = length), robust

gmm ///
(eq1: mpg - {xb: turn gear_ratio _cons}) ///
(eq2: mpg - {xc: turn gear_ratio _cons}), ///
instruments(eq1: gear_ratio weight) ///
instruments(eq2: gear_ratio length) ///
onestep winitial(unadjusted, indep)

test _b[xb:turn] = _b[xc:turn]


text:
Q: How to mongodump from OpenShift and mongorestore locally on MongoDB 2.4.9? I just did this myself (as a RockMongo export and import was corrupted) so just posting here.
Note this was for MongoDB verison 2.4.9 with corresponding versions of mongodump and mongorestore.

A: Read the documentation relevant to your versions first, backup, make sure the solution below is relevant to your scenario etc.
http://docs.mongodb.org/v2.4/reference/program/mongodump/
http://docs.mongodb.org/v2.4/reference/program/mongorestore/
Getting the OC command line interface
The steps below use the OpenShift command line interface (to run the oc commands).
The download link for your relevant operating system can be found by going to:
OpenShift Online Console > [Click on help icon] > Command Line Tools
That location also contains the command required to login.
It looks something like this:
oc login https://api.pro-ap-southeast-2.openshift.com --token=******

You can then run the following to display all the pods in your project:
oc get pods

BEGIN 20/11/18 update
I just had to revisit these steps again, the following may be helpful to others:
01)  To view all MongoDB environment variables, from local computer run:
oc exec mongodb-XX-XXXXX env

(gleaned from comments here)
02)  To perform the dump, go to pod terminal in openshift console:
OpenShift Online Console > Applications > Pods > MongoDB-**-***** > Terminal
and enter this:
mongodump --host MONGODB_SERVICE_HOST:MONGODB_SERVICE_PORT --username admin --password "MONGODB_ADMIN_PASSWORD"

replacing the variable names with the actual values displayed from running the previous command.
I had to use the username admin rather than the environment variable value for MONGODB_USER.
I got this returned in terminal when running the above command:
2023-01-14T06:09:37.689+0000    writing admin.system.users to
2023-01-14T06:09:37.690+0000    done dumping admin.system.users (2 documents)
2023-01-14T06:09:37.690+0000    writing admin.system.version to
2023-01-14T06:09:37.692+0000    done dumping admin.system.version (2 documents)
2023-01-14T06:09:37.692+0000    writing <my-db-name-1>.<my-collection-name-1> to
2023-01-14T06:09:37.692+0000    writing <my-db-name-2>.<my-collection-name-2> to
2023-01-14T06:09:37.692+0000    writing <my-db-name-3>.<my-collection-name-3> to
2023-01-14T06:09:37.692+0000    writing users.users to
2023-01-14T06:09:37.694+0000    done dumping <my-db-name-1>.<my-collection-name-1> (100 documents)
2023-01-14T06:09:37.694+0000    writing <my-db-name-4>.<my-collection-name-4> to
2023-01-14T06:09:37.695+0000    done dumping <my-db-name-4>.<my-collection-name-4> (3 documents)
2023-01-14T06:09:37.695+0000    writing <my-db-name-5>.<my-collection-name-5> to
2023-01-14T06:09:37.696+0000    done dumping <my-db-name-5>.<my-collection-name-5> (1 document)
2023-01-14T06:09:37.707+0000    done dumping users.users (6 documents)
2023-01-14T06:09:37.709+0000    done dumping <my-db-name-3>.<my-collection-name-3> (13 documents)
2023-01-14T06:09:37.716+0000    done dumping <my-db-name-2>.<my-collection-name-2> (78 documents)

03)  If you want to zip the dump folder, do this from pod terminal in console:
# sanity check to see where you are
pwd
# returns /opt/app-root/src

# list the directory contents
ls
# returns dump

# zip the folder
tar czf my_dump.tar.gz dump

# list the directory contents again
ls
# returns dump  my_dump.tar.gz

(gleaned from comments here)
04)  To download the folder, from local PC terminal, do this:
oc rsync mongodb-20-XXXXX:/opt/app-root/src/dump /c/Users/Your-Directory

Or if you want to download the zip file instead, do this:
oc rsync mongodb-20-XXXXX:/opt/app-root/src/my_dump.tar.gz /c/Users/Your-Directory

(gleaned from official docs and blog post here)
For reference, if you wanted to do a mongoexport of a collection to a .json file (as opposed to a mongodump of all databases), you can do the following from the pod terminal and then download the file using oc rsync as shown above:
mongoexport --host ***.**.**.** --port 27017 --authenticationDatabase admin --username admin --password "*******" --db <your-db-name> --collection <your-collection-name> --out my_collection_export.json

Random update (14/01/23):
Annoyingly, I cannot see what version of mongodump is being used when I run the following from the pod terminal:
mongodump --version
mongodump version: built-without-version-string
git version: built-without-git-spec
Go version: go1.8.5
   os: linux
   arch: amd64
   compiler: gc
OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013

So I don't know if that will be problematic when it comes to doing a mongorestore and needing to ensure that the mongodump and mongorestore versions are compatible :/.
END 20/11/18 update

SSH In
rhc ssh [app-name]
cd app-root/repo/

Check what version of mongodump you have:
mongodump --version
mongodump version 2.4.9

mongodump
The command below will dump *ALL* databases.
mongodump --host $OPENSHIFT_MONGODB_DB_HOST:$OPENSHIFT_MONGODB_DB_PORT --username $OPENSHIFT_MONGODB_DB_USERNAME --password $OPENSHIFT_MONGODB_DB_PASSWORD

Zip Dump Folder
zip -r dump.zip dump

Exit SSH
exit

Download via SCP
(Replace the environment variable below with the actual value).
scp OPENSHIFT_APP_UUID@appname-username.rhcloud.com:~/app-root/repo/dump.zip /var/www/html

SSH back in and delete dump files
rhc ssh [app-name]
cd app-root/repo/
rm -r dump
rm -r dump.zip

In local command line, go to the directory where you downloaded the zip file:
cd /var/www/html

Unzip Dump Folder
unzip dump.zip -d dump

See what version of mongorestore you have and that everything is compatible:
mongorestore --version
mongorestore version 2.4.9

At this point, I deleted all my local *corresponding* databases in RockMongo so that the restore process would create them from scratch.
mongorestore
mongorestore dump

The default host and port used is localhost and 27017.


text:
Q: WordPress custom vvv conf format When using the vvv-nginx-custom.conf file to override the default settings, do you need to keep the same format as default? Does it need to include everything default has as well?
I'm a little confused or maybe I misunderstood the directions.
Default file configuration:
server {
    listen       80;
    listen       443 ssl http2;
    server_name  {vvv_hosts};
    root         {vvv_path_to_site}{vvv_public_dir};

    # Nginx logs
    error_log    {vvv_path_to_site}/log/nginx-error.log;
    access_log   {vvv_path_to_site}/log/nginx-access.log;

    # This is needed to set the PHP being used
    set          $upstream {upstream};

    # Enable server push if SSL/HTTP2 is being used for link preload headers
    http2_push_preload on;

    {vvv_tls_cert}
    {vvv_tls_key}

    # Nginx rules for WordPress, rewrite rules, permalinks, etc
    include      /etc/nginx/nginx-wp-common.conf;

    {{LIVE_URL}}

    location ~* \.(css|eot|gif|ico|jpeg|jpg|js|png|svg|tiff|tiff|ttf|webp|woff|woff2)$ {
        expires 100d;
    }
}

Does this mean the customized one would need to look like this?
server {
    listen       80;
    listen       443 ssl http2;
    server_name  {vvv_hosts};
    root         {vvv_path_to_site}{vvv_public_dir};

    # Nginx logs
    error_log    {vvv_path_to_site}/log/nginx-error.log;
    access_log   {vvv_path_to_site}/log/nginx-access.log;

    # This is needed to set the PHP being used
    set          $upstream {upstream};

    # Enable server push if SSL/HTTP2 is being used for link preload headers
    http2_push_preload on;

    {vvv_tls_cert}
    {vvv_tls_key}

    # Nginx rules for WordPress, rewrite rules, permalinks, etc
    include      /etc/nginx/nginx-wp-common.conf;

    {{LIVE_URL}}

    location ~* \.(css|eot|gif|ico|jpeg|jpg|js|png|svg|tiff|tiff|ttf|webp|woff|woff2)$ {
        expires 100d;
    }

    # Custom rules
    install_plugins: # Various way to install a plugin
     - query-monitor
     - classic-editor
     - wordpress-seo
     - all-in-one-wp-migration
     - timber-library
    wpconfig_constants:
        WP_DEBUG: true
        WP_DEBUG_LOG: true
        WP_DISABLE_FATAL_ERROR_HANDLER: true # To disable in WP 5.2 the FER mode
}

A: Stricly speaking, you don't have to include everything, just some things will break, when you remove or alter them.
You can look things up in the NGINX documentation and conclude, if you can safely remove or alter the config line. A good starting point would be How nginx processes a request.
And read the comments in that config. If you don't need the described feature, you could remove it without breaking stuff.
Or just alter stuff, run vagrant reload --provision and inspect, if everything's working. But I admit, this could take ages.
For example, if you remove server_name, it defaults to server_name "";, see NGINX Docs for server. Then you might not hit the right server, because ...

If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one — which is nginx's standard default behaviour.
-- How nginx processes a request

Changing root will sent requests to the wrong folder... Don't change it.
You could remove the logs without problem, if you want.

This is a minimal config for a WordPress site in VVV. You lose all log, HTTPS and caching, but it technically works.
server {
    # Could be removed, because default is `listen *:80 | *:8000;`
    listen       80;
    server_name  {vvv_hosts};
    root         {vvv_path_to_site}/public_html;

    # This is needed to set the PHP being used
    set          $upstream {upstream};

    # Nginx rules for WordPress, rewrite rules, permalinks, etc
    include      /etc/nginx/nginx-wp-common.conf;

    {{LIVE_URL}}
}


text:
Q: EmPubLite Tutorial 12-crashes I have been going through Tutorial 12 of Busy Coders Guide version 5.1.
When I run the emulator the app keeps crashing during startup.  I am not clear on what to look for in my logcat file.  Can you please help me understand what I need to look for.  Thanks.
I searched and didn't see any other posts regarding Tutorial 12.  If there is can you please point me in the right direction.  Thanks.
  10-01 16:01:11.921: D/dalvikvm(1397): GC_FOR_ALLOC freed 103K, 8%
 free 2808K/3028K, paused 37ms, total 39ms 10-01 16:01:11.921:
 I/dalvikvm-heap(1397): Grow heap (frag case) to 3.460MB for
 635812-byte allocation 10-01 16:01:12.041: D/dalvikvm(1397):
 GC_FOR_ALLOC freed 3K, 7% free 3426K/3652K, paused 114ms, total 114ms
 10-01 16:01:12.291: D/gralloc_goldfish(1397): Emulator without GPU
 emulation detected. 10-01 16:01:12.491: D/AndroidRuntime(1397):
 Shutting down VM 10-01 16:01:12.511: W/dalvikvm(1397): threadid=1:
 thread exiting with uncaught exception (group=0x41465700) 10-01
 16:01:12.581: E/AndroidRuntime(1397): FATAL EXCEPTION: main 10-01
 16:01:12.581: E/AndroidRuntime(1397): java.lang.NullPointerException
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.commonsware.empublite.BookContents.getChapterCount(BookContents.java:16)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.commonsware.empublite.ContentsAdapter.getCount(ContentsAdapter.java:26)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 android.support.v4.view.ViewPager.setAdapter(ViewPager.java:434) 10-01
 16:01:12.581: E/AndroidRuntime(1397):  at
 com.commonsware.empublite.EmPubLiteActivity.setupPager(EmPubLiteActivity.java:70)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.commonsware.empublite.ModelFragment.deliverModel(ModelFragment.java:29)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.commonsware.empublite.ModelFragment.access$2(ModelFragment.java:27)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.commonsware.empublite.ModelFragment$ContentsLoadTask.onPostExecute(ModelFragment.java:82)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.commonsware.empublite.ModelFragment$ContentsLoadTask.onPostExecute(ModelFragment.java:1)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 android.os.AsyncTask.finish(AsyncTask.java:631) 10-01 16:01:12.581:
 E/AndroidRuntime(1397):    at
 android.os.AsyncTask.access$600(AsyncTask.java:177) 10-01
 16:01:12.581: E/AndroidRuntime(1397):  at
 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 android.os.Handler.dispatchMessage(Handler.java:99) 10-01
 16:01:12.581: E/AndroidRuntime(1397):  at
 android.os.Looper.loop(Looper.java:137) 10-01 16:01:12.581:
 E/AndroidRuntime(1397):    at
 android.app.ActivityThread.main(ActivityThread.java:5103) 10-01
 16:01:12.581: E/AndroidRuntime(1397):  at
 java.lang.reflect.Method.invokeNative(Native Method) 10-01
 16:01:12.581: E/AndroidRuntime(1397):  at
 java.lang.reflect.Method.invoke(Method.java:525) 10-01 16:01:12.581:
 E/AndroidRuntime(1397):    at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 10-01 16:01:12.581: E/AndroidRuntime(1397):    at
 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-01
 16:01:12.581: E/AndroidRuntime(1397):  at
 dalvik.system.NativeStart.main(Native Method)

A:
I am not clear on what to look for in my logcat file

That would be the exception and line where you are crashing:
10-01 16:01:12.581: E/AndroidRuntime(1397): FATAL EXCEPTION: main
10-01 16:01:12.581: E/AndroidRuntime(1397): java.lang.NullPointerException
10-01 16:01:12.581: E/AndroidRuntime(1397): at com.commonsware.empublite.BookContents.getChapterCount(BookContents.java:16)

Hence, you are crashing in line 16 of BookContents.java, in the getChapterCount() method of the BookContents class.
That method should look like:
  int getChapterCount() {
    return(chapters.length());
  }

That indicates that either:

*

*You are missing the chapters=raw.optJSONArray("chapters"); line in the constructor, or

*Your JSON is missing the chapters array
Here is a working implementation of Tutorial 12, including the BookContents class.


text:
Q: I get the following error while running the program : Uncaught Error: [TodoProvider] is not a  component. All component children of  must be a  or <React.Fragment>
import Header from "./cdomponents/Header";
import Home from "./pages/Home";
import TodoProvider from "./contex/TodoProvider";
import Todos from "./pages/Todos";

function App() {
  return (
 <BrowserRouter>
 <Header/>
 <Routes>
   <Route path="/" element= {<Home/>} />
   <Route path="/todos/*"  >
   **<TodoProvider>
   {<Todos/>}
   </TodoProvider>**
   </Route>
 </Routes>
 </BrowserRouter>
  );
}

export default App;```


text:
Q: Value in variable disappears when a second submit button is pressed My program first requests the user to enter a customer no. This is achieved when submit 1 button is pressed. Then this customer no is used to extract information from a database and display it. Then the address of this customer has to be altered so this change is asked for on the second form and submit 2 button is pressed.
The problem is:

*

*When submit 2 button is pressed the customer no disappears from the enter customer no box and the information displayed also disappears.

*The variable $custno has lost its value. I need this variable to update the database.

Why does this happen?
I even used POST for the submit 1 REQUEST METHOD and GET for the submit 2 REQUEST METHOD.
Here is the code I have used:
<!DOCTYPE html>

<?php
$custno=""; $custexists=1; // $custexists=1 means the customer exists in the database
$newaddress1=""; $newaddress2="";

if ($_SERVER["REQUEST_METHOD"] == 'POST' ) {
if (isset ($_POST["submit1"])) {$custno=$_POST["cust"];

goprintcust($custno,$custexists,$newaddress1,$newaddress2);}}

?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Enter Customer No. <input type="number" name="cust" min="1" value="<?php echo $custno; ?>"/>

<input type="submit" name="submit1" value="Submit 1"/>

</form>

<?php
function goprintcust($custno,$custexists,$newaddress1,$newaddress2) {
?>
<?php
// Here search database for $custno and if it exists set $custexists=1
if ($custexists==1) {echo "current data for customer $custno is as follows ..."; // Print the current customer data from the database here
             getnewinput($newaddress1,$newaddress2);}} // we assume the customer exists in the database
                                   // so now get the new data to write into the database

function getnewinput($newaddress1,$newaddress2) {
?>

<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"">

New Address 1 :	  <input type="text" name="newaddress1" value="<?php echo $newaddress1; ?>"/>

New Address 2 :	  <input type="text" name="newaddress2" value="<?php echo $newaddress2; ?>"/>

<input type="hidden" name="cust" value="<?php echo $custno; ?>">

<input type="submit" name="submit2" value="Submit 2">

</form>

<?php             }

if ($_SERVER["REQUEST_METHOD"]=="GET") {
if (isset ($_GET["submit2"])) {
$newaddress1=$_GET["newaddress1"]; $newaddress2=$_GET["newaddress2"];
getnewinput($newaddress1,$newaddress2);
?>
<?php
// Here write the new Address into the database
echo "
"."Database updated for Customer No. ".$custno;
}}

?>

A: Recommend you add <input type="hidden" name="cust" value="<?php echo $custno; ?>"> to your second form.
When you submit your second form your $_POST array is reset, meaning that $_POST['cust'] no longer exists.  Without that you have $cust defined as an empty value.