text:
Q: PhpStorm is throwing an error if running phpcs First of all, let me list some versions so you know the setup.
OS: Windows 10
php: 7.2.7 NTS with xDebug 2.6.1 active
PhpStorm: 2016.2.2
PHP_CodeSniffer: version 3.4.0 (stable) by Squiz (http://www.squiz.net)
PEAR: 1.10.7
Now let me describe the problem:
The code sniffer was installed via pear. I'm using the following bat script for starting the sniffer.
@echo off

set folder=C:\Program Files\php
set phpcs=%folder%\phpcs

php "%phpcs%" %*

If I start the code sniffer via the PowerShell with the following command:
phpcs.bat index.php --standard=PSR2 --encoding=utf-8 --report=xml

I'm getting a valid output:
xml version="1.0" encoding="UTF-8"?>
<file name="C:\Users\simon\Documents\Repositories\mm-BIT\CatalogGenerator\index.php" errors="3" warnings="0" fixable="3">
    <error line="1" column="1" source="Generic.Files.LineEndings.InvalidEOLChar" severity="5" fixable="1">End of line character is invalid; expected "\n" but found "\r\n"</error>
    <error line="124" column="1" source="PSR2.Methods.FunctionCallSignature.SpaceBeforeOpenBracket" severity="5" fixable="1">Space before opening parenthesis of function call prohibited</error>
    <error line="129" column="1" source="PSR2.Methods.FunctionCallSignature.SpaceBeforeOpenBracket" severity="5" fixable="1">Space before opening parenthesis of function call prohibited</error>
</file>
</phpcs>

In PhpStorm the setting looks like this:

If I validate the installation PhpStorm tells me everything is fine:

The data for the coding standards on the Inspections page was loaded automatically, so this seems to work as well.
If PhpStorm is running the script I'm getting the following error:
PHP Code Sniffer
phpcs: xml version="1.0" encoding="UTF-8"?>

I was exposing some data via the script which is getting called:
PHP Code Sniffer
phpcs: C:/temp/___1.tmp/Core/DataContainers/Language.php --standard=PSR2 --encoding=utf-8 --report=xml
command: php "C:\Program Files\php\phpcs" C:/temp/___1.tmp/Core/DataContainers/Language.php --standard=PSR2 --encoding=utf-8 --report=xml
xml version="1.0" encoding="UTF-8"?>

I did check the temp folder for writing permissions and was checking if the file is created correctly on the path mentioned above. I did copy the folder as soon as it was created and did run the command line by hand in the PowerShell successfully.
php "C:\Program Files\php\phpcs"
C:/temp/___.tmp/Core/DataContainers/Modules/SimpleTableModule.php --
standard=PSR2 --encoding=utf-8 --report=xml

which delivers the following output:
<?xml version="1.0" encoding="UTF-8"?>
<phpcs version="3.4.0">
xml version="1.0" encoding="UTF-8"?>
<file name="C:\temp\___.tmp\Core\DataContainers\Modules\SimpleTableModule.php" errors="1" warnings="1" fixable="1">
    <warning line="82" column="114" source="Generic.Files.LineLength.TooLong" severity="5" fixable="0">Line exceeds 120 characters; contains 123 characters</warning>
    <error line="106" column="1" source="PSR2.Files.EndFileNewline.NoneFound" severity="5" fixable="1">Expected 1 newline at end of file; 0 found</error>
</file>
</phpcs>

I don't know how to fix this if you could provide me with some ideas I would be really happy.

A: The problem was solved, I did replace the content of the phpcs.bat file with the official script:
@echo off
REM PHP_CodeSniffer detects violations of a defined coding standard.
REM
REM @author    Greg Sherwood <gsherwood@squiz.net>
REM @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
REM @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence

if "%PHP_PEAR_PHP_BIN%" neq "" (
    set PHPBIN=%PHP_PEAR_PHP_BIN%
) else set PHPBIN=php

"%PHPBIN%" "%~dp0\phpcs" %*

Script in the repository
I was trying this before but it was not working, I was giving myself full access rights on the PHP installation folder as well. Seems like the problem is fixed now.
Still a big thanks to everyone taking a look.
Edit: I checked my bat file again and it was not completely identical with the one from the git repository. I did leave my old code as a comment in the file. After I cleaned this up this morning the sniffer wasn't working anymore, after I readded the comments again the feature was working again. So here is the complete content of the file in the current working state:
@echo off
REM PHP_CodeSniffer detects violations of a defined coding standard.
REM
REM @author    Greg Sherwood <gsherwood@squiz.net>
REM @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
REM @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence

if "%PHP_PEAR_PHP_BIN%" neq "" (
    set PHPBIN=%PHP_PEAR_PHP_BIN%
) else set PHPBIN=php

"%PHPBIN%" "%~dp0\phpcs" %*
REM End of file

We did confirm this behavior on another computer with the same installed software, so this seems to be the problem.
Edit2: Seems like you just need a comment line after the last line of the original script. I did update the code snippet I'm using at the moment.


text:
Q: Low frame rate with Irrlicht on Android I've compiled an Android port of Irrlicht from http://gitorious.org/irrlichtandroid/ and made an application to just load a lo res SkyBox. However, I get unpredictable frame rates. On emulator, fps never goes beyond 5. On my DELL XCD35 with eclair, it usually doesn't go beyond 10 fps, BUT, in about 1 out of 10 launches, the application runs nice at 60 fps.
Activity is configured for fullscreen landscape mode.
Following is the code, I've omitted class header files to keep the post short.
BlueStoneActivity.java
public class BlueStoneActivity extends Activity {
    static {
        System.loadLibrary("irrlicht");
        System.loadLibrary("bluestone");
    }

    GLSurfaceView glView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        glView=new GLSurfaceView(this);
        glView.setRenderer(new IrrlichtRenderer(this));
        setContentView(glView);
        Debug.startMethodTracing("bstone");
        nativeOnCreate();
    }

    @Override
    protected void onDestroy() {
        nativeOnDestroy();
        super.onDestroy();
        Debug.stopMethodTracing();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public native void nativeOnCreate();
    public native void nativeOnDestroy();
    public native void nativeOnPause();
    public native void nativeOnResume();
    public native void nativeOnResize(int w, int h);
    public native void nativeDrawIteration();
}

IrrlichtRender.java
 public class IrrlichtRenderer implements Renderer {
        BlueStoneActivity activity;

        IrrlichtRenderer(BlueStoneActivity activity){
            this.activity=activity;
        }

        @Override
        public void onDrawFrame(GL10 arg0) {
            activity.nativeDrawIteration();
        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            activity.nativeOnResize(width, height);
        }

        @Override
        public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
        }
    }

JNI wrapper
    #include <jni.h>
#include <android/log.h>
#include "EngineManager.h"
#include "InputManager.h"

game::EngineManager *engine;

int importGLInit();
void importGLDeinit();

#ifndef _Included_com_devin_BlueStoneActivity
#define _Included_com_devin_BlueStoneActivity
#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL Java_com_devin_BlueStoneActivity_nativeOnCreate
  (JNIEnv *, jobject){
    engine=new game::EngineManager();
}

JNIEXPORT void JNICALL Java_com_devin_BlueStoneActivity_nativeOnDestroy
  (JNIEnv *, jobject){
    engine->device->drop();
    importGLDeinit();
}

JNIEXPORT void JNICALL Java_com_devin_BlueStoneActivity_nativeOnResize
  (JNIEnv *env, jobject thiz, jint width, jint height){
    __android_log_print(ANDROID_LOG_INFO, "NDK", "ONRESIZE - [%d %d]", width, height);
    engine->mWidth=width;
    engine->mHeight=height;
    importGLInit();
    engine->glInit();
}

JNIEXPORT void JNICALL Java_com_devin_BlueStoneActivity_nativeDrawIteration
  (JNIEnv *, jobject){
    engine->drawIteration();
}

JNIEXPORT void JNICALL Java_com_devin_BlueStoneActivity_nativeOnPause
  (JNIEnv *, jobject){
}

JNIEXPORT void JNICALL Java_com_devin_BlueStoneActivity_nativeOnResume
  (JNIEnv *, jobject){

}

#ifdef __cplusplus
}
#endif
#endif

EngineManager.cpp
#include <irrlicht.h>
#include "EngineManager.h"

namespace game {

EngineManager::EngineManager() {
    input=new game::InputManager();
    app=new game::ApplicationManager(input);
}

EngineManager::~EngineManager() {
}

void EngineManager::glInit(){
    device=createDevice( video::EDT_OGLES1, core::dimension2d<u32>(mWidth, mHeight), 16, false, false, false, 0);
    driver=device->getVideoDriver();
    scenegraph=device->getSceneManager();
    guienv=device->getGUIEnvironment();

    app->initApp(device);
}

void EngineManager::drawIteration(){
    device->run();
    driver->beginScene(true, true, app->clearColor);

    app->drawIteration();

    scenegraph->drawAll();
    guienv->drawAll();
    driver->endScene();
}

} /* namespace game */

ApplicationManager.cpp
#include "ApplicationManager.h"
#include "InputManager.h"

namespace game {

ApplicationManager::ApplicationManager(InputManager *in) {
    this->input=in;
}

ApplicationManager::~ApplicationManager() {
}

void ApplicationManager::initApp(IrrlichtDevice *device){
    this->device=device;
    this->driver=device->getVideoDriver();
    this->scenegraph=device->getSceneManager();
    this->guienv=device->getGUIEnvironment();

    // Camera setup
    camera=scenegraph->addCameraSceneNode();
    camera->setPosition(core::vector3df(20.0f, 15.0f, 15.0f));
    camera->setTarget(core::vector3df(0.0f, 0.0f, 0.0f));

    // Sample objects
    bool sceneLoaded=scenegraph->loadScene("/sdcard/BlueStone/redsky.irr");
    if(sceneLoaded)
        __android_log_print(ANDROID_LOG_INFO, "NDK", "SceneLoaded");
    else
        __android_log_print(ANDROID_LOG_INFO, "NDK", "SceneLoaded false");

    clearColor=video::SColor(255, 20, 40, 40);
    statsText=L"START";
    text=guienv->addStaticText(statsText.c_str(), core::recti(50,50,50+100,50+60), true, true, 0, 18, false);
    text->setOverrideColor(video::SColor(255, 64, 20, 20));
}

void ApplicationManager::drawIteration(){
    statsText=L"FPS: ";
    statsText+=driver->getFPS();
    text->setText(statsText.c_str());
}

} /* namespace game */

Please help !!

A: Got it finally!!
It seems Android SDK has a bug. When you try to set screen orientation to landscape from AndroidManifest.xml using 'android:screenOrientation="landscape"', you get low frame rates on GLSurfaceView.
Using
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE );

in code solved all problems. My code now runs at consistent 60fps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic Programming: Retrieve all solutions I have successfully used DP to get optimal solution to a problem. The issue I am facing though is, now if I want to reconstruct the solution, I end up with only one such way to get optimal solution. Is there a way, such that I will be able to backtrack all the ways/choices which could have lead to an optimum result??
e.g If I am selecting a team from players a, b, c, d with skills {1, 2, 2, 1}, I can get that optimum team skill count will be 3 and I can get one possible way to achieve this as {{a, b}, {c, d}}. What I am looking for is, a way so that I can get all the ways in which I can divide the team fairly with team skill count as 3 i.e {{a, c}, {b, d}} and {{a, b}, {c, d}}

A: If X is the number of players. (X-1)! is the number of possible solutions. Then you can use a for loop with the possible solutions as your length, if the result is equal to your optimum team skill then store that result in an array.

A: Main step in DP is to find solution of a problem by knowing solutions of a subproblems. That is done by finding minimal (or maximal) value of subproblems. With that you can construct a directed graph by connecting problem with it's subproblems that have minimal (or maximal) value. Like in last image on the page. To find all solutions just find all possible paths from the solution of whole problem.


text:
Q: how does the characteristic polynomial of a matrix change with respect to the action of taking a principal minor Let $A$ be an $n\times n$ matrix of complex numbers. Let $B$ be the matrix $A$ with the last row and column removed. Is there a relation between the characteristic polynomials of $A$ and $B$? More generally, how does the characteristic polynomial of a matrix change with respect to the action of taking a principal minor?
We can ask the same questions for eigenvalues/eigenvectors, which are closely related with the char polynomial. Intuitively, I feel that the eigenvalues of $B$ are also the eigenvalues of $A$.

A: Your intuition is completely wrong, as simple examples will show.
The best way I can relate the characteristic polynomials is this.  Write
$$ A = \pmatrix{B & c\cr  d &  e\cr} $$
where $B$ is $(n-1)\times (n-1)$, $c$ is $(n-1) \times 1$, $d = 1 \times (n-1)$, and $e$ is a scalar.  Then
$$ \det(A-\lambda I) = \det(B-\lambda I) (e - \lambda) - d \; \text{adj}(B-\lambda I) c$$
where $\text{adj}$ is the classical adjoint.  In general the term $d \; \text{adj}(B-\lambda I) c$ will be a polynomial of degree $n-2$.


text:
Q: Mark a 3rd party dependency as deprecated in Gradle buid script In the build.gradle of my project, I have a dependency added:
dependencies {
    testImplementation 'some-lib'
}

I want to deprecate the usage of this library in the project. I.e., I want it to be there, to compile and run but just warn the user when he's using methods from this library.
I can't remove the dependency right away because I need some time to refactor already existing usages. With deprecation, I want to prevent new usages of this lib.
Is it possible to mark the dependency as deprecated in Gradle?

A: There's no way to mark a dependency as deprecated, but you should be able to add
afterEvaluate {
    if ('some-lib' in configurations.testImplementation.allDependencies.name) {
        logger.warn("**** WARNING: some-lib is deprecated and will be removed.")
    }
}


text:
Q: Disabled Text Input with onclick I need a way of capturing onclick, for a text input that is disabled.
I would prefer not to use jQuery, but if there was no javascript alternative, would use it.
Thanks in advance
EDIT:
I have tried simply adding an onclick="" to a disabled text field, which did not work.
Is there any way to do it without jquery?
Thanks

A: How about delegation events to parent elements like here?
<span style="position:relative;" onClick="event.target.value='clicked';">
  <input type="text" disabled "/>
</span>

If my answer is acceptable please comment it and I'll make an explanation.

A: You are probably lookinf for this:-
$("div").click(function (evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});

DEMO JSFIDDLE

A: This is the modified jsfiddle proposed by Rahul Tripathi using pure javascript.
This is the function that made it works:
document.getElementById("textInput").onclick = function() {
    alert("Input clicked");
}


text:
Q: Angular Navigate to "/unauthorised" route but keep the URL the same I have a guard that navigates to a "/unauthorised" route when the user doesn't have permission to access the current page (can be any page).
@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(private readonly permissionService: PermissionService, private readonly router: Router) {}

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    const hasPermission = await this.permissionService.userHasPermissionForRoute(state.url);

    if (!hasPermission) {
      await this.router.navigate(['/unauthorised']); // still need to show the state.url in the browser
    }

    return hasPermission;
  }
}

However, I've had a request for the URL to stay the same.
Ie. If they access /my-page and they don't have permission they are navigated the /unauthorised page but the URL in the browser remains /my-page.
Any idea how I can achieve this?
I had thought that using this.router.navigate('/unauthorised', {replaceUrl: false}) would work, but doesn't.

A: You can use { skipLocationChange: true }. According to the documentation:
// When true, navigates without pushing a new state into history.

// Navigate silently to /view
this.router.navigate(['/view'], { skipLocationChange: true });

You'll be able to route to /unauthorised without the URL changing.


text:
Q: NHibernate with multiple databases and transactions We are having a few problems understanding how best to use NHibernate.  We typically have a relatively large number of quite small (in terms of number of tables) SQL Server databases rather than one database with a lot of objects.
We are looking at various options for handling multiple session factories and probably have this under control.  However we are not sure how we would wrap all calls in a single transaction.  Using hand-rolled data access you would just wrap it all in a TransactionScope but we are a little reluctant to do this with NHibernate as it seems to like to handle all its own Transactions.
Using multiple databases with shared transactions seems like the sort of thing lots of people would want to do with NHibernate.
Are we just barking up the wrong tree entirely?

A: You can safely use TransactionScope. But you have to open NHibernate transactions too.
Example:
using (var ts = new TransactionScope())
using (var session1 = sessionFactory1.OpenSession())
using (var tx1 = session1.BeginTransaction())
using (var session2 = sessionFactory2.OpenSession())
using (var tx2 = session2.BeginTransaction())
{
    //Do work...
    tx1.Commit();
    tx2.Commit();
    ts.Complete();
}


text:
Q: Error (if/else dentro de un foreach) Razor Estoy agregando una condicional dentro de un foreach y al momento de ejecutar me sale error de que falta una llave. Cuando quito el código, funciona sin ningún problema, pero con la condicional if se cae, y si agrego el else, el lenguaje no lo reconoce, lo toma como si fuera HTML, estoy que le agrego una arroba "@" para ver si se quita el error y nada.

Código
    @model IEnumerable<wsCharlas.Models.ClsCharla>

@{
    ViewBag.Title = "MostrarCharlasExternos";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

LISTADO DE CHARLAS DISPONIBLES:

    @using (Html.BeginForm())
    {

Dependencia:

                @Html.DropDownList("sed", (SelectList)ViewBag.allSedes, "Seleccione una Sede", new { onchange = "this.form.submit();", @class = "form-control" })

Meses:

                @Html.DropDownList("sed", (SelectList)ViewBag.allSedes, "Seleccione una Sede", new { onchange = "this.form.submit();", @class = "form-control" })

    }

        @foreach (var item in Model)
        {
            string hora = @Html.DisplayFor(modelItem => item.hora_Charla).ToString();

            string hora_modificada = "p.m.";

            if (
            hora.Substring(0, 2).Equals("00") ||
            hora.Substring(0, 2).Equals("01") ||
            hora.Substring(0, 2).Equals("02") ||
            hora.Substring(0, 2).Equals("03") ||
            hora.Substring(0, 2).Equals("04") ||
            hora.Substring(0, 2).Equals("05") ||
            hora.Substring(0, 2).Equals("06") ||
            hora.Substring(0, 2).Equals("07") ||
            hora.Substring(0, 2).Equals("08") ||
            hora.Substring(0, 2).Equals("09") ||
            hora.Substring(0, 2).Equals("10") ||
            hora.Substring(0, 2).Equals("11"))
            {
                hora_modificada = "a.m.";
            }

@Html.DisplayFor(modelItem => item.titulo_Charla)

Fecha:

@Html.DisplayFor(modelItem => item.fecha_Charla)

Hora:

@Html.DisplayFor(modelItem => item.hora_Charla)

Sede:

@Html.DisplayFor(modelItem => item.sede_Charla)

Dirección:

@Html.DisplayFor(modelItem => item.lugar_Charla)

                        @Html.ActionLink("Inscribirse", "CrearInteresado", new {
                                                                                id = item.ID_Charla,
                                                                                titulo = item.titulo_Charla,
                                                                                descripcion = item.descrip_Charla,
                                                                                fecha = item.fecha_Charla,
                                                                                hora = item.hora_Charla,
                                                                                direccion = item.lugar_Charla
                                                                               }, new { @class = "btn btn-primary" })

        }


text:
Q: Missing code-signing certificate when uploading OS X app I am very new on apple app development. I just updated the app for my company and trying to reupload it. But I can't pass the validate on xcode.
I am using xcode 5.01.
Below are my project setting:
   General:
            Bundle Identifier: com.company_name.program_name.
            Version and Build Are both 1.1
            Signing: Mac App Store.
   Build Settings:
            Code Signing Identity both Debug and Release are chossing Mac Developer
            Provisioning Profile, I tried all of the profiles
I am still getting Invalid Provisioning Profile "Missing code-signing certificate" when validating.
I saw this post
"Invalid Provisioning Profile... [Missing code-signing certificate.]" for brand new, Vanilla Mac App in OS X Mavericks
But deleting and recreating an account doesn't help. Can anyone help me?


text:
Q: How to Interpret the Inverted Question Mark via SQL Query  SELECT 'Hello Word... Test…' FROM DUAL

Running the above SQL query in Oracle developer gives me the following output:

How can I maintain the special character in the output and prevent the inverted question mark to appear?
The characterset of my Oracle database: WE81SO8859P1
Here is the list:

A: There are 3 levels to manage:

*

*database

*instance

*session (client)

Be careful of the parameters set on your sql client. You can check with the below query.
SELECT
  data.parameter "PARAMETERS",
  data.value "DATABASE PARAMETERS",
  inst.value "INSTANCE PARAMETERS",
  sess.value "SESSION PARAMETERS"
FROM
  nls_database_parameters data LEFT OUTER JOIN nls_instance_parameters inst
                                             ON(data.parameter = inst.parameter)
                                LEFT OUTER JOIN nls_session_parameters sess
                                            ON(data.parameter = sess.parameter)
ORDER BY 1;


text:
Q: SQL for Retrieving all users and default team from CRM 2013 I need to be able to retrieve all users and the default team of the Business Unit to which they belong.
How do I identify the default team of a Business Unit apart from the same name being used for both the team and BU. Is there a flag which identifies it as a default team?
My required output is the following columns

*

*Domain Name

*Team Name + GUID of Team Name (of the default team of the
BU to which they belong).

Here is my query.
SELECT dbo_SystemUser.DomainName, (dbo_Team.Name + ' ' + dbo_Team.TeamId)
FROM (dbo_Team INNER JOIN (dbo_TeamMembership INNER JOIN dbo_SystemUser ON dbo_TeamMembership.SystemUserId = dbo_SystemUser.SystemUserId) ON dbo_Team.TeamId = dbo_TeamMembership.TeamId) INNER JOIN dbo_BusinessUnit ON dbo_Team.BusinessUnitId = dbo_BusinessUnit.BusinessUnitId
WHERE dbo_Team.Name = dbo_BusinessUnit.Name

A: Team table has IsDefault column which is TRUE for a BU's default team.
It's also included in the FilteredTeam view.
Query that solves the OP issue:
-- Pay attention to the FROMs, tables ignore Security Roles.
-- To respect security, query the filtered views
-- (FilteredSystemUser, FilteredTeam, FilteredTeamMembership)
-- On the other hand, querying tables is much faster

SELECT U.DomainName as [Domain Name], T.Name as [Team Name], T.TeamId as [Team ID]
FROM SystemUser U
    INNER JOIN TeamMembership TM ON U.SystemUserId = TM.SystemUserId
    INNER JOIN Team T ON TM.TeamId = T.TeamId
WHERE T.IsDefault = 1

A: This should do it.
SELECT FilteredSystemUser.domainname, FilteredTeam.name, FilteredTeam.teamid
FROM FilteredSystemUser
    INNER JOIN FilteredBusinessUnit ON FilteredSystemUser.businessunitid = FilteredBusinessUnit.businessunitid
    INNER JOIN FilteredTeam ON FilteredTeam.businessunitid = FilteredBusinessUnit.businessunitid
        WHERE FilteredTeam.isdefault = 1

You also need to be using the Filtered Views.


text:
Q: How to have control on the object that started a background process in android, after the application is closed? I used AlarmManager to schedule recurring background task. When an alarm is triggered, a Pending Intent is broadcast by the Android system. The receiver class simply displays a toast repeatedly, every 10 sec. I have created the intent in startAlarm method, and cancel in cancelAlarm method.
My problem is: when I close the application after creating the alarm, the toast is getting displayed continuously, and when I reopen the app, I lose control on the object that created the background task, so I cannot cancel it. Help?
Here are the methods that control the alarm :
public void startAlarm(Context context)
{
    ser=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
    Intent serviceIntent = new Intent(context, AlarmReceiver.class);
    pi=PendingIntent.getBroadcast(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal=Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);
    ser.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pi);
}
public void cancelAlarm(Context context)
{
    if (ser != null)
    {
        ser.cancel(pi);
        ser=null;
        Toast.makeText(context, "Alarm Canceled", Toast.LENGTH_SHORT).show();
    }
}

And here is the receiver class for the alarm:
public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context arg0, Intent arg1)
    {
    Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
    }
}

A: for control of background service you can use
Process.killProcess(int pid)
ActivityManager.killBackgroundProcesses(String packageName)

or forceclose
       Intent intent = new Intent(yourCurrentActivity.this,yourNextActivity.class);
       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
       startActivity(intent);
       android.os.Process.killProcess(android.os.Process.myPid());

or for alarm manager u can blew code to cancel alarm.
Depending on your app, you may want to include the ability to cancel the alarm. To cancel an alarm, call cancel() on the Alarm Manager, passing in the PendingIntent you no longer want to fire. For example:
   //If the alarm has been set, cancel it.
   if (alarmMgr!= null) {
     alarmMgr.cancel(alarmIntent);
   }


text:
Q: Permutation problem, combining objects from multiple sets I've been working on a hobby coding project in my free time and I've run into quite an interesting problem, which I'm not completely sure how to solve. The problem is roughly stated as follows:

There are two sets, set A and set B. Set A contains the numbers from
  1-10 inclusive, and set B contains the numbers from 11-20 inclusive.
  What are all the ways to uniquely arrange 4 objects from set A and 2 objects from set B, in a linear fashion?

So I'm thinking that this is a permutation problem. P(10,4) is the unique number of ways to pick and arrange four numbers from set A, and P(10,2) is the unique number of ways to pick and arrange two numbers from set B. Now, you need to uniquely combine the four numbers from A, and two numbers to B. So you would need to find the number of unique ways that you can arrange four values from A and two values from B. But how would you combine these values to find the total number of solutions?
I think I'm on the right track to finding the number of total combinations. However, what's more important is that I develop an algorithm to actually be able to list all the different permutations. I understand that this may be unrelated to the Math StackExchange, but I am hoping that someone can help with either of these problems.
Thank you very much!

A: The number of different arrangements of 4 objects from $A$ and 2 from $B$ is
\begin{equation}
\binom{10}{4} \times \binom{10}{2} \times (2+4)!
\end{equation}
which is different from $P(10,4)\times P(10,2)$.
You can divide the algorithm into 2 parts:

*

*find an algorithm that generates all subsets of size up to $m$ from a set of size $n$. Here in your example, $n=10$ and $m=4$ or $2$.

*find all permutations of objects in a set of size $n$. Here in your example, $n = 2+4 = 6$.


text:
Q: Random Cursor Images with Javascript I have a div in the middle of a simple webpage. When I hover this div, I want my cursor to change randomly to a customized image. I know how to set my own cursor image with css. But how to use javascript to make this cursor image different each time we refresh the page?
This website shows exactly what I want to achieve. When we hover an image, the cursor becomes a little icon that is different each time we refresh the page.
https://glossier.com/#!/
Thanks in advance.

A: You need an array of your cursors, a function to randomly select one, you need to select the element and finally you need to change the style of the element using the cursor property. Something like this:

// The array for your cursors
var arrayOfCursors = ['pointer', 'crosshair', 'help', 'wait'];

// Returns a random element from the provided array
function random(arr){
  var num = Math.floor(Math.random() * arr.length);
  return arr[num];
}

// Selects the element
var el = document.getElementById('idName');

// Changes the cursor
el.style.cursor = random(arrayOfCursors);
#idName {
  width:300px;
  height:300px;
  background:#eee;
}

Reload to see the effect again

EDIT:
It was difficult to read the comment I posted in response so here's how you should be able to bring in your own custom cursors:
1) You could either save them in arrayOfCursors like this:
["url(images/my-cursor.png), auto", "url(images/other-cursor.png), auto"]

2) OR If they're all in the same folder, you could do something like:
el.style.cursor = "url(images/" + random(arrayOfCursors) + "), auto";

and just save the name of the files (with extensions) in arrayOfCursors.


text:
Q: Ninja forms datepicker wordpress beforeShowDay I'm making a Ninja Forms datepicker where some days have to be blocked. I found a php function in the NF documentation to add arguments to the datepicker.
Now I want to put in an array with dates and disable the dates in the array.
So here is my function:
function nf_datepicker_modify_script( $args ){
//for a list of arguments which can be used here, see the options here http://api.jqueryui.com/datepicker/

    $args['minDate'] = 0
    return $args;
}

add_filter( 'ninja_forms_forms_display_datepicker_args'
,'nf_datepicker_modify_script' );

This works fine. The dates before today are blocked.
Now I want to use: $args['beforeShowDay'] but I can't get the right array format in.
This is what jQuery tells me: http://api.jqueryui.com/datepicker/#option-beforeShowDay
This is what I tried:
$args['beforeShowDay'] = array('25-06-2016' => false, '26-06-2016' => true);
But that doesn't work.
Can someone help me on my way by telling me in which format my array should be formatted? Then I'll be able to get it to work.

A: I found out the answer. Maybe it's usefull for others as well.
The beforeShowDate argument is a callback, so you need to call a function that checks the dates. I solved it by adding a JS function to the datepicker by doing:
$('.ninja-forms-datepicker').datepicker('option', 'beforeShowDay', myJsFunction);


text:
Q: How to add mathematically the results of two commands in Linux In a Debian Linux shell, I am trying to add the results of two separate commands so that I know the sum of both.
I already tried:
echo $(expr $(du -sh /srv/mysql) + $(du -sh /srv/www))

and variations of it.
It's returning: expr:

"syntax error: unexpected argument '/srv/mysql'

"
of course I also tried to paraphrase the folders, etc.

A: Like this:
could be used with any shell (bash, zsh, sh, dash...)
echo "$((
    (
        $(du -s /srv/mysql | awk '{print $1}') +
        $(du -s   /srv/www | awk '{print $1}')
    ) / 1024
))MiB"

Or simply:
du -shc /srv/www /srv/mysql | awk 'END{print $1}'

The -c act as the count operator

A: Assuming you are dealing with integers …
I note that expr is considered archaic and obsolete.
It has two main uses, arithmetic and regex matching, both of which are available in most shells.
(By the by, "Debian Linux shell" isn't just one thing; it could be Bash or Dash or indeed whichever shell is chosen when the user is added or changed subsequent.)
For arithmetic, POSIX requires the shell (any shell claiming compliance, including /bin/sh) to evaluate $(( expression )) according to rules similar to those for integer expressions in the C language, so that $((1+2*3)) should give 7.
The main problem with the original question was that other information besides the digits were included in the output. The first thing to try should be to ask the program generating those digits not to output anything else. Only if that fails, then filter the output. There are many many ways to do that, but the simplest is just
tr -dc 0-9

which will remove everything that's not a digit.
If you need decimal fractions …
(decimal fractions are usually fixed point, like 1.23, but floating point systems can understand fixed point numbers as well, so you can use either.)
Neither expr nor $((…)) can cope with decimal fractions. For that you need bc or to use a separate scripting language that has fixed point or floating point built in, such as awk or perl or python.


text:
Q: Swift, how to tell a controller that another controller is its delegate I'm learning Swift and I'm studying the delegation pattern.
I think I understand exactly what is delegation and how it works, but I have a question.
I have a situation where Controller A is the delegate for Controller B.
In controller B I define a delegate protocol.
In controller B I set a variable delegate (optional)
In controller B I send message when something happens to the delegate
Controller A must adopt method of my protocol to become a delegate
I cannot understand if every delegate controller (in this case A) listens for messages sent by controller B or If I have to tell to controller B that A is now his delegate.
I notice that someone use this code (in controller A)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
 if segue.identifier == "Example" {
 let navigationController = segue.destinationViewController as UINavigationController
 let controller = navigationController.topViewController as AddItemViewController
controller.delegate = self
 }
}

Is this the only way to tell a delegator who is his delegate?

A: I believe, you need to tell a deligator who is its delegate upon creation of that it. Now, the delegator can be created programatically or through storyboard. So, based on that you have two options, you can tell it who is its delegator programatically like you showed in the code or from IB.
The key here is upon creation. Let's me explain myself. Take the case of a UIView. Say, you want a Custom UIView object(CustomView). So, you drag and drop a UIView in your View Controller and in the identity inspector, you assign its class as of your CustomView's class. So, basically, as soon as the controller is created, your custom view will also be created. Now, you can either say it that the View Controller in which it is created is its delegate or You can go to the IB and connect the view's delegate to the View Controller.
Now, let's  assume that you wanted the custom view to be created in your ViewController programatically. In that case, you would probably call the -initWithFrame: method to create the view and upon creation you tell that delegator that who is its delegate like-
myCustomView.delegate = self;

same goes with a View Controller.
 controller.delegate = self;

So, basically to tell a delegator who is its delegate, you first need that delegator to be created. At least, that's what I think.

A: I think one of the best example of delegation is UITableView.
Whenever you want the control of various properties of a tableView e.g. rowHeight etc, you set your controller to be the delegate of your tableview. To set the delegate of your tableView you need to have tableView created obviously as pointed out by @natasha.
So in your case, you can set delegate of your delegator when you create it or when you find a need for the controller to be delegate of your delegator but you definitely need your delegator to be present to set its property.
You can set your controller as delegate at any time when you require control.

A: I'm sure you want your UIViewController to act like described, but here is a simpler example how to use the delegation pattern with custom classes:
protocol ControllerBDelegate: class {

    func somethingHappendInControllerB(value: String)
    /* not optional here and passes a value from B to A*/
    /* forces you to implement the function */
}

class ControllerB {

    var delegate: ControllerBDelegate?

    private func someFunctionThatDoSomethingWhenThisControllerIsAlive() {

        /* did some magic here and now I want to tell it to my delegate */
        self.delegate?.somethingHappendInControllerB(value: "hey there, I'm a magician")
    }

    func doSomething() {

        /* do something here */
        self.someFunctionThatDoSomethingWhenThisControllerIsAlive()
        /* call the function so the magic can really happen in this example */
    }
}

class ControllerA: ControllerBDelegate {

    let controllerB = ControllerB()

    init() {

        self.controllerB.delegate = self /* lets say we add here our delegate*/
        self.controllerB.doSomething() /* tell your controller B to do something */
    }

    func somethingHappendInControllerB(value: String) {

        print(value) /* should print "hey there, I'm a magician" */
    }
}

I wrote the code from my mind and not testet it yet, but you should get the idea how to use such a pattern.


text:
Q: CORS ERROR: Multiple CORS header 'Access-Control-Allow-Origin' not allowed I am learning to use the "Article Search API" provided by the New York Times to allow my web application to display news articles based on the search results. I followed the tutorial at https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs and used their javascript code as closely as I could. The issue is that when I clicked on the 'submit search' button, my web-developer's console on Firefox showed me the message:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json?api-key=(MY KEY: CENSORED)&page=0&q=Trump&fq=document_type:(%22article%22)&begin_date=2019-01-01&end_date=2019-01-05. (Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed)."
This is where I am getting stuck. I really do not know what is happening here.
The 'Article Search API' is currently using the base URL 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json', which I did carefully examine. I do not think the base-url has any problem, as can be conjectured based on the error message I got. I also tried to run this on Chrome and was using the Python testing server, but the problem remains.
I am willing to show the entire html file including the javascript.
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>NY Times API example</title>
    <link href="nytimes.css" rel="stylesheet">

NY Times video search

        <form>

            Enter a SINGLE search term (required):
            <input type="text" id="search" class="search" required>

            Enter a start date (format YYYYMMDD):
            <input type="date" id="start-date" class="start-date" pattern="[0-9]{8}">

            Enter an end date (format YYYYMMDD):
            <input type="date" id="end-date" class="end-date" pattern="[0-9]{8}">

            <button class="submit">Submit search</button>

        </form>

          <button class="prev">Previous 10</button>
          <button class="next">Next 10</button>

But I think the most important lines are as follows:
var baseURL = 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json';
var key = 'CENSORED';
...
...
url = baseURL + '?api-key=' + key + '&page=' + pageNumber + '&q=' + searchTerm.value + '&fq=document_type:("article")';
...
...
fetch(url).then(function(result) {
      return result.json();
    }).then(function(json) {
      displayResults(json);
    });
...
...
if(current.multimedia.length > 0) {
          img.src = 'http://www.nytimes.com/' + current.multimedia[0].url;
          img.alt = current.headline.main;
        }

The news articles are supposed to show up on the right hand side in blocks arranged in a vertical fashion. With this error, I saw nothing. I hope someone can help me.


text:
Q: dates in postgres I want to see how long the client spend time connecting to our website daily.
My table source in created as below and contains the data as shown below.
CREATE TABLE source_ (
"nbr" numeric (10),
"begdate" timestamp,
"enddate" timestamp,
"str" varchar(35))
;
INSERT INTO source_
("nbr", "begdate", "enddate", "str")
VALUES
(111, '2019-11-25 07:00:00', '2019-11-25 08:00:00', 'TMP123'),
  (222, '2019-03-01 12:04:02', '2019-03-01 12:05:02', 'SOC'),
  (111, '2019-11-25 19:00:00', '2019-11-25 19:30:00', 'TMP12'),
  (444, '2020-02-11 22:00:00', '2020-02-12 02:00:00', 'MARATEN'),
  (444, '2020-02-11 23:00:00', '2020-02-12 01:00:00', 'MARA12'),
  (444, '2020-02-12 13:00:00', '2020-02-12 14:00:00', 'MARA12'),
  (444, '2020-02-12 07:00:00', '2020-02-12 08:00:00', 'MARA1222')

;

create table target_ (nbr numeric (10), date_ int(10), state varchar(30), terms interval);

I did an attempt below, but as you can see i associated the date_ (day of the event) to the beddate which is not always true see (4th row)  when the event is between two days.
INSERT INTO target_
(nbr, date_, state,  terms)
 select
   nbr,
   DATE_TRUNC('day', begdate) as date_,
   state,
   sum(term) as terms
   from (
  select
      nbr, begdate,
      (case
            when trim(str) ~ '^TMP' then 'TMP'
            when trim(str) ~ '^MARA' then 'MARATEN'
            else 'SOC'
       end) as state,
 (enddate - begdate)as term from source_ ) X

   group by nbr, date_, state;

expected output
111   2019-11-25 00:00:00+00  TMP 90
222   2019-03-01 00:00:00+00  SOC 60
444   2020-02-11 00:00:00+00  MARATEN 180
444   2020-02-12 00:00:00+00  MARATEN 300

A: If I understand correctly, you can use generate_series() to expand the periods and then aggregate:
select gs.dte,
       (case when trim(str) ~ '^TMP' then 'TMP'
             when trim(str) ~ '^MARA' then 'MARATEN'
             else 'SOC'
        end) as state,
       sum( least(s.enddate, gs.dte + interval '1 day') - greatest(s.begdate, gs.dte))
from source s cross join lateral
     generate_series(begdate::date, enddate::date, interval '1 day') gs(dte)
group by state, gs.dte
order by gs.dte, state;

Here is a db<>fiddle.


text:
Q: Identify a group given by a list of generators and relations I am looking at a matrix group ($3 \times 3$ matrices) with the following set of generators and relations:
$$\Gamma = \langle A,B,C \space | \space  A^2 = B^2 = C^2=I, \space AC=CA\rangle$$
What group is this?
$\textit{Work so far}:$
Since $AC=CA$ and $A$ and $C$ are both self-inverse, then $\langle A,C\rangle \cong \mathbb{Z}_2 \times \mathbb{Z}_2 \cong K_4$ (Klein-4 group). $\langle A,B\rangle$ and $\langle B,C\rangle$ are infinite, so are (I think) isomorphic to $\mathbb{Z}_2 \star \mathbb{Z}_2$ (free group or free product). Those are some subgroups, but how can we identify/describe the full group?


text:
Q: Check if tab was added to TabControl.TabPages I am trying to make a wrapper for a TabControl, does anyone know how to listen for when a tab has been added to TabControl.TabPages?
Regards,
Jordan

A: You can hook to the TabPages' parent, which is the TabControl, and hook onto its ControlAdded event, and then check to see if that control's type is a TabPage. So something like this:
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
    if (e.Control.GetType() == typeof(TabPage)) {
        MessageBox.Show("Yippee!"); // Insert code here
    }
}

Just remember the event goes on the TabControl, not the TabPage

A: There is a ControlAdded event that you can try and hook into


text:
Q: How to start app from first when home button is clicked In my application when i click home button and when again when i open the app it should come from first.I am having splash screen as my first activity.when i open the app,the app should start from  splash screen.
         @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

      if(keyCode == KeyEvent.KEYCODE_HOME)
       {
        Log.i("Home Button","Clicked");

        onPause();
       }

   return false;

      }
    protected void onPause() {
         super.onPause();
        Intent i=new Intent(H2.this,HomeexampleActivity.class);
        startActivity(i);
        // Start your first Activity as you would normally do

    }

I tried in this way by overriding on pause method but it is not working.please help me how to solve this issue

A: You can try this:
 Boolean hasGone = false;
  @Override
 void onResume() {
  super.onResume();
  if(hasGone){
      Intent intent = new Intent(H2.this, HomeexampleActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);
  }
 }

 @Override
 void onPause() {
     super.onPause();
     hasGone = true;
  }

A: Try writing this line in your each activity tag in Manifest file
android:launchMode="singleTask"

A: use i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); before startActivity(i);

A: You should have that code in onResume() not in onPause(). Because, when you click on your Home button, onPause() is called. But when you resume your application, onResume() is called. Hence, if you want to redirect your application to start from the beginning again, start your first Activity in onResume() method in all your Activity classes.
Keep in mind, that onResume() is also called once immediately after onCreate(), so keep a flag value to check whether your onResume() is called after onCreate() or is it called when your application is resuming.


text:
Q: some arrows do not appear The following code produces two graphs and I wanted arrows everywhere, but only some edges are arrows, the other are normal edges.
I don't understand how it is even possible.
The arrow edges in the end are p1->p2, q2->q3 and q2'->q4
\begin{tikzpicture}
\tikzstyle{vertex}=[draw,circle]
\node at (-1,-.5) {$H:$};
\node[vertex] (p1) at (0,0) {};
\node[vertex] (p2) at (0,-1) {};
\node[vertex] (p3) at (-1,-2) {};
\node[vertex] (p4) at (1,-2) {};
\draw[->] (p1) -- (p2);;
\draw[->] (p2) -- (p3);
\draw[->] (p2) -- (p4);
\node at (3.5,-.5) {$G:$};
\node[vertex] (q1) at (5,0) {};
\node[vertex] (q2) at (4,-1) {};
\node[vertex] (q2') at (6,-1) {};
\node[vertex] (q3) at (4,-2) {};
\node[vertex] (q4) at (6,-2) {};
\draw[->] (q1) -- (q2);
\draw[->] (q1) -- (q2');
\draw[->] (q2) -- (q3);
\draw[->] (q2') -- (q4);
\end{tikzpicture}

A: TikZ has a graph drawing library which will make the drawing of these graphs significantly easier.
In the following example, the baseline key sets the vertical alignment of the graphs with the H and G.  With each node, the part before the slash / identifies the node uniquely so that it can be used again in the layout specification.  For example, you cold add another edge connecting nodes 3 and 4 in H by adding 3 -- 4, in the graph specification.
The part in the quotes determines the label (or text) in the node.
\documentclass[convert]{standalone}

\usepackage{tikz}
\usetikzlibrary{
  graphs,
  graphdrawing,
}
\usegdlibrary{trees}

\begin{document}
\(H\):
\tikz [baseline=(2), >=stealth] \graph [tree layout, nodes={draw,circle}] {
  1/"" -> 2/"" -> {3/"", 4/""},
};
\(G\):
\tikz [baseline=(2), >=stealth] \graph [tree layout, nodes={draw,circle}] {
  1/"" -> {2/"" -> 3/"", 4/"" -> 5/""},
};
\end{document}


text:
Q: How to install Tensorflow in Raspberry pi 4b 8gb , i am aslo try but getting this error . plese give some good suggestion, how to install? from tensorflow import keras
Traceback (most recent call last):
File "", line 1, in
from tensorflow import keras
ImportError: cannot import name 'keras' from 'tensorflow' (unknown location)enter image description here

A: Install Tensorflow lite on Raspberry pi.
TensorFlow Lite with Python is great for embedded devices based on Linux, such as Raspberry Pi.
python3 -m pip install tflite-runtime

Follow the instructions mentioned https://www.tensorflow.org/lite/guide/python


text:
Q: Pytorch / Numpy dimensions math: Why [n] + [n, 1] = [n, n] I'm trying to understand the logic for inferring the sematics of addition in numpy/torch. Here is an example that caused a bug in my program:
import numpy as np

x = np.arange(2)     # shape (2,)
y = x.reshape(-1, 1) # shape (2, 1)
z = y + x            # expected (2,) or (2, 1)
print(z.shape)       # (2, 2)

So basically reshape happened in unrelated operation, however x and y still had same number of elements, and I've expected to get resulting shape either [2,] or [2, 1] as the addition happens on the axis where all elements live.
My questions:

*

*why do I get [2,2] shape?

*What's bigger picture behind it that can help expect this outcome in similar, but different scenarios?

A: This is caused by broadcasting, where the following example is given:
x  = np.arange(4)   # shape (4,)
xx = x.reshape(4,1) # shape (4,1)
y  = np.ones(5)     # shape (5,)

x + y  # ValueError: operands could not be broadcast together with shapes (4,) (5,)
xx + y  # shape (4, 5)

"When either of the dimensions compared is 1, the other is used. In other words, dimensions with size 1 are stretched or "copied" to match the other."


text:
Q: Import or not to import classmethod? I hope this isn't a stupid question but I found some code where they imported classmethod and some code where they don't so there is difference?
I'm using python 3.6 but the code originally I think was for python 2.7 (it used from __builtin__ import)
import unittest
from selenium import webdriver
from builtins import classmethod #original code was from __builtin__ import classmethod

class HomePageTest(unittest.TestCase):
    @classmethod
    def setUp(cls):
        # create a new Firefox session
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(30)
        cls.driver.maximize_window()

        # navigate to the application home page
        cls.driver.get("http://demo-store.seleniumacademy.com/")

    def test_search_field(self):
        pass

    #My tests without @classmethod

    @classmethod
    def tearDown(cls):
        # close the browser window
        cls.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)

A: Normally you only import builtins or __builtin__ if you also have a variable in your code with the same name as a builtin and also want to access the builtin name. The documentation of the module explains it rather well:

builtins — Built-in objects
This module provides direct access to all 'built-in' identifiers of Python; for example, builtins.open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation.
This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly:
import builtins

def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '''Wrapper around a file that converts output to upper-case.'''

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

However in your case there seems to be no classmethod definition in the file so you don't actually need the from builtins import classmethod.

A: In Python 3, there's no need to import the builtins module, or anything inside it. When the lookup for a name in the current scope fails, builtins is looked up as a fallback.
If you need to maintain code integrity, consider explicitly checking Python version before this.
import sys
if sys.version_info[0] == 2:
    from __builtin__ import classmethod


text:
Q: Determine if a table exists when performing an EF Migration I recently switched from .edmx to Code First and am trying to implement migrations.  Is it possible to determine if a table exists before calling CreateTable in a DbMigration's Up() function?  I have an initial migration set to create the tables, but existing databases should not apply this initial migration.
I am using EF 6.1 and .Net 4.6

A: If your database equals to initial migration execute this command:
Update-Database -Script -IgnoreChanges -SourceMigration: $InitialDatabase

After that for every new migration execute:
Update-Database -Script -SourceMigration: $InitialDatabase

This command will check for every migration if it was already applied to database and if it is it wont apply it again. So the generated migration script will work no matter in which state is database.


text:
Q: How do I add "active" class to dashboard menu button when visiting in CodeIgniter I have successfully implemented this code to set a specific class to active menus when visitors are on a page. But I can't figure out how I can manage to do the same with the home page, or in other words the very first index page.
This works on the other pages
<?=($this->uri->segment(1)==='profiles')?'active':'not-active'?>

Then I tried this, but that didn't work...
<?=($this->uri->segment(1)==='index')?'active':'not-active'?>

Ideas?

A: Check for the controller (class) and/or method instead. If you're visiting http://example.com/, then your default controller being used, but nothing is set to uri segment 1.
Codeigniter 2:
<?=($this->router->fetch_class()==='index')?'active':'not-active'?>

Codeigniter 3:
<?=($this->router->class==='index')?'active':'not-active'?>


text:
Q: App Rejected Due to Auto Renewable Subscription I hope all is well for everyone, I have an app offering auto renewing subscription. Problem is I can't seem to figure out what they want me to do with it, I offer optional registration in order for users to access the paid subscription across all devices, but in their policy they require all auto-renewable must be accessible across all devices. But the other problem is they also don't want me to force users to register. My question is how can we be able to keep track of the subscription across all devices without tying it into an account? Did I miss something? any help is greatly appreciated.
App rejected due to reason:
To resolve this issue, please make it clear to the user that registering will enable them to access the content from any of their iOS devices and provide them a way to register at any time, if they wish to later extend access to additional iOS devices.
Please note that although guideline 3.1.2 of the App Store Review Guidelines requires an app to make subscription content available to all the iOS devices owned by a single user, it is not appropriate to force user registration to meet this requirement; such user registration must be made optional.

A: Subscriptions are tied to a user's Apple ID. So, even without you registering them into your own account system, their subscriptions already are tied to an account.
If you use the StoreKit system for restoring purchases (https://developer.apple.com/documentation/storekit/in-app_purchase/restoring_purchased_products), the device will get any subscription/purchase data for your app that was done on any device with their Apple ID.
This means that on your subscription page, you can (and should) offer a restore button will allow users to get their subscription data on that device (whether it is from a different device or perhaps even the same device that was reset).
You can also choose to link it to your own account system, but that's all optional, since everything's already linked to their Apple ID.


text:
Q: Dynamic image change on keypress VB6 So I'm trying to make this form in VB6 with just an image, and whenever you press say the "Q" key that image changes, and if you press "E" it changes to back to the previous one. Simple stuff.
Here's what I have:
Private Sub Form_KeyPress(KeyAscii As Integer)
If KeyAscii = 81 Then Image.Picture = LoadPicture("E:\Imagenes\Avatars\4.jpg")
If KeyAscii = 69 Then Image.Picture = LoadPicture("E:\Imagenes\Avatars\3.gif")
End Sub

Well, that doesn't work. What could I do to make it work? Thanks!

A: In reading your comment, you say that you are using the Default Image Control, there is not a Default Image Control you need to add an instance of it to your Form or just use the Forms Picture Property.
These examples work for me:
Private Sub Form_KeyPress(KeyAscii As Integer)
    If (Chr(KeyAscii) = "Q" Or Chr(KeyAscii) = "q") Then Form1.Picture = LoadPicture("E:\Imagenes\Avatars\4.jpg")
    If (Chr(KeyAscii) = "E" Or Chr(KeyAscii) = "e") Then Form1.Picture = LoadPicture("E:\Imagenes\Avatars\3.gif")
End Sub

and
Private Sub Form_KeyPress(KeyAscii As Integer)
    If (Chr(KeyAscii) = "Q" Or Chr(KeyAscii) = "q") Then Image1.Picture = LoadPicture("E:\Imagenes\Avatars\4.jpg")
    If (Chr(KeyAscii) = "E" Or Chr(KeyAscii) = "e") Then Image1.Picture = LoadPicture("E:\Imagenes\Avatars\3.gif")
End Sub


text:
Q: NEHotspotConfigurationManager not creating/joining hotspot I am trying to create/add a Hotspot configuration in iOS 11 installed device.
My code is as follows
let hotspotConfig = NEHotspotConfiguration(ssid: "testNetwork")
hotspotConfig.joinOnce = true
NEHotspotConfigurationManager.shared.apply(hotspotConfig) { (configurationError) in
    if configurationError != nil {
      print("error")
      print(configurationError!.localizedDescription)
    } else {
      print("success")
    }
}

When i try to run the code. Device prompts for permissions as the following:-
"AppName" wants to join Wi-Fi Network "testNetwork"

But on tapping "Join", I am getting the following response
Unable to join the network "testNetwork"

However, on debug console "success" is getting printed.
Please tell me what am i doing wrong.

A: The network is being added to the device's known network list, making it available to be auto joined.  Unless you have a nearby network named "testNetwork" it will always fail to join.

A: Enable Hotspot on App Id configure services

After Enable Hotspot Configuration


text:
Q: React routes gets conflicted with express routes I have the build files (from npm run build) of the react application in the /public folder on my backend folder.
This is what is in my index.js on my backend
const express = require('express')
const mysql = require('mysql');

const path = require('path')

const app = express()
app.use(express.static(path.join(__dirname + "/public")))
app.use(express.json())

const PORT = 5000
app.listen(PORT)

app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
        if (err) {
            res.status(500).send(err)
        }
    })
})

const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "",
    database: "project_db",
});

const users =
[
    { id: 1,name: "Andrew" },
    { id: 2, name: "Steve" },
    { id: 3, name: "John" },
    { id: 4, name: "Michael" },
    { id: 5, name: "Christian"  }
];

app.get("/api/users", (req, res) => {
    res.json(users);
})

app.post("/api/register", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;

    db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

    res.send({
        "message": "account registered",
        "status": 1,
    });
});

App.js on my react app
import { Route, Routes } from 'react-router-dom'
import './components/App.css'
import Home from './pages/Home'
import Login from './pages/Login'
import Register from './pages/Register'

function App() {
    return (
        <>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="*" element={
Not found (404)
 } />
            </Routes>
        </>
    );
}

export default App;

My question: When I go to http://localhost:5000/api/users it gets the 404 not found from my react app
How can I fix this problem?

A: List your backend API endpoints before the "*" "endpoint" that returns the React app.
const express = require('express');

...

// Backend APIs
app.get("/api/users", (req, res) => {
  res.json(users);
})

app.post("/api/register", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const email = req.body.email;

  db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

  res.send({
    "message": "account registered",
    "status": 1,
  });
});

// Frontend React app routes
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
});


text:
Q: What is the difference between a widget and plugin? Is it better to develop a plugin or widget.Which one should I choose either plugin or widget.

A: It actually depends on you.  First you need to understand the requirement and difference between them.
A widget is generally a drag & drop component which you can use in Widget Areas, You can use that in many widget Areas and you can define some setting for that widget, Usually by program.
A plugin is a actually a php snippet which can be Activated/Deactivated according to the requirement, This snippet can perform many functions defined in the file, a plugin can be make some widget which can be used in the WP.
a plugin is easy to handle and easy to change. A plugin can be updates time to time as per the requirement.
I will prefer you to make a plugin instead of a widget


text:
Q: pandas.read_sql using mysql stored procedure I'm trying to run a simple MySQL 'select * ...' query to populate a pandas data frame.
This works:
def read_sql():
    engine = create_engine("mysql+mysqlconnector://user:password@hostname:3306/dbname")
    connection = engine.connect()
    dataFrame = pd.read_sql_query('select * from documents;', connection)
    connection.close()
    return dataFrame

But if I create a stored procedure and call it instead, like so:
dataFrame = pd.read_sql_query('CALL getAllDocuments();', connection)

I get a very long series of errors, the most interesting are as follows:
Error closing cursor
mysql.connector.errors.InterfaceError: Use multi=True when executing multiple statements
mysql.connector.errors.InternalError: Unread result found
mysql.connector.errors.InterfaceError: Use cmd_query_iter for statements with multiple queries.

I've also tried iterating over chunks like so:
for chunk in pd.read_sql_query('CALL getAllDocumentsProcedure();', connection, chunksize=5):
    print(chunk)

The errors seem to be originating in the read_sql_query calls. I can't simply close the cursor after those calls.
Is there some special rule about calling stored procedures with read_sql or read_sql_query?


text:
Q: How to get the complete result of command "top -c -b -n 1" through java, Runtime.getRuntime().exec(command) I want to get the result of command "top -c -b -n 1" through java, Runtime.getRuntime().exec(command),
but the COMMAND column of the process list was compressed like "/usr/lib/x+"!
How to get the complete result like command executed directly on the linux terminal ?

A: The top man page mentions a -w COLS option to specify the number of columns it tries to format the output too:
$ top -c -b -n 1 -w 1000 | head -n10
top - 05:01:40 up 19 days, 13:29,  1 user,  load average: 1.62, 1.49, 1.43
Tasks: 287 total,   2 running, 285 sleeping,   0 stopped,   0 zombie
%Cpu(s):  7.5 us,  3.1 sy,  0.0 ni, 89.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem : 32771952 total,   742552 free,  9000236 used, 23029164 buff/cache
KiB Swap:        0 total,        0 free,        0 used. 23029384 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 4227 qemu      20   0 10.628g 5.797g   4688 S 112.5 18.5  34262:17 /usr/libexec/qemu-kvm -name test-vm -S -machine pc-i440fx-rhel7.0.0,accel=kvm,usb=off -cpu Nehalem -m 6144 -realtime mlock=off -smp 3,sockets=3,cores=1,threads=1 -uuid A5A5DC7B-3F35-40F9-B799-954D5411A219 -nographic -no-user-config -nodefaults -chardev socket,id=charmonitor,path=/var/lib/libvirt/qemu/test-vm.monitor,server,nowait -mon chardev=charmonitor,id=monitor,mode=control -rtc base=utc,driftfix=slew -global kvm-p+
  84 root      25   5       0      0      0 R  68.8  0.0  13144:24 [ksmd]
2834 andrew    20   0  130180   1888   1284 R   6.2  0.0   0:00.02 top -c -b -n 1 -w 1000
...

Now it's cut off after about 500 characters, but hopefully that's enough for what you're doing.


text:
Q: getting error "Invalid value" when trying to use secret value in flux Kustomization patchesStrategicMerge I am getting the error
dry-run failed, reason: Invalid, error: Deployment.apps "server" is invalid: spec.template.spec.containers[0].env[0].valueFrom: Invalid value:
"": may not be specified when `value` is not empty

when trying to override a value in flux Kustomization using patchesStrategicMerge like:
  env:
  - name: DATABASE_URL
    valueFrom:
      secretKeyRef:
        name: server-db-url
        key: dburl

The secret server-db-url exists and contains the key dburl
I am not sure if this has something to do with https://github.com/kubernetes/kubernetes/issues/46861

A: As workaround (mentioned in github issue you linked) you can add "value: null" to configuration:
  env:
  - name: DATABASE_URL
    value: null
    valueFrom:
      secretKeyRef:
        name: server-db-url
        key: dburl


text:
Q: GDI+ image loading efficiency The existing application loads a lot of image thumbnails and rotating/positioning them in a canvas (a GDI+ Graphics object).
The way it does this is not very efficient but is OK until we have a feature request that to add a scaling transform to the images.
The current code looks like
//Images is a collection of ImgInfo, a user defined class
//contains the width, height, offsets, scale factors, and rotation
//in addition to a Bitmap thumbnail.
foreach (var imgInfo in Images)
{
    var imgRect = new Rectangle(0, 0, imgInfo.Width, imgInfo.Height);
    int dx = imgInfo.XOffset, dy = imgInfo.YOffset;

    //Transform the canvas to the drawing coordinate system
    graphics.TranslateTransform(dx, dy);
    graphics.ScaleTransform(1 / (float)imgInfo.ScaleX, 1 / (float)imgInfo.ScaleY);
    graphics.RotateTransform(-imgInfo.Rotation);
    //Center the image
    graphics.TranslateTransform(-imgInfo.Width / 2, -imgInfo.Height / 2);

    graphics.DrawImage(imgInfo.Thumbnail, imgRect);

    //Transform back to the display coordinate system
    graphics.TranslateTransform(imgInfo.Width / 2, imgInfo.Height / 2);
    graphics.RotateTransform(imgInfo.Rotation);
    graphics.ScaleTransform((float)imgInfo.ScaleX, (float)imgInfo.ScaleY);
    graphics.TranslateTransform(-dx, -dy);
}

The reason of this I suspect, is the following. Suppose I have 1000 thumbnails, drawing the 999th thumbnail will result in translating, rotating, and scaling all the 998 images drawn so far. This is not so bad as long as we do not use scale transform - (I guess the system have optimized for rotations).
So the question is, what is the way to optimize this?

A: It turn out that this issue is not the scale transform. The problem is that the code introduced an exception during GUI rendering. Since exception handling is expansive, we have the above performance issue. Until we checked the log we didn't realize this problem because the code have to continue after exception in GUI rendering and so there is no apparent signs for exception being occurred.


text:
Q: Building phonegap 1.7. app I would like to build an app with existing 1.7 sources.
Since they are created one year ago, I maybe need to migrate the project. Or build the files, as they are.
I don't need to modify anything.
Phonegap 3 does not provide support for 1.7 projects.
Also I can't find any xml, but the Cordova.plist.
And there is no Eclipse project file.
I could use cli of version 1.7.
So here are my questions:
Which commands do I need in cli to build a phonegap 1.7 project?
How to migrate my project to phonegap 3.2.?

A:
I could use cli of version 1.7.

There isn't a "CLI" per-se for 1.7 but there are shell scripts that you can use to create a project. You have to manually add the plugin code.

So here are my questions: Which commands do I need in cli to build a
  phonegap 1.7 project?

You'll need to run the /bin/create script for each platform that you want to run the application on. This will create a basic cordova app for you that can be launched onto devices.

How to migrate my project to phonegap 3.2.?

The best way is to download the latest Cordova from npm and follow the Command Line Interface Guide to build a basic hello world app. Then add the plugins that you need, then copy over your custom HTML code into the new app, build, and test. Yes there are Upgrade guides but when you are jumping from 1.7 to 3.2 it is probably going to be easiest to just build a new app and copy as much code over as you can, rather than following the upgrade guides.


text:
Q: How does a C++ std::container (vector) store its internals (element address, access by index)? I am trying to "hack" a game (Red Alert 3), I try to make a program which shows the unit list of my opponents. As for that I first need to find a (static) pointer to my own list which I can do on single player.
I have noticed this behaviour: (by looking at which addresses are changed by the add_unit code):

*

*if a units hasn't been build yet, create a new address for it (random?) and set the value to 1 (amount of units of that type)

*when the unit has been already build once in the game, increment the original address of the unit type by 1

This looks to me like  std::vector behaviour. Now I am having trouble to find the "base" address of the vector, and a bigger problem: How would I access by index? Where does a std::vector store it's addresses it has for elements?
Extra info:
The code is (from what I have read from the assembly) compiled with MS Visual C++ 2005 (MSVCR80 dll's are required to play)
This is what the addresses in the vector look like:

(The highlighted address is the one which appeared as the first element - first unit build)
This doesn't look like I could iterate by adding a constant value?
Whenever a new address is added, all the other addresses are perfectly valid and don't change.

A: A typical (though by no means mandatory) implementation of vector is to have three consecutive words:
struct TypicalVector
{
    T * start;
    T * end;
    T * capacity;
};

Element access is done via start[i] (which is why it's important to have the start pointer at the front, to avoid unnecessary offset computations), size is end - start, and capacity is capacity - start. Memory allocation obtains c * sizeof(T) bytes and sets start to the address of the allocated memory and capacity to start + c. Element construction increments end.


text:
Q: How to update many documents using UpdateManyAsync I have the following method to update a document in MongoDB:
public async Task UpdateAsync(T entity)
{
    await _collection.ReplaceOneAsync(filter => filter.Id == entity.Id, entity);
}

Which works fine - I was just wondering if anybody has an example of how the UpdateManyAsync function works:
public async Task UpdateManyAsync(IEnumerable<T> entities)
{
    await _collection.UpdateManyAsync(); // What are the parameters here
}

Any advice is appreciated!

A: UpdateManyAsync works the same way as update with multi: true in Mongo shell. So you can specify filtering condition and update operation and it will affect multiple documents. For instance to increment all a fields where a is greater than 10 you can use this method:
var builder = Builders<SampleClass>.Update;
await myCollection.UpdateManyAsync(x => x.a > 10, builder.Inc(x => x.a, 1));

I guess you'd like to replace multiple documents. That can be achieved using bulkWrite method. If you need generic method in C# then you can introduce some kind of marker interface to build filter part of replace operation:
public interface IMongoIdentity
{
    ObjectId Id { get; set; }
}

Then you can add generic constaint to your class and use BuikWrite in .NET like below:
class YourRepository<T> where T : IMongoIdentity
{
    IMongoCollection<T> collection;

    public async Task UpdateManyAsync(IEnumerable<T> entities)
    {
        var updates = new List<WriteModel<T>>();
        var filterBuilder = Builders<T>.Filter;

        foreach (var doc in entities)
        {
            var filter = filterBuilder.Where(x => x.Id == doc.Id);
            updates.Add(new ReplaceOneModel<T>(filter, doc));
        }

        await collection.BulkWriteAsync(updates);
    }
}

A: As @mickl answer, you can not use x=> x.Id because it is a Generic
Use as below:
public async Task<string> UpdateManyAsync(IEnumerable<T> entities)
{
     var updates = new List<WriteModel<T>>();
     var filterBuilder = Builders<T>.Filter;

     foreach (var doc in entities)
     {
          foreach (PropertyInfo prop in typeof(T).GetProperties())
          {
              if (prop.Name == "Id")
              {
                  var filter = filterBuilder.Eq(prop.Name, prop.GetValue(doc));
                  updates.Add(new ReplaceOneModel<T>(filter, doc));
                  break;
              }
          }
     }
     BulkWriteResult result = await _collection.BulkWriteAsync(updates);
     return result.ModifiedCount.ToString();
}

A: Or you go by Bson attribute:
public async Task UpdateManyAsync(IEnumerable<TEntity> objs, CancellationToken cancellationToken = default)
{
var updates = new List<WriteModel<TEntity>>();
var filterBuilder = Builders<TEntity>.Filter;

foreach (var obj in objs)
{
    foreach (var prop in typeof(TEntity).GetProperties())
    {
        object[] attrs = prop.GetCustomAttributes(true);
        foreach (object attr in attrs)
        {
            var bsonId = attr as BsonIdAttribute;
            if (bsonId != null)
            {
                var filter = filterBuilder.Eq(prop.Name, prop.GetValue(obj));
                updates.Add(new ReplaceOneModel<TEntity>(filter, obj));
                break;
            }
        }
    }
}

await _dbCollection.BulkWriteAsync(updates, null, cancellationToken);

}


text:
Q: CakePHP Cake Bake "database configuration was not found" I am working on a legacy CakePHP 1.3 app and while I have years of experience with PHP, I am still finding my feet with CakePHP. I am following Chapter 4 'How to use the bakery' in Jamie Munro's Rapid Application Development with CakePHP, however the steps he suggests do not seem to go the way I'd expect them too.
I feel a good way of explaining this is going through the steps involved:

*

*Following the books 'Hello World' example outlined in earlier chapters, I have setup a basic CakePHP app at this location on my machine: /home/public_html/helloworld.local. I can see the 'Hello World' example in a web browser on my local machine when I access: http://helloworld.local/users/add

*Chapter 4 suggests that I move to this directory: home/public_html/helloworld.local/cake/console

*I then run: ./cake bake

*I get prompted to enter the location of the app and I add:
/home/public_html/helloworld.local/app

*I then proceed to select defaults for the next few selections and there are no problems until I run into the line:
Your database configuration was not found. Take a moment to create one.
I do not understand this since there is a database file configured in ~/public_html/helloworld.local/app/config/database.php, and when I access the helloworld app outlined earlier (available on my local machine at http://helloworld.local/users/add), there is a database connection successfully established and records can be inserted.
I have also tried re-entering my database details when offered the chance to by cake bake, but end up with the error after succesfully adding the correct details:

Fatal error: Class 'DATABASE_CONFIG' not found in
  /home/public_html/helloworld.local/cake/console/libs/tasks/db_config.php
  on line 260

But either way, it should have found the existing database connection details, so not sure what is going on.

A: For using console command like cake bake you have to use your operating system terminal(for linux)/ command prompt(for windows). So you have to do the step mentioned in step 2 and 3 in you console. You can read documentation here to know how to use console commands.
Then, make sure that you have the file home/public_html/helloworld.local/app/config/database.php. I hope you removed .default from its name and rename it to database.php. To link up your database with your cakephp project you have to specify credentials in database.php.
    var $default = array('driver'      => 'mysql',
                     'persistent'  => false,
                     'host'        => 'localhost',
                     'login'       => 'root',
                     'password'    => 'password',
                     'database'    => 'database_name',
                     'prefix'      => ''
);

A: I don't have a running CakePHP 1.3 installation here at hand, but this is what is happening at that location:
// @link: https://github.com/cakephp/cakephp/blob/1.3/cake/console/libs/tasks/db_config.php#L260
config('database');
$db = new $this->databaseClassName; // i.o.w. $db = new DATABASE_CONFIG;

This line:
    config('database');
Does nothing more than including the database.php configuration file, simplified to;
include_once(CONFIGS . $arg . '.php'); // i.o.w. include_once(CONFIGS . 'database.php');

(https://github.com/cakephp/cakephp/blob/1.3/cake/basics.php#L77)
So IMO two problems may cause your error;

*

*app/config/database.php was not found

You can try to check if this outputs the right path:
die(CONFIGS . 'database.php');

*

*There is an error in your app/config/database.php, causing the DATABASE_CONFIG class to be malformed and unable to be initialized

A word of notice
Aparently your running 'bake' for everything including setting up a new database configuration. This may overwrite your
existing database configuration. It is possible to bake only parts of your application (e.g. bake controllers only or models).
The manual on baking in CakePHP 1.3 is located here:
http://book.cakephp.org/1.3/en/The-Manual/Core-Console-Applications/Code-Generation-with-Bake.html
And this
If this is your first CakePHP project, you should realy consider the option to upgrade to CakePHP 2.x CakePHP 1.3 is really outdated and, although it's still able to run fine, I wouldn't invest too much time in 1.3 as a lot of things have changed in CakePHP 2.x. It's probably better to start with CakePHP 2.x then to start with 1.3 and learn things that no longer work in CakePHP 2.

A: Copy your app/Config folder to app/Console, so the final path would be app/Console/Config. That worked for me.


text:
Q: get status column from "net use" with winapi via C# When issuing the "net use" command in Windows there is a "Status" column. Is it possible to get that via any of the methods found in the mpr.dll?
I'm currently using WNetOpenEnum and then using WNetEnumResource to iterate though the drives that are mapped. I can get all of the columns except status.
I thought that one of the fields in the NetResource struct would specify the status, but when I run "net use" and have two drives, one of which has Status of "OK" and one of which is "Unavailable" the fields are all the same.

A: You might be able to do this with the win32_share class since it supports IPC and status.
try checking out
http://www.mvps.org/emorcillo/en/code/grl/share.shtml
Yes - its vb.net, but may give you what you need here

A: I know this is a really old post, but I stumbled upon it during some searches, and thought I'd chime in with an idea anyway. Sometimes when all else fails, I go a 'hacky' route to get what I need done.
In this case, I might try just piping the output of net use to a .txt file, (probably in the System's Temp folder), reading it in, and parsing it for what I need, then deleting it from the system, just to keep things clean.
i.e.
net use > C:\Temp\netuse.txt


text:
Q: How do I update an object in Reactjs I have a form in reactjs, that I am going to use to create user.  Here is the important part my code:
   var AddUser = React.createClass({
    mixins: [OverlayMixin],
    getInitialState: function() {
        this.state.user = {}
        return {
            isModalOpen: false
        };
    },
    addScout: function() {
       UserCreator.addUser({
         user: this.state.user
       })
    },
    ....
    updateUser: function(e) {
        this.state.user[e.currentTarget.id] = e.currentTarget.value;
    },
    ...
    render: function() {
        return ( < button onClick = { this.toggleModal} type = "button" className = "btn btn-success" >Add User < /button>
        );
    },
    renderOverlay: function() {
        if (!this.state.isModalOpen) {
            return
        }
        return (
            < Modal title = "Add a User" onRequestHide = { this.handleToggle} >

                    <form>

                            First Name
                            <input id="first_name" className="form-control" onBlur={this.updateUser}></input>

                            Last Name
                            <input id="last_name" className="form-control" onBlur={this.updateUser}></input>

                    </form>

                    <button onClick={this.addUser} className="btn btn-primary">Add</button >
                    <button onClick={this.toggleModal} className="btn btn-warning">Cancel</button >

            </Modal >
        );
    }
});

When the user opens the modal and inputs a first or last name, then the blur event triggers the updateUser.  When the addUser button is clicked then the UserCreator.addUser is called.
The problem is that I am not setting the state with setState.  What is the reactjs way to handle these inputs.  How do I create an object to push the inputs into?

A:
The problem is that I am not setting the state with setState. What is the reactjs way to handle these inputs. How do I create an object to push the inputs into?

The react way to handle it is with setState.
You can just do this.setState({user:user}) and it'll update your view.
Or you can do something like this if you have a merge/defaults function.  It's not mutating the user object, it creates an updated version of it.
updateUser: function(e) {
    var update = {};
    update[e.currentTarget.id] = e.currentTarget.value;
    this.setState({user: merge({}, user, update)};
},

You shouldn't be using ids because you're making an assumption about every other component's implementation (ids must be unique!).  Instead of this, you could use a function which returns a change handler.
makeChangeHandler: function(property) {
    return function(event){
        // apply it to state; optionally replace this with the immutable example from above
        this.state.user[property] = event.target.value;
        this.setState({user: this.state.user});
    }.bind(this)
}

<input className="form-control" onBlur={this.makeChangeHandler('first_name')}></input>

You getInitialState function should look like this:
getInitialState: function() {
    return {
        isModalOpen: false,
        user: {}
    };
},

Side note: read Working with Forms.


text:
Q: Breaking Out of Multiple Loops When a Condition is Met Without Using Goto (C++) In the method below, I have a two-dimensional array of characters called myarr and a string called code. I go through each character in code using the counter i, and look for a character in myarr that matches code[i]. When I find the character in myarr that matches code[i], I want to exit both of the for loops and the if statement and go back to the beginning of the while loop. The only way I can think of doing this is by using a goto statement. However, using goto is generally discouraged, so I was wondering if there was any other way to achieve this.
string decrypt(string code, char myarr[][5])
{
int r = 0;
int c = 0;
int i = 0;
string newstr = "";

while(i<code.length()-1)
{
    //This is where I want to go back to
    if (code[i] != ' ')
    {
        for (r = 0; r < 4; r++)
        {
            for (c = 0; c < 4; c++)
            {
                if (code[i] = myarr[r][c])
                {
                    newstr += myarr[c][r];
                    i++;
                    //This is where I want to exit
                }
            }
        }
    }
    else
    {
        newstr += " ";
        i++;
    }

}
return newstr;
}

A: You use a flag-ish variabele.
set a boolean to true at the beginning of the while loop.
then when the condition is met, you set it to false.
in every inner loop you also check for that flag being true.
Also. in my opinion this is one of the cases where goto is justified.

A: What I'd do:
char decrypthelper(char codech, // returns the substitution character for codech
                   const char myarr[][5]) //const because we aren't changing myarr.
                                          // This will make sure we don't, and maybe
                                          // the compiler can do something sneaky.
{
    if (codech != ' ')
    {
        for (int r = 0; r < 5; r++) // fixed off by one error
                                    // declare index variable here. No one else needs it
        {
            for (int c = 0; c < 5; c++) // fixed off by one error
            {
                if (codech == myarr[r][c]) // was assignment not compare
                {
                    return myarr[c][r]; // found substitution. Exit
                }
            }
        }
    }
    else
    {
        return ' '; // space... the final frontier
    }
    return '?'; // unknown character
}

string decrypt(string code, char myarr[][5])
{
    string newstr = "";

    for (auto codech: code) // for each character in code
    {
        newstr += decrypthelper(codech, myarr); // add substitution character
    }
    return newstr;
}

I tried to keep the code recognizable. There are a whole bunch of other tricks you can use to make your job a lot easier, so once you have your program up and running and bug free, take Quentin's suggestion about asking for a code review.
Note that many returns in a function is viewed in some circles as just as bad as goto.

A: As others have mentioned you can use a flag-ish variable. You can also use an exception as a way to break out of multiple loops.
You can also put the two inner loops into a separate function and use return.
But looking at the code why not change the algorithm? You should create a map from char to decrypted char so you can simply use:
newstr += map[code[i]];


text:
Q: How to create dynamic pages to a component from endpoints in Svelte? For example, I have a component blog-post.svelte. This component contains the basic layout for my blog post. Then based on data of fetch endpoints, I want to create different pages from component blog-post.svelte.

*

*example.com/how-to-start-website

*example.com/how-to-eat-apple

*example.com/how-to-eat-cake

A: You can instantiate components dynamically with <svelte:component>, so you could potentially pick different components based on your current endpoint :
<script>
  // Import all your components here

  let myComponent = false;
  let endpoint = ; // add your code to determine your endpoint here

  switch (endpoint) {
    case 'endpoint 1':
      myComponent = EndpointComponent1;
      break;
    case 'endpoint 2':
      myComponent = EndpointComponent2;
      break;
    case 'endpoint 3':
      myComponent = EndpointComponent3;
      break;
    default:
      myComponent = DefaultEndpointComponent;
      break;
  }
</script>

<svelte:component this={myComponent} />

A: If you're not interested in diving into Sapper and SSR, it's not too difficult to implement your own simple hash routing on the client side, utilising the <svelte:component> special element, to achieve what you're after.
Here's a small project I threw together to show how you might go about it: https://github.com/joshmanderson/svelte-blog-hash-router-example
And here's a demo: https://svelte-blog-hash-router-example-437uuzkc5.now.sh
One caveat with that solution is that all the blog post hashes are of the form: post-{id} to be able to easily match the blog post route. There are ways around that of course, for example: if the current hash doesn't match any predefined routes you could assume that it's a blog post, then if you can't find a matching blog post you can fall back to your not found or index route. However you would want to implement that is totally up to you though.


text:
Q: How do I concatenate newlines in Java? I've got a very strange question. Say I am implementing an object that has a toString() method that returns a single string formatted in a square, as such:
010203
040506
070809

Now, clearly the entire string, when listed character-wise (and excluding the terminating \0), is as such:
010203\n040506\n070809\n

How would I go about concatenating entire square blocks like these? For instance, if I wanted to have:
010203     101112    010203101112
040506  +  131415 =  040506131415
070809     161718    070809161718

How could I do this? Note that I cannot import Java.util or any other classes.
Edit:
The example above was merely an example; ideally I'd like the solution to be extensible to an arbitrarily large number of 'square objects', where I could just call a hypothetical aSquareObject.squareConcat(otherSquareObject).squareConcat(anotherSquareObject).....squareConcat(finalSquareObject) method and it'd spit out two, three, five, fifteen squares side by side.

A: public class T27Concat {

public static void main(String[] args) {
    String s1 = "010203\n040506\n070809";
    String s2 = "101112\n131415\n161718";

    String plus = "   \n + \n   ";
    String equals = "   \n = \n   ";

    System.out.println(concat(concat(concat(concat(s1, plus), s2), equals), concat(s1, s2)));
}

public static String concat(String s, String t) {
    String[] ss = s.split("\n");
    String[] tt = t.split("\n");
    String result = "";
    for (int i = 0; i < ss.length; i++) {
        result += ss[i] + tt[i] + "\n";
    }
    return result.substring(0, result.length() - 1);
}

}

A: public class multiDarr {

    public static void main(String[] args) {

        String str1 = "010203\n040506\n070809\n";
        String str2 = "010203\n040506\n070809\n";

        String ttl = "";

        for(int i = 0;i<str1.length();i= i+7){
            ttl = ttl + str1.substring(i,i+6);
            ttl = ttl +str2.substring(i,i+6);
            ttl = ttl+'\n';

        }
        System.out.println(ttl);
        //System.out.println(ttl);

    }

}

you have to tune i = i+ n for your need , i put 7  because your original string have 6 chars,
result -
010203010203
040506040506
070809070809

A: I attempted solving this on paper, and arrived at a similar solution to that of @mayamar's:
 public String sqConcat(String string1, String string2)
 {
    String[] rows1 = string1.split("\n");
    String[] rows2 = string2.split("\n");

    return new String(rows1[0] + rows2[0] + "\n"
                    + rows1[1] + rows2[1] + "\n"
                    + rows1[2] + rows2[2] + "\n");
 }

Thanks for the help, everyone.