text:
Q: PHP/MySQL Update database on session timeout I'm working on a "flash website". In this program, I'd like to add an "Online Users" list, which relies on sessions: A session is started when a user logs in, and the user is marked as Online in the database. As soon as the logs out or closes the browser, the user is marked as Offline in the database.
I know that running some functions when the browser is closed will require Javascript, and it's not safe either: If the browser were to crash, the functions wouldn't run. That's why I've settled for the database updating if the user logs out or if the user's session times out.
I've been looking up session timeouts, and ran into this, along with many others like it marked as duplicates: How do I expire a PHP session after 30 minutes?
The problem with the answer's method is; It's a conditional sentence that checks if the user's last activity was X seconds ago, and if there was no activity, it times out. Useful in some websites, but useless for the Online Users list, since it updateds when a new request is sent, and since there won't be any requests after the user closes the browser.
Also mentioned in other answers is the use of session.gc_maxlifetime and session.cookie_lifetime, but the Best answer states that using them is a bad idea; One doesn't destroy the session, just the cookies, and the other is "cost-intensive".
What I want is the user to time out and the database to update and mark the user as Offline without using the If-Conditional sentence, or maybe with using a different If-conditional sentence that only has to be used once when the user logs in, like a timer or something, and whenever a request is sent, the timer restarts...those are just my ideas so far on how to solve this problem.
But, how do I do this? I'm sorry if the answer is something very simple and obvious, I'm very new to PHP.
Edit: Long Story Short:
I want to run a function after the user closes his browser, or is inactive for 20 minutes.
Clarification...
I want to update the database after 20 minutes of inactivity even if the browser has been closed.

A:
I want to update the database after 20 minutes of the browser being
  closed.

I don't think this is really possible to do with browsers being closed (reliably). If they click the logout button you can obviously run some code to mark the user as logged out. You can specify how long a session is good for with the functions you mentioned but all this does is makes the cookie be deleted on the client side, it doesn't trigger anything on the server side.
About the only thing you can do is track the time of the user's last activity and if they haven't had activity in a while assume they are gone. So just add a field to your user table and store a datetime or unix timestamp of their last activity. Then you can either run a cron job every few minutes that marks users as logged out or you can simply modify your SQL query to pull only users that have a last activity less than 20 minutes ago.

A: You can do this with the help of a online users table with last active field,
window.setInterval(function() {
    $.ajax({
      url: "http://yourdomain/updateLastactive/?uid=" + User_ID,
      success: function(data) {

      }
    });
}, 5000); // 5 seconds

This page will update the current time-stamp as last active for that user
Then on online users query you can do like below,
SELECT UID FROM ONLINE_USERS WHERE LAST_ACTIVE >  DATE_SUB(NOW(), INTERVAL 30 MINUTE));

A: if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
    // session started more than 30 minutes ago
    session_regenerate_id(true);    // change session ID for the current session an invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
}

Also read this
http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime

A: You want to catch the event by using the information here:
How to capture the browser window close event?
You will then need a page on the server that you call in that event handler with the sessionID.
That page calls a local script, page, or service that you set up to delay 20 minutes and expire the session.  If you want to restart the clock if the user revisites before expiration, you will need to include a way to interrupt or cancel that script's process and you will need to retain the SessionID in a cookie which will need to be looked for upon every page load. If the cookie's SessionID is found and matches, the timeout gets interrupted/stopped (if it's still going).  If it already completed, a new SessionID will need to be issued.
If you have a lot of these cancellations at the same time, you will instead queue them up on the server and have a process periodically check the queue and expire them as needed.
The way most sites avoid all this is to set a 30 minute or whatever session timeout that is enforced whether the visitor is active or not.

A: The easiest way to do this is to write a MySQL stored procedure that looks at the session timestamp and deletes the session data when it is > 20min old.   You can also do it as an external cron job, but a stored procedure would be better.
In addition, you need to refresh the session timestamp every time the user connects.
If you want to make sure you don't delete a session when the user still has your 'page' open, then some background JavaScript refresh to your site will function as a keep-alive.  Note that if the user closes the 'window' or 'tab', it will be the same as the whole browser being closed - I'm not sure you can do anything about this.
Of course, you to do this, you need to store your sessions in MySQL.
TL;DR

*

*MySQL stored procedure or cron job deletes session if session_timestamp > 20min

*Client-side Javascript does ajax refreshes to keep session open

*Session timestamp updated every time the 'page' is requested (browser or ajax).


text:
Q: Why must an inverse function be bijective? Explain why $f^{-1}$ is a function if and only if $f$ is a bijective function.
My attempt:
$f^{1}$ is the inverse relation from B to A $\equiv$ function from B to A
By definition of a function from setA to setB, there is a relation from setA to B. (ARB? relation) such that is satisfies two properties:
1) All element in the domain A must be related to some function in the codomain B
2) No element in A is related to more than one element in B.
Hence, that would mean that 1) the function must be onto and 2) the function must be one-to-one.
Since the function from A to B has to be bijective, the inverse function must be bijective too.

It's hard for me explain. But basically because the function from A to B is described to have a relation from A to B and that the inverse has a relation from B to A. Since the relation from A to B is bijective, hence the inverse must be bijective too. Also, does bijection has anything to do with equivalence relation on a single set where a relation R on set A must be reflexive, symmetric and transitive.
Thanks!

A: If $f:A \rightarrow B$ is a function then it must be the case that $\forall a \in A, f(a)$ is unique. If $f^{-1}: B \rightarrow A$ exists, then it must be the case that $\forall b \in B, f^{-1}(b)$ is unique. So, each element in A is paired with one element in $B$ (and vice versa), specifically, $a \in A$ is paired with $f(a) \in B$.

A: I recommend you explain it like this:
Let $f : A \to B$ be a bijection.  Let $f^{-1}$ be the inverse function of $f$.
We want to show $f^{-1}$ is a bijection, so we need to show $f^{-1}$ is one-to-one and onto.
First, let's show $f^{-1}$ is onto:
Since $f^{-1} : B \to A$, we need to show for each $a \in A$, there is some $b \in B$ so that $f^{-1}(b) = a$.  Well, let $a$ be any element of $A$, then.  Since $f : A \to B$, $f(a)$ is an element of $B$.  But by definition of the inverse function $f^{-1}$, this map sends $f(a)$ from $B$ to $a$ in $A$.  So that means we found a $b \in B$ with $f^{-1}(b) = a$, namely, the element $b = f(a)$.
Now to show $f^{-1}$ is one-to-one:
Since $f^{-1} : B \to A$, we need to show if for any $b_{1}, b_{2} \in B$, we have $f^{-1}(b_{1}) = f^{-1}(b_{2})$, then it should hold that $b_{1} = b_{2}$.  Well then, suppose $f^{-1}(b_{1}) = f^{-1}(b_{2})$.  Since $f : A \to B$ is onto, we can find $a_{1}$ and $a_{2}$ in $A$ so that $f(a_{1}) = b_{1}$ and $f(a_{2}) = b_{2}$.  So we have $f^{-1}(b_{1}) = f^{-1}(b_{2})$ implies $f^{-1}(f(a_{1})) = f^{-1}(f(a_{2}))$.  But by definition of the inverse function, $f^{-1}$ sends the element $f(a)$ to $a$, so $f^{-1}(f(a_{1})) = a_{1}$ and $f^{-1}(f(a_{2})) = a_{2}$, and so this implies $a_{1} = a_{2}$.  Since $a_{1} = a_{2}$, and $f$ is a function (and thus well-defined), it can't send one element to two different elements, so that means $f(a_{1}) = f(a_{2})$, i.e., $b_{1} = b_{2}$.
Note: where did we use the fact that the original function $f$ is one-to-one and onto here?  Well, we didn't use one-to-one directly in the arguments above (but onto was used in the second argument).  But they are still necessary.  If $f : A \to B$ is onto, then that would allow us to construct a potential inverse with domain $B$.  If $f$ were not onto, our inverse function could not have domain $B$.  Similarly, if $f$ is one-to-one, then that allows us to construct a well-defined inverse, i.e., an inverse that's actually a function (i.e., it doesn't send one element to more than one element).  Both of these are necessary to discuss the existence of a function $f^{-1}: B \to A$ defined in the usual way an inverse is defined.

A: I assume your $f^1$ notation actually means $f^{-1}$.The function $f$ has to be bijective because otherwise, our so called "$f^{-1}$" would not even be a function. Let's see why:
1) Assume $f:A\rightarrow B$ is not surjective: then there is an element $b' \in B$ that doesn't have a preimage. Therefore if we attempt to construct a relation   from every $b \in B$ to an $a\in A$, so that $b\mathcal Ra$ if $ b=f(a)$, $b'$ is left behind, then $\mathcal R$ cannot be a function.
2)Assume $f:A\rightarrow B$ is not injective. Then for some $a_1 $ and $ a_2$ in $A$ we have that $f(a_1)=f(a_2)$, then if we attempt to construct the same relation $\mathcal R$ we conclude it cannot be a function because for some $b \in B$ we have that $b\mathcal Ra_1$ and $b\mathcal Ra_2$
Your explanation works, I just tried to explain it in a more technical way. And no, $f$ being an equivalence relation has nothing to do with $f^{-1}$ existing

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are void pointers safe? I'm working on bitwise operations for unsigned integer types. I want to write left-circular-shift function for uint8_t, uint16_t, ... ,uint64_t types.
My solution is:
(void*) left_circular_shift(void* number, size_t size);

If size is 64, I convert void* to uint64_t etc., but many programmers avoid using void*. Should I implement that function for all unsigned integer types?

A: In your case you can't use void*. If you have a generic function that takes void* you will not be able to measure the size of what you got (how does it know where your number ends?), so you won't be able to cast it back.
Regarding Void* being "safe": The reason why you might have heard that it was "not safe" is because it being a generic no-type pointer it requires you to know exactly with what kind of data you're dealing with (you need to cast it back). So it is more prone to cause unexpected and weird errors if used carelessly.
The simple way to do this is to use one function for each. Another option is, like other people suggested, use a generic macro, regarding that, this might interest you: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

A: In C++ it makes sense to implement this function for all unsigned types (keeping the same function name). In C it is not possible, but you can create different functions for all types, like left_circular_shift_64 etc.
If you want to keep your interface, then you should convert void* to uint64_t* (not to uint64_t). It also might be useful to specify the size in bytes, not bits. Then the following construction can be used:
uint64_t value;
left_circular_shift(&value, sizeof(value));

This will help if, for instance, the type of value is changed to uint32_t.
Even though this option is valid and "safe", I would suggest to use distinct functions for each type. Some reasons to support this option:

*

*It is impossible to pass incorrect data to the function, e.g. float, struct or object.

*It is impossible to pass incorrect size to the function, e.g. 62. Thus, you do not need to invent what to do if the function gets strange input.

*You do not need to keep both parameters (pointer and size) sane, what reduces the possibility of bugs.

*In C++ there might be problems with casting void* to some complex types (e.g. classes with multiple inheritance), if you need to implement the shift operation for such types.

A: There is no reason to use a pointer type at all for such a basic task. Use
inline
uintmax_t left_circular_shift(uintmax_t number, size_t size) {
  return /* your implementation goes here */
}

in a header file, and
extern inline uintmax_t left_circular_shift(uintmax_t number, size_t size);

in one .c file.
Then a modern compiler should be able to inline the calls in cases where size is a constant.

A: Since you would need to dereference the void pointer in order to shift the number pointed to, this is not allowed, since e.g. pointers to differently sized numbers might be aligned differently.
Without knowing more details, this might be a case where a macro would be appropriate - this could change your number variable in place, if that is what you want.


text:
Q: Generating istanbul code coverage reports for jasmine tests run (via grunt) on a browserify bundle in phantomjs The title says it all really. Despite trawling the internet I haven't found a single example of a solution to this problem.
Here are some near misses

*

*https://github.com/amitayd/grunt-browserify-jasmine-node-example - grunt, browserify and jasmine

*https://github.com/gotwarlost/istanbul/issues/59#issuecomment-18799734 - browserify and istanbul

Here is my in-progress code https://github.com/wheresrhys/on-guard/tree/browserify (note it's the 'browserify' branch - Gruntfile.js is a bit of a mess but will tidy it up shortly). My initial investigations using console.log indicate that somehow bundle.src.js is being loaded in the page but when the tests are run (and passed!) the code in bundle.src.js isn't being run, so I have a feeling it might be an aliasing problem... though one that's limited to phantomjs as when I open the specrunner in chrome the code is getting run.

A: I'm using grunt-browserify + browserify-istanbul + grunt-contrib-jasmine + grunt-template-jasmine-istanbul as solution. This solution has also excluded third party libraries when building source files using browserify.
Show the code first, I'll explain later,
grunt.initConfig({
browserify: {
  // build specs using browserify
  specs: {
    src: ["spec/**/*Spec.js"],
    dest: "spec/build/specs.js",
    options: {
      debug: true
    }
  },
  // build source files using browserify and browserify-istanbul
  dev: {
    options: {
      debug: true,
      browserifyOptions: {
        standalone: 'abc'
      },
      transform: [['browserify-istanbul', {
        ignore: ['**/node_modules/**'], // ignore third party libs
        defaultIgnore: true
      }]]
    },
    src: ['abc.js'],
    dest: 'dist/abc.js'
  }
},
connect: {
  server: {
    options: {
      port: 7000
    }
  }
},
// test using jasmine, generate coverage report using istanbul
jasmine: {
  coverage: {
    src: ['dist/abc.js'],
    options: {
      junit: {
            path: 'bin/junit'
        },
      host: 'http://localhost:7000/',
      specs:  'spec/build/specs.js',
      keepRunner: true,
      summary: true,
      template: require('grunt-template-jasmine-istanbul'),
      templateOptions: {
        replace: false, // *** this option is very important
        coverage: 'bin/coverage/coverage.json',
        report: [
          {
          type: 'html',
          options: {
            dir: 'spec/coverage/html'
          }
        }]
      }
    }
  }
}

  grunt.registerTask('specs', ['browserify:specs', 'browserify:dev', 'connect', 'jasmine']);

The steps of generating istanbul coverage report can be concluded into three:

*

*Instrument code

*Run test

*Generate coverage report

In our solution, we use browerify-istanbul in step 1, grunt-contrib-jasmine and runt-template-jasmine-istanbul in step 2 and 3.
browserify-istanbul will let you instrument code in browserify building step, in this way, we can easily ignore third party libs. But the grunt-template-jasmine-istanbul will instrument code again. To avoid this, you can set replace to false in the options.
Refs:

*

*Istanbul steps

*broswerify-istanbul

*grunt-contrib-jasmine

*grunt-template-jasmine-istanbul -- replace option


text:
Q: Change hotkey volume indicator Im using ubuntu 12.04 with gnome shell everything is fine, but I find a bit ugly the image used when I change the sound via fn keys:
http://s15.postimage.org/xn01s5vsb/icon.png
Is there any way to modify this image or any gnome-shell extension that changes it?

A: It should be using the larger version. Make sure you have gnome-icon-theme-full installed if you're using gnome-shell.
You can change the theme you're using in dconf-editor by changing the /org/gnome/desktop/interface/icon-theme entry to be gnome. It looks like you are currently using the Humanity theme (or ubuntu-mono-dark, which is the Ubuntu default), and it does not provide high resolution versions of that icon. The lack of high resolution versions of the icons in any of the Humanity or ubuntu-mono icon themes may be considered a bug, and you should report it in Launchpad.


text:
Q: ArgumentNullException in ConcurrentDictionary.AddOrUpdate I am getting some weird behavior when calling AddOrUpdate method of the ConcurrentDictionary:
static void Main(string[] args)
{
    var t = new ConcurrentDictionary<string, object>();
    t.AddOrUpdate("boo", null, (k, v) => null);
}

throws ArgumentNullException:
System.ArgumentNullException was unhandled
  HResult=-2147467261
  Message=Value cannot be null.
Parameter name: addValueFactory
  ParamName=addValueFactory
  Source=mscorlib
  StackTrace:
       at System.Collections.Concurrent.ConcurrentDictionary`2.AddOrUpdate(TKey key, Func`2 addValueFactory, Func`3 updateValueFactory)
       at ConcurrentDictionaryTest.Program.Main(String[] args)

Why? Am I not allowed to add null's as values to concurrent dictionary? Documentation does not say anything special about null as value and following works fine:
static void Main(string[] args)
{
    var t = new ConcurrentDictionary<string, object>();
    const object defaultValue = null;
    t.AddOrUpdate("boo", defaultValue, (k, v) => defaultValue);
}

So, what's going on?

A: See the documentation for the overload you are using. The second argument is supposed to be a function invoked when the key doesn't exist. You're free to return null from this function, but you still have to provide it.
t.AddOrUpdate("boo", k => null, (k, v) => null);

If you want to use the other overload you can use casting:
t.AddOrUpdate("boo", (object)null, (k, v) => null);


text:
Q: Calling an unmanaged delegate with BeginInvoke I've a delegate to an unmanaged function on a DLL (which I loaded using GetProcAddress). I can call this delegate with no trouble. When I call the delegates with BeginInvoke, however, I get the following exception:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in '...'.
Additional Information: The runtime has encountered a fatal error. The address of the
error was at 0x63fd8687, on thread 0xb4c. The error code is 0xc0000005. This error may
be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common
sources of this bug include user marshaling errors for COM-interop or PInvoke, which
may corrupt the stack.

This is the code:
        private void OnConnectFinished(IAsyncResult a_oResult)
        {
            ConnectDelegate l_oDelegate = (ConnectDelegate)a_oResult.AsyncState;

            if (ConnectFinished != null)
            {
                ConnectFinished(l_oDelegate.EndInvoke(a_oResult));
            }
        }

        public bool Connect()
        {
            AsyncCallback l_oCallback = new AsyncCallback(OnConnectFinished);
            IAsyncResult l_oResult = DLLConnect.BeginInvoke(l_oCallback, DLLConnect);

                    //This Works!:
            //bool l_bResult = DLLConnect(m_oConnectFinishedDelegate);
            //return l_bResult;

            return true;
        }

Any ideas on why is this happening?

A: Passing the delegate as userState (the second argument in BeginInvoke) seems suspicious. Will it work if you pass null there? (Yes, I know that your callback won't work, but this issue can be handled another way. Let's check if the reported error disappears.)


text:
Q: SYSTEM_ALERT_WINDOW permission from Lux renders parts of our app inoperable For a few months, our application has been getting bad reviews due to a complaint from users that the main portion of our application cannot be interacted with.  Our app uses the support libraries and has an action bar.  According to these users, the action bar is the only part of the app that responds to user touch.  Everything below the action bar (except for the android home, back etc. buttons) is unresponsive.
After a lot of trouble on our end trying to reproduce the issue, we finally found that installing the app Lux causes this behavior.  When Lux is installed, the only thing that responds to user touch is the action bar.
Looking at Lux's permissions, I see this:

Other Application UI
  draw over other apps

Which, after looking it up, corresponds to this android permission:
android.permission.SYSTEM_ALERT_WINDOW

Users have already confirmed that the Lux application is what is causing the issue.
My question is, how can this be fixed without telling the users to uninstall Lux?  Is this an android bug, or ours? Is there something that we could be doing that renders our app unresponsive, but not others?
My next step I guess would be to send an email over to the Lux team to see if they know what could be causing this (alongside our own investigation).  My instinct is to also email the Android team, because in my opinion no outside application should be able to affect the behavior of another so dramatically.

A: Are you by any chance using a view with the android:filterTouchesWhenObscured property?  When set to true, I believe this could be causing your issue.
For example, in the XML, it would look like:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:filterTouchesWhenObscured="true"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"/>

Remove the filterTouchesWhenObscured line and it should be fine.


text:
Q: Какой язык выбрать для написания ботов Здравствуйте.
Подскажите язык для написания ботов для игр.
Требуемые функции:
 - Определение текущего статуса. Т.е. допустим чтобы можно было сравнивать скрин с текущим положением в игре. Т.е. допустим определить, идёт ли игра, либо пользователь в меню.
A: Пиши на python. Скорость разработки, а также всякие плюшки упростят эту задачу.
A: Как насчёт Sikuli
A: В java есть всё что надо:умеет делать скрины (можно реализовать пиксельный контроль), есть также функции для передвижения курсора, нажатия кнопок. Когда-то писал на java нечто подобное.
A: По скрину определять - не совсем удачная идея. Потому как зная основы крекинга, можно сделать куда больше и проще. Вообщем, если хочешь этим серьезно заняться, то как вариант выбирай asm и C/C++, пройдись по основам того и другого, а потом ищи на этом сайте
статьи, видео уроки и т.д, только сильно не разменивайся на все, основ будет достаточно для начала, если хочешь быстрый старт. И пробуй сделать что-то простенькое, а потом уже углубляйся в то, что нужно будет. То есть, найди какую-нибудь интересующую игру к которой есть хаки с исходным кодом и дальше уже по ним учись делать свои.

A: можно использовать LUA 5.1
вот из википедии:

Язык широко используется для создания тиражируемого программного обеспечения — в частности, на нём написан графический интерфейс пакета Adobe Lightroom. Также получил известность как язык программирования уровней и расширений во многих играх (например, World of Warcraft) из-за удобства встраивания, скорости исполнения кода и лёгкости обучения.


text:
Q: Log4Net with Mono is missing file name and line numbers I have a simple C# application that I can run on a windows platform or a linux platform (CentOS 7) using mono 4.2.3.4/832de4b.
When I try to log something using log4Net 2.0.5 on a windows machine I get the following output using a RollingFileAppender:
2016-03-24 09:09:40,374 DEBUG 8 C:\src\Test\Program.cs::20::This is my debug message.
2016-03-24 09:09:40,397 INFO  8 C:\src\Test\Program.cs::21::This is my info message.
2016-03-24 09:09:40,398 WARN  8 C:\src\Test\Program.cs::22::This is my warning message.
2016-03-24 09:09:40,398 FATAL 8 C:\src\Test\Program.cs::23::This is my fatal message.
2016-03-24 09:09:40,399 ERROR 8 C:\src\Test\Program.cs::24::This is my error message.

When I copy this over to a linux box and execute using mono I get the following:
2016-03-24 09:58:58,913 DEBUG 1 ::0::This is my debug message.
2016-03-24 09:58:58,920 INFO  1 ::0::This is my info message.
2016-03-24 09:58:58,920 WARN  1 ::0::This is my warning message.
2016-03-24 09:58:58,923 FATAL 1 ::0::This is my fatal message.
2016-03-24 09:58:58,923 ERROR 1 ::0::This is my error message.

Why am I missing the file name and line numbers from my output?  Ideally I would like to have this work with rsyslog but right now I'm trying to get my simple app working correctly.
NOTE:  I have a wrapper class around log4net which I have implemented using the information from here.
The RollingFileAppender config looks like this:
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="test_logfile.txt" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="50MB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %-5level %thread %file::%line::%message%newline" />
        </layout>
    </appender>

A: The reason for this is the way log4net gets this information in the first place. I didn't look at source code, but I'm pretty sure it takes this information from stack trace, using something like:
var frame = new System.Diagnostics.StackTrace(true).GetFrame(0);
var filename = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber();

Where runtime gets this information? Usually from debugging symbols which you put near your .dll or .exe files (those .pdb files). Try to not put .pdb file near your exe and run code above - it will return nothing for file name and line number.
Now to mono. First, mono uses another debugging symbols format (.mdb files). If you run on windows also - most likely you did not compile with mono compiler, so you have regular .NET .pdb files. Second - mono will not collect information you want by default, even with correct symbols. You have to pass --debug flag ("mono --debug ").
Summary:

*

*Compile with mono compiler.

*Bring debugging symbols files (.mdb) with your .exe.

*Run mono with --debug flag.


text:
Q: whenever i try to import models.py in my main.py file it shows me sqlalchemy.exc.ArgumentError from xmlrpc.client import Boolean
from sqlalchemy import TIMESTAMP, Column, Integer, String
from sqlalchemy.sql.expression import text
from .database import Base

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, unique=True, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, server_default='True', nullable=False)
    created_at= Column(TIMESTAMP(timezone=True), nullable= False, server_default=text)

I couldn't find the error. When I try to create the tables using models.Base.metadata.create_all(bind=engine) it gives me the following error:
Traceback (most recent call last):
  File "C:\Users\MINTU\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlalchemy\sql\schema.py", line 125, in _init_items
    spwd = item._set_parent_with_dispatch
AttributeError: type object 'bool' has no attribute '_set_parent_with_dispatch'

The above exception was the direct cause of the following exception:

File "C:\Users\MINTU\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
sqlalchemy.exc.ArgumentError: 'SchemaItem' object, such as a 'Column' or a 'Constraint' expected, got <class 'bool'>

A: First, Boolean must not be imported from xmlrpc.client but from sqlalchemy
Second, the name of your table is not written as tablename but as __tablename__.
Third, text in TIMESTAMP must be called with an argument that I would let you adapt to your needs

from sqlalchemy import TIMESTAMP, Column, Integer, String, Boolean
from sqlalchemy.sql.expression import text
from .database import Base

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, unique=True, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, server_default='True', nullable=False)
    created_at= Column(TIMESTAMP(timezone=True), nullable= False, server_default=text('(now() at time zone "utc")'))


text:
Q: How to find the sum $\sum_{k=1}^{∞} \frac{k^2}{(k+1)!}$ I've tried to find the sum of $\sum_{k=1}^{∞} \frac{k^2}{(k+1)!}$ and calculator says its sum is $e-1$. I thought that it is related to the Maclaurin series of $e$, well I could not derive the $-1$ term for answer. What is an elementary way to derive the answer? Thank you for your help.

A: $$
\begin{split}
\sum_{k=1}^\infty \frac{k^2}{(k+1)!}
 &= \sum_{k=1}^\infty \frac{k(k+1)}{(k+1)!}
  - \sum_{k=1}^\infty \frac{k+1}{(k+1)!}
  + \sum_{k=1}^\infty \frac{1}{(k+1)!} \\
 &= \sum_{k=1}^\infty \frac{1}{(k-1)!}
  - \sum_{k=1}^\infty \frac{1}{k!}
  + \sum_{k=1}^\infty \frac{1}{(k+1)!} \\
 &= \sum_{k=0}^\infty \frac{1}{k!}
  - \left(\sum_{k=0}^\infty \frac{1}{k!} - 1\right)
  + \left(\sum_{k=0}^\infty \frac{1}{(k+1)!} - 1 - 1 \right)\\
 &= \sum_{k=0}^\infty \frac{1}{k!} - 1 \\
 &= e - 1.
\end{split}
$$


text:
Q: Fully-qualified urls in HTTP Location header. Why it is important? So I've got some warnings from Fiddler that I have bad urls in HTTP Location header and they are should be fully-qualified. Why it's so important and what issues that can lead to?

A: The old standard for HTTP/1.1 (RFC 2616 § 14.30) required that Location be an absolute URI.
Implementation experience showed that this was not important, and many implementations allowed relative URIs in Location, so the current standard (RFC 7231 § 7.1.2) allows relative URIs.


text:
Q: Can I damage a device using opposite polarity? I have a device that requires input of 12V DC with positive polarity and a power supply that outputs 12V DC negative polarity (see figures below). Can I plug it in to try to see if it's working or will that harm the device?

A: Using the wrong polarity will very likely damage the device, if it is polarity-sensitive.  If the device has reverse-polarity protection, it won't work, but won't be damaged.


text:
Q: trying to return to start: unrecognized selector sent to instance After the results page, I want the user to press "done" and return to the first question on the list. At the moment, the app crashes with "unrecognized selector sent to instance.
2018-04-19 11:56:49.072392-0400 test[62142:269319] -[test.ResultsController done]: unrecognized selector sent to instance 0x7f8c62f43b10
2018-04-19 11:56:49.078012-0400 test[62142:269319] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[test.ResultsController done]: unrecognized selector sent to instance 0x7f8c62f43b10'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000114a8b1e6 __exceptionPreprocess + 294
1   libobjc.A.dylib                     0x000000011074d031 objc_exception_throw + 48
2   CoreFoundation                      0x0000000114b0c784 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3   UIKit                               0x000000011192c9eb -[UIResponder doesNotRecognizeSelector:] + 295
4   CoreFoundation                      0x0000000114a0d898 ___forwarding___ + 1432
5   CoreFoundation                      0x0000000114a0d278 _CF_forwarding_prep_0 + 120
6   UIKit                               0x00000001116ff6f8 -[UIApplication sendAction:to:from:forEvent:] + 83
7   UIKit                               0x0000000112104271 __45-[_UIButtonBarTargetAction _invoke:forEvent:]_block_invoke + 154
8   UIKit                               0x00000001121041aa -[_UIButtonBarTargetAction _invoke:forEvent:] + 154
9   UIKit                               0x00000001116ff6f8 -[UIApplication sendAction:to:from:forEvent:] + 83
10  UIKit                               0x000000011187aab4 -[UIControl sendAction:to:forEvent:] + 67
11  UIKit                               0x000000011187add1 -[UIControl _sendActionsForEvents:withEvent:] + 450
12  UIKit                               0x0000000111879d19 -[UIControl touchesEnded:withEvent:] + 580
13  UIKit                               0x00000001117743cf -[UIWindow _sendTouchesForEvent:] + 2729
14  UIKit                               0x0000000111775ad1 -[UIWindow sendEvent:] + 4086
15  UIKit                               0x0000000111719620 -[UIApplication sendEvent:] + 352
16  UIKit                               0x000000012ed78e6b -[UIApplicationAccessibility sendEvent:] + 85
17  UIKit                               0x000000011205a717 __dispatchPreprocessedEventFromEventQueue + 2796
18  UIKit                               0x000000011205d32c __handleEventQueueInternal + 5949
19  CoreFoundation                      0x0000000114a2dbb1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
20  CoreFoundation                      0x0000000114a124af __CFRunLoopDoSources0 + 271
21  CoreFoundation                      0x0000000114a11a6f __CFRunLoopRun + 1263
22  CoreFoundation                      0x0000000114a1130b CFRunLoopRunSpecific + 635
23  GraphicsServices                    0x00000001184aea73 GSEventRunModal + 62
24  UIKit                               0x00000001116fe367 UIApplicationMain + 159
25  test                                0x000000010fe329e0 main + 48
26  libdyld.dylib                       0x0000000115c6c955 start + 1
27  ???                                 0x0000000000000001 0x0 + 1

)
    libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I've read the issue might be its placement in the code, but it seems to be fine?
Here's the creation of the button:
        override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: Selector(("done")))

        navigationItem.title = "Results"

        view.backgroundColor = UIColor.white

        view.addSubview(resultsLabel)
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resultsLabel]))
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": resultsLabel]))

        let names = ["Ross", "Joey", "Chandler", "Monica", "Rachel", "Phoebe"]

        var score = 0
        for question in QuestionController.questionsList {
            score += question.selectedAnswerIndex!
        }

        let result = names[score % names.count]
        resultsLabel.text = "Congratulations! \(result)."
    }

    func done() {
        navigationController?.popToRootViewController(animated: true)

And

A: Couple of points to note:

*

*You missed the argument for the sender in your done function

*Use #selector, it is type safe and would throw a compilation error

*Objective-C methods need to be prefixed with @objc
Button:
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done",
                                                    style: .plain,
                                                    target: self,
                                                    action: #selector(done(sender:)))

Function:
@objc func done(sender: UIBarButtonItem) {

    navigationController?.popToRootViewController(animated: true)

}


text:
Q: Describe all metric spaces whose completions are compact. So, I'm basically being asked to prove the following Theorem: A metric space is totally bounded if and only if its completion is compact.
Here is the definition of completion: A completion of a metric space $(X,d)$ is a pair consisting of a complete metric space $(X^{*},d^{*})$ and an isometry $\phi :X\rightarrow X^{*}$ such that $\phi (X)$ is dense in $X^{*}$.
Proof.
$(\Rightarrow )$ Suppose a metric space $(X,d)$ is totally bounded, then so is its completion.  So, the completion is a totally bounded, complete metric space.  (A metric space is totally bounded and complete if and only if it is compact.) Hence, the completion is compact.
$(\Leftarrow )$ Suppse the completion is compact.   (A metric space is totally bounded and complete if and only if it is compact.) Then it is totally bounded and so are its subsets.  So, the metric space is totally bounded.
Can someone explain to me further why we have that if a metric space is totally bounded, then so is its completion?  I'm not quite understanding why this is true.

A: Suppose that $\langle X,d\rangle$ is totally bounded. Then for each $\epsilon>0$ there is a finite $F_\epsilon\subseteq X$ such that
$$\bigcup_{x\in F_\epsilon}B_d(x,\epsilon)=X\;.$$
We want to show that there is a finite $F_\epsilon^*\subseteq X^*$ such that
$$\bigcup_{x\in F_\epsilon^*}B_{d^*}(x,\epsilon)=X^*\;,$$
so let $\epsilon>0$. Since $\varphi[X]$ is dense in $X^*$, for each $y\in X^*$ and $\epsilon>0$ there is an $x\in X$ such that
$$d^*\big(y,\varphi(x)\big)<\frac{\epsilon}2\;.$$
There is a $z\in F_{\epsilon/2}$ such that
$$d^*\big(\varphi(x),\varphi(z)\big)=d(x,z)<\frac{\epsilon}2\;,$$
so $d^*\big(y,\varphi(z)\big)<\epsilon$ by the triangle inequality. Thus,
$$\bigcup_{z\in F_{\epsilon/2}}B_{d^*}\big(\varphi(z),\epsilon\big)=X^*\;,$$
and and we may set $F_\epsilon^*=\varphi[F_{\epsilon/2}]$.


text:
Q: Homotopy fixed points in terms of a homotopy limit Let G be some nice group. Let X be a G-space (topological space, simplicial set, spectra - adjusting G accordingly). Can $X^{hG}$ be stated in terms of a holim?
For example, if G is seen as a groupoid with one point, then we have a map $X \colon G \rightarrow Spaces$. Is it true that $X^{hG} \cong holim_G X$? When would such a thing be true? If this is true, is it also true that the homotopy orbit space is the homotopy colimit of the same diagram?

A: Note that given a diagram $X:I\to \mathbf{Top}$, a model for $\mathrm{holim}\;X$ is as the equalizer of $\displaystyle\prod_i X_i^{|N(I/i)|} \rightrightarrows \prod_{i\to j}X_j^{|N(I/i)|}$ where $N(C)$ denotes the nerve (simplicial set) of the category $C$.
Now if you look at $I=G$ a discrete group, then $N(G/\bullet)$ (where $\bullet$ is the only object of $G$ seen as a category) has $EG$ as its nerve, and taking a look at the arrows in the above diagram shows that, seeing your $G$-space as a functor $G\to \mathbf{Top}$, $\mathrm{holim}_G \; X = \mathrm{Map}(EG,X)^G = \mathrm{Map}^G(EG,X) = X^{hG}$.
I don't know about more general versions of "$G$-space" (spectra and so on), or what happens if you let $G$ be non-discrete. This probably works for simplicial sets too ($G$ still being discete)


text:
Q: ¿Por que no me devuelve resultado ni error? Al ejecutar este código no me devuelve ni error ni resultado:
import numpy as np

def precio_cerveza(coste, cantidad, ingredientes):

    total = np.array(cost_list_float) @ np.array(cost_list_float)

coste = {"lupulo" : "2.5",
            "malta" : "1.5",
            "agua" : "0.006",
            "levadura" : "0.45"}

cantidad = {"lupulo" : "6u",
               "malta" : "14u",
               "agua" : "7u",
               "levadura" : "11u"}

ingredientes = {"lupulo" : "lupulo",
                   "malta" : "malta",
                   "agua" : "agua",
                   "levadura" : "levadura"}

cost_list = list(coste.values())
cantidad_list = list(cantidad.values())

cost_list_float = []
cantidad_list_float = []
for c, d in zip(cost_list, cantidad_list):
        cost_list_float.append(float(c[:-1]))
        cantidad_list_float.append(float(d[:-1]))

A: Deduzco que buscas calcular el precio e insumos de la cerveza en base a costos, cantidad e ingredientes.
La función para calcular sería
def precio_cerveza(coste, cantidad, ingredientes):
    cost_list = list(coste.values())
    cantidad_list = list(cantidad.values())

    cost_list_float = []
    cantidad_list_float = []
    for c, d in zip(cost_list, cantidad_list):
        cost_list_float.append(float(c[:-1]))
        cantidad_list_float.append(float(d[:-1]))

    return cost_list, cantidad_list

y luego ponemos los antecedentes:
coste = {"lupulo": "2.5",
         "malta": "1.5",
         "agua": "0.006",
         "levadura": "0.45"}

cantidad = {"lupulo": "6u",
            "malta": "14u",
            "agua": "7u",
            "levadura": "11u"}

ingredientes = {"lupulo": "lupulo",
                "malta": "malta",
                "agua": "agua",
                "levadura": "levadura"}

con lo cual podemos obtener
costos, cantidades = precio_cerveza(coste, cantidad, ingredientes)
print("Costo", costos)
print("Cantidades", cantidades)

produce:
Costo ['2.5', '1.5', '0.006', '0.45']
Cantidades ['6u', '14u', '7u', '11u']

Process finished with exit code 0


text:
Q: Why can I not acquire the keyboard with DirectInput? I just started getting into DirectInput today, using DirectInput8 with MinGW on Windows 7 Ultimate N. I started off with a simple program to report which keys are currently down every second (just codes, not readable keys). However, I can't even get as far as acquiring the keyboard before it errors out:
#define _WIN32_WINNT 0x0601
#include <dinput.h>
//link to dinput8.lib and dxguid.lib

int main() {
    IDirectInput8 *dinput;
    DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, nullptr);

    IDirectInputDevice8 *kb;
    dinput->CreateDevice(GUID_SysKeyboard, &kb, nullptr);

    kb->SetDataFormat(&c_dfDIKeyboard);
    kb->SetCooperativeLevel(GetConsoleWindow(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    kb->Acquire(); //fails with DIERR_INVALIDPARAM
}

I omitted error checking, but what happens is that every call succeeds (by judgement of the FAILED macro) up to Acquire(). That call fails with the error DIERR_INVALIDPARAM. I looked on the MSDN pages and across the web, but I can't find any reason it would fail with that based on everything before it present and working.
For good measure, I also tried looping the Acquire() call until it succeeded and then played around with windows and the keyboard while it was running, but the program never successfully acquired the keyboard in all the time it was running. How can I successfully acquire the keyboard?

A: Experimenting with direct input in a console program for the keyboard and joystick
It is not necessary to have a handle to a window to use direct input.  You can just use null in the parameter for a handle to a window.
Instead of:
kb->SetCooperativeLevel(GetConsoleWindow(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

Use:
kb->SetCooperativeLevel(NULL, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

Here is an example program that uses direct input to display the keys 'a' and 'd' when those keys are pressed.  It will repeat those keys when they are held for 300 milliseconds.  The example program is also a good example of a high resolution counter.  There is no need to add in properties in Visual Studio to add the libraries dinput8.lib and dxguid.lib.  The #pragma comment code lines at the top of the program do that for you.
 #include <dinput.h>
#include <iostream>
#include <Windows.h>

#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"dxguid.lib")

using std::cout;
using std::endl;

LPDIRECTINPUT8 di;
LPDIRECTINPUTDEVICE8 keyboard;

class CTimer
{
public:
    CTimer() {
        QueryPerformanceFrequency(&mqFreq);
    }
    ~CTimer() {}

    void Start() {
        QueryPerformanceCounter(&mqStart);
    }
    void End() {
        QueryPerformanceCounter(&mqEnd);
    }
    double GetTimeInSeconds() {
        return (mqEnd.QuadPart - mqStart.QuadPart)/(double)mqFreq.QuadPart;
    }
    double GetTimeInMilliseconds() {
        return (1.0e3*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
    }
    double GetTimeInMicroseconds() {
        return (1.0e6*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
    }
    double GetTimeInNanoseconds() {
        return (1.0e9*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
    }

private:
    LARGE_INTEGER mqStart;
    LARGE_INTEGER mqEnd;
    LARGE_INTEGER mqFreq;
};

HRESULT initializedirectinput8() {
    HRESULT hr;
    // Create a DirectInput device
if (FAILED(hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION,
                                   IID_IDirectInput8, (VOID**)&di, NULL))) {
    return hr;
}
}

void createdikeyboard() {
    di->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
    keyboard->SetDataFormat(&c_dfDIKeyboard);
    keyboard->SetCooperativeLevel(NULL,DISCL_FOREGROUND | DISCL_EXCLUSIVE);
    keyboard->Acquire();
}

void destroydikeyboard() {
    keyboard->Unacquire();
    keyboard->Release();
}

#define keydown(name,key) (name[key] & 0x80)

void main() {
    HRESULT hr;
    BYTE dikeys[256];
    CTimer timeint;
    CTimer timekeywaspressedclass;
    double gettime;
    double lastkeywasa=false;
    double timekeywaspressed=0;
    bool lasttimetherewasakeypress=false;
    bool akeywaspressed=false;
    initializedirectinput8();
    createdikeyboard();
    hr=keyboard->GetDeviceState(256,dikeys);
    timeint.Start();
    while (!keydown(dikeys,DIK_ESCAPE)) {
        timeint.End();
        gettime=timeint.GetTimeInMilliseconds();
        if (gettime >=5) {
            hr=keyboard->GetDeviceState(256,dikeys);
            akeywaspressed=false;
            if (keydown(dikeys,DIK_A)) {
                akeywaspressed=true;
                if (timekeywaspressed >=300) {
                    cout << "a";
                    lasttimetherewasakeypress=false;
                }

            }
            if (keydown(dikeys,DIK_D)) {
                akeywaspressed=true;
                if (timekeywaspressed >=300) {
                    cout << "d";
                    lasttimetherewasakeypress=false;
                }
            }
            if (lasttimetherewasakeypress==false && akeywaspressed==true) {
                timekeywaspressedclass.Start();
                timekeywaspressed=0;
                lasttimetherewasakeypress=true;
            }
            if (lasttimetherewasakeypress==true && akeywaspressed==true) {
                timekeywaspressedclass.End();
                gettime=timekeywaspressedclass.GetTimeInMilliseconds();
                timekeywaspressed+=gettime;
                timekeywaspressedclass.Start();
            }
            if (akeywaspressed==false) {
                lasttimetherewasakeypress=false;
                timekeywaspressed=0;
            }

        } // end if (gettime >=5)

        } // end while
destroydikeyboard();

} // end main

Here is an example console program for the joystick.
#include <dinput.h>
#include <iostream>
#include <Windows.h>

#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"dxguid.lib")

using std::cout;
using std::endl;

LPDIRECTINPUT8 di;
LPDIRECTINPUTDEVICE8 joystick;
LPDIRECTINPUTDEVICE8 keyboard;
DIJOYSTATE2 js;
BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE* instance, VOID* context);
BOOL CALLBACK enumAxesCallback(const DIDEVICEOBJECTINSTANCE* instance, VOID* context);

HRESULT selectjoystick() {
    HRESULT hr;
    // Look for the first simple joystick we can find.
if (FAILED(hr = di->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback,
                                NULL, DIEDFL_ATTACHEDONLY))) {
    return hr;
}

// Make sure we got a joystick
if (joystick == NULL) {
  //  printf("Joystick not found.\n");
    return E_FAIL;
}
}

DIDEVCAPS capabilities;

HRESULT setjoystickproperties() {
    HRESULT hr;
    // Set the data format to "simple joystick" - a predefined data format
//
// A data format specifies which controls on a device we are interested in,
// and how they should be reported. This tells DInput that we will be
// passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState().
if (FAILED(hr = joystick->SetDataFormat(&c_dfDIJoystick2))) {
    return hr;
}

// Set the cooperative level to let DInput know how this device should
// interact with the system and with other DInput applications.
if (FAILED(hr = joystick->SetCooperativeLevel(NULL, DISCL_EXCLUSIVE |
                                              DISCL_FOREGROUND))) {
    return hr;
}

// Determine how many axis the joystick has (so we don't error out setting
// properties for unavailable axis)

capabilities.dwSize = sizeof(DIDEVCAPS);
if (FAILED(hr = joystick->GetCapabilities(&capabilities))) {
    return hr;
}
}

BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE* instance, VOID* context)
{
    HRESULT hr;

    // Obtain an interface to the enumerated joystick.
    hr = di->CreateDevice(instance->guidInstance, &joystick, NULL);

    // If it failed, then we can't use this joystick. (Maybe the user unplugged
    // it while we were in the middle of enumerating it.)
    if (FAILED(hr)) {
        return DIENUM_CONTINUE;
    }

    // Stop enumeration. Note: we're just taking the first joystick we get. You
    // could store all the enumerated joysticks and let the user pick.
    return DIENUM_STOP;
}

HRESULT enumaxes() {
    HRESULT hr;
// Enumerate the axes of the joyctick and set the range of each axis. Note:
// we could just use the defaults, but we're just trying to show an example
// of enumerating device objects (axes, buttons, etc.).
if (FAILED(hr = joystick->EnumObjects(enumAxesCallback, NULL, DIDFT_AXIS))) {
    return hr;
}
}

BOOL CALLBACK enumAxesCallback(const DIDEVICEOBJECTINSTANCE* instance, VOID* context)
{
    HWND hDlg = (HWND)context;

    DIPROPRANGE propRange;
    propRange.diph.dwSize       = sizeof(DIPROPRANGE);
    propRange.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    propRange.diph.dwHow        = DIPH_BYID;
    propRange.diph.dwObj        = instance->dwType;
    propRange.lMin              = -1000;
    propRange.lMax              = +1000;

    // Set the range for the axis
    if (FAILED(joystick->SetProperty(DIPROP_RANGE, &propRange.diph))) {
        return DIENUM_STOP;
    }

    return DIENUM_CONTINUE;
}

HRESULT polljoy() {
    HRESULT     hr;

    if (joystick == NULL) {
        return S_OK;
    }

    // Poll the device to read the current state
    hr = joystick->Poll();
    if (FAILED(hr)) {
        // DInput is telling us that the input stream has been
        // interrupted. We aren't tracking any state between polls, so
        // we don't have any special reset that needs to be done. We
        // just re-acquire and try again.
        hr = joystick->Acquire();
        while (hr == DIERR_INPUTLOST) {
            hr = joystick->Acquire();
        }

        // If we encounter a fatal error, return failure.
        if ((hr == DIERR_INVALIDPARAM) || (hr == DIERR_NOTINITIALIZED)) {
            return E_FAIL;
        }

        // If another application has control of this device, return successfully.
        // We'll just have to wait our turn to use the joystick.
        if (hr == DIERR_OTHERAPPHASPRIO) {
            return S_OK;
        }
    }

    // Get the input's device state
    if (FAILED(hr = joystick->GetDeviceState(sizeof(DIJOYSTATE2), &js))) {
        return hr; // The device should have been acquired during the Poll()
    }

    return S_OK;
}

class CTimer
{
public:
    CTimer() {
        QueryPerformanceFrequency(&mqFreq);
    }
    ~CTimer() {}

    void Start() {
        QueryPerformanceCounter(&mqStart);
    }
    void End() {
        QueryPerformanceCounter(&mqEnd);
    }
    double GetTimeInSeconds() {
        return (mqEnd.QuadPart - mqStart.QuadPart)/(double)mqFreq.QuadPart;
    }
    double GetTimeInMilliseconds() {
        return (1.0e3*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
    }
    double GetTimeInMicroseconds() {
        return (1.0e6*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
    }
    double GetTimeInNanoseconds() {
        return (1.0e9*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
    }

private:
    LARGE_INTEGER mqStart;
    LARGE_INTEGER mqEnd;
    LARGE_INTEGER mqFreq;
};

HRESULT initializedirectinput8() {
    HRESULT hr;
    // Create a DirectInput device
if (FAILED(hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION,
                                   IID_IDirectInput8, (VOID**)&di, NULL))) {
    return hr;
}
}

void createdikeyboard() {
    di->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
    keyboard->SetDataFormat(&c_dfDIKeyboard);
    keyboard->SetCooperativeLevel(NULL,DISCL_FOREGROUND | DISCL_EXCLUSIVE);
    keyboard->Acquire();
}

void destroydikeyboard() {
    keyboard->Unacquire();
    keyboard->Release();
}

void closejoystick() {
    if (joystick) {
    joystick->Unacquire();
    }
    if (joystick) {
        joystick->Release();
    }
}

#define keydown(name,key) (name[key] & 0x80)

void main() {
    HRESULT hr;
    CTimer pollintclass;
    hr=initializedirectinput8();
    createdikeyboard();
    hr=selectjoystick();
    hr=setjoystickproperties();
    hr=enumaxes();
    bool endloop=false;
    double gettime;
    BYTE dikeys[256];
    pollintclass.Start();
    while (endloop==false) {
        pollintclass.End();
        gettime=pollintclass.GetTimeInMilliseconds();
        if (gettime >=5) {
            hr=keyboard->GetDeviceState(256,dikeys);
            if (FAILED(hr))
                keyboard->Acquire();
            if (keydown(dikeys,DIK_ESCAPE))
                endloop=true;
            polljoy();
            cout << "joy x-axis=" << js.lX << " " << "joy y-axis=" << js.lY << endl;
            pollintclass.Start();
        }
    }
destroydikeyboard();
    closejoystick();

}

A: Have you tried DISCL_BACKGROUND instead of DISCL_FOREGROUND ?

A: It actually happens that the error magically disappears when I change it from associating with the console window (which is visibly existent) to one I create in the SetCooperativeLevel() call. Why a console window can't be used I don't know, so I'll leave this unaccepted for a while in lieu of an answerer who does, but this does solve the problem.


text:
Q: How to make Flash ActiveX control compatible on deployment machine? The application used the ActiveX control axshockwaveflash, when you install and deploy the application on another machine there is a problem of compatibility version Flash, how to solve this problem? Can someone experienced in the past?

A: Hello friend from Russia. I think you're seeking a solution to use both languages.
In fact, with C#, you can make Silverlight applications, which can do some of the functions that Flash provides, such as simple animations, form elements, and even camera & microphone. End users need to install Silverlight player in their browsers ( supported by Mac OS X & Windows ).
With Flash ( ActionScript ), you can make Flash animations as well as games. End users need to install Flash player in their browsers ( Google Chrome has built-in Flash player ).
In short, you need only either language to bring your contents to end users. No need to use ActiveX as it is commonly disabled / blocked by browsers.


text:
Q: How Can I Take Down Big Daddies? I'm at the beginning of the game on Normal, and am currently finding fighting the Big Daddies to be a bit challenging. As in I wasted half a clip of Machine Gun Ammo and 3 EVE Hypos taking down the ones in the Medical Bay, and I'm now being toasted in Neptune's Bounty.
Should I just wait till later in the game, or are there tips for defeating the Daddies?

A: In addition to the tactics listed by GnomeSlice, the choice of ammo is instrumental in conserving ammo. Especially with Big Daddies. Before I decide to take on one of those, I

*

*equip the Shotgun with electric ammo

*equip the Tommy gun with armour piercing ammo

*make sure my pistol is set on either regular or anti-personnel ammo (*)

*select the electricity or bee plasmid (I usually prefer the electric in most situations, but that's personal preference)
(*) The pistol is helpful if splicers pop up and want to take part in the action. They can be dispatched most easily and without wasting ammo by paralysing and head-shooting them. You don't have much time when a Big Daddy is charging at you so splicers have to be dealt with quickly.
Now, you can paralyse the Big Daddy repeatedly with either the electricity or bee plasmid or the shotgun. Then hit him with either a burst from your Tommy gun or a grenade (sticky grenades work nicely, too). The armour piercing rounds are insanely more effective than the regular rounds, so you won't waste nearly as much ammo.
Alternatively to the Tommy gun you can also use the pistol's armour piercing rounds. They're incredibly effective, too. But I would always keep one weapon ready to take on splicers.

A: The most important thing to remember is that as long as the Big Daddy is mobile with a line of sight on you, you are in mortal danger.
The trick to bringing down a Big Daddy is to use whatever means possible to immobilize him.  There are various tools you can use to impede his movement, or attacks, and you're going to need to learn to use all of them if you want to bring down Big Daddies repeatedly.
Some of the best ones to use are as follows:

*

*Ice Plasmid  Freezing a Big Daddy on the spot can give you a chance to get to cover, but also makes it harder to damage them while frozen.

*Hacked Turrets  A friendly turret won't put up a fight for very long against a Big Daddy, but it may give you the time you need to get to cover.

*Bee Arms  The Bee Arms are one of the best weapons to use against a Big Daddy.  For periods at a time after being unleashed, your bees will swarm the Big Daddy, causing him to stumble around waving his arms in the air.  Higher level Bee Arms will disorient the Big Daddy for longer periods, as well as deal more damage to him over time.

*Electricity Stun  While not as effective (in my opinion) as the bee arms, this plasmid is available fairly early in the game (as @Ender pointed out), and can be very useful for immobilizing Big Daddies when you need to get to cover.

*Shotgun (Point Blank)  A shotgun blast at point blank range will stun the Big Daddy for a short period of time; do this repeatedly to deal a ton of damage quickly, then use one of the above techniques to escape.  Using Electric rounds for your Shotgun will extend this stun period substantially.

*Trap Bolts  These are pretty self-explanatory.  Just use them in doorways and suchlike before getting on a Big Daddy's bad side, then get him to run through them.  These do a ton of damage, though ammo is rare.

*Another Big Daddy  No, you're not crazy.  Sometimes, getting two Daddies to fight one another is a viable option for bringing the one you initially attacked down to size, but this isn't always easy to achieve, nor is it usually terribly safe.
Of note is the fact that if you pick up a dead Rosie type Big Daddy using telekinesis, it will slowly rotate to upside-down, and you can then stand it on its head with its legs hanging out to the sides.  I went on a Big Daddy killing spree in one section and got a gallery of about six of them posed this way.  Then one of the character models 'broke' somehow, and kind of melted into a puddle of boneless Big Daddy.  It was great.


text:
Q: Alert user when selected options are not availabe So i have been working on this for a while now. in my html/php i have two dropdowns that become dates. That is working fine in my php when i POST. but that looks like this:
<?php for($x=1; $x<=20; $x++){ ?>

                <?php echo "$x"; ?>.
                <select class="form-control" name="month<?php echo $x ;?>">
                  <option selected disabled>- Month -</option>
                  <option value="06">June</option>
                  <option value="07">July</option>
                  <option value="08">August</option>
                </select>
                <select class="form-control" name="day<?php echo $x ;?>">
                  <option selected disabled>- Day -</option>
                  <option value="01">1</option>
                  <option value="02">2</option>
                  <option value="03">3</option>
                  <option value="04">4</option>
                  <option value="05">5</option>
                  <option value="06">6</option>
                  <option value="07">7</option>
                  <option value="08">8</option>
                  <option value="09">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                  <option value="17">17</option>
                  <option value="18">18</option>
                  <option value="19">19</option>
                  <option value="20">20</option>
                  <option value="21">21</option>
                  <option value="22">22</option>
                  <option value="23">23</option>
                  <option value="24">24</option>
                  <option value="25">25</option>
                  <option value="26">26</option>
                  <option value="27">27</option>
                  <option value="28">28</option>
                  <option value="29">29</option>
                  <option value="30">30</option>
                  <option value="31">31</option>
                </select>

 <?php } ?>

So with that i want to have certain days from the drop down disabled when a certain month is picked from the other. To do this i figured javascript would be the easiest way. The available dates are listed above  the drop down to the user so i was just going to validate the day and use an alert if they were wrong. js code is as follows:
function validate(){
  for(i=1;i<=20;i++){
    var month = document.getElementByName("month"+i);
    var day   = document.getElementByName("day"+i);

    if(month == "06"){//alert user if selecting a disabled date for june
      if(day == "01" || day == "02" || day == "03" || day == "04" || day == "05" || day == "06" || day == "07" || day == "08" || day == "09" || day == "10" || day == "11" || day == "17"){
        if(day == "18" || day =="24" || day == "25"){
          alert("Please choose a daily dropin date that corresponds to a date available during a session!");
        }
      }
    }//end if for june

    if(month == "07"){//alert user if selecting a disabled date for july
      if(day == "01" || day == "02" || day == "03" || day == "04" || day == "08" || day == "09" || day == "15" || day == "16" || day == "22" || day == "23" || day == "29" || day == "30"){
          alert("Please choose a daily dropin date that corresponds to a date available during a session!");
      }
    }//end if for july

    if(month == "08"){//alert user if selecting a disabled date for august
      if(day == "05" || day == "06" || day == "12" || day == "13" || day == "19" || day == "20" || day == "26" || day == "27"){
          alert("Please choose a daily dropin date that corresponds to a date available during a session!");
      }
    }//end if for august
  }
}

the button im using to run the onlcick function is the same one used to POST the form. i dont know if that matters but i am kinda lost right now with what is wrong in my javascript

A: This is an interesting and common task. As a programmer you should strive not to create control structures that require you to excessively nest or multiply your code base.
The way that you should try to organize your code is with the DRY(don't repeat yourself) principle. This includes using loops to complete otherwise lengthy tasks and control structures. Otherwise you'll get what you have in your validation code if this or this or this or this or this or this or this... etc and that's not maintainable as well as being rather unsightly.
To give a more clear example of this, if you were to build a tic-tac-toe game, would you painstakingly write in every scenario of a win by saying "if top-left is x and top-mid is x and top-right is x OR top-left is x mid-left is x and bottom-left is x OR if top-left is x and middle is x and bottom-right is x..." for both team "X" and "O" respectively, or would you simply ask the browser "Is there a row of three boxes that all contain the same value?"
It's not something that you'll understand immediately, but it's important to realize that you will have to think a bit differently about your programs, but not to worry because if you keep at it I guarantee it will happen!
To answer your question:
https://jsfiddle.net/ygpqqmL9/3/
//create our data
data = {
  disabled_days: {
    "June": [3, 5, 7, 9],
    "July": [10, 20, 30],
    "August": [1, 2, 3, 4]
  }
}

//get the select month box
let select_month = document.querySelector('select[name="month"]');

//when a month is selected...
select_month.addEventListener('change', function(e) {

//get the name of the month
  let month = select_month[select_month.selectedIndex].textContent;

// get all the days in the day select box
// enable all of them
  let day_arr = [].slice.call(document.querySelectorAll('select[name="day"] option'))
  for (let day of day_arr) day.disabled = false;

// loop over all the days to be disabled
// find them in the data object based on the month name
// disable those days
 for (let disabled_day of data.disabled_days[month]) {
    for (let day of day_arr) {
      if (day.textContent == disabled_day) day.disabled = true;
    }
  }
})


text:
Q: Azure DevOps Deploying IIS to windows server password limit? We have an Azure DevOps release pipeline that deploys a .NET website to IIS on a remote server.  Everything was working fine until we changed the password.  The password is correctly changed on the pipeline but for some reason the app pool doesn't get updated properly.  When I input the password manually into the application pool on the server itself, it works fine, but when the pipeline does it, it fails.  The only thing I can think of is that the previous password length was about 10 characters and the new password is much longer.  >35 characters.  Is there a password length limit with Azure DevOps releases?

A: I noticed that if the password begins with a backslsash (\) no matter the length it will fail on deployment, try a different starting character.
Also, there may be other characters causing this, I will edit the post once I have figured out which other characters cause the problem.
As of now, I have successfully used a 39 character password...


text:
Q: How to check if /var/some-dir/* returns anything How to check if /var/some-dir/* returns anything?
I use find /var/some-dir/* ... but if the pattern is empty I get an error.. I don't want to redirect stderr
I want to check before executing find is the pattern will return anything or an error

A: You should be able to process the return value.
If find when used in this way finds nothing, it returns 1, so you can do
find /var/some-dir/*
if [[ $? -eq 1 ]]
then
  perform_failure_action
fi

If you want to check that beforehand, you can try the following:
shopt -s nullglob
f=/var/some-dir/*
if [ -z $f ]
then
   echo "No such file"
else
   find /var/some-dir/*
fi

The shopt line will ensure that if no file matches a glob pattern, it will expand to an empty string, which can then be tested via -z.
In this case, be sure not to quote the $f as you want glob expansion in that test. For the same reason, you must use the single-bracket test operator, not the double-bracket operator, which may implement its own "protection" scheme for the variable under test.


text:
Q: regex expression any character with spaces and carriage returns I would like to find an regex expression that contains any characters and any carriage returns:
Example . I would like to find the String from "Mytext.." to "EndofMyText"
Anytext
Mytextstartshere
        more text
        more text
EndofMyText
LastTet

my Problem is the carriage returns.
What is the correct regex match expression ? :
I started with : Mytext(.*?[\r\n])EndofMyText

A: Maybe you could repeat this part one or more times (?:.*?[\r\n])+ and make it a non capturing group
Mytext(?:.*?[\r\n])+EndofMyText
or use [\s\S]+?
Mytext[\s\S]+?EndofMyText
When using a flag for dot matches newline, you could use Mytext.*?EndofMyText


text:
Q: Assign number jobs as variable in SLURM [bash] I've written a sbatch script for array launching and I'd like to automatically add the number of jobs (without specifying it manually within the script).
I was thinking maybe as a variable, something like that:
sbatch myscript.sbs --n_jobs=30 (or sbatch --n_jobs=30 myscript.sbs)
... and this would be the ideal script (which, of course, it's not working):
#!/bin/bash

#SBATCH --job-name=test
#SBATCH --output=test.log
#SBATCH --mem=2G
#SBATCH --partition=short
#SBATCH --cpus-per-task=10

#SBATCH --array=1-${n_jobs}%5 # <<<--- adjust according number of files to process

<misc commands>

A: Bash variables are not expanded in Bash comments so unfortunately the current version of Slurm does not allow what you are trying to do.
What would work, and is similar to your attempt sbatch --n_jobs=30 myscript.sbs would be
sbatch --array=1-30 myscript.sbs


text:
Q: itextsharp new line in middle of text? my question is how to make text in new line I tried "\n", but its didn't work. My code:
 Dim cell1 As New PdfPCell(New Phrase("line 1 \n line2 \n line3"))
    cell1.Border = 0
    cell1.HorizontalAlignment = 0
    table.AddCell(cell1)

A: Use CHR(10) instead of using the C# '\' escape character.

A: You are currently creating a PdfPCell using text mode. This is meant for simple text only. See Right aligning text in PdfPCell
As soon as you have more text and maybe other types of content such as images, it may be better to use composite mode and to create a cell with different lines by using different Paragraph objects instead of a Phrase (a Phrase isn't supposed to have newlines).
Your code would then look like this:
Dim cell1 As New PdfPCell()
cell1.Border = PdfPCell.NO_BORDER
Dim p1 As New Paragraph("line 1");
p1.Alignment = Element.ALIGN_LEFT;
cell.AddElement(p1);
Dim p2 As New Paragraph("line 2");
p1.Alignment = Element.ALIGN_CENTER
cell.AddElement(p2)
Dim p3 As New Paragraph("line 3");
p1.Alignment = Element.ALIGN_RIGHT
cell.AddElement(p3)
table.AddCell(cell1)

Do yourself (and especially the people who will have to maintain your code) a favor and never use lines such as:
cell1.Border = 0

Replace this by:
cell1.Border = PdfPCell.NO_BORDER

The same goes for:
cell1.HorizontalAlignment = 0

Replace this by:
cell1.HorizontalAlignment = Element.ALIGN_LEFT

You will notice that the people who have to read your code will start respecting you more, because writing code that is easy for them to read and understand is proof that you respect them.
Note: a PdfPCell switches from text mode to composite mode as soon as you use the AddElement() method. In composite mode, the following line will be ignored:
cell1.HorizontalAlignment = Element.ALIGN_LEFT

In composite mode, the cell will use the alignment of the different components in favor of the alignment defined at the level of the cell.


text:
Q: SQL Query fails while running in SQLCMD Mode I need help, I am writing the SQL code shown below for extracting data from multiple servers from the SSMS window of one SQL Server. I have CMC on SERVER1 and have registered SERVER2 as well and all looks good.
But I have a issue in this code:
:CONNECT SERVER1
USE [SOURCE_NAP]
SELECT [CUST_ID]
FROM [SOURCE_NAP].[dbo].[Customer]
GO
EXCEPT

:CONNECT SERVER2
USE [NAP]
SELECT [CUST_ID]
FROM [NAP].[dbo].[Customer]
GO

When I execute individual selects with :CONNECT above them it works fine but when I want to display the output using an EXCEPT between there two selects, I get this error:
Connecting to SERVER1...
Disconnecting connection from SERVER1...
Connecting to SERVER2...

Msg 208, Level 16, State 1, Line 1
Invalid object name 'NNSW_NAP.dbo.[Customer]'

Disconnecting connection from SERVER2...

Seems like before connecting to another instance it tries to disconnect from earlier instance and hence this error. Any way to fix this else Is there any alternate way around to query data from multiple server and then using EXCEPT/UNION etc between them ???
Thanks

A: You cannot separate the batches by introducing GO in the middle. You should have them as single batch.
:connect SERVER1
SELECT [CUST_ID]
FROM [SOURCE_NAP].[dbo].[Customer]
EXCEPT
:connect SERVER2
SELECT [CUST_ID]
FROM [NAP].[dbo].[Customer]
GO


text:
Q: WPF UserControl Initialized event fireing before notmal properties are set This is the situation , you can test it for yourselves :
  The microsoft documentation specifies that when the initialized event is fired , all the properties are set (except bindings)
  If you create a new user control and in the code behind file you define a simple string property, then you put this new control on a page and set that property there , when the initialized event is fired on the user control that property will not be set.
  What is the workaround for this except for using the loaded event (cannot do that as I am only creating the controls in memory without displaying them.
Here is the code for the user control :
Public Class UserControl1

Private _Test As String
Public Property test() As String
    Get
        Return _Test
    End Get
    Set(ByVal value As String)
        _Test = value
    End Set
End Property

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

End Sub

Protected Overrides Sub OnInitialized(ByVal e As System.EventArgs)
    'MyBase.OnInitialized(e)
    Debug.Write(_Test)
End Sub

Private Sub UserControl_Initialized(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Initialized
    Dim parent As FrameworkElement = Me.Parent
    parent = LogicalTreeHelper.GetParent(Me)
End Sub

End Class

A: I'm wondering why you comment out MyBase.OnInitialized(e)?
What your trying to do is to set a property on a child element via XAML. I believe the MSDN article is saying that properties for the current UserControl (if set in XAML) will be set during the call to InitializeComponent.
InitializeComponent is called during the constructor of the UserControl. The parent element (your page) will have to create the UserControl, and therefore cause the constructor to run, before setting any properties on it.
If you want your child to be notified when a property is set, simply add code to that properties setter.
Another option may be to call a sub on the child after the parent has fully loaded.


text:
Q: Multiple inheritance: The derived class gets attributes from one base class only? I was trying to learn the concepts of multiple-inheritance in Python. Consider a class Derv derived from two classes, Base1 and Base2. Derv inherits members from the first base class only:
class Base1:
    def __init__(self):
        self.x=10

class Base2:
    def __init__(self):
        self.y=10

class Derv (Base1, Base2):
    pass

d = Derv()
print (d.__dict__)

The result is { 'x' : 10 } and reversing the order of inheritance gives only { 'y' : 10 }.
Shouldn't the derived class inherit attributes from both the base classes?

A: I don't fully understand why it's like this, but I can tell you how to fix it:
For some reason, Python only calls the __init__ method of one of it's parents. However, this fixes your problem:
class Base1:
     def __init__(self):
         super().__init__()
         print('b1')
         self.x=10

 class Base2:
     def __init__(self):
         super().__init__() # This line isn't needed. Still not sure why
         print('b2')
         self.y=10

 class Derv (Base1, Base2):

     def __init__(self):
         super().__init__()

 d = Derv()
 print (d.__dict__)

'b2'
'b1'
{'y': 10, 'x': 10}

Update, adding print statements actually sheds some light on the situation. For example,
class Base1:
     def __init__(self):
         print('Before Base1 call to super()')
         super().__init__()
         print('b1')
         self.x=10

 class Base2:
     def __init__(self):
         print('Before Base2 call to super()')
         super().__init__() # No remaining super classes to call
         print('b2')
         self.y=10

 class Derv (Base1, Base2):

     def __init__(self):
         super().__init__()

 d = Derv()
 print (d.__dict__)

'Before Base1 call to super()' # Just before the call to super
'Before Base2 call to super()' # Just before call to super (but there are no more super classes)
'b2' # Calls the remaining super's __init__
'b1' # Finishes Base1 __init__
{'y': 10, 'x': 10}

A: When a class inherits from multiple superclasses, and there are 2 or more conflicting methods, the one in the first listed class is called. Because both Base1 and Base2 define __init__, the version of __init__ in the first listed class is called, therefore not defining both of the attributes.

A: This is explained better in Python docs.

For most purposes, in the simplest cases, you can think of the search
  for attributes inherited from a parent class as depth-first,
  left-to-right, not searching twice in the same class where there is an
  overlap in the hierarchy. Thus, if an attribute is not found in
  DerivedClassName, it is searched for in Base1, then (recursively) in
  the base classes of Base1, and if it was not found there, it was
  searched for in Base2, and so on.

Then, as __init__ is first find in your left class, it won't look for others. As other users explained, super() should be used to let Python know how to look for other __init__ methods.

A: You could create objects with class attributes like this:
class Base1:
    x=10

class Base2:
    y=10

Then your Derv class would indeed inherit both properties.
class Derv (Base1, Base2):
    pass

d = Derv()
print(d.x, d.y)  # prints: 10, 10

The __init__ method is called when you create an instance of an object (ie, d = Derv()). An object can only have one version of a given method, so your Derv class only inherits the first one.


text:
Q: send parameter in to shell command I'm newbie to linux so please to help me.
I am using ModemManager on Ubuntu 18.04LTS (Srv1) with GSM modem connected. My task is when some trigger action on server monitor, zabbix will run a script ssh to Srv1 and send SMS to administrator. Here is code:
#!/bin/bash
v1=$1
v2=$2
count=$( cat countmess)
count=$((count+1))
//textt="$v1 have issue $v2"
sshpass -p "12345678" ssh -o StrictHostKeyChecking=no monitor@192.168.29.190 sudo mmcli -m 1 --messaging-create-sms="text='$(v1) have issue $(v2)',number='+8412345678'"
sshpass -p "12345678" ssh -o StrictHostKeyChecking=no monitor@192.168.29.190 sudo mmcli -s $count --send exit
rm -f countmess
echo "$count" >> countmess
exit

call: ./sms_script.sh abc check
sh file receive 2 arguments v1 as hostname(abc) and v2 as trigger name(check). Then it reads a counter variable from "countmess" file. The problem here is the command:
> sudo mmcli -m 1 --messaging-create-sms="text='$(v1) have issue $(v2)',number='+8412345678'"

it returns error:

error: cannot parse properties string: 'Unexpected content (have issue check,number=+8412345678) after value'

please show me the way to fix it.
sorry for my bad  english

A: In your script call v1 and v2 Like this:
sudo mmcli -m 1 --messaging-create-sms="text='$v1 have issue $v2',number='+8412345678'"


text:
Q: Can I use Google Calendar API v3 to access someone else's public calendar without auth? If someone has shared their Google calendar (for example, with a widget that displays it on a web page), then I can get the calendarID, e.g: p75ig3ni1smg4267qg0j0nhodc@group.calendar.google.com
I want to write an Alexa App (in NodeJS) to provide information from that calendar.  (I'm using this sample as a model: https://developers.google.com/google-apps/calendar/quickstart/nodejs).
I have two questions:
1) Can I access it in the Google API without asking the owner of the calendar to perform some steps
2) Since the calendar is public, do I have to be authenticated in the API to access it? The above example assumes you need to authenticate.

A:
Q1) Can I access it in the Google API without asking the owner of the calendar to perform some steps?

*

*A1. Yes. When the owner of the calendar shares calendars, other users can access the calendar using Google Calendar API
. At that time, the owner is not required to do something.

Q2) Since the calendar is public, do I have to be authenticated in the API to access it?

*

*A2. Yes. When users, who are not owner, know the ID of shared calendar, the users can access to the ID by authorizing for each account. Each user can use by the authorization process used at the Quickstart script.

*

*You can test about this using here. When you put the ID of other user's calendar, if the calendar is shared, you can access to it.

If I misunderstand your question, I'm sorry.


text:
Q: How to upgrade a custom jQuery UI theme? I created 2 custom themes with themeroller for JQuery UI 1.7 with themeroller. Now that I update to jQuery UI 1.8.5, I want to make sure that also my themes are updated. How can I automatically re-generate/update my custom themes with themeroller?

A: The jQuery UI theme css file includes an edit link in its comments. This link opens Themeroller with the settings of your custom theme.
  /*
* jQuery UI CSS Framework
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Segoe%20UI,%20Arial,%[...]*/

A: To add to fbuchinger's answer, this didn't work for me at first - one of the colours came through invalid, so the page did not display the theme properly and I was unable to download it.
If you have the same problem, check there is nothing highlighted red (error), correct as required and it should be OK.
And yes I know this would be better as a comment, but I don't have the required 50 reputation to comment.


text:
Q: Map UnsupportedMediaTypeException using ExceptionMapper Is there a place where it is clearly documented that I cannot map UnsupportedMediaTypeException (because it's a rest easy exception and not custom application exception) using the javax.ws.rs.ext.ExceptionMapper?
I want to prove that to my client. Or another thing I would like to do is map this exception to a Response that can be fetched at the client to show the error. Right now when this exception is thrown it provides no information to the client as the application ends abruptly.
Any help would be appreciated.
Thanks

A: You can map this exception. Why not? Do you get an error?
This code should do the job
@Provider
public class EJBExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.UnsupportedMediaTypeException>{

  Response toResponse(org.jboss.resteasy.spi.UnsupportedMediaTypeException exception) {
    return Response.status(415).build();
  }

}

Don't forget to declare that provider in Spring configuration file.
If you want to provide more information to the client create class
@XmlRootElement
public class Error{
   private String message;
   //getter and setter for message field
}

and then you can
@Provider
public class EJBExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.UnsupportedMediaTypeException>{

  Response toResponse(org.jboss.resteasy.spi.UnsupportedMediaTypeException exception) {
    Error error = new Error();
    error.setMessage("Whatever message you want to send to user");
    return Response.entity(error).status(415).build();
  }

}

If you don't want to use Error entity simply pass a string to Response.entity() call.
If you want to catch whatever is thrown in you application create generic exception mapper:
@Provider
public class ThrowableMapper implements ExceptionMapper<Throwable> {

    public Response toResponse(Throwable t) {

        ErrorDTO errorDTO = new ErrorDTO(code);
        return Response.status(500).build();
    }
}