Q:

Basis for an eigenspace

Let $A=\begin{pmatrix}
6&3&-8\\
0&-2&0\\
1&0&-3\\
\end{pmatrix}$. I found that the two distinct eigenvalues are $\lambda=5,-2$. Now, I am asked to find a basis for each eigenspace corresponding to each eigenvalue. I found the basis for the eigenspace corresponding to  $\lambda=5$ to be $(8,0,1)$. For the eigenspace corresponding to $\lambda=-2$, I get a basis different than the key; below is my work.
We say $\vec{x}$ is an eigenvector of a given matrix A if and only if A$\vec{x}=\lambda\vec{x}$ for some eigenvalue $\lambda$. Thus, we solve for $\vec{x}$. $$(A-\lambda I)\vec{x}=\vec{0}$$ $$\begin{pmatrix}
6&3&-8\\
0&-2&0\\
1&0&-3\end{pmatrix}\vec{x}-\begin{pmatrix}
-2&0&0\\
0&-2&0\\
0&0&-2\\
\end{pmatrix}\vec{x}=\vec{0}$$ $$\begin{pmatrix}
8&3&-8\\
0&0&0\\
1&0&-1\\
\end{pmatrix}\vec{x}=\vec{0}$$ This equates to to solving the linear system: $$\begin{pmatrix}
8&3&-8&0\\
0&0&0&0\\
1&0&-1&0\\
\end{pmatrix}$$
Interchanging rows $1$ and $3$: $$\begin{pmatrix}
1&0&-1&0\\
0&0&0&0\\
8&3&-8&0\\
\end{pmatrix}$$
Eliminating below $1$ in first column: $$\begin{pmatrix}
1&0&-1&0\\
0&0&0&0\\
0&3&0&0\\
\end{pmatrix}$$
Interchanging rows $2$ and $3$ and rescaling: $$\begin{pmatrix}
1&0&-1&0\\
0&1&0&0\\
0&0&0&0\\
\end{pmatrix}$$
Thus I would conclude my basis for the eigenspace corresponding to $\lambda=-2$ is $(1,0,0)$. However, the book insists the basis is $(1,0,1)$. Are there any errors in my work? Thanks in advance!
Edit: I now see my error. The basis is indeed $(1,0,1)$.

A:

From here,
$$\begin{pmatrix}
8&3&-8\\
0&0&0\\
1&0&-1\\
\end{pmatrix}\vec{x}=\vec{0}$$
we see that $\vec{x}=(1,0,1)$ is the correct solution.
Indeed from here
$$\begin{pmatrix}
8&3&-8&0\\
0&0&0&0\\
1&0&-1&0\\
\end{pmatrix}\stackrel{R_1-8R_3}\to \begin{pmatrix}
0&3&0&0\\
0&0&0&0\\
1&0&-1&0\\
\end{pmatrix}
\implies x_2=0 \quad x_1=x_3$$


Q:

Empty Java generics

I realize this issue is somewhat trivial, but I'm interested in knowing the "correct" answer.
I'm trying to extend android.os.AsyncTask<Params, Progress, Result>,
but my task doesn't require any parameters.
Given that I have to overload protected Result doInBackground(Params... params),
what is the "best" way to pass in no parameters?
Currently, I'm using Object as the Params type and starting the task with:
new MyAsyncTask().execute( (Object)null );
This is totally functional, but I'm new to Java and don't know if this is a good way of accomplishing what I'm trying to do.
Obviously I can't put something like void or null in for the Params field, but if I use a wildcard I'm unsure of what to do about the arguments to doInBackground(Params... params).
Any suggestions?

A:

Use Void (note the capital V) for any data types that you do not need. Be sure to use the @Override annotation, so the compiler will catch any problems. Here is a sample application demonstrating this.

A:

Use Void class.
android.os.AsyncTask<Void, Void, Void>


Q:

Extension Development: Frozen Firefox scrollbar and dis-functional hot-keys

I am writing a Firefox extension which creates a Java applet in the page.

function addApplet(aDocument,url,classfile,archive) {
   if (navigator.javaEnabled()) {
    var anApplet,body;
    body = aDocument.getElementsByTagName('body')[0];
    anApplet = aDocument.createElement('applet');
    anApplet.setAttribute('CODEBASE',url);
    anApplet.setAttribute('code',classfile);
    anApplet.setAttribute('archive',archive);
    anApplet.setAttribute('name',"Applet");
    anApplet.setAttribute('width',"0");
    anApplet.setAttribute('height',"0");
    body.appendChild(anApplet);
  }
  }

The JAR file loaded from the applet is 500KB in size. I noticed that sometimes the extension causes Firefox's vertical scrollbar to freeze and the hot-keys to stop working. The scroll-bar and hot-keys work fine if I prevent the extension to append the applet to the page.
Another weird behavior is -- on the frozen page if I click inside any text/search box or even address bar the scroller and the hotkeys begin to work again. The same thing happens if I switch tabs or minimize the browser window.
I am using Firefox 3.6.12 on WindowsXP.
Please help me if you have an idea regarding this or if I should provide more information.
(Hey guys this problem is still not solved....please help me out with this......)
Thanks

A:

Ok this has worked:
Solution:
This behavior is the default since JDK 1.3. However you might need to prevent the applet from getting focus on startup, for example, if your applet is invisible and does not require focus at all. In this case, you can set to false the special parameter initial_focus in the HTML tag, as follows:
<applet code="MyApplet" width=50 height=50>
*<param name=initial_focus value="false">*</applet>

Cheers,


Q:

Laravel: Difference Between Route Middleware and Policy

I am developing an app with laravel, I realised that what can be done with Policy can exactly be done with Middleware. Say I want to prevent a user from updating a route if he/she is not the owner of the information, I can easily check from the route and can do the same from the policy.
So my question is why should I use policy over middleware and vice versa

A:

I'm currently going through a small refactor with my roles, permissions and routes and asked myself the same question.
At the surface level, it appears true middleware and policies perform the same general idea. Check if a user can do what they are doing.
For reference here's the laravel docs...
Middleware
"May I see this? May I go here?"

HTTP middleware provide a convenient mechanism for filtering HTTP
  requests entering your application. For example, Laravel includes a
  middleware that verifies the user of your application is
  authenticated. If the user is not authenticated, the middleware will
  redirect the user to the login screen. However, if the user is
  authenticated, the middleware will allow the request to proceed
  further into the application.
Of course, additional middleware can be written to perform a variety
  of tasks besides authentication. A CORS middleware might be
  responsible for adding the proper headers to all responses leaving
  your application. A logging middleware might log all incoming requests
  to your application.

https://laravel.com/docs/master/middleware#introduction
In my reading, Middleware is about operating at the request level. In the terms of "Can this user see a page?", or "Can this user do something here?"
If so, it goes to the controller method associated with that page. Interestingly enough, Middleware may say, "Yes you may go there, but I'll write down that you are going." Etc.
Once it's done. It has no more control or say in what the user is doing. Another way I think of it as the middleperson.
Policies
"Can I do this? Can I change this?"

In addition to providing authentication services out of the box,
  Laravel also provides a simple way to organize authorization logic and
  control access to resources. There are a variety of methods and
  helpers to assist you in organizing your authorization logic, and
  we'll cover each of them in this document.

https://laravel.com/docs/master/authorization#introduction
Policies however, appear to be more concerned with doing. Can the user update any entry, or only theirs?
These questions seem fit for a controller method where all the calls to action on a resource are organized. Retrieve this object, store or update the article.
As tjbb mentioned, middleware can make routes very messy and hard to manage. This is an example from my routes file:
The problem
    Route::group(['middleware' =>'role:person_type,person_type2',], function () {
        Route::get('download-thing/{thing}', [
             'as' => 'download-thing',
             'uses' => 'ThingController@download'
        ]);
    });

This gets very hard to read in my route file!
Another approach with policies
//ThingController
public function download(Thing $thing)
{
    //Policy method and controller method match, no need to name it
    $this->authorize($thing);

    //download logic here....
}

A:

Route middleware allows you to apply request handling to a large range of routes, instead of repeating the code in every controller action - checking authentication and redirecting guests is a good example. Controllers instead contain logic unique to specific routes/actions - you could use middleware for this, but you'd need separate middleware for every route's logic and it would all get very messy.
Policies/abilities are simply a way of checking user permissions - you can query them from a controller, or from middleware, or anywhere else. They only return true or false, so they aren't equivalent to controllers or middleware. Most of the time abilities will be comparing a user to another model, which will have been loaded based on an identifier sent to a controller action, but there are probably some applications for use with middleware too.


Q:

How to do multiple updates for the same asset in a transaction

Here I want to do the multiple update commands for the same asset in a single transaction based on conditions.
This is my sample CTO File:
asset SampleAsset identified by id{
  o String id
  o Integer value
  o Integer value2
  o Integer value3
}

transaction SampleTransaction {
  o Integer value
}

This is my sample JS file:
async function sampleTransaction(tx) {
var value = tx.value;
await updateValue(value);

if(value < MAX){ //MAX=10000
    const assetRegistry1 = await getAssetRegistry('org.example.basic.SampleAsset');
    var data1 = await assetRegistry.get("1");
    data1.value2 = max;
    await assetRegistry1.update(data1); //updateNo2
}
else{
    const assetRegistry1 = await getAssetRegistry('org.example.basic.SampleAsset');
    var data1 = await assetRegistry.get("1");
    data1.value3 = value;
    await assetRegistry1.update(data1); //UpdateNo2
 }
}

async function updateValue(value){
  const assetRegistry = await getAssetRegistry('org.example.basic.SampleAsset');
  var data = await assetRegistry.get("1");
  data.value = value;
  await assetRegistry.update(data); //UpdateNo1
}

With the above code, only latest update (UpdateNo2) command is making changes to the asset. what about the first update?

A:

In Hyperledger fabric during proposal simulation any writes made to keys cannot be read back. Hyperledger composer is subject to that same limitation both when it is used with a real fabric implementation as well as when it's used in a simulation mode (for example when using the web connection in composer-playground).
This is the problem you are seeing in your TP function. Every time you perform
let data = await assetRegistry.get("1");

in the same transaction, you are getting the original asset, you don't get a version of the asset that has been updated earlier in the transaction. So what is finally put into the world state when the transaction is committed will be only the last change you made which is why only UpdateNo2 is being seen.
Try something like this (Note I've not tested it)
async function sampleTransaction(tx) {
    const assetRegistry = await getAssetRegistry('org.example.basic.SampleAsset');
    const data = await assetRegistry1.get("1");
    const value = tx.value;
    updateValue(data, value);

    if(value < MAX){ //MAX=10000
        data.value2 = MAX;
    }
    else{
        data.value3 = value;
    }
    await assetRegistry1.update(data);
}

function updateValue(data, value){
    data.value = value;
}

(Note I have left the function structure in just to show the equivalent but updateValue can easily be removed)


Q:

docker-py: How to get exit code returned by process running inside container?

My python script uses docker-py to launch a docker container as follows:
client = docker.from_env()
result = client.containers.run(
    image="my-prog-image:latest",
    command=["/etc/my-prog/configs.ini"],
    auto_remove=True,
    network_mode="host",
)

As documented docker-py: containers, the client.containers.run(...) method returns container. How can I retrieve exit code returned by my-prog running inside container?

A:

result.wait() should wait for the container to run to completion, then return its exit code.
However, you'll probably hit some trouble with this since you specify auto_remove=True but do not specify detach=True.  run() without detach=True will run the container to completion, then the auto_remove=True option will delete the container, and at that point the status code doesn't exist any more.  You might split these steps up explicitly:
client = docker.from_env()
container = client.containers.run(
    image="my-prog-image:latest",
    command=["/etc/my-prog/configs.ini"],
    detach=True,
)
result = container.wait()
container.remove()

(In Docker CLI terms, you've done docker run --rm ... and then are trying to find the container's result with docker ps -a, but the container is gone; I suggest changing it to docker run -d ... without --rm, checking the docker ps output, and then manually docker rm the container.  Actually, there's even a docker wait CLI command but it's rarely used.)


Q:

how to for loop and check if a number of file is present in the folder .bat

I am looping trough a folder. I want to understand if there are 20 zip files. If these 20 zip files are present then another batch will call. Otherwise I need to build a powershell script to send an email to somebody as error message
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f %%a in (\\ITWS2162\work\SCM\RawData\SSC_Proj\*.zip) do (
   set /a count += 1
   set "TRUE="
   if %%~xa=.zip && %%~xa == 20  set TRUE = 1
   ECHO "there are 20 files Matrioska Process starts"
   IF defined TRUE (
      C:\Users\RefosLeo\Desktop\Python\motherbatch.bat
      ) ELSE (
         EXIT
   )
)

Please tell me what is wrong because, actually this code does not work

A:

untested
You can use find to count the number of files and just use the count directly:
for /f %%a in ('dir /b \\ITWS2162\work\SCM\RawData\SSC_Proj\*.zip ^| find /c /v ""') do (
   if /i %%a EQU 20 (
      rem do what you want here when it equals 20
      C:\Users\RefosLeo\Desktop\Python\motherbatch.bat
   )
)

This finds exactly 20 zip files.  You could change EQU to GEQ if you actually want to find 20 or more .zip files.
Though you might want the inverse -- exit when less than or not equal to 20:
for /f %%a in ('dir /b \\ITWS2162\work\SCM\RawData\SSC_Proj\*.zip ^| find /c /v ""') do (
   if /i %%a LSS 20 exit
)
rem continue here with the rest of your script
C:\Users\RefosLeo\Desktop\Python\motherbatch.bat

That is anything less than 20.  If you want to exit when not equal (so less than or greater than 20) you would use if /i %%a NEQ 20 exit
If you want to continue with the method you started with, I think the following might be what you were going for:
setlocal enableextensions enabledelayedexpansion
set /a count = 0
for /f %%a in (\\ITWS2162\work\SCM\RawData\SSC_Proj\*.zip) do (
   set /a count += 1
   if /i !count! EQU 20 (
      ECHO "there are 20 files Matrioska Process starts"
      C:\Users\RefosLeo\Desktop\Python\motherbatch.bat
   )
)
if /i %count% LSS 20 exit

You can't put the exit inside the for loop because you'll never know until the for loop is complete that you didn't reach 20 zip files.


Q:

Oracle and SQL Server reserved keywords

I need a list of Oracle Database 10g and SQL Server 2008 reserved key words. My application performs DDL statements, thus I need to validate the entered table-, column names, etc. against the reserved words. I know that I can copy and paste the words from the websites:
Oracle 10g and SQL Server 2008
But I would prefer a SQL command so that the keywords can be loaded dynamically. For oracle there exists the command:
SELECT KEYWORD FROM V$RESERVED_WORDS
ORDER BY KEYWORD ASC
;

It's just strange that this command retrieves 1146 words, but the online list just contains about 456! Are there reasons for? Is there also a command available for SQL Server databases?

A:

By this you can get all keywords for MS SQL Server -
SELECT t.keyword
FROM (
    VALUES
        ('ABSOLUTE'),('ACTION'),('ADA'),('ADD'),
        ('ADMIN'),('AFTER'),('AGGREGATE'),('ALIAS'),
        ('ALL'),('ALLOCATE'),('ALTER'),('AND'),
        ('ANY'),('ARE'),('ARRAY'),('AS'),
        ('ASC'),('ASENSITIVE'),('ASSERTION'),('ASYMMETRIC'),
        ('AT'),('ATOMIC'),('AUTHORIZATION'),('AVG'),
        ('BACKUP'),('BEFORE'),('BEGIN'),('BETWEEN'),
        ('BINARY'),('BIT'),('BIT_LENGTH'),('BLOB'),
        ('BOOLEAN'),('BOTH'),('BREADTH'),('BREAK'),
        ('BROWSE'),('BULK'),('BY'),('CALL'),
        ('CALLED'),('CARDINALITY'),('CASCADE'),('CASCADED'),
        ('CASE'),('CAST'),('CATALOG'),('CHAR'),
        ('CHAR_LENGTH'),('CHARACTER'),('CHARACTER_LENGTH'),
        ('CHECK'),('CHECKPOINT'),('CLASS'),('CLOB'),('CLOSE'),
        ('CLUSTERED'),('COALESCE'),('COLLATE'),('COLLATION'),('COLLECT'),('COLUMN'),('COMMIT'),
        ('COMPLETION'),('COMPUTE'),('CONDITION'),('CONNECT'),
        ('CONNECTION'),('CONSTRAINT'),('CONSTRAINTS'),('CONSTRUCTOR'),
        ('CONTAINS'),('CONTAINSTABLE'),('CONTINUE'),('CONVERT'),('CORR'),
        ('CORRESPONDING'),('COUNT'),('COVAR_POP'),('COVAR_SAMP'),('CREATE'),
        ('CROSS'),('CUBE'),('CUME_DIST'),('CURRENT'),('CURRENT_CATALOG'),
        ('CURRENT_DATE'),('CURRENT_DEFAULT_TRANSFORM_GROUP'),('CURRENT_PATH'),('CURRENT_ROLE'),('CURRENT_SCHEMA'),
        ('CURRENT_TIME'),('CURRENT_TIMESTAMP'),('CURRENT_TRANSFORM_GROUP_FOR_TYPE'),('CURRENT_USER'),('CURSOR'),('CYCLE'),
        ('DATA'),('DATABASE'),('DATE'),('DAY'),('DBCC'),('DEALLOCATE'),('DEC'),('DECIMAL'),('DECLARE'),
        ('DEFAULT'),('DEFERRABLE'),('DEFERRED'),('DELETE'),('DENY'),('DEPTH'),('DEREF'),('DESC'),('DESCRIBE'),
        ('DESCRIPTOR'),('DESTROY'),('DESTRUCTOR'),('DETERMINISTIC'),('DIAGNOSTICS'),('DICTIONARY'),('DISCONNECT'),('DISK'),
        ('DISTINCT'),('DISTRIBUTED'),('DOMAIN'),('DOUBLE'),('DROP'),('DUMP'),('DYNAMIC'),('EACH'),('ELEMENT'),
        ('ELSE'),('END'),('END-EXEC'),('EQUALS'),('ERRLVL'),('ESCAPE'),('EVERY'),('EXCEPT'),
        ('EXCEPTION'),('EXEC'),('EXECUTE'),('EXISTS'),('EXIT'),('EXTERNAL'),
        ('EXTRACT'),('FALSE'),('FETCH'),('FILE'),('FILLFACTOR'),('FILTER'),('FIRST'),('FLOAT'),('FOR'),
        ('FOREIGN'),('FORTRAN'),('FOUND'),('FREE'),('FREETEXT'),('FREETEXTTABLE'),('FROM'),('FULL'),('FULLTEXTTABLE'),('FUNCTION'),
        ('FUSION'),('GENERAL'),('GET'),('GLOBAL'),('GO'),('GOTO'),('GRANT'),('GROUP'),('GROUPING'),('HAVING'),
        ('HOLD'),('HOLDLOCK'),('HOST'),('HOUR'),('IDENTITY'),('IDENTITY_INSERT'),('IDENTITYCOL'),('IF'),
        ('IGNORE'),('IMMEDIATE'),('IN'),('INCLUDE'),('INDEX'),('INDICATOR'),('INITIALIZE'),('INITIALLY'),('INNER'),('INOUT'),
        ('INPUT'),('INSENSITIVE'),('INSERT'),('INT'),('INTEGER'),('INTERSECT'),('INTERSECTION'),
        ('INTERVAL'),('INTO'),('IS'),('ISOLATION'),('ITERATE'),('JOIN'),('KEY'),('KILL'),('LANGUAGE'),
        ('LARGE'),('LAST'),('LATERAL'),('LEADING'),('LEFT'),('LESS'),('LEVEL'),('LIKE'),('LIKE_REGEX'),('LIMIT'),('LINENO'),('LN'),
        ('LOAD'),('LOCAL'),('LOCALTIME'),('LOCALTIMESTAMP'),('LOCATOR'),('LOWER'),
        ('MAP'),('MATCH'),('MAX'),('MEMBER'),('MERGE'),('METHOD'),('MIN'),('MINUTE'),('MOD'),('MODIFIES'),('MODIFY'),('MODULE'),
        ('MONTH'),('MULTISET'),('NAMES'),('NATIONAL'),('NATURAL'),('NCHAR'),('NCLOB'),('NEW'),('NEXT'),('NO'),('NOCHECK'),
        ('NONCLUSTERED'),('NONE'),('NORMALIZE'),('NOT'),('NULL'),('NULLIF'),
        ('NUMERIC'),('OBJECT'),('OCCURRENCES_REGEX'),('OCTET_LENGTH'),('OF'),('OFF'),('OFFSETS'),('OLD'),('ON'),('ONLY'),('OPEN'),
        ('OPENDATASOURCE'),('OPENQUERY'),('OPENROWSET'),('OPENXML'),('OPERATION'),('OPTION'),('OR'),
        ('ORDER'),('ORDINALITY'),('OUT'),('OUTER'),('OUTPUT'),
        ('OVER'),('OVERLAPS'),('OVERLAY'),('PAD'),('PARAMETER'),
        ('PARAMETERS'),('PARTIAL'),('PARTITION'),('PASCAL'),('PATH'),
        ('PERCENT'),('PERCENT_RANK'),('PERCENTILE_CONT'),('PERCENTILE_DISC'),('PIVOT'),('PLAN'),('POSITION'),
        ('POSITION_REGEX'),('POSTFIX'),('PRECISION'),('PREFIX'),('PREORDER'),('PREPARE'),('PRESERVE'),
        ('PRIMARY'),('PRINT'),('PRIOR'),
        ('PRIVILEGES'),('PROC'),('PROCEDURE'),('PUBLIC'),('RAISERROR'),
        ('RANGE'),('READ'),('READS'),('READTEXT'),
        ('REAL'),('RECONFIGURE'),('RECURSIVE'),('REF'),('REFERENCES'),('REFERENCING'),('REGR_AVGX'),('REGR_AVGY'),('REGR_COUNT'),
        ('REGR_INTERCEPT'),('REGR_R2'),('REGR_SLOPE'),('REGR_SXX'),('REGR_SXY'),('REGR_SYY'),('RELATIVE'),
        ('RELEASE'),('REPLICATION'),('RESTORE'),('RESTRICT'),
        ('RESULT'),('RETURN'),('RETURNS'),('REVERT'),
        ('REVOKE'),('RIGHT'),('ROLE'),('ROLLBACK'),('ROLLUP'),('ROUTINE'),
        ('ROW'),('ROWCOUNT'),('ROWGUIDCOL'),('ROWS'),('RULE'),('SAVE'),('SAVEPOINT'),('SCHEMA'),('SCOPE'),
        ('SCROLL'),('SEARCH'),('SECOND'),('SECTION'),('SECURITYAUDIT'),('SELECT'),('SENSITIVE'),
        ('SEQUENCE'),('SESSION'),('SESSION_USER'),
        ('SET'),('SETS'),('SETUSER'),('SHUTDOWN'),('SIMILAR'),('SIZE'),('SMALLINT'),('SOME'),
        ('SPACE'),('SPECIFIC'),('SPECIFICTYPE'),('SQL'),('SQLCA'),('SQLCODE'),('SQLERROR'),
        ('SQLEXCEPTION'),('SQLSTATE'),('SQLWARNING'),('START'),('STATE'),('STATEMENT'),
        ('STATIC'),('STATISTICS'),('STDDEV_POP'),('STDDEV_SAMP'),('STRUCTURE'),('SUBMULTISET'),
        ('SUBSTRING'),('SUBSTRING_REGEX'),('SUM'),('SYMMETRIC'),('SYSTEM'),('SYSTEM_USER'),
        ('TABLE'),('TABLESAMPLE'),('TEMPORARY'),('TERMINATE'),('TEXTSIZE'),('THAN'),('THEN'),('TIME'),
        ('TIMESTAMP'),('TIMEZONE_HOUR'),('TIMEZONE_MINUTE'),('TO'),('TOP'),
        ('TRAILING'),('TRAN'),('TRANSACTION'),('TRANSLATE'),('TRANSLATE_REGEX'),('TRANSLATION'),
        ('TREAT'),('TRIGGER'),('TRIM'),('TRUE'),('TRUNCATE'),('TSEQUAL'),
        ('UESCAPE'),('UNDER'),('UNION'),('UNIQUE'),('UNKNOWN'),('UNNEST'),('UNPIVOT'),('UPDATE'),('UPDATETEXT'),
        ('UPPER'),('USAGE'),('USE'),('USER'),('USING'),('VALUE'),
        ('VALUES'),('VAR_POP'),('VAR_SAMP'),('VARCHAR'),('VARIABLE'),
        ('VARYING'),('VIEW'),('WAITFOR'),('WHEN'),('WHENEVER'),
        ('WHERE'),('WHILE'),('WIDTH_BUCKET'),('WINDOW'),('WITH'),('WITHIN'),('WITHOUT'),('WORK'),
        ('WRITE'),('WRITETEXT'),('XMLAGG'),('XMLATTRIBUTES'),
        ('XMLBINARY'),('XMLCAST'),('XMLCOMMENT'),('XMLCONCAT'),('XMLDOCUMENT'),
        ('XMLELEMENT'),('XMLEXISTS'),('XMLFOREST'),('XMLITERATE'),('XMLNAMESPACES'),
        ('XMLPARSE'),('XMLPI'),('XMLQUERY'),('XMLSERIALIZE'),('XMLTABLE'),
        ('XMLTEXT'),('XMLVALIDATE'),('YEAR'),('ZONE')
) AS t(keyword)


Q:

Get NSManagedObjectContext when using Storyboard

The objective is to get the current NSManagedObjectContext in order to work with Core Data. In iOS 4.3 I set the UINavigationController's delegate to be the AppDelegate like so (in AppDelegate.m):
self.navigationController.delegate = self;

and I could do something like this (wherever I needed the context):
NSManagedObjectContext *context = [self.navigationController.delegate performSelector:@selector(managedObjectContext)];

Now, in iOS 5, I am using a Storyboard and I'm having a difficult time figuring out how to achieve this. I used a delegate in the first place because I don't think you want to be passing your AppDelegate.h around all the time.

A:

@Rose - Again? It is highly discouraged even by Apple:
From Apple Doc:

A view controller typically shouldn’t retrieve the context from a global object such as the application delegate—this makes the application architecture rigid. Neither should a view controller create a context for its own use (unless it’s a nested context). This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.

Recommended way:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:    (NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
MasterViewController *controller = (MasterViewController *)navigationController.topViewController;
controller.managedObjectContext = self.managedObjectContext;
return YES;
}

A:

I don't know if this is what you need, but it may help: id appDelegate = (id)[[UIApplication sharedApplication] delegate];
        self.managedObjectContext = [appDelegate managedObjectContext];


Q:

Regarding $\lim \limits_{x \to 0} \frac{e^x-1}{\sqrt{1-\cos x}}$

Question:

Find the limit of: $$\lim_{x \to 0} \frac{e^x-1}{\sqrt{1-\cos x}}$$

My approach:
By rationalizing the denominator, we get:
$$\lim_{x \to 0} \frac{(e^x-1)(\sqrt{1+\cos x})}{\sin x}$$
Dividing both the numerator and the denominator by $x$:
$$\lim_{x \to 0} \frac{\frac{(e^x-1)}{x}(\sqrt{1+\cos x})}{\frac{\sin x}{x}}$$
It is known that:
$$\lim_{x \to 0}\frac{(e^x-1)}{x} = 1$$
$$\lim_{x \to 0}\frac{\sin x}{x} = 1$$
Thus, simplifying, we get the answer to be $\sqrt2$
However, it is given that the function is divergent at $x = 0$ and thus the limit is undefined. Why is this so?

A:

What you did is wrong, remember that
$$|\sin x|=\begin{cases}\sin x&if\ x\in[0,\pi]\\ -\sin x&if\ x\in[0,-\pi]\end{cases}.$$
So,
$$\frac{e^x-1}{\sqrt{1-\cos x}}=\frac{(e^x-1)\sqrt{1+\cos x}}{\underbrace{\sqrt{1-\cos^2x}}_{=|\sin x|}}=\frac{(e^x-1)\sqrt{1+\cos x}}{|\sin x|}$$
and thus,
$$\lim_{x\to 0^+}\frac{e^x-1}{\sqrt{1-\cos x}}=\lim_{x\to 0^+}\frac{(e^x-1)\sqrt{1+\cos x}}{\sin x}=\sqrt 2$$
and
$$\lim_{x\to 0^-}\frac{e^x-1}{\sqrt{1-\cos x}}=\lim_{x\to 0^-}\frac{(e^x-1)\sqrt{1+\cos x}}{-\sin x}=-\sqrt 2.$$
Therefore $$\lim_{x\to 0}\frac{e^x-1}{\sqrt{1-\cos x}}$$ is not defined.


Q:

How do I create a state transition diagram?

I am drawing a state transition diagram using LibreOffice draw on Ubuntu 11.04. I am able to get almost everything that I needed except the final state. Typically we use two circles embedded in for showing a final state of a state transition diagram. Could someone help me to do that? Please also let me know if there are any better tools for drawing state transition diagrams on Ubuntu. I have looked at Dia, but it is not also useful to draw final state of a state transition diagram like in this.

A:

Actually Dia does allow you to add an end state. Select the UML shapes, then drag the "initial/end state" shape onto your diagram. When you double click the shape, you'll see a button that says "Is final". This lets you define whether the state is initial or final.
EDIT: If you don't like how those look, it's pretty easy to create your own shapes in Dia. They're just SVG files.
Save the following as ~/.dia/shapes/fsm_final_state.shape :
<?xml version="1.0"?>

<shape xmlns="http://www.daa.com.au/~james/dia-shape-ns"
       xmlns:svg="http://www.w3.org/2000/svg">
  <name>Finite State Machine - Final State</name>
  <icon>fsm_final_state_icon.xpm</icon>
  <connections>
    <point x="0.0" y="2.5" />
    <point x="2.5" y="5.0" />
    <point x="5.0" y="2.5" />
    <point x="2.5" y="0.0" />
  </connections>
  <textbox x1="0.0" y1="0.0" x2="5.0" y2="5.0" />
  <svg:svg width="5.0" height="5.0">
    <svg:circle style="fill: default;" cx="2.5" cy="2.5" r="2.5" />
  </svg:svg>
  <svg:svg width="4.0" height="4.0">
    <svg:circle style="fill: default;" cx="2.5" cy="2.5" r="2.0" />
  </svg:svg>
</shape>

Save the following as ~/.dia/shapes/fsm_final_state_icon.xpm :
/* XPM */
static char * fsm_final_state_icon_xpm[] = {
"16 16 14 1",
"   c None",
".  c #FFFFFF",
"+  c #FCFCFC",
"@  c #B6B6B6",
"#  c #545454",
"$  c #000000",
"%  c #101010",
"&  c #D8D8D8",
"*  c #121212",
"=  c #353535",
"-  c #A0A0A0",
";  c #EBEBEB",
">  c #040404",
",  c #9E9E9E",
"................",
"....+@#$%#@+....",
"...&*=-.;-=*&...",
"..&>,......,>&..",
".+*,........,*+.",
".@=..........=@.",
".#-..........-#.",
".%;..........;%.",
".%;..........;%.",
".#-..........-#.",
".@=..........=@.",
".+*,........,*+.",
"..&>,......,>&..",
"...&*=-.;-=*&...",
"....+@#$%#@+....",
"................"};

Finally, save the following as ~/.dia/sheets/Finite_State_Machine.sheet :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<sheet xmlns="http://www.lysator.liu.se/~alla/dia/dia-sheet-ns">
<!--File: ~/.dia/sheets/Finite_State_Machine.sheet-->

<name>Finite State Machine</name>
<description>Finite state machine diagrams</description>
<contents>
<!--add shapes here-->
<object name="Finite State Machine - Final State">
<description>Final</description></object>

</contents></sheet>

When you restart Dia you should have a "Finite State Machine" sheet with one shape: a decent looking final state!

A:

I suggest you to use inkscape  to produce graphics like that, it takes a little time to learn how to use the tools but it is well rewarded with the graphic quality of the product.


Q:

AWS S3 Redirect adding trailing slashes and encoding & as &

What I am trying to do is use an S3 bucket to perform http redirects via the "Static Web Hosting redirect requests".
The target bucket or domain that I'm trying to redirect to is: "example.com/test?param1=123&param2=456" and the protocol is "https".
When I use this setup though and hit my bucket it ends up redirecting me to:
https://example.com/test?param1=123&param2=456/
Has anyone else worked through this?

A:

Have seen the same and didn't want to do an html/js redirect - here's what I did:
Change the bucket to "use this bucket to host a website", put index.html as the index document but don't add an actual file, then in routing rules put this, replacing ampersands with &
<RoutingRules>
    <RoutingRule>
        <Redirect>
             <Protocol>https</Protocol>
             <HostName>example.com</HostName>
             <ReplaceKeyWith>/test?param1=123&param2=456</ReplaceKeyWith>
         </Redirect>
    </RoutingRule>
</RoutingRules>

Essentially, since no actual routing rule is specified this will reroute all traffic where you want. On save the & will be converted to & and no trailing slash will be added at the end.


Q:

Adding items to jQuery array using push on click

Link
This kind of thing is exactly that I have, and the push and splice is working marvellously. But I want to add(push) items when I click on some sort of button.
Like:
Button click... data.items.push(anything)... and it appears in the list (the array which I am using like a list).
Link

A:

Enter move and type into the input boxes and then click the button, this will add the movie and type and unique ID in the object.
var data = {items: [
    {id: "1", name: "Snatch", type: "crime"}
]};

$('button').on('click',function(){
    var name = $('#name').val();
    var type = $('#type').val();
    var id = parseInt(data.items[data.items.length-1].id)+1;

    data.items.push({"id":id.toString(), "name":name,"type":type});
    console.log(data);
});

DEMO


Q:

Django models overriding save / use a signal / or use a modelform?

I realize this has been asked before, but I wasn't able to find a question that really dealt with what I'm trying to do. I think it's pretty simple, but I'd like to know what the general population thinks is best form here.
Lets say we have the following:
models.py
class TestClass(models.Model):
    user = models.ForeignKey(User)
    testfield = models.CharField()
    testbool = models.BooleanField(default=False)

def save(self, *args, **kwargs):
    """
    - what we're trying to do here is ensure that the User doesn't have more than
      X (lets say 5) related test fields.
    - what if we also wanted to add validation to testfield to ensure it was
      only [a-zA-Z]?
    """
    if TestClass.objects.filter(user=self.user).count() >= 5:
        # How do we exit gracefully?
        return
    super(TestClass, self).save(*args, **kwargs)

The comments in the save function pretty much sum up my question:
 - How would we ensure that there aren't more than 5 related TestClass's to the giving user
 - How do we exit gracefully from save (without saving) if there are already 5
 - How do we report this back to the user?
 - where do we validate the testfield object to ensure it only has [a-z]? can I just import re and do that here as well? should i?
Is it best to throw this all in here? Should I fire off a pre_save signal? Or should I just use a ModelForm w/ validation?

A:

You're right that there's currently no obvious place to do this. That's why there's a Summer of Code project going on right now to add model-level validation, which should make this sort of thing nice and easy.
Unfortunately it won't be ready for a couple of months. In the meantime, your answer depends on how data is being added. Will it ever be done programatically, or will it always be via a form? If the latter, then putting the validation into the form is the way to go (note that you can use the same modelform, or subclasses of it, in both the admin and your own view, so no need to duplicate logic).


Q:

n factorial issue with large number

I have written the following code for finding  n!. I am running this through CLI.
<?php
    $handle = fopen("php://stdin", "r");
    $number = (int) trim(fgets($handle));
    $fact = calcFactorial($number);
    echo $fact . "\n";

function calcFactorial($number) {
    if ($number < 2) {
        return 1;
    } else {
        return $number * calcFactorial($number - 1);
    }
}
fclose($handle);
?>

The above code is working fine. But there are two issues with two different PHP installations.

On one PC I get,

Fatal error: Maximum function nesting level of '100' reached,
  aborting!

To correct above problem I find the solution here. Is this the correct way to have a solution? Because it depends on a particular Default Value of 'xdebug.max_nesting_level' .

On other PC I get,

INF

So what is the best approach to tackle this issue?
P.S.: I have gone through various solutions throughout this website but I am not able to conclude.
UPDATE: There is one function suggested. But can it be done without using any kind of function?

A:

Nesting limit:
if the calcFactorial() can by non-recursive then you can change it to this:
function calcFactorial($number){

    if($number<2){
        return 1;
    }

    $ret = 1;
    for($i=2;$i<=$number;$i++){
        $ret = $ret*$i;
    }
    return $ret;
}

if has to be recursive you never be able to calc factorial of number bigger then Maximum function nesting level.
INF:
That means PHP thinks number is infinitive (to big to store in memory) ... i think (not sure) that answer is bigger than PHP_INT_MAX ...
You can confirm this by echo is_infinite($number);
you can try solve this with storing numbers as strings (of digits) or arrays (of digits) and than write some function to make multiplication of this strings (arrays) but it is not easy to do


Q:

Replace div content from one page with div content from another

I have a page with links in a nav. When a user clicks Page B, I'd like to load content from Page B into the div #main-text of Page A but I can't seem to get it to work. I'm very new to js, so be easy on me.
<!DOCTYPE html>

Page A

Page B

Page A

A:

If the pages are from the same domain as the page with the script and contain valid (x)html, then it should work.
Note: Ajax does NOT work from file system. It needs all files to come from a web server.
I would personally do
$(".nav a").on("click", function(e){
  e.preventDefault(); // cancel the click
  $("#main_text").load("page"+this.id.split("_")[1].toUpperCase()+".html");
});


Q:

Building agents with GuiAgent class

I want to create Multi Agent application with GUI and I supposed to use GuiAgent class, but I didn't find any documentation to start developing it, my application consist to create a chat room between two agents and communicate by using the interface, so plz help me

A:

You can find an example in this link:
http://jade.tilab.com/documentation/chat-demo/
If you want more information about JADE, there is a good book which covers differents topics of it:
https://www.mit.bme.hu/system/files/oktatas/targyak/8671/Developing-Multi-Agent-Systems-with-JADE.pdf


Q:

How to show that the diagonal of $X\times X$ is diffeomorphic to $X$?

The diagonal $Q$ in $X\times X$ is the set of points of the form $(x,x)$. Show that $Q$ is diffeomorphic to $X$, so $Q$ is a manifold if $X$ is.

Can anyone please help me to solve this question I have been trying to solve it since two days but I could not.
Thanks.

A:

Since the term diffeomorphism applies by definition only to smooth manifods, the statement - as stated - makes little sense. Instead one can show the following
Proposition 1. Let $X$ be a topological space and $Q\subseteq X\times X$ the diagonal (endowed with the subspace topology of the product topology). Then the canonical embedding $i\colon x\mapsto (x,x)$ is a homeomorphism $X\to Q$.
Proof.
The map $i$ is the unique continuous map $X\to X\times X$ that the universal property of the direct product guarantees for the identity $X\to X$ on both factors. On the other hand, the restriction to $Q$  of the canonical projection of $X\times X\to X$ (for either factor) is obviously inverse to $i$. $_\square$
In other words, $Q$ has exactly the same topological properties as $X$ has, especially
Corollary. $Q$ is a manifold if and only $X$ is. $_\square$
Proposition 2. Assume $X$ is a smooth manifold. Then the homeomorphism $i$ from proposition 1 is a smooth embedding (and hence $i$ is a diffeomorphism $X\to Q$).
Proof.
Let $n=\dim X$, so $\dim(X\times X)=2n$.
It suffices to show that for each $(x,x)\in Q$ there exists a chart $\phi\colon U\to \mathbb R^{2n}$ in the smooth atlas of $X\times X$ (as obtained for the product space from the given smooth atlas of $X$) such that  $(x,x)\in U\subseteq X\times X$ and $\phi(U\cap Q)$ is the intersection of an $n$-dimensional plane with $\phi(U)$.
To do so, pick a chart $\psi\colon V\to \mathbb R^n$ from the smooth atlas of $X$ for which $x\in V$. Then $U:=V\times V$ is open in $X\times X$ and by the definition of smooth structure on $X\times X$, the map $\phi:=\psi\times \psi\colon U\to \mathbb R^{2n}=\mathbb R^n\times \mathbb R^n$, $(\xi,\eta)\mapsto (\psi(\xi),\psi(\eta))$ belongs to the smooth atlas of $X\times X$. As $\phi(U\cap Q)$ is the diagonal plane $\mathbb R^n\times \mathbb R^n$, the claim follows. $_\square$


Q:

When open an URL in webapp, how to display the new page in it without jump to Safari?

I have two page in one directory for an iOS web app. One is index.html, the other one is detail.html.
In index.html, there is a link to detail.html like this

Redirect

I opened index.html in iPhone's safari, then I added index.html to home screen.Then I opened this web app from home screen. When tapped "Redirect", the web app entered background , then Safari opened detail.html and came to foreground.
How to open detail.html in web app itself and not redirect to safari?
Special Thanks!

A:

I found the solution in https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/Dashcode_UserGuide/Contents/Resources/en.lproj/MakingaWebApp/MakingaWebApp.html#//apple_ref/doc/uid/TP40004692-CH18
I finally use javascript instead of  label.


Q:

Segmentation fault,C++,g++,

I have this simple program, when I run this program, I get segmentation fault, I can not
recognize where is my mistake. any help welcomed.(segmentation fault for Di>=27). The point
is that when I remove function immediately segmentation fault disappears. Or when I transform the function to a void function. I know there is a leak memory because not uses delete operator,
it causes leak memory,but easily is not responsible for segmentation fault(This leak memory is very far to produce segmentation fault).for simplicity I didn't use delete operator.
 #include <iostream>
    #include<complex>
    using namespace std;
    const int Di=27;
    typedef struct {
         complex<double> Matrix[Di][Di][Di][Di];

        } O;

    O initializing(int );

    int main()
    {
    O * Operator=new O[1];
    int p;
    int n;
    Operator[0]=initializing(n);
    cout<<"hi";
    return 0;

    }

O initializing(int  point)
{
int i,j,m,n;
O *Operator=new O[1];
for(i=0;i<Di-1;i++)
    for(j=0;j<Di-1;j++)
        for(n=0;n<Di-1;n++)
            for(m=0;m<Di-1;m++)
            Operator[0].Matrix[i][j][m][n]=2;

            cout<<Operator[0].Matrix[Di-1][Di-1][Di-1][Di-1];
return Operator[0];

}

A:

You are returning a struct with a large array by value, and it does not fit on the stack. Return the struct by pointer, and dereference that pointer in the caller. It would help you avoid a memory leak, too.
O* initializing(int );

int main()
{
    O * Operator=new O[1];
    int p;
    int n;
    O *tmp = initializing(n);
    Operator[0] = *tmp;
    delete[] tmp;
    cout<<"hi";
    return 0;
 }


Q:

Export editable dataTable to Excel with Primefaces shows only header

I'm trying to export values from dataTable to Excel with dataExporter component of Primefaces.

I'm using primefaces 3.5 and jsf 2.2;

My dataTable and commandlink are following:
<p:dataTable id="tableTemp" binding="#{ledgerComplMB.tableTemp}" value="#{ledgerComplMB.listaTemp}"
         var="q" emptyMessage="No Registry" paginator="true" rows="10"
         rowsPerPageTemplate="10,50,200,500"
         paginatorTemplate=" {CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
         scrollable="true" scrollWidth="100%" scrollRows="10"
         filteredValue="#{ledgerComplMB.listaTempFilter}"
         filterDelay="1500" resizableColumns="true" editable="true">

<f:facet name="header">
    <p:commandButton id="btGravar" icon="ui-icon-disk"
                     value="Write data" actionListener="#{ledgerComplMB.gravar}"
                     disabled="${empty ledgerComplMB.listaTemp}" style="width:200px;"  />

    <p:commandButton id="btLimpar" value="Clean data"
                     actionListener="#{ledgerComplMB.limpar}" icon="ui-icon-trash"
                     disabled="${empty ledgerComplMB.listaTemp}"
                     style="width:200px;font-weight: bold;margin-left: 20px"/>

    <br />
    <h:outputText
        value="Total: #{fn:length(ledgerComplMB.listaTemp)}"
        rendered="#{not empty ledgerComplMB.listaTemp}" />
</f:facet>

<p:ajax event="rowEdit"
        oncomplete="dlgConfirma.show()" update=":form:dialogConfirmacao" />

<p:column exportable="false" style="width:30px">
    <p:rowEditor />
      </p:column>

<p:column filterBy="#{q.ledger.accountNumber}" filterMatchMode="exact"  style="width:100px">
    <f:facet name="header">AccountNumber</f:facet>
    <h:outputText value="#{q.ledger.accountNumber}" />
</p:column>

<p:column filterBy="#{q.ledger.vendor}" filterMatchMode="exact" style="width:100px">
    <f:facet name="header">Vendor</f:facet>
    <p:cellEditor>
        <f:facet name="output">
            <h:outputText value="#{q.ledger.vendor}" />
        </f:facet>
        <f:facet name="input">
            <p:inputText value="#{q.ledger.vendor}" />
        </f:facet>
    </p:cellEditor>
</p:column>

</p:dataTable>

<p:commandLink id="exp1" ajax="false">
      <p:graphicImage library="img" name="pdf.png" />
<p:dataExporter type="xlsx" target="tableTemp" fileName="#{ledgerComplMB.retornaDataExport}"  />

When I request the export only the header values appear.

A:

The only solution that I've found  is to make your own class that extends Exporter and to override method
protected String exportValue(FacesContext context, UIComponent component).
You should only add to existing code following lines:
else if (component instanceof CellEditor) {
 return exportValue(context, ((CellEditor) component).getFacet("output"));
}

That happens because CellEditor is not exportable. I haven't check if it is still an issue in PrimeFaces 4.0.
This was repported as an issue issue4013 by BalusC
In case of export to Excel file here is what I wrote and it workse (this is in class that extends ExcelExporter):
@Override
protected String exportValue(FacesContext context, UIComponent component) {
        if (component instanceof HtmlCommandLink) { // support for PrimeFaces
                                                    // and standard
                                                    // HtmlCommandLink
            HtmlCommandLink link = (HtmlCommandLink) component;
            Object value = link.getValue();

            if (value != null) {
                return String.valueOf(value);
            } else {
                // export first value holder
                for (UIComponent child : link.getChildren()) {
                    //if (child instanceof ValueHolder) {
                        return exportValue(context, child);
                    //}
                }

                return "";
            }
        } else if (component instanceof CellEditor) { // Handle in-cell editable datatables
            return exportValue(context,
                    ((CellEditor) component).getFacet("output"));
        } else if (component instanceof ValueHolder) {

            if (component instanceof EditableValueHolder) {
                Object submittedValue = ((EditableValueHolder) component)
                        .getSubmittedValue();
                if (submittedValue != null) {
                    return submittedValue.toString();
                }
            }

            ValueHolder valueHolder = (ValueHolder) component;
            Object value = valueHolder.getValue();
            if (value == null)
                return "";

            // first ask the converter
            if (valueHolder.getConverter() != null) {
                return valueHolder.getConverter().getAsString(context,
                        component, value);
            }
            // Try to guess
            else {
                ValueExpression expr = component.getValueExpression("value");
                if (expr != null) {
                    Class<?> valueType = expr.getType(context.getELContext());
                    if (valueType != null) {
                        Converter converterForType = context.getApplication()
                                .createConverter(valueType);

                        if (converterForType != null)
                            return converterForType.getAsString(context,
                                    component, value);
                    }
                }
            }

            // No converter found just return the value as string
            return value.toString();
        } else {
            // This would get the plain texts on UIInstructions when using
            // Facelets
            String value = component.toString();

            if (value != null)
                return value.trim();
            else
                return "";
        }

}


Q:

Apostrophe CMS + apostrophe-external-notifications: How to implement support for a new event

I want to send Slack notifications from my CMS on every 'Submit' event. I successfully got the existing events to fire off in Slack but when I included the following code in the node modules package for apostrophe-external-notifications as follows, I do not receive any notifications.
     self.notifyOn('apostrophe-workflow:afterSubmit', (req, submit) =>
    ['{user} submitted the {type} {title} which has these tags: {string}.', submit.from, submit.from, submit.from.tags]
  );

A:

afterSubmit is not a server event that apostrophe-workflow emits at the moment. There's only a browser event, workflowSubmitted, from that action.
Update 2020-03-05: This event was added as of apostrophe-workflow@2.32.0.


Q:

How can i prevent timer skips my asp.net online exam project when multiples user login at a time?

My problem is that I'm using a timer in my asp.net online exam website.
One user logins to attempt to test my timer reducing the time value work as expected but multiple users attempted to the test that time my timer has skipping the ticks and its goes very fast. I don't know what the reason is
My code.cs is
protected void timer1_tick(object sender, EventArgs e)
{
    if (TimeAllSecondes > 0)
    {
        TimeAllSecondes = TimeAllSecondes - 1;
        if (TimeAllSecondes < 0)
        {
            Session["endtime"] = DateTime.Now;
            //Session["SubjectID3"] = txtsubid.Value;
            //Session["SubjectName3"] = txtsubname.Value;
            mcqmethod.update_astatus(Convert.ToString(Session["empid"]), Convert.ToInt32(Session["EXAMID"]));
            Response.Redirect("~/MCQ/students/s_thankyou.aspx");

        }
    }

    TimeSpan time_Span = TimeSpan.FromSeconds(TimeAllSecondes);
    hh = time_Span.Hours;
    mm = time_Span.Minutes;
    ss = time_Span.Seconds;
    lblTimer.Text = " Your exam time is remaining :  " + hh + ":" + mm + ":" + ss + "[H:M:S]";
}

<asp:Timer ID="timer1" runat="server" Interval="1000" OnTick="timer1_tick" ></asp:Timer>

This is the method define
static double TimeAllSecondes;

public void getexam()
{
    DataTable dt = new DataTable();
    dt = mcqmethod.getexambysub(Convert.ToInt32(Session["EXAMID"]),Convert.ToString(Session["empid"]));
    lblsubject.Text = Convert.ToString(dt.Rows[0]["subname"]);
    lbltime.Text = Convert.ToString(dt.Rows[0]["etime"]);
    noofquestion = Convert.ToInt32(dt.Rows[0]["t_n_q"]);
    Session["ExamDate"] = dt.Rows[0]["e_date"];
    Session["examtime"] = Convert.ToString(dt.Rows[0]["etime"]);//Minutes of exam
    DateTime examdate = Convert.ToDateTime(Session["ExamDate"]);//date of exam
    DateTime  endexam = examdate.AddMinutes(Convert.ToDouble(Session["examtime"]));

    Session["starttime"] = DateTime.Now;
    TimeSpan remingtime = endexam.Subtract(DateTime.Now);
    TimeAllSecondes = remingtime.TotalSeconds;
    Session["noq"] = Convert.ToInt16(dt.Rows[0]["t_n_q"]);
    btnprev.Visible = false;
}

A:

You shouldn't use static fields inside an asp.net application for something that is user specific since they're shared across all users.1
Likewise, you cannot use instance fields since page instances only last the lifetime of a single request/response lifecycle.
What you want is something that is isolated to a single user and has a lifetime length the same as the time the user spends on your site.
That's ASP.Net Session State, and that's where you should store your TimeAllSecondes value.

1This glosses over lots of instances where they will appear to lose their state also, such as when an application pool recycles or when you're running multiple instances of your process. But in short, they don't have the right isolation and lifetime semantics.


Q:

Problems with using fontawesome icons as background on

As title says, I want to have font-awesome icon as a background on my <input> element. For some reason it's not working. My code is:
HTML:
<input class="mod mod-inp inp-alr" placeholder="This is an alert"/>

CSS:
.mod-inp {
    position: relative;
}

.mod-inp:before {
    content: "\f000";
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    text-decoration: inherit;
    color: #000;
    font-size: 18px;
    padding-right: 0.5em;
    position: absolute;
    top: 0;
    left: 10px;
}

A:

HTML elements like input and img are considered empty. There is no content in them, and therefore they cannot have :before or :after attributes as there's nothing to wrap.
What you may consider is using a <label> in your code, like this:
<label class="mod-inp"><input type="text" /></label>
and applying the icon to the label. That way, clicking on the label/icon will still give focus to the child input element.


Q:

Switches not changing state in Java

I'm trying to write code which will oscillate the set_player between 2 states of player1.name and player2.name, I have written the following code with val = 0 when it is initialised, inside a while loop. set_player never seems to change state and stays at player2.name the whole time. Any help would be great.
switch (val){
                case 0:
                    set_player = player1.name;
                    val = 2;
                case 1:
                    set_player = player1.name;
                    val = 2;
                case 2:
                    set_player = player2.name;
                    val = 1;
            }

A:

You are missing break statements. Without breaking after each case, case 2 will always execute if val is either 0, 1 or 2. Therefore set_player ends up being assigned  player2.name.
        switch (val){
            case 0:
                set_player = player1.name;
                val = 2;
                break;
            case 1:
                set_player = player1.name;
                val = 2;
                break;
            case 2:
                set_player = player2.name;
                val = 1;
                break;
        }


Q:

When fitting ideals determine the module?

Let $M$ be a module over a local ring $(R,m)$, everything is finitely generated/presented. The fitting ideals, $I_j(M)$ carry a lot of information about the module. When do they actually determine the module?
For example, there is no hope for a positive answer unless the ring is local or graded. And the fitting ideals do determine the module over PID.
What is known about other cases? (at least, for regular local rings, for Gorenstein rings of low dimensions, for Cohen-Macaulay modules...)
Any strengthening of such "fitting type" invariants that determines the module?
upd. In view of W.Sawin's example, probably one should assume the module to be Cohen-Macaulay. Or, at least, some "purity" conditions on the support of $M$. For me the most interesting case is a Cohen-Macaulay module over hypersurface singularity. (alternatively, a module over a local ring, whose minimal presentation is a square matrix)
upd2. Well, the simplest example is: given $M$, let $A$ be its presentation matrix, i.e. $M=coker(A)$. Then  $coker(A)$ and $coker(A^T)$ have the same fitting ideals, though the modules are non-isomorphic in general

A:

This should never really work in dimension at least two.
Let $x$ and $y$ be linearly independent elements of $m/m^2$.
Consider the modules $R^2/(ya-xb)$ and $R\oplus R/(x,y)$. They both have the same fitting ideals $I_0(M)=0$, $I_1(M)=(x,y)$, $I_2(M)=1$. These modules are nonisomorphic because the kernels of the map $M \otimes R/m^2 \to M \otimes R/m$ have different dimensions as vector spaces over $R/m$ because there is a different number of relations, $1$ in the first case and $2$ in the second.


Q:

OAuth in google app engine

I am trying to implement Oauth in google app engine on python. For my application i am using gae sessions and my model to authenticate users. It will be more helpful for me. .If you could provide some examples..

A:

You might want to check out the following resources:
The App Engine OAuth Library, which has support for Dropbox, Twitter, MySpace, and LinkedIn.
The Tipfy Framework (EDIT: links removed to the now defunct tipfy.org).
Using those as a basis, even if you can't use the libraries themselves, you'll have some solid, working examples of how to use OAuth on App Engine.

A:

here's an alternative that supports oauth 1.0, 2.0 and openid:
https://github.com/crhym3/simpleauth


Q:

Three-column variable width CSS page layout, centre column expands

There is a plethora of CSS column layout information, but it all seems to rely on at least some of the columns having a fixed width (or percentage) which the others can then be based off.
What I'm trying to accomplish is a three-column layout, with the left and right columns being variable width (they could have anything in them) but being stuck to the left and right respectively. The centre column then should expand to take up any remaining space between them. I.e. if the right column has nothing in it, the centre column would then expand to the right of the screen.
Here's a quick shop to demonstrate:

A:

If you don't mind to put the center element after left and right columns you could do something like this:

Just float the side elements, and for the middle one just add an overflow (could be hidden or scroll).
.left {
  float: left;
}

.right {
  float: right;
}

.center {
  overflow: hidden;
}

Here's the fiddle:


Q:

How to encrypt zip file on app engine blobstore

I have a problem how to encrypt compressed blobs of type zip. Because of some reasons I cannot use chilkat module, zipfile module provides only decryption, so I do not know what to use to encrypt zips with a key.
Could you please give me some suggestions how this problem is (could be) solved?
ideal solution would look something like this:
blob_info = blobstore.BlobInfo.all()[0] #lets say we want to read the first blob we find
blob_reader = blobstore.BlobReader(blob_info.key())

file = zipfile.ZipFile(blob_reader, 'r')
data = file.read(file.namelist()[0])

output = StringIO.StringIO()
outfile = zipfile.ZipFile(output, "w")

outfile.writestr(file.namelist()[0], data)
outfile.setpassword('testpass') #it would be nice if there was a module that could set pass like this, .setpassword() only works with decryption

outfile.close()

outputStream = files.blobstore.create(mime_type='application/zip', _blobinfo_uploaded_filename = file.namelist()[0].split('.')[0] + '.zip')
with files.open(outputStream, 'a') as f:
    f.write(output.getvalue())
files.finalize(outputStream)

A:

First of all, allow me to say that zip encryption is weak and obsolete. You shouldn't rely on it if you need a strong security. This has been proved on many papers (Google says that the most popular is "Known Plaintext Attack on the PKZIP Stream Cipher" by Eli Biham and Paul C. Kocher).
Second, GAE only works with libraries that are pure python. Probably you can't use chilkat because it is a C library.
Third, zip file encryption/decryption in pure python is going to be slow as hell, and probably you'll have CPU problems with GAE...
Perhaps you should look into another way to do this?
Regards


Q:

Property Not Found On Type

I'm trying to use this in JSF to dynamically show the title of a page.
<h:panelGroup rendered="#{not empty searchBean.fsResultsTitleOne}"><h2>#{msgs.fireStudySearchTitle}</h2></h:panelGroup>

And I'm getting this error:
rendered="#{not empty searchBean.fsResultsTitleOne}": Property 'fsResultsTitleOne' not found on type

However, I did define it in on the type like this:
private String fsResultsTitleOne;
public String getFSResultsTitleOne(){return fsResultsTitleOne;}
public void setFSResultsTitleOne(String newValue){fsResultsTitleOne = newValue;}

And set it to something:
setFSResultsTitleOne("I'm not Empty!");

And even used this to make sure it would be set:
System.out.println("This is the FS Results Page Title: " + fsResultsTitleOne);

And it seems to be working:
This is the FS Results Page Title: I'm not Empty!

Am I setting it wrong someplace?

A:

Change
getFSResultsTitleOne
setFSResultsTitleOne

to
getFsResultsTitleOne
setFsResultsTitleOne


Q:

Server-sided timestamp with AWS DynamoDB V2 when using an IoT Core Action?

I'm currently using the IoT Core action to store some JSON Data in a DynamoDB table. Everything works fine, the only problem is, that everything is stored in one column (payload in my case).
I found out that when using the DynamoDB V2 action every Key-Value pair of my JSON input will be stored in a separat column. I was also able to implement this.
But now I have the problem that I'm not able anymore to create the timestamp column which could be defined when using DynamoDB V1. There I could just say that my secondary key is a timestamp and with the function timestamp() it will automatically create a server-sided timestamp of each input.
As there is no option like this when using the Version 2 I was wondering if there is a way to add a column with a timestamp to input that comes through the IoT Core MQTT gateway?
I think I could go the lambda-path and trigger a function which writes each input to the V2 to DynamoDB but I try to avoid this as I will have a huge amount of data coming through.
If you have any thoughts or ideas I would be pleased to hear them.
Cheers,

A:

This can already be done with the DynamoDB V2 action by using the SELECT clause of the IoT rule.
The keys that it uses when writing to DynamoDB can come from the payload and/or the SELECT Clause of the IoT rule. So the timestamp() function can be used to automatically create a server-side timestamp.
e.g. setup a rule such as:
SELECT *, timestamp() AS Timestamp FROM 'mytopic/#'

The DynamoDB V2 action writes into a table with the primary key:
Primary partition key    Id (String)
Primary sort key         Timestamp (Number)

In this example the Id field comes from the payload and is the partition key. The timestamp() function is the server-side timestamp that is the sort key.
So publishing to a topic with this payload:
{
  "message": "Hello from AWS IoT console",
  "value": "101",
  "Id": "2"
}

Will create items using the Id in the payload and the Timestamp from the timestamp() function.


Q:

Xcode 9.3 - NSPredicate Bool crash

After the Xcode 9.3 update, I've noticed that if you want to have Predicate like this:
let predicate = NSPredicate(format: "preferred = %@", true as CVarArg)

You have a crash. But in Xcode 9.2 this wasn't a problem. Any idea?

A:

// Solution 3 [ Apple Documentation ]
let predicate = NSPredicate(format: "preferred == TRUE")

The exception occurs because true is not an object (%@). You need the %d placeholder
let predicate = NSPredicate(format: "preferred = %d", true)


Q:

Find the number of group isomorphisms from the group $(\mathbb{Z}_3, +)$ to itself.

I have to find the number of isomorphisms from the group $( \mathbb{Z}_3, + )$ to itself.
I don't know of any procedure to do this so I basically just tried to guess functions until I cannot find anything else. I found that the functions:
$$f(x) = x$$
$$f(x) = \hat{2}x$$
are both bijective and they hold the equality:
$$f(x + y) = f(x) + f(y)$$
true for any $x, y \in \mathbb{Z}_3$. So I concluded that these are all the isomorphism from the group $(\mathbb{Z}_3, +)$ to itself, since I couldn't find any more functions to be bijective and satisfy that condition.
I checked the answer of the exercise and it agrees with me, saying that the correct answer is $2$ (meaning $2$ isomorphisms, I guess the ones I found).

My question is this: Is there a more organized, general way of finding the answer to this question.

Guessing all the possible function seems a bit weird, there are infinite possibilities.
How do I know that I found the maximum number of isomorphisms and that I can stop? Is there a better strategy than guessing the functions and coming up with the answer?

A:

There aren't an infinite number, for it to be a bijection, you have $3$ choices for $f(0)$, $2$ choices for $f(1)$, and then $f(2)$ is determined.
That is, your choices are
$f(0), f(1), f(2)  = 0,1,2$
$f(0), f(1), f(2)  = 0,2,1$
$f(0), f(1), f(2)  = 1,0,2$
$f(0), f(1), f(2)  = 1,2,0$
$f(0), f(1), f(2)  = 2,0,1$
$f(0), f(1), f(2)  = 2,1,0$
and then not all of these will respect the group operation, e.g. for $f(0), f(1), f(2)  = 2,1,0$, you have $f(0 + 1) = f(1) = 2$, but $f(0) + f(1) = 2 + 1 = 0$.
This is still a little brute force, but by observing, e.g. that $f(0) = 0$ is true for any group isomorphism, you narrow things down even more.


Q:

Running SQL in Python and apply parameters from Python Dataframe

I'm loading some data from SQL database to Python, but I need to apply some criteria from Python Dataframe, to be simplified, see example below:
    some_sql = """
               select column1,columns2
               from table
               where a between '{}' and '{}'
                    or a between '{}' and '{}'
                    or a between '{}' and '{}'
              """.format(date1,date2,date3,date4,date5,date6)

date1,date2,date3,date4,date5,date6 are sourced from Python Dataframe. I can manually specify all 6 parameters, but I do have over 20 in fact...
     df = DataFrame({'col1':['date1','date3','date5'],
                     'col2':['date2','date4','date6']})

is there a way I am able to do a loop here to be more efficient

A:

Setup
# Create a dummy dataframe
df = pd.DataFrame({'col1':['date1','date3','date5'],
                   'col2':['date2','date4','date6']})

# Prepare the SQL (conditions will be added later)
some_sql = """
select column1,columns2
from table
where """

First approach
conditions = []
for row in df.iterrows():
    # Ignore the index
    data = row[1]
    conditions.append(f"or a between '{data['col1']}' and '{data['col2']}'")

some_sql += '\n'.join(conditions)

By using iterrows() we can iterate through the dataframe, rows by row.
Alternative
some_sql += '\nor '.join(df.apply(lambda x: f"a between '{x['col1']}' and '{x['col2']}'", axis=1).tolist())

Using apply() should be faster that iterrows():

Although apply() also inherently loops through rows, it does so much
  more efficiently than iterrows() by taking advantage of a number of
  internal optimizations, such as using iterators in Cython.

source
Another alternative
some_sql += '\nor '.join([f"a between '{row['col1']}' and '{row['col2']}'" for row in df.to_dict('records')])

This converts the dataframe to a list of dicts, and then applies a list comprehension to create the conditions.
Result
select column1,columns2
from table
where a between 'date1' and 'date2'
or a between 'date3' and 'date4'
or a between 'date5' and 'date6'


Q:

Как может существовать одновремено две верхних/нижних границы у множества?

Читаю определение в вики:

Точной (наименьшей) верхней гранью (границей), или супре́мумом (лат. supremum — самый высокий) подмножества {\displaystyle X} X упорядоченного множества (или класса) {\displaystyle M} M, называется наименьший элемент {\displaystyle M} M, который равен или больше всех элементов множества {\displaystyle X} X. Другими словами, супремум — это наименьшая из всех верхних граней. Обозначается {\displaystyle \sup X} \sup X.

Но как может быть несколько верхних граней одновременно?

A:

Читайте внимательнее определение верхней (и нижней) границы. Например, для множества { 1, 2, 3 } значения 3, 42, 100500 являются верхними границами.
И таких верхних границ можно напридумывать бесконечно много. Точной верхней границей является только 3.


Q:

Strip a newline and add more text to a Go bytes.Buffer

I wrote a little timer middleware to append the request duration to the end of the log message returned by the excellent Gorilla Toolkit's CombinedLoggingHandler from the handlers package.
That handler accepts an io.Writer and an http.Handler, and fills the Writer with a newline-terminate string containing the Apache Combined Format log entry for the current server request. I would like to remove the trailing newline and add " completed in xxx", where xxx is the amount of time the request took.
The following code works, but I am not sure that I made the best use of the Go bytes.Buffer in the way I stripped the newline:
func timerHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        var b bytes.Buffer
        hand := handlers.CombinedLoggingHandler(&b, h)

        defer func(start time.Time) {
            prefix := bytes.TrimRight(b.Bytes(), "\n")
            os.Stdout.Write(prefix)
            fmt.Printf(" completed in %v\n", time.Since(start))
        }(time.Now())

        hand.ServeHTTP(res, req)
    })
}

Is there a better way to write this in Go?

A:

I believe you are over-complicating the handler function by introducing the deferred function with the start time closure. Additionally, you are performing 2 writes to accomplish the logging, when one would be better.
So, Why have the "defer"? This code:

    var b bytes.Buffer
    hand := handlers.CombinedLoggingHandler(&b, h)

    defer func(start time.Time) {
        prefix := bytes.TrimRight(b.Bytes(), "\n")
        os.Stdout.Write(prefix)
        fmt.Printf(" completed in %v\n", time.Since(start))
    }(time.Now())

    hand.ServeHTTP(res, req)

would be simpler to understand as:
    start := time.Now()
    var b bytes.Buffer
    hand := handlers.CombinedLoggingHandler(&b, h)

    hand.ServeHTTP(res, req)

    prefix := bytes.TrimRight(b.Bytes(), "\n")
    os.Stdout.Write(prefix)
    fmt.Printf(" completed in %v\n", time.Since(start))

Then, in addition, I would manipulate the bytes to trim and add the completion message, and then output them...., so I would change the last part of the code to be something like:
    msg := bytes.TrimRight(b.Bytes(), "\n")
    msg := append(msg, []byte(fmt.Sprintf(" completed in %v\n", time.Since(start)...)
    os.Stdout.Write(msg)

That still irks me a bit, because i don't like the os.Stdout.Write being a constant value in there.... I would make that a parameter somehow, or a constant of some sort....
var logDest io.Writer = os.Stdout


Q:

Is there a way to import a .txt file into a workbook from another workbook?

So i have a workbook A that create a .txtfile and i was wondering if there's a way to import that .txtfile to workbook B? I need to import the .txtfile into workbook B because the workbook B have a sheet that contain a table that need to be fill with the data in the .txtfile.
So is it possible to do so while working in workbook A?
so all from workbook A:   WB A = `.txt' -> WB B

A:

Depending on how your .txt table is formatted, change semicolon:=true to another delimiter.
    Workbooks.OpenText Filename:=Insert path here, DataType:=xlDelimited, local:=True, semicolon:=True

        'Code to copy the contents of the .txt file to your table

    ActiveWorkbook.Close SaveChanges:=False


Q:

apt-get hangs on Setting up grub-pc

Yesterday I did my usual
apt-get update
apt-get upgrade

Everything went fine until it hit
Setting up grub-pc (2.02-2ubuntu8.12) ...

where it became unresponsive. I ended up killing the process and trying to fix it with
dpkg --configure -a

but the same thing happens. If I recall correctly from previous upgrades, grub-pc brings up a text based GUI on the terminal that lets you select some parameter before continuing the process. I suspect the reason it hangs is because it's waiting for me to select something, but I have no way of doing it because the menu never shows up. Does anyone have any idea what may be causing this? I'm afraid of rebooting my computer now. My computer is running Ubuntu 18.04.2 LTS.

A:

Unfortunately I did not find out what was causing the issue, but I did manage to effectively fix the problem. If you're at the stage where apt is stuck, I've found the only way to kill the process is to kill the terminal session. This will leave stale lock files that I removed by hand. I'm almost certain there is a smarter way to go about this, but nothing else I tried worked. You can try your luck with dpkg --configure -a but in my case I had to terminate that process as well because it hangs the same way apt does. Just in case I ran ps -aux | grep dpkg and killed every associated process.
In my desperation I risked rebooting the computer, which ended up also hanging on the very last step, which I saw by hitting esc on the reboot splash screen. I ended up holding down the power button for a hard reset. Booting up the computer worked fine though, and rerunning dpkg --configure -a worked after the reboot, allowing me to finish the configuration for grub-pc.
I have since run apt-get upgrade and apt-get dist-upgrade. Rebooting the machine after this went smoothly, and everything appears to be fine now.


Q:

How to convert shape file x, y coordinate to lat long in php

Hello I am working with shape file in my yii2 project. I have created function to upload and read shape files. (.shp, .shx, .dbf).
I am getting data like :

In above image I am getting x and y cordinate. From it how can i get lat and long ?
I need to save this in database and display in map.
How to convert x and y to lat and long in php.

A:

The x coordinates are the latitudes and y coordinates are the longitudes. There is no need to convert these unless you want to work with a coordinate system that doesn't use decimal degrees.


Q:

$G$ is bipartite $\Leftrightarrow$ $\forall H$, $H$ is sub-graph of $G$ $\Rightarrow$ $\alpha(H) \ge \frac{|H|}{2}$

$G$ is bipartite $\Leftrightarrow$ $\forall H$, $H$ is sub-graph of $G$ $\Rightarrow$ $\alpha(H) \ge \frac{|H|}{2}$, where $\alpha(H)$ is the vertex independence number of $H$
Give some clue please!
Thanks anyway!

A:

Since this is homework, I will not give a full solution but rather a series of hints.
The forward direction is rather simple:

If the graph is bipartite then there is a bipartition of the vertices.
What can you say about the vertices of each bipartition?
How large is the largest bipartition?
Is each subgraph bipartite?

For the backward direction:

If a graph satisfies
$$\alpha(H) \ge \frac{|H|}{2},\ \forall H\subseteq G$$
then can it have odd cycles?
What is the size of a maximally independent vertex set in an odd cycle?
Is a graph without odd cycles necessarily bipartite?

I will  offer additional hints if you need them, but only if you make a serious effort and show me some of the progress you've made. Good luck!


Q:

Are all reference types class types in C#?

Is there any reference type in C# which is not a class? does the constraint in following generic, include all reference types?
static void f<T>() where T : class
{
    T t = default;
    Console.WriteLine(t);
}

A:

You are asking 2 different questions

Are all reference types class types in C#?

No

does the constraint in following generic [where T : class], includes all reference
  types?

Yes, it will constrain all reference types

Firstly, lets determine what a reference type actually is.
Reference types (C# Reference)

There are two kinds of types in C#: reference types and value types.
  Variables of reference types store references to their data (objects),
  while variables of value types directly contain their data.
The following keywords are used to declare reference types:

class
interface
delegate

C# also provides the following built-in reference types:

dynamic
object
string

Note : Not mentioned above, Array types are also reference types derived from the abstract base type Array
Secondly, lets work out what the class constraint constrains
Constraints on type parameters (C# Programming Guide)

where T : class
The type argument must be a reference type. This constraint applies
  also to any class, interface, delegate, or array type.

Note : Not mentioned above, the class constraint also includes dynamic

As a Bonus fact, since C# 7.3 you can also explicitly constrain by delegate
Delegate constraints

Also beginning with C# 7.3, you can use System.Delegate or
  System.MulticastDelegate as a base class constraint. The CLR always
  allowed this constraint, but the C# language disallowed it


Q:

Force horizontal expansion

For a sort of thumbnail horizontal sliding viewer
How can I make the divs inside the horizontal scrolling divs force the scrolling div horizontally, instead of reaching the end and starting a new line?
I am already using float: left and display: inline-block but they reach the end of their container and make a new line instead of forcing the container to expand horizontally to fit them and thus forcing the horizontal scrollbar to be needed
so the div boxes are force to do this:
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
      <---->scroll

instead of:
[ ][ ][ ][ ]
[ ][ ][ ][ ]

code:

.box{
    width: 100px;
    height: 100px;
    border: solid 1px black;
    float:left;
    display: inline-block;
}

A:

You don't need float and display:inline-block, and floats won't do it.. so you have to remove the float rule, (add a workaround for IE7 and below *) -  When float is present browsers ignore the display property
.box{
    width: 100px;
    height: 100px;
    border: solid 1px black;
    display: inline-block;
}

.box {display: inline !ie7;} /* to make it work in IE7 and below */

with white-space: nowrap on the inner div

etc..


Q:

How much does it cost to build or rent a building?

A player playing a Paladin in my current D&D campaign has asked how much it would cost to build or rent a building to house his followers from the Leadership feat. It would only be a small premises, enough to house a handful of followers, but it'd need to be able to be upgraded should the need arise.
I applaud the players thinking around this so I'm going to allow it – I just haven't a clue how much this should cost. How much should I charge the player for building a new premises for this purpose and how long should it take to build in-game? Also, if a building were rented, what would be an appropriate weekly charge?

A:

The 3.5 Dungeon Master's Guide contains a small table on building costs. Page 101.
But, for detailed guidelines on how to handle character-made buildings in 3E (including detailed cost and construction time rules), refer to the Stronghold Builder's Guidebook. It is a 3.0 book, but requires minimal updating.
As far as renting goes... you could calculate the building's cost, and decide on a PE Ratio (price-rent ratio in real estate) to get some kind of a guideline on how much you should be charging. D&D economics are not exactly fleshed out, though (and they probably shouldn't be), so you have a lot of freedom here.

A:

The economic systems in D&D3+ strongly emphasize game balance over realism. The reward system is tightly tied to character level, and the pricing system is tied to combat and adventuring value. To avoid equipment and power imbalances, it's a good idea to keep utility items relatively cheap, even though something like a keep might realistically cost much more. To address realism concerns, you can use a grant from the local rulers to offset the cost of the keep. You could even provide a stronghold at no monetary cost to the paladin – perhaps he could swear loyalty to the local lord instead. That way you pay for a primarily role-playing benefit with a role-playing cost.


Q:

Using CheckButtons to modify functions in tkinter for python 3x

I want to build a simple dice rolling app (personal project to get better with python) in which the user can select whether to roll a 6 or 20 sided dice using tkinter.
Basically, there should be 4 widgets:
a label (to print the result)
a button (to run the dice rolling function)
and 2 checkboxes (to select which dice to roll)
so the code I have tried looks like this.
from tkinter import *
import tkinter as tk
import random

window = tk.Tk()

def roll():
    if var1 == 1:
        print("your result is " + str(random.randint(1,6)))
    elif var2 == 1:
        print("your result is " +  str(random.randint(1,20)))
    label = tk.Label(canvas, text = roll(), width = 20, font = 40,
                 height = 1)
    label.place(relx=.5, rely = .2,  anchor='n')

var1 = IntVar()
var2 = IntVar()

canvas = tk.Canvas(window, height = 600, width = 300, bg = 'blue').pack()

C1 = Checkbutton(canvas, text = "6", variable = var1.get(),
                 onvalue = 1, offvalue = 0, height=1,
                 width = 10)
C1.place(relx = .01, rely = .7)

C2 = Checkbutton(canvas, text = "20", variable = var2.get(),
                 onvalue = 1, offvalue = 0, height=1,
                 width = 10)
C2.place(relx = .5, rely = .7)

btn = tk.Button(canvas, text = 'roll dem bones!', command = lambda:
                roll())
btn.place(relx = .5, rely = .9)

window.mainloop()

I have two problems so far.
1: when I click either CheckButtons a tick appears in both, meaning both are getting activated (this is probably something I can fix just by getting better with tkinter, but if you spot the problem I'd appreciate the advice.
2: when I click the button I get the error "RecursionError: maximum recursion depth exceeded in comparison".
I think the issue is that I just can't get my head around calling functions in this way with tkinter. I'm actually using this as an exercise to build a more complex RPG app to use with some friends where you would choose the attribute bonus to add to a D20 roll, but I wanted to try something that was more simple without the rest of the app in the code.
The python community so far has been the most helpful and least dismissive of all the coding groups I've sought help from so thanks in advance for the help.
Kev.

A:

There are many things wrong with your code, but let's just focus on the questions you asked. The first problem comes from your mis-use of IntVar: you created two IntVar, but you set the variable of your Checkbuttons to var1.get(). get is only a method to return the value set to your IntVar. To correctly associate the variables:
C1 = Checkbutton(canvas, text = "6", variable = var1,
                 onvalue = 1, offvalue = 0, height=1,
                 width = 10)

Same for the other Checkbutton.
Next, the error comes from your function roll. You created a label with text=roll(), which executes the roll function again, and then also executes itself again... which results in your maximum recursion error.
To properly fix only the roll part, you can define another function which returns the result within roll:
def roll():
    def get_result():
        if var1.get() == 1:
            return "your result is " + str(random.randint(1,6))
        elif var2.get() == 1:
            return "your result is " +  str(random.randint(1,20))
    label = tk.Label(canvas, text = get_result(), width = 20, font = 40,
                 height = 1)
    label.place(relx=.5, rely = .2,  anchor='n')

Notice that I have changed if var1 == 1: to if var1.get() ==1: as explained earlier.
You still have other problems like stacking new labels upon each click, redundant use of lambda function, the variable canvas being set to None... but I'll leave those for you to fix by yourself.


Q:

JPA - Reload @OneToMany dependencies automatically

I have this scenario:
public abstract class AbstractEntity {
    @Id @GeneratedValue(strategy = GenerationType.TABLE)
    protected Long id;
}

public class User extends AbstractEntity {
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Dependent> dependents;
}

public class Dependent extends AbstractEntity {
     @ManyToOne
     @JoinColumn
     private User user;
}

When I try to insert() a new User instance with some Dependent's that already are present in database, what means they have the id field populated, I get a Detached entity passed to persist exception.
It can be solved by manually loading all the Dependents from database, but it don't look right.
I would like to know how to make JPA automatically load them when id field is populated. How can I do that?

A:

If you are using JPA API use:
EntityManager.merge(T t)

instead of
EntityManager.persist(Object object)

Since you are using CascadeType.ALL, when you use merge, the JPA Provider will try to update the Users (in case they exists in database) or will create new ones.
Documentation: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html.


Q:

jQuery to select elements based on the text inside them

How to select a tag having a specific text inside it and nothing else? For example if I have the following:

       Assets	Asset

       Play	Players	Plays

Is there any way that I may select the Asset	 and nothing else. I tried it with contains i.e. $("table tr td:contains(Play)") but it returns all the tds in the second tr (as it should). Whereas I just want Play	.
Is there any way to achieve this, like there's a way to select elements based on their attributes. Is there any way to select elements based on the text inside them?

A:

How about that:
var lookup = 'Asset';
$('td:contains('+ lookup +')').filter(function() {
    return $(this).text() === lookup;
});

Demo
Try before buy


Q:

How to make tinyMCE content for ASP.Net MVC as XHTML strict?

How to make tinyMCE editor content of ASP.Net MVC page to XHTML strict?

A:

A simple google search turns up this detailed article:
http://www.gethifi.com/blog/how-to-produce-xhtml-10-strict-markup-with-tinymce
Did you try that already?


Q:

Android create new thread in service class

I created a service class and now I'am trying to run a new thread in this class. Service is started in my MainActivity and this works well. The first Toast.Message in the onCreate() section shows up, but the message in my thread runa() doesn't come up. Thought that it should work with a new Runnable().
public class My Service extends Service {
    private static final String TAG = "MyService";
    Thread readthread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); //is shown

        readthread = new Thread(new Runnable() { public void run() { try {
            runa();
        } catch (Exception e) {
             //TODO Auto-generated catch block
            e.printStackTrace();
        } } });

        readthread.start();

        Log.d(TAG, "onCreate");

    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

    }

    @Override
    public void onStart(Intent intent, int startid) {

        //Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();

        //Log.d(TAG, "onStart");

    }
    public void runa() throws Exception{

        Toast.makeText(this, "test", Toast.LENGTH_LONG).show(); //doesn't show up

    }
}

Would be nice if anyone could help me:)

A:

The Thread that you are creating, will not be executed on the MainThread, thus you can not show a Toast from it. To display a Toast from a background Thread you will have to use a Handler, and use that Handler to display the Toast.
private MyService extends Service {
    Handler mHandler=new Handler();
    //...

    public void runa() throws Exception{
        mHandler.post(new Runnable(){
            public void run(){
                Toast.makeText(MyService.this, "test", Toast.LENGTH_LONG).show()
            }
        }
    }
}

This would be the solution for your exact problem, although I don't consider it a good 'architecture' or practice as I don't know exactly what you want to achieve.


Q:

Как заменить все символы в строке кроме первого и последнего?

Есть фраза - "ПРЫГНИСЮДА". Как написать запрос, чтобы выдавалось П********А?
Писал через:
regexp_replace('ПРЫГНИСЮДА', '.' , '*', 2)

Но не могу понять, как написать на регулярке до последнего символа в строке.

A:

SELECT regexp_replace( 'hellllow', '(^\D{1})(.*)(\D{1}$)', '\1**********\3' ) example FROM dual;
Результат: h**********w