text:
Q: DRF: Method GET return objects based on parameter I am learning Django and am trying to build an endpoint that returns the objects based on a parameter given in the URL.
Currently I have these URLS:
/api/v1/ as root which returns:
GET /api/v1/

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "device-groups": "http://127.0.0.1:8000/api/v1/device-groups/"
}

/api/v1/device-groups/ which returns all the device groups:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "device_group_name": "Default",
        "group_uuid": "7465febe-7c46-4420-85a1-73dfe0af812c",
        "color": "4286f4",
        "is_default": true,
        "customer": {
            "customer_name": "Customer1",
            "customer_uuid": "b3eb5d7d-d1a8-4997-a65b-28bed71b7cc6"
        }
    },
    {
        "device_group_name": "Default",
        "group_uuid": "e12d02d0-7916-477e-b318-9680a38617db",
        "color": "4286f4",
        "is_default": true,
        "customer": {
            "customer_name": "Another customer",
            "customer_uuid": "5b5dafab-c311-4f58-80f5-c50d77fcf8a5"
        }
    },
    {
        "device_group_name": "group of customer1",
        "group_uuid": "c72e87b1-e7c8-4dcd-a9c7-4f6a016d7676",
        "color": "#ffffff",
        "is_default": false,
        "customer": {
            "customer_name": "Customer1",
            "customer_uuid": "b3eb5d7d-d1a8-4997-a65b-28bed71b7cc6"
        }
    }
]

I want an endpoint like /api/v1/device-groups/<customer_uuid>/ which returns the device groups that are related to the given customer_uuid.
My serializers.py:
class CustomerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Customer
        fields = ('customer_name', 'customer_uuid')

class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer):
    customer = CustomerSerializer(many=False, read_only=True)

    class Meta:
        model = DeviceGroup
        fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer')

My views.py:
class DeviceGroupViewSet(viewsets.ModelViewSet):
    serializer_class = DeviceGroupSerializer
    queryset = DeviceGroup.objects.all()

My urls.py:
router = routers.DefaultRouter()
router.register(r'device-groups', views.DeviceGroupViewSet)

urlpatterns = [
   path('admin/', admin.site.urls),
   path('api/v1/', include(router.urls)),
]

I tried overriding get_queryset like this:
def get_queryset(self):
    customer = self.request.GET['customer']
    queryset = DeviceGroup.objects.filter(customer=customer)
    return queryset

But it results in: AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.
What do I need to change to get an /api/v1/device-groups/<customer_uuid>/ endpoint which only shows device groups that are related to the given customer_uuid?
EDIT
Internal Server Error: /api/v1/device-groups/
Traceback (most recent call last):
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\utils\datastructures.py", line 77, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'customer'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\mixins.py", line 40, in list
queryset = self.filter_queryset(self.get_queryset())
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\app\core\views.py", line
13, in get_queryset
customer = self.request.GET['customer']
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\utils\datastructures.py", line 79, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'customer'`

A: Router could not determine basename. You have to define a basename in your router. Like this
router.register(r'device-groups', views.DeviceGroupViewSet, base_name='device-groups')

base_name is actually used to generate names for routes / urls. You can read more about it here.

A: I am not familiar with DRF but in general in order to get the object based on a parameter you have to:
1) Define your url in such a way to take in mind the customer_uuid you are going to type dynamically when you want to build your endpoint
So, with the help of regex you have to build something like:
url(r'^/api/v1/device-groups/(?P<customer_uuid>\d+)/$', views.your_view, name='your_view')

The regex \d+ will match an integer of arbitrary size. This integer will be used to retrieve the Customer from the database. Now observe that I wrote the regex as (?P\d+), this is telling Django to capture the value into a keyword argument named customer_uuid.
2) Define your view function
from django.shortcuts import render, get_object_or_404
from .models import Customer

def your_view(request, customer_uuid):
    customer = get_object_or_404(Customer, pk=customer_uuid)
    return render(request, 'customer.html', {'customer': customer})

Hope it helps

A: You should get what you want if you define a different lookup_field in the view like:
class DeviceGroupViewSet(viewsets.ModelViewSet):
    serializer_class = DeviceGroupSerializer
    queryset = DeviceGroup.objects.all()
    lookup_field = 'customer_uuid'

Or maybe you'dl like to take a look to this documentation to consider a different approach.


text:
Q: Summing Every Other Element of a List/Turning Every Other Element Complex Given a general list of numbers, say, [1, 2, 3, 4, 5, 6], I need to split this list into the form [(1 + 2j), (3 + 4j), (5 + 6j)].
I can split the list into two lists - [1, 3, 5] and [2, 4, 6] - but encounter two problems when attempting to combine them into the desired form: i) that I cannot multiply the second list by 1j, returning the error "can't multiply sequence by non-int of type 'complex'", and ii) the list would be of the form [1, 3, 5, 2, 4, 6] anyway due to concatenation.
Given that I'm working with lists that have 2048 elements, could anybody suggest any quick solutions to this problem, as obviously the size makes individually inputting the data in the desired format impractical.

A: use zip() and slicing:
In [72]: lis=[1, 2, 3, 4, 5, 6]

In [73]: [complex(a,b) for a,b in zip(lis[::2],lis[1::2])]
Out[73]: [(1+2j), (3+4j), (5+6j)]

or:
In [74]: [complex(lis[i],lis[i+1]) for i in range(0,len(lis),2)]
Out[74]: [(1+2j), (3+4j), (5+6j)]

or using an iterator, a memory efficient solution:
In [76]: it=iter(lis)

In [77]: [complex(next(it),next(it)) for _ in range(len(lis)/2)]
Out[77]: [(1+2j), (3+4j), (5+6j)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to "properly" send sms when call is received? I am trying to have an Android Service listen for an incoming phone call and when one does occur, grab the incoming number and text it a message.
In my service I have made a PhoneStateListener:
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener listener = new PhoneStateListener()
{
    @Override
    public void onCallStateChanged(int state, String incomingNumber)
    {
        switch(state)
        {
            case TelephonyManager.CALL_STATE_IDLE:
                Log.d(TAG, "Phone: Idle");
            break;
            case TelephonyManager.CALL_STATE_RINGING:
                Log.d(TAG, "Phone: Ringing.");
                Log.i(TAG, "Incoming call from: " + incomingNumber);
                sendSms();
            break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Log.d(TAG, "Phone: Off Hook");
            break;
        }
    }
};
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

My sendSms() function is as follows:
private void sendSms()
{
    SmsManager manager = SmsManager.getDefault();

    wakeLock.acquire();
    Log.d(TAG, "Wake Lock Acquired!");

    if (getMessageContent(getInformStatus()).length() > 160)
    {
        ArrayList<String> messagelist = manager.divideMessage(getMessageContent(getInformStatus()));

        manager.sendMultipartTextMessage(getReturnAddress(), null, messagelist, null, null);
        Log.i(TAG, "Multipart Text Message Sent!");
    }
    else
    {
        manager.sendTextMessage(getReturnAddress(), null, getMessageContent(getInformStatus()), sentPI, null);
        Log.i(TAG, "Text Message Sent!");
    }

    wakeLock.release();
    Log.d(TAG, "Wake Lock Released!");
}

I even have an SMS_SENT Broadcast Receiver to check if the text message sent out correctly that will recall the sendSms() function if it did not sent for whatever reason:
resend = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        switch (getResultCode())
        {
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Log.e(TAG, "Text did NOT send (GENERIC_FAILURE)");
                Log.i(TAG, "Attempting to resend");
                sendSms();
            break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Log.e(TAG, "Text did NOT send (NO_SERVICE)");
                Log.i(TAG, "Attempting to resend");
                sendSms();
            break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Log.e(TAG, "Text did NOT send (RADIO_OFF)");
                Log.i(TAG, "Attempting to resend");
                sendSms();
            break;
        }
    }
};
registerReceiver(resend, new IntentFilter("android.provider.Telephony.SMS_SENT"));

This works on my phone fine, however on other people's phones it likes to sometimes toggle back and forth between RINGING and IDLE in the PhoneStateListener a few times before "sending"..  The phone actually says that the application is trying to send multiple text messages and asks the user if that is okay.  When they click yes, it just asks again.
To make it better, it never actually sends the text message either..
On another phone, it doesn't do this at all..  The other phone will go through the motions and the logcat is identical to mine.. It actually says it sends, but the recipient never gets the SMS..
It is suppose to be an auto-response service of sorts and I wanted to try and make it work on at least Froyo, Gingerbread, and Ice Cream Sandwich..
By the way, it works 100% on my:
  Galaxy Nexus (toro) (Android 4.0.3)
  Droid 1 (sholes) (Android 2.3.7)
  HTC Thunderbolt (mecha) (Android 2.3.7)

However, if it's my friend's:
  Nexus S 4G (crespo4g) (Android 4.0.3)
    or my other friend's
  Galaxy Nexus (toro) (Android 4.0.3)

It does not work..
What I really don't understand is that it doesn't work with my friend with the exact same phone as me..
I feel like this code implementation is a hit or miss and was wondering if anyone had some insight to help out.
Appreciate it!

A: I think I figured it out.  What I ended up doing is putting a Handler that called a Runnable 30 seconds after the phone call was initially received..  This gave the phone time to finish the phone call (assuming it was in your pocket) and then cleanly send the text message..
I hope this is the only issues I was having, but it seems to work on my friends Galaxy Nexus (toro) now..
Hope this helps anyone else wondering about this..
Cheers!


text:
Q: Word for resembling the truth How do we refer to the act of resembling the truth, regardless if it is indeed the truth?
Some context: suppose you are watching a film and the story bears a striking resemblance to "real life". Perhaps you remember similar events from your own background or the story has a strong internal coherence. So you feel that the story could be true, even though you know it is fictional. Or, as the legend has it, when Michelangelo finished his "Pietà" and the sculpture seemed so "real" and "natural" to him, that he was amazed that the sculpture couldn't talk. One last example: you hear the promises of a politician in election campaign and he seems to be telling the truth, but of course you have no way to figure out, beforehand, if he is being honest or not.
The word "likelihood" comes to mind, but this word suggests some kind of numerical (even statistical) evaluation, which is akin to "probability". The word I am looking for describes the feeling you get, which leads to a subjective "binary" judgement (either it resembles the truth or not).
In Portuguese, such word is "verossimilhança" (from Latin verum, truth + similis, similar).

A: I think you're looking for realistic.

A: You might try plausible. From NOAD:

plausible |ˈplôzəbəl|
adjective
(of an argument or statement) seeming reasonable or probable : a plausible explanation | it seems plausible that one of two things may happen. See note at believable.

Or look at the usage notes under believable for a synonym:

THE RIGHT WORD
Believable is the most general of these terms, used to describe anything we accept as true, even in the absence of absolute proof (: a believable story about why she was late).
Credible also means worthy of belief or confidence and is often used interchangeably with believable, but it goes one step further: a credible excuse is one that is supported by known facts.
Creditable, often confused with credible, at one time meant worthy of belief but nowadays is used to mean respectable or decent, deserving of honor, reputation, or esteem (: leading a creditable life).
Something that is convincing is believable because it overcomes doubts or opposition (: a convincing performance), while something that is plausible may appear to be convincing or believable on the surface, but may not be so upon closer examination.
Valid means legally sound, just, or authoritative; a valid criticism seldom provokes opposition.
Cogent, on the other hand, means having the power to convince; a cogent argument is believable because of its clear, forceful, or incisive presentation.

A: You might say, "Something has an air of verisimilitude about it," meaning you have the feeling that it's true or real.
For an example in the negative:

No air of verisimilitude to this otherwise unconvincing narrative

Verisimilitude:

1.The quality of appearing to be true or real.
  2. Something that has the appearance of being true or real.

A: To add to the others:

*

*for objects, scenes, narratives that are either constructed or found, they can be described as realistic, and have realism or verisimilitude.

*for people speaking, they can be sincere, and what they say can be plausible.

truthiness has a tendentious nuance to the latter (in the direction of disingenuous but not quite as deliberate).

A: Verisimilitude.  It's hardly used these days (even in Gilbert & Sullivan it was only for comic effect), but that's undoubtedly what it means.

A: A story that is generally supposed to be true, but for whose accuracy little or no hard evidence exists, is apocryphal, anecdotal, or an example of wishful thinking or even magical thinking.
A fact that is stated to be true without actually being true is sometimes called a factoid (a term coined by Norman Mailer -- see http://en.wikipedia.org/wiki/Factoid ). Today, it also has a secondary connotation as 'a trivial fact'.


text:
Q: React ErrorBoundary doesn't work with render exceptions I implemented the React Error Boundaries as described here: https://reactjs.org/docs/error-boundaries.html
It works as expected when there are exceptions produced in function components, however, today I got a white screen and I just noticed that the exception came from the Render section of the component.
This is my ErrorBoundary component:
  export class ErrorBoundary extends React.Component {
  static getDerivedStateFromError(error: Error) {
    console.error(error);
  }
  render() {
    return this.props.children;
  }
}

Which is implemented as followed:
export default function App() {
 return (
 <ErrorBoundary>
    <ChildComponent />
 </ErrorBoundary>
);
}

ChildComponent:
interface Item {
      name: string;
      value: number;
   }

export const ChildComponent: React.FC = () => {
 const [collection, setCollection] = useState<Item[]>([]);

 return (
 <>
   <button
     onClick={() => console.log(collection[0].name)}>//this throws a console.error but the component keep mounted correctly
     Click
     {collection[0].name}//this throws a console.error and a white screen
   </button>
 </>
);
}

I'd like to know what could I do to handle this type of exceptions since it is inevitable to have these situations where there might be an error and a white screen is not ideal.

A: Your ErrorBoundary always renders the children when an error is caught, which ones again throws the same error.
You should conditionally render a different fallback UI component when there are errors.
export class ErrorBoundary extends React.Component {
   static getDerivedStateFromError(error: Error) {
     return {
       error // set some state based on error
     }
   }
   render() {
     if (this.state.error) { // render fallback UI if error occured
       return (<div> an error occured - action </div>);
     }
     // render children only when there isn't an error
     return this.props.children;
   }
}


text:
Q: Get Subfolder for a folder using WMI I am trying to access Subfolders for a folders. Below is my Code.
ConnectionOptions conn = new ConnectionOptions();
                conn.Impersonation = ImpersonationLevel.Impersonate;
                conn.Username = _userName;
                conn.Password = _password;

ManagementScope theScope = new ManagementScope("\\\\" + selectedServer.IPAddress + "\\root\\cimv2", conn);
ManagementObjectSearcher servSearcher2 = new ManagementObjectSearcher(theScope, new ObjectQuery(@"ASSOCIATORS OF {Win32_Directory.Name ='c:\\users'} WHERE AssocClass = Win32_Subdirectory ResultRole = PartComponent "));
ManagementObjectCollection servObj1= servSearcher2.Get();
foreach (ManagementObject obj in servObj1){}

Its Giving an error "Invalid object path". Any idea what I m doing wrong?

A: in the windows Operating systems the ".." folder is a linked folder to the parent folder and will take you up one level
you could call a loop that continues to navigate to ".." until you find the folder name your looking for.  A 'top folder' of any folder would be your drive letter (root dir).  Be careful though as ".." is found in every directory (except your root dir) so ".." would be relative to the folder your currently in.


text:
Q: Why handle Observables inside of middleware - vs dispatching the output of combined Observables? I feel like I'm taking crazy pills when I see all these middlewares that encourage you to dispatch an action which emits other actions asynchronously. I think the async CAN (and maybe should?) be done before the store.
To me the benefit of Rx is that you can take an incoming stream of actions, map some of them to observables of other actions, and flatMap the entire result to get an ordered series of events. Then you can chain that resultant stream into the store by dispatching each event to it.
Not only does putting async inside of actions take the simple model of Redux and complicate it, but it means that as you time-travel debug - you may cause firing off of new AJAX requests (which can rewrite your history as you scrub?).
I guess I feel like putting the power of RxJS in front of the store makes plenty of sense to me, but I'm confused why a library to put it in
side the store makes sense. I agree that Observables are a great model for Epics, but I wonder if Redux is being made to care about things that it should never know about.
Background: I've watched this video https://www.youtube.com/watch?v=AslncyG8whg, have been learning Rx for a few years, Redux half a year.

A: Store enhancers wrap around each other.  Using Redux's compose function, the enhancers passed to compose are ordered from right to left.  So, if I use const storeEnhancer = compose(applyMiddleware(...middlewares), DevTools.instrument()), the DevTools enhancer will wrap around the real store, and the middleware enhancer will wrap around the DevTools enhancer.
That means that time-travel debugging will only use actions that have gotten through all the middleware, and replaying those actions will not pass them through the middleware chain again.  In other words, only actions that actually affected the store will be replayed.
The other thing to consider is that things like middleware allow access to the store's API for purposes of dispatching and checking state, and can be considered "inside" the store, but ultimately the key is that they are handled in a layer above the "real" store itself.
You may want to read Dan's excellent writeups on middleware and async behavior: How to dispatch a Redux action with a timeout? and Why do we need middleware for async flow in Redux? , which help clarify the reason for middleware, as well as the other links and explanations at http://redux.js.org/docs/FAQ.html#actions-side-effects .


text:
Q: How to get rid of error when building React-native app in Xcode I have created an application on React-native and have fully tested it on Android platform, where it works perfectly well. Now I want to build it for iOS.
So what I did was:

*

*Cloned the repository of my project from GIT to my Mac machine

*Run npm install

*Run react-native link

*Run react-native run-ios

This launched the simulator perfectly and I got exactly what I wanted.
But, when I try to build my app in Xcode, it fails with the following error:
ld: warning: directory not found for option '-F/Users/admin/Library/Developer/Xcode/DerivedData/DataCollector-ggwfxznelyjbjzcodfrlmajkazaj/Build/Products/Debug-iphonesimulator/React'
ld: framework not found React
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'm using React-native version 0.35 on Mac OS 10.11.6 with Xcode 8.1.


text:
Q: What is a type? In terms of mathematical logic can someone give me a definition of the word 'type' along with a few examples of the word being used.
The book I am reading defines it as a "representative of inscriptions that look the same and utterances that sound the same", I find this kind of vague, and I can't understand the definition given by wikipedia.

A: Looking at page 3 of the book linked, the author is using "type" in the philosophical sense, not the mathematical sense. This "type-token distinction" is a topic that gets a lot of attention in philosophy, but most books on mathematical logic don't discuss it, because we can get by for a long time without worrying very much about it, and because the time it takes to discuss it properly would take time and energy away from the mathematics.
The general idea is that there is some collection of abstract "types" of things. For example, there is a type of "bicycles" and a type of "apples". Then there are specific bicycles - each of which is a "token" of the type of bicycles, and there are specific apples, which are tokens of the type of "apples". This should sound vaguely like something from Plato.
Similarly, there is a type of "the string 101". Each time I write down "101", I write down only a token of the string. So 101, 101, and 101 are three different tokens of the same string.
In philosophy, the question "what is a type, really?" has received a lot of discussion, as you might imagine. But that question is not particularly important to the direct study of mathematics, we can do a lot of math without ever worrying about it.
One place that the type/token distinction does arise in logic is with occurrences of variables. Consider the sentence of first-order logic
$$
R(x) \land (\exists x) [P(x)]
$$
Here there is only one variable, "x" - so a variable is a type. There are two occurrences (tokens) of the variable, though (three if we count "$(\exists x)$"). One of them is in the scope of a quantifier, and the other is not. This distinction between "variables" and "occurrences of variables" is quite important for understanding the concept of free and bound variables.
In the field of type theory (and computer programming) there is a somewhat related idea of the type of a variable. In these systems, every variable has a "type" associated with it, and the type of the variable dictates what can be done with the variable. For example, in one system I have a type of natural numbers and a type of sets of natural numbers. If I have two numbers, I can add them. If I have a number and a set, I can ask whether the number is an element of the set. But, in this typed system, I cannot add two sets or ask whether a number is an element of another number, because those operations don't match those types. Most first-order logic is done in a non-typed way (so there is only one type of variable).
So do you need to worry about the type-token distinction for propositional logic as a student learning it for the first time? If you are interested in the philosophical aspects of the subject, then you certainly do. If you are only interested in the purely mathematical relationships between the formulas of the logic, and less about the applications of the logic to philosophy, then you may be able to get by, as many texts do, using some common sense but otherwise not spending too much time distinguishing types from tokens.

A: I think that the author may refer to an ontological concept of type-token. Perhaps you could find more on this link.

A: In computer languages like C or Haskell, you're only allowed to perform operations that make sense for the type. So, you could append a letter to a string of letters "hello"+'s'="hellos", but unless you define what it means to, you wouldn't be able to append 's' to a number, and indeed you might not expect + to carry the semantics of appending something.
The model theory version of a type is essentially a duck typing system, like you find in Ruby - if it looks like a string, and you can append strings to it like a string, then it's a string. To do this you need a way to build a type's set of behaviors, which is implemented as a set of first-order formulas.

EDIT: I've thought of a programming metaphor for the type/token distinction, as well.
Object-oriented programming is based around defining classes, which are types in the previous senses of the word, to use as a template for creating tokens of that type. For example, in games where many of the same enemy can exist at once, you could define a class for that enemy and instantiate it many times, thus creating many enemies all of the same type. But the difference between the type and the tokens is one can have the type "string", and an actual string, like "hello world," and you would check the type of "hello world", not the token itself, when making sure you don't set a character's position in space to "hello world." Same goes for removing all (tokens) of one type of enemy from the game - which doesn't remove the type itself from the game.

A: Actually, the central logical place, where the notion of type is present is the realm of higher-order logics, since these logics are usually developed as extensions of type-theories (, which need not be logics). In this higher-order context types are intuitively best understood as sorts of interpretable expressions, that determine the kind of semantic objects assigned to expressions of these sorts.
Precise definitions of types in a general format are difficult to give, so I will try to convey some precision by outlining (the beginnings of) Church style (extensional) higher-order logic, which extends Church's simple theory of types. Let the set of types, $T$, be the smallest set containing some set of simple types (usually represented as $e$ and $t$) which is closed under the construction of functional types $\sigma \rightarrow \tau$ (functional types $\sigma \rightarrow \tau$ are interpreted as functions from things of type $\sigma$ to things of type $\tau$). We assume that the vocabulary contains, besides the logical constants $=$ and $\lambda$,  an denumerably infinite list of variables of type $\tau$ and a list of constants of type $\tau$, for all $\tau \in T$. Syntax is given in Backus-Naur form (Indices indicate types):
$$
\alpha_\sigma ::= x_\sigma~ | ~c_\sigma~ |~ \beta_\tau = \gamma_\tau, ~\text{where}~ \sigma = t~|~ \beta_{\eta \rightarrow \sigma}(\gamma_\eta)~|~\lambda x_\eta. \beta_ \rho, \text{where}~ \sigma = \eta \rightarrow \rho
$$
For some $D \not = \emptyset$ let $I_{e, D} := D; I_{t, D} := 2 = \lbrace 0, 1 \rbrace; I_{\sigma \rightarrow \tau, D} := I_{\tau, D}^{I_{\sigma, D}}$. Let a model be a pair $M=\langle D, a \rangle$ such that $a: Con_\sigma \rightarrow I_{\sigma, D}$ ($Con_\sigma := \lbrace c_\sigma: \sigma \in T\rbrace$), and an assignment (in $M$) a function $\theta: Var_\sigma \rightarrow I_{\sigma, D}$ ($Var_\sigma := \lbrace x_\sigma : \sigma \in T \rbrace$). Finally we define a denotation function $\mathcal{\Delta}_{M, \theta}$, that assigns to each $\alpha_\sigma$ a member from $I_\sigma$. Let $\Delta_{M, \theta}(c) := a(c); \Delta_{M, \theta}(x) := \theta(x); \Delta_{M, \theta} (\beta = \gamma) := 1 ~\text{iff}~ \Delta_{M, \theta}(\beta) = \Delta_{M, \theta} (\gamma); \Delta_{M, \theta}(\beta(\gamma)) := \Delta_{M, \theta}(\beta) (\Delta_{M, \theta}(\gamma)); \Delta{M, \theta}(\lambda x. \beta):=f: I_\sigma \rightarrow I_\tau ~\text{such that} f(d) = \Delta_{M, \theta \frac{d}{x}}(\beta).$ The usual truth functions and higher-order quantifiers can be introduced via Henkin style definitions.


text:
Q: (SQLite + Javascript) issue with INSERT followed by SELECT in a for loop I am having an issue with the following and I guess it's due to SQLite asynchronous mode. The code is pretty long so I'll try to explain briefly.
I have 4 inputs
<input id="input0" name="tbleName3">
<input id="input1" name="tbleName4">
<input id="input2" name="tbleName1">
<input id="input3" name="tbleName1">

Actually, in my application the number of inputs is not fixed and is dynamically changed by the user. The order of the input id is fixed, i.e the index is incremental index++... However, the name can be changed dynamically. The name of the input is the name of a table in the db. Here is what I am trying to accomplish: I put all the names in an array.
 arrInput=array(tbleName3, tbleName4, tbleName1, tbleName1).
Now, I want to partially fill each of the db table, whose name is in the array, and get the newly created id values in each of the tables. Note that all tables have the same two first columns: tablePattern[id INT, some TXT, ......]
db.transaction(function(tx) {
   for(var i=0; i < arrInput.length; i++){
      var thisTble = arrInput[i];
      var insertSqlArg = "INSERT INTO "+thisTble+" (some) VALUES (?)";
      tx.executeSql(insertSqlArg, ["thing"], (function(i, thisTble){return     function(tx,resultIdNew){
         var selectSqlArg = "SELECT id from "+thisTble+" order by id DESC limit 1";
         tx.executeSql(selectSqlArg, [], function(tx,resultId){
        var datasetId = resultId.rows;
            var itemId = datasetId.item(0);
        var idValue = itemId['id'];
        alert("i="+i+", tbleName="+thisTble+", New id="+idValue);
         }), fnError);
      };})(i, thisTble), fnError);
   }
}

If the name of the 4 inputs are different (for instance {tbleName1, tbleName2, tbleName3, tbleName4}), the code works great. The bug occurs when 2 or more inputs use the same name (for instance {tbleName1, tbleName2, tbleName3, tbleName3}), i.e 1 row is added to tbleName1 and tbleName2, and 2 rows to tbleName3. In that case, instead of reporting the id of the first row created (for instant 14) and then the 2nd row created (15) in tbleName3, the alert box will show twice the id of the very last row added (15). I don't know how to fix that. It seems that the command to create the 2nd row is fired before the id of the row created first is read.
//The final goal of the code is to insert idValue and thisTble in another table 'flowTble'. The line:
alert("i="+i+", tbleName="+thisTble+", New id="+idValue);

is in fact replaced by:
var insertFlow = "INSERT INTO flowTble (some, tbleName, idTbleName, index) VALUES (thing, ?, ?, ?)";
tx.executeSql(insertFlow , [tbleName, idValue, i], null, onError);

The problem is still the same though (select gives only the very last id created). However, I might have a better chance by using a 'Trigger' that would run just after "INSERT INTO "+thisTble+" (some) VALUES (?)", and insert a set of values in flowTble. BUT, I don't know how to create such a Trigger with JS wrapper. Here is a try:
var createTrigger = "CREATE TRIGGER fillFlowTble AFTER INSERT ON "+TbleName+" FOR EACH ROW INSERT INTO flowTble (some, tbleName, idTbleName, index) VALUES (thing, tbleName, idValue, i)";
db.transaction(function(tx) {
    tx.executeSql(createTrigger, [], null, onError);
});


text:
Q: Need batch file to print the IPV4 Address, Subnet, Gateway and DNS Servers to a text file please I am trying to automate a task for work - we are currently doing screenshots of the ipconfig /all screen but all I need is the IPV4 Address, subnet, gateway ad DNS Servers.
I can get the IP address to print using the following:
echo IPAddress is: >> Admin.doc
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip% >> Admin.doc

I have several tasks that I need to automate and will be updating this document with each task.

A: for /f "tokens=1-5 delims=," %A in ('wmic nicconfig get ipaddress^,ipsubnet^,DNSHostname^,defaultipgateway /format:csv') do echo %A - %B - %C - %D - %E

or perhaps
for /f "tokens=2-5 delims=," %A in ('wmic nicconfig get ipaddress^,ipsubnet^,DNSHostname^,defaultipgateway /format:csv') do echo %A - %B - %C - %D

or
wmic nicconfig get ipaddress^,ipsubnet^,DNSHostname^,defaultipgateway /format:csv > File.txt

or
wmic /output:"file.txt" nicconfig get ipaddress^,ipsubnet^,DNSHostname^,defaultipgateway /format:csv

See wmic /?, wmic /node /?, wmic /output /?, wmic /append /?, wmic nicconfig /?, wmic nicconfig get /?, wmic nicconfig call /?, wmic nicconfig set /?, wmic /format /?.

A: I think I figured this out - need to get the MAC id fixed though... its not pulling the MAC ID...
echo IPAddress is: >> Admin.doc
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip% >> Admin.doc

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "Subnet"') do set     sub=%%b
set sub=%sub:~1%
echo Subnet is: >> Admin.doc
echo %sub% >> Admin.doc

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "Default"') do set gate=%%b
set gate=%gate:~1%
echo Gateway is: >> Admin.doc
echo %gate% >> Admin.doc

echo MAC ID is: >> Admin.doc
getmac >> Admin.doc

The mac is not necessary - but would be nice.


text:
Q: joomla using menu item type alias in multilingual website I have a multi language website ( English and arabic) , two menus ( one for arabic and one for english),  I am trying to make the menu item types of arabic menu as alias for the english menu items , The result in front end:
when not using SEO, the arabic meu items are working normally as alias for the english ones , But when turning SEO Enabled , clicking on arabic menu items give 404 Article not found.
any help please?

A: Definitely joomla supported for Multilingual. you can edit to change the menu alias urls.can i know the joomla version you have installed
Below the very useful to you can you check it now.
http://www.templatemonster.com/help/joomla-3-x-configuration-multilanguage-site.html
http://multilingual.demojoomla.com/multi-lingual-tips.html


text:
Q: Python can't add to dictionary, TypeError: list indices must be integers, not str I'm having trouble writing a key:value to a dictionary. My code is fairly straight forward, I loop through an existing dictionary, calculate a score, and add that score to a new dictionary:
        results = {}
        for key in db:
            pickleFilePath = db[key][0]
            fileObject = open(pickleFilePath,'r')
            (kps, descs) = pickle.load(fileObject)
            fileObject.close()

            score = self.match(queryKps, queryDescs, kps, descs)

            results[key] = score
            if len(results) > 0:
                results = sorted([(v,k) for (k, v) in results.items() if v > 0],
                         reverse = True)

However I get this error: TypeError: list indices must be integers, not str. It seems to pop up after successfully adding 1 key-value to the dict. Any help appreciated, thanks.

A: In this line you are converting your results dict to a list.
   results = sorted([(v,k) for (k, v) in results.items() if v > 0],
                         reverse = True)

Then in your next loop, you will try to index results with a string and you will get TypeError: list indices must be integers, not str
Remember, usually a dict has no order sense.


text:
Q: Error -another entity of the same type already has the same primary key value (.NET) Good afternoon,
I have an error, and I think you can help me.

*

*Error

System.InvalidOperationException
HResult=0x80131509
Message=Attaching an entity of type 'SGI2DataAccess.Models.ProjectForecast' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Objects.ObjectContext.VerifyRootForAdd(Boolean doAttach, String entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, EntitySet& entitySet, Boolean& isNoOperation)
at System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassa.<Attach>b__9()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
at System.Data.Entity.DbSet`1.Attach(TEntity entity)
at SGI2.Data.Infrastructure.RepositoryBase`1.Update(T entity) in C:\work\sgi\SGI2.Data\Infrastructure\RepositoryBase.cs:line 41
at SGI2.Service.Services.Projects.ForecastProject.UpdateForecast(List`1 forecasts, ProjetoVM Projeto) in C:\work\sgi\SGI2.Service\Services\Projects\ForecastProject.cs:line 79
at SGI2.Service.ProjetosService.UpdateProjeto(ProjetoEditVM VM, Int32 userId, String userNomeConhecido) in C:\work\sgi\SGI2.Service\Services\Projects\ProjetosService.cs:line 1212
at SGI2.Controllers.ProjetosController.Edit(ProjetoEditVM VM, String Command) in C:\work\sgi\SGI2\SGI2\Controllers\Projeto\ProjetosController.cs:line 312
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()

*

*Code
object: \sgi2\SGI2\Controllers\Projeto\ProjetosController.cs

(...)
// Interface
private readonly IProjetosService _service;
(...)

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(ProjetoEditVM VM, string Command)
    {
        #region PERMISSOES
        if (!ClaimsAuthorization.CheckAccess("generic-editprojetos", VM.Projeto.Id.ToString(), VM.Projeto.EstadoId.ToString()))
            return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

        // Completed projects should never be able to be edited
        if (_service.GetProjeto(VM.Projeto.Id).EstadoId == 2)
            return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

        #endregion
        else if (ModelState.IsValid)
        {
            if (VM.Projeto.EstadoId == 2 && (VM.Projeto.TipoId == 8 || VM.Projeto.TipoId == 9) && !_service.GetAllProjetosPPRInfo(x => x.ProjetoId == VM.Projeto.Id && x.IsTheLast).Any())
            {
                return RedirectToAction("Edit", new { Id = VM.Projeto.Id, param = "CloseProjectLastPPRInfoError" });
            }

            // Se vem do botão "Refresh Forecast", atualizar valores, antes de submeter com valores desatualizados
            if (Command == "RefreshForecastButton")
            {
                _service.UpdateProjetoRF(VM, UserId, UserNomeConhecido); // ok
                RefreshForecastButton(VM, Command, UserId, UserNomeConhecido);
                _service.UpdateProjeto(VM, UserId, UserNomeConhecido); // NOT ok
            }
            (...)
        }  (...)

    }
(...)

object: \sgi\SGI2.Service\Services\Projects\ProjetosService.cs
public void UpdateProjeto(ProjetoEditVM VM, int userId, string userNomeConhecido)
{
    //Atualiza projeto

    var dbObj = projetosRepository.GetById(VM.Projeto.Id);
    (...)
    new ForecastProject(projectForecastRepository, projetoPPRInfoRepository).UpdateForecast(VM.Forecasts, VM.Projeto);
    (...)
    unitOfWork.Commit();

}

object: \sgi\SGI2.Service\Services\Projects\ForecastProject.cs
namespace SGI2.Service.Services.Projects
{
    //Tenho de criar uma interface e remover a dependecia dos repositórios
    public class ForecastProject
    {

        private readonly IProjectForecastRepository projectForecastRepository;
        private readonly IProjetoPPRInfoRepository projetoPPRInfoRepository;
        private readonly IForecastDomain Iforecast = new ForecastDomain();

        public ForecastProject(IProjectForecastRepository projectForecastRepository, IProjetoPPRInfoRepository projetoPPRInfoRepository)
        {
            this.projectForecastRepository = projectForecastRepository;
            this.projetoPPRInfoRepository = projetoPPRInfoRepository;
        }
        (...)

        public void UpdateForecast(List<ProjectForecastEditVM> forecasts, ProjetoVM Projeto)
        {
            // 1º Caso não exista linhas
            if (forecasts == null || forecasts.Count() == 0)
            {
                foreach (var item in Iforecast.InitialLinesForecast(Projeto))
                {
                    projectForecastRepository.Add(item);
                }
            }

            // 2º caso a data de fim do projeto aumente
            else if (Projeto.RealEndDate > forecasts.LastOrDefault().EndDate)
            {
                foreach (var item in Iforecast.ChangeRealEndDateForecast(Projeto,forecasts.LastOrDefault().EndDate))
                {
                    projectForecastRepository.Add(item);
                }
            }

            else
            {
                List<ProjectForecast> Forecasts = new List<ProjectForecast>();
                foreach (var i in forecasts)
                {
                    //Está assim pois a data fim pode mudar e deixar de ser o ultimo dia do mês
                    DateTime EndDate = new DateTime(i.EndDate.Year, i.EndDate.Month, DateTime.DaysInMonth(i.EndDate.Year, i.EndDate.Month));
                    //Ultimo dia do mês do projeto
                    DateTime LastDateofProject = new DateTime(Projeto.RealEndDate.Value.Year, Projeto.RealEndDate.Value.Month, DateTime.DaysInMonth(Projeto.RealEndDate.Value.Year, Projeto.RealEndDate.Value.Month));

                    if (EndDate > LastDateofProject && i.CanWrite == true)
                    {
                        projectForecastRepository.Delete(projectForecastRepository.GetById(i.Id));
                    }
                    else
                    {
                        Forecasts.Add(UpdateForecastForecastFactory(Projeto, i));
                    }
                }

                foreach (var item in Forecasts)
                {
                    projectForecastRepository.Update(item); ! The error is thrown here !
                }
            }
        }

    }
}

object: \SGI2.Data\Infrastructure\IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace SGI2.Data.Infrastructure
{
    public interface IRepository<T> where T : class
    {
        // Marks an entity as new
        void Add(T entity);
        // Marks an entity as modified
        void Update(T entity);
        // Marks an entity to be removed
        void Delete(T entity);
        void Delete(Expression<Func<T, bool>> where);
        // Get an entity by int id
        T GetById(int id);
        // Get an entity using delegate
        T Get(Expression<Func<T, bool>> where);
        // Gets all entities of type T
        IEnumerable<T> GetAll();
        // Gets entities using delegate
        IEnumerable<T> GetMany(Expression<Func<T, bool>> where);

    }
}

object: \SGI2.Data\Infrastructure\RepositoryBase.cs
public virtual void Update(T entity)
{
    dbSet.Attach(entity); ! The error is thrown here !
    dataContext.Entry(entity).State = EntityState.Modified;
}

What can I do to resolve?
What i want is call twice  :_service.UpdateProjeto
Best regards
Isabel Fonseca


text:
Q: Why did my zpool replace never finish and what should I do now? I have a ZFS zpool with two disks in a mirror configuration, da0 and da1. da1 failed, and so I replaced it with da2 using
zpool replace BearCow da1 da2

This ran for a few hours, during which zpool status showed that the array was being resilvered. When that finished, zpool status showed that the resilver was completed, but the array was still degraded...
I tried a zpool scrub and a zpool clear, but the array still shows as degraded:
[root@chef] ~# zpool status BearCow
  pool: BearCow
 state: DEGRADED
 scrub: scrub completed after 0h20m with 0 errors on Tue Oct  9 16:13:27 2012
config:

        NAME           STATE     READ WRITE CKSUM
        BearCow        DEGRADED     0     0     0
          mirror       DEGRADED     0     0     0
            da0        ONLINE       0     0     0
            replacing  DEGRADED     0     0     0
              da1      OFFLINE      0     0     0
              da2      ONLINE       0     0     0

errors: No known data errors

I can't zpool replace BearCow da1 da2 anymore because da2 is already a member of BearCow...
This is FreeBSD (FreeNAS) running ZFS pool version 15.
How do I get my array to show as healthy again?

A: Try:
zpool detach BearCow da1

See if it spits out any error messages or resolves the issue.
This should automatically happen when the resilvering is done, but it looks like yours hung for some reason. There's additional measures that can be taken if this doesn't work. It should work, but it also shouldn't be necessary in the first place.


text:
Q: Basis of Kernel and image of matrix Let $
\begin{pmatrix}
0&1&0&0&0\\
0 & 0&0&0&0\\
0 & 0&0&0&0\\
0 & 0 & 0 & 1 & 1\\
0 & 0 & 0 & 0 &1
\end{pmatrix}
$  $\in \mathbb R^{5,5}$
I think a basis of the image of this matrix is given by $\cal B_I=\{ e_2,e_4,e_5\}$ and a basis of the kernel by $\cal B_k=\{ e_1,e_3\}$. In the solution it is given by $B_I\{ e_1,e_4,e_5\}$ and $B_k=\{e_1,e_3\}$. Actually the image is simply the linearly independent colums in the reduced matrix form. I just want to make sure that the solution is wrong, if so, a comment if I am right would be enough, thanks!

A: Note that the second column $C_2$ is $e_1$, $C_4=e_4$ and $C_5-C_4=e_5$ thus $\cal B_I=\{ e_1,e_4,e_5\}$ for the image is correct.


text:
Q: Jenkins doesn't find fonts for phpDocumentor I have a problem with Jenkins and phpDocumentor. After a successful build, I want to open the documentation. Everything works fine except the icons, which are displayed as squares. A short look in the developer tools shows this error message:
Request:

GET /job/PROJECTNAME/javadoc/font/fontawesome-webfont.woff?v=3.2.1 HTTP/1.1
  Host: URLTOJENKINS
  Connection: keep-alive
  Cache-Control: no-cache
  Pragma: no-cache
  User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
  Accept: /
  Referer: http://URLTOJENKINS.com/job/PROJECTNAME/javadoc/namespaces/SOMEPAGE.html
  Accept-Encoding: gzip,deflate,sdch
  Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

Response:

HTTP/1.1 404 Not Found
  Content-Type: text/html;charset=ISO-8859-1
  Cache-Control: must-revalidate,no-cache,no-store
  Content-Length: 1410
  Server: Jetty(8.y.z-SNAPSHOT)


text:
Q: Show that $\epsilon ( integer(a/\epsilon) - integer(b/\epsilon) )= a - b + O(\epsilon)$ $integer(a)$ = the integer part of a real number $a$. For example, $integer (\pi) =3$. Let $\epsilon >0$ and $a<b$ real numbers.
How to show that $$\epsilon ( integer(a/\epsilon) - integer(b/\epsilon)) = a - b + O(\epsilon)$$

A: Instead of some computer language, let me use mathematical language.
Claim:
$$
\epsilon\left(\left\lfloor\frac{a}{\epsilon}\right\rfloor
- \left\lfloor\frac{b}{\epsilon}\right\rfloor\right) = a-b+O(\epsilon)\quad\text{as $\epsilon \to 0^+$}
$$
We will use this property of the integer part:
$$
x-1 < \lfloor x \rfloor \le x.
$$
First an upper bound
$$
\epsilon\left(\left\lfloor\frac{a}{\epsilon}\right\rfloor
- \left\lfloor\frac{b}{\epsilon}\right\rfloor\right) \le
\epsilon\left(\frac{a}{\epsilon}
- \frac{b}{\epsilon}+1\right)
= a-b+\epsilon
$$
Simlarly, prove a lower bound
$$
\epsilon\left(\left\lfloor\frac{a}{\epsilon}\right\rfloor
- \left\lfloor\frac{b}{\epsilon}\right\rfloor\right) \ge
\epsilon\left(\frac{a}{\epsilon} - 1
- \frac{b}{\epsilon}\right)
= a-b-\epsilon
$$
I hope you can finish the proof from these two inequalities.


text:
Q: How to include GWT Generated files in mvn:package So I am trying to convert and existing maven project over to SmartGWT. I have GWT working but SmartGWT has some kind of problem working with Chrome and GWT doesn't work with firefox 8+ (I have 9). So I am not very good with GWT but my understanding is I should be able to get SmartGWT to work if I can deploy a compiled verison. I tried using mvn package but that doesn't include the GWT files in the JAR.
How do you package a Jar with the GWT files using Maven so it can be run on tomcat?
update:
mvn clean compile gwt:compile package worked for me

A: Instead of always entering the full build command mvn clean compile gwt:compile package, you, you could also bind the gwt:compile goal to the prepare-package phase, so that it will run just before the package phase (and after the testing goals have completed, among others), so you can just run mvn package (or mvn clean package, which would be closer to what you have above). Add an execution to the gwt-maven-plugin definition, something like this
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>gwt-maven-plugin</artifactId>
    <version>2.4.0</version>
    <executions>
      <execution>
        <phase>prepare-package</phase>
        <goals>
          <goal>compile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

A: You can do two things to help out.  One is to install smartGWT into your local maven repository so it's sources and jar are available for builds.
mvn install:install-file -Dfile=path/to/smart-gwt.jar -Dsources=path/to/smart-gwt.jar -Dversion=1.2.3 -DgroupId=group-id-to-use -DartifactId=smart-gwt -DgeneratePom=true -Dpackaging=jar

Replace the values with whatever you want, so long as the version and path to jar is correct.  Now just include it as you would with any other dependency; use the groupId and artifactId you made up.
Next, if you want to use smart-gwt source instead of jar, you can generate a gwt-friendly jar of your own that has bundled sources. Setup an exportModule as follows
<packaging>jar</packaging>

<!--...-->

<build>
 <sourceDirectory>src/main/java</sourceDirectory>
 <testSourceDirectory>tests/main/java</testSourceDirectory>

<resources>
  <resource>
    <directory>${basedir}/src/main/java</directory>
    <includes>
      <include>**/*.java</include>
      <include>**/*.json</include>
      <include>**/*.png</include>
      <include>**/*.gwt.xml</include>
    </includes>
  </resource>
  <resource>
    <directory>${basedir}/super/main/java</directory>
    <includes>
      <include>**/*.java</include>
      <include>**/*.json</include>
      <include>**/*.png</include>
      <include>**/*.gwt.xml</include>
    </includes>
  </resource>
</resources>

<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
  </plugin>

  <plugin>
    <artifactId>maven-clean-plugin</artifactId>
    <configuration>
      <filesets>
        <fileset><directory>war</directory></fileset>
        <fileset><directory>gwt-unitCache/</directory></fileset>
      </filesets>
    </configuration>
  </plugin>
 </plugins>
</build>

You can install your own gwt jar with the above module, assumed to be named exportModule using the command
 mvn -f exportModule/pom.xml clean install


text:
Q: Rails 3 Full_Calendar Does anyone know if there is a step-by-step tutorial for intergrating Rails on Rails 3 fullcalendar into an existing Rails app? I have looked at the documentation, implemented what I can, but as a newbie unsure where I may be going wrong... I'm basically looking to see if anyone else has done it and shared their experiences?

A: You just need to have the JavaScript files in your asset pipeline. You should put it to /vendor/assets/javascripts/fullcalendar and then include it in your application.js via
//= require_tree ./fullcalendar
[...other scripts]
$(document).ready(function() {

  // page is now ready, initialize the calendar...

  $('#calendar').fullCalendar({
    // put your options and callbacks here
  })

});

In your view you have to include the following element to place the calendar there:

Just try it. It is not that hard. Ask again if you have more specific questions.


text:
Q: Javascript - Insert spaces after numbers in textboxes I'm looking for a way to insert a space after 4 numbers within a textbox.
Example: XXXX XXXX XXXX
I've been able to get the spacing with no arrow keys or arrow keys with no spacing.
I have looked into this question and a few others on the site but I've been unable to solve the issue of the backspace and arrow keys.
Here is my code:
function isNumber(event) {
    event = (event) ? event : window.event;
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
return true;
}

And here is a JSFiddle for it. This example is very close but I haven't quite got the spacing correct.
Is this possible to do with my current function or do I need to approach this in a different manner?
EDIT: Is it possible to add arrow key functionality without the cursor allows returning to the back after being released?

A: Demo
Problem is You have used keypress events.
 <input type="text" id="test" maxlength="14" name="test"
     onkeyup="return isNumber(event)" />

Same function from the answer you referred
  function isNumber(e) {
   e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').
                      replace(/(.{4})/g, '$1 ').trim();
 }

This Article will clearly explain why keyup and keydown event works but not keypress
To allow arrow keys Demo
You have to use keydown event

A: I sugest you use oninput event that takes care of keyword paste and mouse paste
 <input type="text" id="test" maxlength="14" name="test" oninput="return isNumber(event)" />

js:
function isNumber(e) {
     e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
}

A: I see why you're sticking with the keypress event, so this function should make what you want to do possible.
Please read the notes inside the commented area's, I try to explain what it's doing.
I'm not very good with regex yet, but thanks to the other answer, I think this one will work best.
Code using REgex from @Gops AB:
function isNumber(event,el) {
    event = (event) ? event : window.event;

    var charCode = (event.which) ? event.which : event.keyCode;

      if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    //Add a space after 4 numbers.

    var v=el.value + String.fromCharCode(charCode); //Keypress does not let us see the value of the text box after the press, so we have to add the string to our comparison.
    v=v.replace(/\s/g,'');

    el.value=v.replace(/(.{4})/g, '$1 ').trim(); // using regex from other answer. Thanks @Gops AB for the example
    return false;
}

Demo with using Regex:
http://jsfiddle.net/gregborbonus/Lm2hS/3208/

A: Here is the shorthand most efficient way:
//HTML
<input type="text" id="cc" name="cc" maxlength="19">

//JS
init=()=>document.getElementById('cc').addEventListener('keyup',(e)=>e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim());
document.addEventListener('DOMContentLoaded', init);


text:
Q: How to set up a Docker Swarm cluster with overlay network mode I create a docker swarm cluster on 2 Linux machine, but when I use docker-compose up -d   to  start containers ,  some error has occurred.
This is my docker info:
Containers: 4
 Running: 4
 Paused: 0
 Stopped: 0
Images: 28
Server Version: swarm/1.2.5
Role: primary
Strategy: spread
Filters: health, port, containerslots, dependency, affinity, constraint
Nodes: 2
 ozcluster01: 192.168.168.41:2375
  └ ID: CKCO:JGAA:PIOM:F4PL:6TIH:EQFY:KZ6X:B64Q:HRFH:FSTT:MLJT:BJUY
  └ Status: Healthy
  └ Containers: 2 (2 Running, 0 Paused, 0 Stopped)
  └ Reserved CPUs: 0 / 2
  └ Reserved Memory: 0 B / 3.79 GiB
  └ Labels: executiondriver=native-0.2, kernelversion=3.10.0-    327.13.1.el7.x86_64, operatingsystem=CentOS Linux 7 (Core),     storagedriver=devicemapper
  └ UpdatedAt: 2016-11-04T02:05:08Z
  └ ServerVersion: 1.10.3
 ozcluster02: 192.168.168.42:2375
  └ ID: 73GR:6M7W:GMWD:D3DO:UASW:YHJ2:BTH6:DCO5:NJM6:SXPN:PXTY:3NHI
  └ Status: Healthy
  └ Containers: 2 (2 Running, 0 Paused, 0 Stopped)
  └ Reserved CPUs: 0 / 2
  └ Reserved Memory: 64 MiB / 3.79 GiB
  └ Labels: executiondriver=native-0.2, kernelversion=3.10.0-327.10.1.el7.x86_64, operatingsystem=CentOS Linux 7 (Core), storagedriver=devicemapper
  └ UpdatedAt: 2016-11-04T02:05:06Z
  └ ServerVersion: 1.10.3

This is my docker-compose.yml
version: '2'
services:
  rabbitmq:
    image: rabbitmq
    ports:
     - "5672:5672"
     - "15672:15672"
    network_mode: "bridge"
  config-service:
    image: ozms/config-service
    ports:
     - "8888:8888"
    volumes:
     - ~/ozms/configs:/var/tmp/
     - ~/ozms/log:/log
    network_mode: "bridge"
    labels:
     - "affinity:image==ozms/config-service"
  eureka-service:
    image: ozms/eureka-service
    ports:
    - "8761:8761"
    volumes:
     - ~/ozms/log:/log
    links:
     - config-service
     - rabbitmq
    environment:
     - SPRING_RABBITMQ_HOST=rabbitmq
    network_mode: "bridge"

after I exec docker-compose up -d  , the service rabbitmq  and config-service  can be started up , but eureka-service caused an error:
[dannil@ozcluster01 ozms]$ docker-compose up -d
Creating ozms_config-service_1
Creating ozms_rabbitmq_1
Creating ozms_eureka-service_1
ERROR: Unable to find a node that satisfies the following conditions
[port 8761 (Bridge mode)]
[available container slots]
[--link=ozms_config-service_1:config-service --link=ozms_config-service_1:config-service_1 --link=ozms_config-service_1:ozms_config-service_1 --link=ozms_rabbitmq_1:ozms_rabbitmq_1 --link=ozms_rabbitmq_1:rabbitmq --link=ozms_rabbitmq_1:rabbitmq_1]

And I exec docker ps:
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
871afc8e1eb6        rabbitmq              "docker-entrypoint.sh"   2 minutes ago       Up 2 minutes        4369/tcp, 192.168.168.41:5672->5672/tcp, 5671/tcp, 25672/tcp, 192.168.168.41:15672->15672/tcp   ozcluster01/ozms_rabbitmq_1
8ef3f666a7b9        ozms/config-service   "java -Djava.security"   2 minutes ago       Up 2 minutes        192.168.168.42:8888->8888/tcp                                                                   ozcluster02/ozms_config-service_1

I find that rabbitmq is start up on machine ozculster01,  config-service is start up on machine ozculster02.
when docker-compose start config-service, there is no links, so it can be start up successfully.
but when I  start eureka-service on machine ozculster02,there is a links to rabbitmq, but the service rabbitmq is on machine ozculster01,
the error occurred.
How could I do to resolve the problem ?
Is that right to use network_mode: "bridge"  in Docker Swarm cluster ?

A: I resolved the problem myself.
In swarm mode, docker containers can't contact another container with network_mode:bridge.
In swarm mode, one must use network_mode : overlay.  Overlay is used by default if you are using compose-file formate version 2.
see more detail :
 Setting up a Docker Swarm with network overlay
With overlay mode , docker-compose.yml file do not need the config likns , Containers can contact another container with ${service_name_in_composeFile}
Example:
I can enter into the container config-service  , and $ ping eureka-service, and it works fine!
this is my compose-file.yml :
version: '2'
services:
  rabbitmq:
    image: rabbitmq
    ports:
     - "5672:5672"
     - "15672:15672"
  config-service:
    image: ozms/config-service
    ports:
     - "8888:8888"
    volumes:
     - ~/ozms/configs:/var/tmp/
     - ~/ozms/log:/log
    labels:
     - "affinity:image==ozms/config-service"
  eureka-service:
    image: ozms/eureka-service
    ports:
    - "8761:8761"
    volumes:
     - ~/ozms/log:/log
    #links:    it is no need  in overlay mode
    # - config-service
    # - rabbitmq
    environment:
     - SPRING_RABBITMQ_HOST=rabbitmq


text:
Q: How informal is "mind blowing"? I'm writing a statement letter (SOP for graduate school), and I wanted to use "mind-blowing" in a less-formal segment of my letter. Is that too informal for a personal statement or cover letter, or is it just giving a more casual/friendly tone at an acceptable level to my writing?
(I'm using "mind-blowing" as an adjective that is supposed to mean "very impressive".)

A: As our English professor used to say, "When in doubt, leave it out," and the difference between being ambiguous 'on purpose' versus 'by accident' is one letter grade...at least.
So, in a way, you may have already answered your own question (in your footnote):

(I'm using "mind-blowing" as an adjective that is supposed to mean
  "very impressive".)

Synonyms & Antonyms for mind-blowing (per Merriam-Webster; see link below):
Synonyms

breathtaking, charged, electric, electrifying, exciting, exhilarating,
  exhilarative, galvanic, galvanizing, hair-raising, heart-stopping,
  inspiring, intoxicating, mind-bending, mind-boggling, rip-roaring,
  rousing, stimulating, stirring, thrilling

Antonyms

unexciting

https://www.merriam-webster.com/dictionary/mind-blowing
Therefore, it wouldn't be surprising if someone thought you meant very exciting (in some way) if the context is lacking or ambiguous.
Not at all to say that very impressive, or overwhelmingly so, isn't a well-known (albeit informal) definition of mind-blowing...
mind-blowing

ADJECTIVE (informal):
Overwhelmingly impressive.
'for a kid, Chicago was really mind-blowing'

More example sentences:

'The maestro himself blows a mean horn with unbelievable energy and
  mind-blowing skill and has the kind of stage presence so-called pop
  idols cannot be taught.'
'It is described as a mind-blowing journey into spectacular,
  futuristic maze-like 'worlds of wonder'.'
'Support fat loss and gain more energy in the process - the benefits
  of this amazing supplement are mind-blowing!'
'There was - is - no question: Peter Jackson has roared back into
  theatres with the mind-blowing Part Two of the greatest fantasy epic
  in movie history.'
'A work of cinema so visceral, so powerful, so incredibly mind-blowing
  must be seen to be believed.'
'And, then, before he knew it, another song had started up; the same
  voice, the same wonderful, mind-blowing music.'
'This record is impressive, but not mind-blowing.'
''We've had more corporate donations and it's just mind-blowing the
  support we've received,' Emma continued.'

The list goes on; they give a dozen more examples for this definition (see link below).
https://en.oxforddictionaries.com/definition/mind-blowing
Just FYI, this is another definition of mind-blowing (same source):

(of a drug) inducing hallucinations.

Example sentences:

'This teaching has warped more minds than any mind blowing drug has
  ever done.'
'The 1960s was the decade of mind-blowing drug experimentation.'

Curiously, this is the second meaning in Oxford Dictionaries but the first in Merriam-Webster (which states that this is the meaning of its first recorded use in 1966).
In conclusion, I would say (as our professor did)...be yourself, but know your audience. Some things are mind-blowing. That is, the word seems less informal to me when used in its proper context, as in the example sentences above (excluding the ad for the amazing supplement). That being said...not everything in the 80s was awesome (e.g. That was awesome, dude!--referring to a milkshake), so I would caution you: Mind-blowing is the new awesome...I think, so I would use it sparingly. Words like those can be addictive.

A: mind-blowing OED colloquial.
Frequency Band 3. (not commonly found in general text types like novels and newspapers, but at the same they are not overly opaque or obscure)

astonishing, overwhelming; consciousness-altering (esp. as a result of
  drug use), that 'blows one's mind'

As in The Wall Street Journal - a prestigious news/financial magazine in the U.S.:

2000   Wall St. Jrnl. Jan.    Films about the future grew trippy and
  navel-gazing, eschewing action and coherent plot for mind-blowing
  images and wild ideas.

and

Going back to these races is mind-blowing for me," says Rodgers.
  Salon Oct 17, 2018

and

It's not all designer brands either: Wilma & Frieda's Cafe is a great
  brunch spot that does a mind-blowing blackberry custard french toast.
  The Guardian Oct 17, 2018

In AmE, rules are fluid.  As tech is a burgeoning field its usage is more prevalent.  Keep in mind your context and intended audience when using mind-blowing.


text:
Q: Share POCO types between WCF Data Service and Client Generated by Add Service Reference I have a WCF Data Service layer that is exposing POCO entities generated by the POCO T4 template. These POCO entities are created in their own project (i.e. Company.ProjectName.Entities) because I'd like to share them wherever possible.
I have a set of interfaces in another project (Company.ProjectName.Clients) that reference these POCO types by adding an assembly reference to the Company.ProjectName.Entities.dll. One of the implementation of these interfaces is a .NET client that I want to consumes the service using the WCF Data Service Client Library.
I've used the Add Service Reference to add service reference. This generated the DataServiceContext client class and the POCO entities that are used by the service. However, these POCO types gemerated by the Add Service Reference utility now have a different namespace (i.e. Company.ProjectName.Clients.Implementation.WcfDsReference).
What that means is that the POCO types defined in the interfaces cannot be used by the types generated by the utility without have to cast or map.
i.e. Suppose I have:
 1. POCO Entity:     Company.ProjectName.Entities.Account
 2. Interface:       interface IRepository<Company.ProjectName.Entities.Account>{....}
 3. Implementation:  ServiceClientRepository : IRepository<Company.ProjectName.Entities.Account>
 4. WcfDsReference:  Company.ProjectName.Clients.Implementation.WcfDsReference
          &          Company.ProjectName.Clients.Implementation.WcfDsReference.Account

   Let's say I want to create a DataServiceQuery query on the Account, I won't be able to do this:

   var client = new WcfDsReference(baseUrl);
   var accounts = client.CreateQuery<Company.ProjectName.Entities.Account>(...)

      OR:         client.AddToAccounts(Company.ProjectName.Entities.Account)

   , because the CreateQuery<T>() expects T to be of type            &       Company.ProjectName.Clients.Implementation.WcfDsReference.Account

What I currently have to do is to pass the correct entity to the CreateQuery method and have to map the results back to the type the interface understands. (Possible with a mapper but doesn't seems like a good solution.)
So the question is, is there a way to get the Add Service Reference utility to generate methods that use the POCO types that are in the Company.ProjectName.Entities namespace?
One solution I am thinking of is to not use the utility to generate the DataServiceContext and other types, but to create my own.
The other solution is to update the IRepository<T> interface to use the POCO types generated by the utility. But this sounds a little bit hacky.
Is there any better solution that anyone has come up with or if there's any suggestion?

A: Ok, a few hours after starting the bounty I found out why it wasn't working as expected on my end.
It turns out that the sharing process is quite easy. All that needs to be done is mark the model classes with the [DataServiceKey] attribute. This article explains the process quite well, in the 'Exposing another Data Model' section
With that in mind, what I was trying to do is the following:

*

*Placing the model on a separate class library project C, sharing it with both webapplication projects A and B

*Create the data service on project A

*Add the service reference on project B

*Delete the generated model proxies out of the service reference, and update it to use my model classes in project C

*Add the DataServiceKey attribute to the models, specifying the correct keys

When I tried this it did not work, giving me the following error:

There is a type mismatch between the client and the service. Type
  {MyType} is not an entity type, but the type in the
  response payload represents an entity type. Please ensure that types
  defined on the client match the data model of the service, or update
  the service reference on the client.

This problem was caused by a version mismatch between project C (which was using the stock implementations on the System.Data.OData assemblies) and the client project B that was calling the service (using the Microsoft.Data.OData assemblies in the packages). By matching the version on both ends, it worked the first time.
After all this, one problem remained though: The service reference procedure is still not detecting the models to be shared, meaning proxies are being created as usual. This led me to opt out of the automatic service integration mechanic, instead forcing me to go forward with a simple class of my own to serve as the client to the Wcf Data service. Basically, it's a heavily trimmed version of the normally autogenerated class:
using System;
using System.Data.Services.Client;
using System.Data.Services.Common;
using Model;

public class DataServiceClient : DataServiceContext
{
    private readonly Lazy<DataServiceQuery<Unit>> m_units;

    public DataServiceClient(Uri _uri)
        : base(_uri, DataServiceProtocolVersion.V3)
    {
        m_units = new Lazy<DataServiceQuery<Unit>>(() => CreateQuery<Unit>("Units"));
    }

    public DataServiceQuery<Unit> Units
    {
        get { return m_units.Value; }
    }
}

This is simple enough because I'm only using the service in readonly mode. I would still like to use the service reference feature though, potentially avoiding future maintenance problems, as evidenced by the hardcoded EntitySet name in this simple case. At the moment, I'm using this implementation and have deleted the service reference altogether.
I would really like to see this fully integrated with the service reference approach if anyone can share a workaround to it, but this custom method is acceptable for our current needs.


text:
Q: What are the sections of an ideal sheaf on a scheme? Suppose $X$ is a scheme and $f_1,...,f_n\in \Gamma(X,\mathcal O)$ are global sections.
One often reads about the ideal sheaf $\mathcal I=\mathcal (f_1,...,f_n)\subset \mathcal O$, but I have never seen it defined.
The definition should be that $\mathcal I$ is the sheaf associated to the presheaf $\mathcal I^-$ whose value on an open subset $U\subset X$ is $\mathcal I^-(U)=({f_1}{\vert_U},...,{f_n}{\vert_U})\cdot\mathcal O(U)$. Right?
My question is simply: Is there a non-tautological sufficient condition on $U$ and the $f_i$'s guaranteeing that $\mathcal I(U)=\mathcal I^-(U)$?
The only sufficient condition I can think of is that $n=1$ and $U$ is an arbitrary open subset of an integral scheme $X$.

A: @Chris's comment, posted as an answer by request (made CW to avoid reputation):

A sufficient condition is that $U$ is affine.  Indeed $\mathcal I$ fits in an s.e.s. $0 \to \mathcal K \to \mathcal O^n \to \mathcal I \to 0$ and $H^1(U, \mathcal K) = 0$ for $U$ affine.


text:
Q: Installshield - How do I make installshield build the entire cd? Right now the Release build just makes the files necessary for the install. But I want to create the CD structure automatically with InstallShield, so that when I go to Tools, Open Release Folder
it has
\Install
\Tools
\Help
autorun.inf

I've looked at the execute batch file or copy to folder options for a Release, I was hoping there was something more friendly within InstallShield.
using version 12.

A: I created a feature / component called CDOnly which is not visible, selected, and doesn't copy, but does put the files in the Disk Images / Disk1 folder.
So by changing the default directories of features and putting special things in CDOnly I was able to create the structure I wanted.


text:
Q: How to query tables for multi language records with default language I have a problem stuck it. I have a category table and category_translate table to support multi languages.
I want the query that can search all categories with my specified language. If language record not exists, it will return default language (i.e. English). I searched a lot but cannot find a solution. Can anyone help to suggest how to resolve it.
category
---------------
id

category_translate
--------------------
id
category_id
language_id
is_default
name

Except Result:
id   language_id      name.         is_default
------------------------------------------------
1    'en'             'Food'        1
1    'zh'             'Food-ZH'     0
2    'en'             'Cloth'       1

SELECT a.id, b.language_id, b.name, b.is_default
FROM category a, category_translate b
WHERE a.id = b.category_id AND language_id = 'zh'

id   language_id      name          is_default
------------------------------------------------
1    'zh'             'Food-ZH'     0

The above query can get categories with 'zh' language but cannot get other categories with default language 'en'

A: *

*Never use commas in the FROM clause.

*Always use proper, explicit, standard JOIN syntax.

*Use meaningful table aliases!

You can solve your problem with LEFT JOIN.  Two of them in fact:
SELECT c.id,
       COALESCE(ct.language_id, ctdefault.language_id) as language_id,
       COALESCE(ct.name, ctdefault.name) as name,
       (ct.language_id is null) as is_default
FROM category c LEFT JOIN
     category_translate ct
     ON ct.category_id = c.id AND
        ct.language_id = 'zh' LEFT JOIN
     category_translate ctdefault
     ON ctdefault.category_id = c.id AND
        ctdefault.is_default ;

I'm a little unclear on how is_default is determined.  If the language you are searching for is the default, should the value be true or not?


text:
Q: SRC attributes in IFRAME change with onload function if I have the "src" attributes in IFRAME change is the "onload" Function not executed. It works ONLY when first called.
JavaScript:
function dialog () {
    document.getElementById('result').src = "myurl";
}

function loading() {
    document.getElementById('loading').style.display = "none";
    document.getElementById('result').style.display = "block";
}

HTML:

Thank you!

A: Does your page domain and iframe domain the same? If they are different you can use CORS to access iframe events.

EDIT

Loading

It works, live demo -- http://jsfiddle.net/xf2LgLsg/
I believe you write JS after HTML, so this may be a problem.


text:
Q: Preserve Order of IN in ORM Order I'm trying to do a query where I preserve the order of the ids in a IN statement. I can't seem to do it with either the Model Manage Query Builder or the standard ORM 'order' array parameter. Am I missing something? I keep getting:
UNEXPECTED TOKEN IDENTIFIER(, NEAR TO 'id`enter code here`,17743,16688,16650

Here's my model manager:
$query = $this->modelsManager->createQuery('SELECT * FROM Projects WHERE id IN ('.implode(',', array_keys($finalIterations)).')
                    ORDER BY FIELD(id,'.implode(',', array_keys($finalIterations)).'');

It's pretty obvious PhQL doesn't like the FIELD key word. Is there a way for me to do what I'm trying to do with PhQL? It seems I will not be able to do what I need to.

A: Unfortunately as previously said, this is missing a feature in Phalcon.
Have a look at this function, I've put it into my ModelBase abstract class which is parent class of all my models. It uses PhQL variable binding, so it's safe for handling direct user input.
You could have reimplemented custom \Phalcon\Mvc\Model\Criteria but this solution seems to be easier to work with, at least for me.

ModelBase abstract
public function appendCustomOrder( \Phalcon\Mvc\Model\CriteriaInterface &$criteria, $orderField, array &$orderValues = [] ) {
    if(!empty($orderValues)) {
        $queryKeys = $bindParams = [];
        foreach($orderValues as $key => $id) {
            $queryKey = 'pho'.$key;
            $queryKeys[] = ':'.$queryKey.':';
            $bindParams[$queryKey] = $id;
        }

        // TODO: add support for multiple orderBy fields
        $criteria->orderBy('FIELD('.$orderField.','.implode(',',$queryKeys).')');
        // there's no 'addBind' function, need to merge old parameters with new ones
        $criteria->bind( array_merge( (array) @$criteria->getParams()['bind'], $bindParams ) );
    }
}

Controller usage
$projectIDs = [17743, 16688, 16650];
$projectsModel = new Projects();

$criteria = $projectsModel->query->inWhere( 'id', $projectIDs );
$projectsModel->appendCustomOrder( $criteria, 'id', $projectIDs );

$projectsData = $criteria->execute();

This will generate valid PhQL syntax similar to this one:
SELECT `projects`.`id` AS `id`, `projects`.`title` AS `title`
FROM `projects`
WHERE `projects`.`id` IN (:phi0, :phi1, :phi2)
ORDER BY FIELD(`projects`.`id`, :pho0, :pho1, :pho2)


text:
Q: error increasing with no of estimators in adaboost My error gets increased when i increase the n_estimators value in
ada=AdaBoostClassifier(n_estimators=1, base_estimator=SVC(probability=True,kernel="rbf",gamma=.1,C=1))

for n_estmators the predictor is giving the least error, whereas as i increase the value of n_estmator then the error also increases
what could be interpreted from this?
thanks

A: AdaBoost needs internally a weak classifier to work, not SVMs. Usually it is something like a threshold on a single feature. If you use a strong classifier then you end-up with an overfitted model.


text:
Q: ASP.NET MVC Navigational Property I'm looking to add a navigational property to my 'Registration' class, so I can access the parent 'Person'.
Ideally, I would be able to add Public Overrideable Property ParentPerson as Person, but I can't seem to get this to work as it complains about the principle end of association.
Public Class Person
    <Required()>
    Public Property ID As Integer

    <Required()>
    <StringLength(150)>
    Public Property Firstname As String

    <Required()>
    <StringLength(150)>
    Public Property Lastname As String

    Public Overridable Property Registration As Registration
End Class

Public Class Registration

    <Required()>
    Public Property ID As Integer

    Public Property RegistrationDate As Date

    Public Overridable Property Sessions As List(Of RegistrationSession)

End Class


text:
Q: Identifying maximum number and longest set of time intervals Say I have data that look like this:
   level   start     end
1      1 133.631 825.141
2      2 133.631 155.953
3      3 146.844 155.953
4      2 293.754 302.196
5      3 293.754 302.196
6      4 293.754 301.428
7      2 326.253 343.436
8      3 326.253 343.436
9      4 333.827 343.436
10     2 578.066 611.766
11     3 578.066 611.766
12     4 578.066 587.876
13     4 598.052 611.766
14     2 811.228 825.141
15     3 811.228 825.141

or this:
   level      start        end
1      1    3.60353 1112.62000
2      2    3.60353   20.35330
3      3    3.60353    8.77526
4      2   72.03720  143.60700
5      3   73.50530  101.13200
6      4   73.50530   81.64660
7      4   92.19030  101.13200
8      3  121.28500  143.60700
9      4  121.28500  128.25900
10     2  167.19700  185.04800
11     3  167.19700  183.44600
12     4  167.19700  182.84600
13     2  398.12300  418.64300
14     3  398.12300  418.64300
15     2  445.83600  454.54500
16     2  776.59400  798.34800
17     3  776.59400  796.64700
18     4  776.59400  795.91300
19     2  906.68800  915.89700
20     3  906.68800  915.89700
21     2 1099.44000 1112.62000
22     3 1099.44000 1112.62000
23     4 1100.14000 1112.62000

They produce the following graphs:

As you can see there are several time intervals at different levels. The level-1 interval always spans the entire duration of the time of interest.  Levels 2+ have time intervals that are shorter.
What I would like to do is select the maximum number of non-overlapping time intervals covering each period that contain the maximum number of total time within them.  I have marked in pink which ones those would be.
For small dataframes it is possible to brute force this, but obviously there should be some more logical way of doing this. I'm interested in hearing some ideas about what I should try.
EDIT:
I think one thing that could help here is the column 'level'. The results come from Kleinberg's burst detection algorithm (package 'bursts'). You will note that the levels are hierarchically organized. Levels of the same number cannot overlap.  However levels successively increasing e.g. 2,3,4 in successive rows can overlap.
In essence, I think the problem could be shortened to this. Take the levels produced, but remove level 1. This would be the vector for the 2nd example:
 2 3 2 3 4 4 3 4 2 3 4 2 3 2 2 3 4 2 3 2 3 4

Then, look at the 2s... if there are fewer than or only one '3' then that 2 is the longest interval. But if there are two or more 3's between successive 2's, then those 3s should be counted. Do this iteratively for each level. I think that should work...?
e.g.
vec<-df$level %>% as.vector() %>% .[-1]
vec
#[1] 2 3 2 3 4 4 3 4 2 3 4 2 3 2 2 3 4 2 3 2 3 4

max(vec) #4
vec3<-vec #need to find two or more 4's between 3s
vec3[vec3==3]<-NA
names(vec3)<-cumsum(is.na(vec3))

 0  1  1  2  2  2  3  3  3  4  4  4  5  5  5  6  6  6  7  7  8  8
 2 NA  2 NA  4  4 NA  4  2 NA  4  2 NA  2  2 NA  4  2 NA  2 NA  4

vec3.res<-which(table(vec3,names(vec3))["4",]>1)
which(names(vec3)==names(vec3.res) & vec3==4) #5 6

The above identifies rows 5 and 6 (which equate to rows 6 and 7 in original df) as having two  fours that lie between 3's.   Perhaps something using this sort of approach might work?

A: OK here is a stab using your second data set to test. This might not be correct in all cases!!
library(data.table)
dat <- fread("data.csv")
dat[,use:="maybe"]
make.pass <- function(dat,low,high,the.level,use)  {
    check <- dat[(use!="no" & level > the.level)]
    check[,contained.by.above:=(low<=start & end<=high)]
    check[,consecutive.contained.by.above:=
          (contained.by.above &
           !is.na(shift(contained.by.above,1)) &
           shift(contained.by.above,1)),by=level]
    if(!any(check[,consecutive.contained.by.above])) {
        #Cause a side effect where we've learned we don't care:
        dat[check[(contained.by.above),rownum],use:="no"]
        print(check)
        return("yes")
    } else {
        return("no")
    }
}
dat[,rownum:=.I]
dat[level==1,use:=make.pass(dat,start,end,level,use),by=rownum]
dat
dat[use=="maybe" & level==2,use:=make.pass(dat,start,end,level,use),by=rownum]
dat
dat[use=="maybe" & level==3,use:=make.pass(dat,start,end,level,use),by=rownum]
dat
#Finally correct for last level
dat[use=="maybe" & level==4,use:="yes"]

I wrote these last steps out so you can trace in your own interactive session to see what's happening (see the print to get an idea) but you can remove the print and also condense the last steps into something like lapply(1:dat[,max(level)-1], function(the.level) dat[use=="maybe" & level==the.level,use:=make.pass......]) In response to your comment if there are an arbitrary number of levels you will definitely want to use this formalism, and follow it with a final call to dat[use=="maybe" & level==max(level),use:="yes"].
Output:
> dat
    level      start        end use rownum
 1:     1    3.60353 1112.62000  no      1
 2:     2    3.60353   20.35330 yes      2
 3:     3    3.60353    8.77526  no      3
 4:     2   72.03720  143.60700  no      4
 5:     3   73.50530  101.13200  no      5
 6:     4   73.50530   81.64660 yes      6
 7:     4   92.19030  101.13200 yes      7
 8:     3  121.28500  143.60700 yes      8
 9:     4  121.28500  128.25900  no      9
10:     2  167.19700  185.04800 yes     10
11:     3  167.19700  183.44600  no     11
12:     4  167.19700  182.84600  no     12
13:     2  398.12300  418.64300 yes     13
14:     3  398.12300  418.64300  no     14
15:     2  445.83600  454.54500 yes     15
16:     2  776.59400  798.34800 yes     16
17:     3  776.59400  796.64700  no     17
18:     4  776.59400  795.91300  no     18
19:     2  906.68800  915.89700 yes     19
20:     3  906.68800  915.89700  no     20
21:     2 1099.44000 1112.62000 yes     21
22:     3 1099.44000 1112.62000  no     22
23:     4 1100.14000 1112.62000  no     23
    level      start        end use rownum

On the off chance this is correct, the algorithm can roughly be described as follows:

*

*Mark all the intervals as possible.

*Start with a given level. Pick a particular interval (by=rownum) say called X. With X in mind, subset a copy of the data to all higher-level intervals.

*Mark any of these that are contained in X as "contained in X".

*If consecutive intervals at the same level are contained in X, X is no good b/c it wastes intervals. In this case label X's "use" variable as "no" so we'll never think about X again. [Note: if it's possible that non-consecutive intervals are contained in X, or that containing multiple intervals across levels could ruin X's viability, then this logic might need to be changed to count contained intervals instead of finding consecutive ones. I didn't think about this at all, but it's just occurring to me now, so use at your own risk.]

*On the other hand, if X passed the test, then we've already established it's good. Mark it as a "yes." But importantly, we also have to mark any single interval contained in X as "no," or else when we iterate the step it will forget that it was contained inside a good interval and mark itself as "yes" as well. This is the side effect step.

*Now, iterate, ignoring any results that we've already determined.

*Finally any "maybe"s leftover at the highest level are automatically in.

Let me know what you think of this--this is a rough draft and some aspects might not be correct.


text:
Q: Flask Error: If something fails in the flask backend, how does the error propagate to the front end? Consider a simple application where a user fills a form to divide two numbers, in the routes the form data is proceeded [made into float] and then passed as parameters to a python script's function that has the division logic.
The logic fails due to division by 0 is handled as a custom message in the terminal. How does one send this custom message back to the front end UI along with a 500 error message? Trying to make a restful flask app here.
So far I can abort and show a custom message but not the one that propagated from the backend. Also looked into custom error handling but I want to writer of the external python script to be able to write the custom message.

A: You could use the abort() function. From the docs:

When using Flask for web APIs, you can use the same techniques as above to return JSON responses to API errors. abort() is called with a description parameter. The errorhandler() will use that as the JSON error message, and set the status code to 404.

You could implement it like this
@app.route("/div")
def divide():
    x, y = request.form['x'], request.form['y']

    try:
        result = x / y
    except ZeroDivisionError:
        abort(400, description="Your message here")
    else:
        # Proper response

From there, the important step is properly catching that message on your frontend.

A: You can Flask errorhandler(errorcode) to manage your errors and display those on the frontend.
@app.errorhandler(500)
def code_500(error):
    return render_template("errors/500.html", error=error), 500

You can put whatever else you want in the html template.
You can also call the code_500(error) func directly.
Same principle applies for any other HTTP error code if you want to customize the page and the message (401, 403, 404, etc...).
If you're inside a blueprint, you can use app_errorhandler instead.


text:
Q: Import a Git repo from a local server to DevOps How can I import a Git repo from a local server to DevOps? I am not talking about a depo already hosted on GitHub, but a bare repo that is just living on a local server.

A: Thanks all. All your feedback helped me to solve my problem.
I was focused on import, only import. And it seems like it's not possible to directly import from a local repo.
The solution was to create an empty repo in DevOps, add it as remote to my local repo (git remote add), and push to this remote (git push -u). As simple as this, and probably obvious for most people but it wasn't for me!

A: There is only two way:
One:
You need to host the repo to a remote server (github etc.) which is accessible by both local machine and DevOps machine.
Two:
You most likely need to clone the local git project to DevOps machine. In this way you can use scp tools to copy the repo to other machine. For example. i have repo in user's home directory /home/local_machine/git_project.
copy git repo using remote machine:
scp -r <username>@<local_machine_ip>:/home/local_machine/git_project /home/devops_machine/

In this way you will be able to clone or copy local git repository without using 3rd party hosting sites.


text:
Q: How to force lower version Zxing QRcode I'm trying to make QRcode with version 6 41x41 modules, there is requirement for old system.
Here my String data:
"H 4A91K       BB7998  M11AU10406   CBU 4A91471     H 000160        69H 69578 00009Y000                            @N                                      "

I try to generated using Zxing library, the lower possibility I can get only version 7 using below parameter:
Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hints.put(EncodeHintType.QR_VERSION, 7);

I try to compare some web API can generate QRcode as version 6
https://goqr.me/api/

https://www.barcode-generator.org/

How I can force zxing to version 6 based on my String data requirement? is that possible?
Thank you for your support.


text:
Q: IMG tag does not display after INPUT tag Given the html fragment
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Test JQuery AppendTo</title>

Just some text

    <form name="FORMPOST" method="post" action="showform.aspx" id="FORMPOST" >
      Test Label
      <input id="Test2" type="checkbox" />

    </form>

and given that the add2.jpg image is in the same directory as the html code, why does the image not display?  Note that if I move the image tag node to be inside the div node, it will display :(
Note the display does not appear regardless of whether I add the img tag at design time as above, or append it using the jQuery.appendTo function when the form loads.

A: For one, you shouldn't have back slashes there for quotes. Can you give us a link to the page itself? Because that will work.

A: Were the backslashes in  a typo?  should be .
You need the forward slash to end the img tag because you are using XHTML.

A: Your image tag doesn't look correctly formed to me

Does this work for you like the above?


text:
Q: How can I declare a container that has 100% of the remaining size of the viewport? I'm creating a basic layout with css and flexbox, but I'm having problems positioning the elements.
I am trying to declare the main with 100% of the viewport with css, so that the footer always appears at the bottom and the main covers all that empty space.
Try giving the footer the following property:
margin-top: auto;

*, *::before, *::after {
    margin: 0;
    padding:0;
    box-sizing: border-box;
}

html, body {
    margin: 0;
    padding:0;
}

body{
    min-height: 100vh;
    border: 12px solid green;
}

.wrapper{
    display: flex;
    flex-direction: column;
}

.TextStyle{
    color:whitesmoke;
    font-size: 28px;
    text-align: center;
}

header{
    height: 70px;
    background-color: brown;

}

main{
    background-color: cadetblue;
    height: 100%;
    min-height: 100%;
    margin: 0;
    padding: 0;
}

footer{
    background-color: cornflowerblue;
    height: 100px;
    margin-top: auto;
    margin: 0;
    padding: 0;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0"
    />

    <link rel="stylesheet" href="/style.css" />
    <title>Document</title>

      NAV BAR HERE

        Labore nulla non labore deserunt amet magna qui ut aute ut ut.
        Tempor dolore elit velit excepteur. Amet mollit est ut
        exercitation nostrud eu deserunt sint do minim. Deserunt
        exercitation enim nisi anim dolor sunt ullamco do quis
        voluptate excepteur in irure. Veniam dolor do ut id quis ad
        elit aliqua exercitation.

      FOOTER

The result I expect in the photo:


text:
Q: Open shell locations with c# The code listed here does not open the file history in C#:
Process.Start("::{F6B6E965-E9B2-444B-9286-10C9152EDBC5}");

Where is the problem? It says the path was not found.
Running the following with Windows "Run" opens the files history correctly:
shell:::{F6B6E965-E9B2-444B-9286-10C9152EDBC5}

A: There's two problems here. The target platform and the command.

With Windows 8 it works for me

It only works on Windows 8 because it's a new feature in Windows 8. Previous versions don't have anything mapped to that GUID.
eg if you try using something which is supported in previous versions like the classic 'god mode':
shell:::{ED7BA470-8E54-465E-825C-99712043E01C}

works fine,
shell:::{F6B6E965-E9B2-444B-9286-10C9152EDBC5}

will give you an error message.
Secondly, you're leaving out the shell::: prefix when you call Process.Start(). It should look like:
Process.Start("shell:::{F6B6E965-E9B2-444B-9286-10C9152EDBC5}");


text:
Q: Docker: access denied on pulic github repo I am trying to run "docker-compose up" on the docker-compose.yml below (the environment variable are defined in a .env file).
version: "3.4"

services:
  ib-gateway:
    image: ghcr.io/unusualalpha/ib-gateway:latest
    restart: always
    environment:
      TWS_USERID: ${TWS_USERID}
      TWS_PASSWORD: ${TWS_PASSWORD}
      TRADING_MODE: ${TRADING_MODE:-live}
      VNC_SERVER_PASSWORD: ${VNC_SERVER_PASSWORD:-}
    ports:
      - "127.0.0.1:4001:4001"
      - "127.0.0.1:4002:4002"
      - "127.0.0.1:5900:5900"

(see github repo here for more info).
And I am getting the following error:
> PS C:\Users\rapha\Documents\Github\ib-gateway-docker> docker-compose up
> Running 0/1
> ib-gateway Error                                                                                0.5s
> Error response from daemon: Head "https://ghcr.io/v2/unusualalpha/ib-gateway/manifests/latest": denied: denied

The url contains the following message:

{"errors":[{"code":"UNAUTHORIZED","message":"authentication required"}]}

What puzzles me is the following:

*

*If I follow the exact same procedure on my second machine, it works like a charm

*It is a public repo, so I should not need to login anyway

Any idea where this error might be coming from?