text:
Q: How to use a built-in tcl power function? I am using this tcl version
/tools/tcl/8.4.11/linux64/bin/tcl
May i know how can i use the built in power function in my tcl script?
I tried this but it does not work.
namespace import ::tcl::mathfunc::*
puts [pow 10 2]

unknown namespace in import pattern "::tcl::mathfunc::*"
    while executing
"namespace import ::tcl::mathfunc::\*"

May i know why?

A: The ::tcl::mathfunc namespace was added in Tcl 8.5 and is not supported in Tcl 8.4. In Tcl 8.5+ you can use
namespace import ::tcl::mathfunc::*
pow 10 2
# -> 100.0

as well as calling pow from within expr, but in Tcl 8.4 and earlier you must use
expr {pow(10, 2)}
# -> 100.0

The mathfunc commands, when present, can be invoked as regular Tcl commands or be called as pseudofunctions in the expression script passed to expr. In the latter case, C-style syntax with parantheses and commas is used. The point of having them is mainly that it makes it easier to extend expr with new math functions. As a sideeffect, invoking expr can be avoided altogether for the simplest calculations.
The pow function returns a floating-point value, just as in C. As Donal Fellows describes in his answer (q.v.), integer exponentiation can be specified by using the ** operator (which is also a separate command: tcl::mathop::**). This operator is Tcl 8.5+ only.
Documentation: expr, mathfunc, mathop

A: That feature was introduced in Tcl 8.5. In 8.4 and before, functions were implemented using a special API that nobody really understood (passing around pointers to Tcl_Value structures, which were rather strange).
The pow() function is a floating point function in all versions of Tcl (even if written as a call to ::tcl::mathfunc::pow). Integer exponentiation is only available via the ** operator (requires Tcl 8.5, which was also the first version to support arbitrary size integers):
puts [expr { 10 ** 2 }]

# Note the namespace
puts [tcl::mathop::** 10 2]

namespace import tcl::mathop::*
puts [** 10 2]

The ** operator is exactly equivalent to pow() if either of its arguments is a floating point number (and will indeed call the same function in the standard C math library behind the scenes).


text:
Q: Odds Dice Rolls Guys so I have a question.
Let's say I'd like to calculate the odds of rolling either $10+$ (10 or more), $5+$  (5 or more) or $15+$ and an exact $1$ on a icosahedron dice.
Here's what I did:
For $10+$, the odds of not rolling is $\frac{9}{20} = 0.45$. For $5+$, $\frac{5}{90} = 0.20$. For $15+$, $\frac{14}{20} = 0.70$.
So the odds for $10+$, $5+$ and $15+$ are, respectively, $0.55$, $0.80$ and $0.30$. Odds for rolling exactly $1$ is $\frac{1}{20} = 0.05$.
The probability of all this events ($10+$ or $5+$ or $15+$ and $1$) would be what?

A: If I can understand this question, you are asking for the probability you do all of the following possibilities($1, 5+, 10+, 15+$) consecutively.
If you are looking for the exact sequence: $10+, 5+, 15+, 1+$, the probability is just $.55*.8*.3*.05$.
If you are looking for a sequence just containing those for numbers, just do $4!$(number of possible orderings)$*.55*.8*.3*.05$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the current and next item at the same time from MutableMap using Kotlin? I would like to store information such as rowid (key) and orderId (value) in MutableMap. Then iterate through the MutableMap and get the current item key and value and the next item key and value.
The reason for that is that while I am iterating through the Map I am changing the value of the first item using the second item value or I am changing the value of the second item value using the first item value.
Example:
    val mutableMap: MutableMap<Int, Int> = mutableMapOf<Int, Int>()
    mutableMap[350] = 0
    mutableMap[351] = 1
    mutableMap[352] = 2
    mutableMap[353] = 3
    mutableMap.put(354, 4)
    mutableMap.put(355, 5)
    mutableMap.put(356, 6)

    for (key in mutableMap.keys) {
        Log.d("print data", "print data, Key = ${key}, Value = ${mutableMap[key]}")
    }

How to get this item: myLinkedHashMap[450] = 0
and this item myLinkedHashMap[453] = 3 information at the same time so I can swap the value between them ?

A: Although the Map and MutableMap interfaces do not claim to be ordered, the specific implementation used by mutableMapOf is ordered anyway. This is guaranteed because it is declared in the documentation of the function. So if you are working with a MutableMap that you declared locally with mutableMapOf, then you know it is ordered. If you are working with a MutableMap that was passed to you from some other class, then you cannot be sure it is ordered. But that should be a pretty rare occurrence since it is poor encapsulation to pass mutable collections between classes.
To iterate a map that is ordered in pairs, you can use zipWithNext on the keys. This call creates a copy of the list of keys, so you can safely mutate the map inside the loop. This is like a moving window of pairs--each element besides the first and last will appear in two different pairs, once as the second element and then once as the first element.
for ((keyA, keyB) in mutableMap.keys.zipWithNext()) {

}

If you want to iterate exclusive pairs, you can use chunked(2) instead of zipWithNext(), but you would need to be sure you only chunk an even number of elements:
for ((keyA, keyB) in mutableMap.keys.take(mutableMap.size - mutableMap.size % 2).chunked(2)) {

}

// or

for (keys in mutableMap.keys.chunked(2)) {
    if (keys.size == 1) continue
    val (keyA, keyB) = keys

}


text:
Q: Blocked web-fonts from localhost in different ports I want to fix an error, it's this:

Font from origin 'http://localhost:8000' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

All my assets are located en localhost:8000 and my public website is located in localhost:3000, beacuse my assets are located en a directory outside root directory of the public web.
The both directories have an .htaccess file.
Any idea to fix this error?
Thank you.

A: As metioned here, I fixed this issue by adding data-noprefix to the link tag for my stylesheet.
<link href="https://fonts.googleapis.com/yourFont" rel="stylesheet" data-noprefix>


text:
Q: Java: Inherit and Be a Singleton To begin with, I am NOT trying to create a subclass of a singleton class. (At least I'm sure I'm not trying to).
I have a class ClassA that is abstract.
I have two classes, ClassA1 and ClassA2 that extend ClassA.
I want ClassA1 and ClassA2 to be singleton classes. I could just write the code in each one to do so but I would prefer to write the code once in ClassA and reuse it in all of it's sub-classes. Is there a way to do this?

A: Probably not - the singleton pattern requires static methods/fields, which would be shared by ClassA and all its subclasses if defined in one place.

A: I would suggest private constructors for ClassA1 and A2 and having static methods for object creation. This way you have complete control over object creation.
The book EffectiveJava details out the adavatages of this approach.

A: The only place this is done is in the enum classes which extend Enum. It uses a language twist, and something like class ClassA<T extends ClassA>. Either you do:
public class ClassA {

    private static final Map<Class<? extends ClassA>, ClassA> singletons = new HashMap<>();

    public static <T extends ClassA> T get(Class<T> klazz) {
        T singleton = klazz.cast(singletons.get(klazz));
        if (singleton == null) {
            try {
                singleton = klazz.getConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException
                    | NoSuchMethodException | SecurityException e) {
                throw new IllegalArgumentException(e);
            }
            singletons.put(klazz, singleton);
        }
        return singleton;
    }
    protected ClassA() { }
}

Or you rethink your desire of plural singletons, and either do a general container lookup, (maybe with declarative XML or annotations) or a bean container. EJB 3.1 is very nice and simple.


text:
Q: iOS 7 Default image overlapped by status bar in multi-tasking view My app is compiled against iOS 6 SDK (haven't gotten the time to upgrade to iOS 7 SDK). So I just noticed that the Default image is overlapped by the status bar. This seems to happen only in the "multi-tasking" view but not when resuming my app from background for some reason.
See this image:

A: I don't think many people will notice this at all.
However, as far as I know you could possibly disable the Statusbar when the app gets in backround.
To do this just use this method in the delegate:
- (void)applicationWillResignActive:(UIApplication *)application {
    //code to disable statusbar
}

In the applicationDidBecomeActive method you could enable the statusbar again.
- (void)applicationDidBecomeActive:(UIApplication *)application {
//code to enable the statusbar
}

Furthermore you can take a look at this previous asked question: Status bar won't disappear
If you got any questions feel free to ask!

A: edgesForExtendedLayout does the trick for iOS 7. However, if you build the app across iOS 7 SDK and deploy it in iOS 6, the navigation bar appears translucent and the views go beneath it. So, to fix it for both iOS 7 as well as for iOS 6 do this:
  self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
  if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
       self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7


text:
Q: POST multiple values I have a loop which generates a couple of fields which could be field in. I want to POST all the values from these fields into another php page.
The first page:
for ($i = 1; $i <= 10; $i++) {
print "

    <form action='2.php' method='post' id='test_form'>
        <input name='value-$i' type='text' />
        <input id='send' name='send' type='submit' value='Sent'  />
    </form>

";
}

The second page:
while ( ) {
$valuer= $_POST['value'];
}

A: <input name='value[$i]' type='text' />
                  ^--^---- note the []

Then
$fifth_value = $_POST['value'][5];


text:
Q: Wrong IP address in ssh restart I've just set up a second vps (s2.example.com) and when trying to restart SSH I'm getting the following error:
"The authenticity of host 'restart (xxx.xxx.xxx.74)' can't be established."
The IP address (ending .74) is not the IP address of that server. It is the IP address of another vps running at www.example.com.
I've set an A record for s2 to point to the correct IP address for that server.
Any ideas what I'm doing wrong?
Thanks

A: Try service sshd restart! ssh restart is an instruction to make an ssh connection to the host called restart (hence the error message).
And while I'm turning this into an actual answer, may I put in a plea - not just to you, DavidM, but to anyone who asks a question on SF - to post as much detail as they can about what they did, not just what they were trying to do.  Dennis' question cracked this one wide-open, but he should never have had to ask it.  I highly recommend the accepted answer to this meta question to anyone thinking of asking a question on SF.


text:
Q: React Native: HeadslessJS and Redux - How to access store from task We have a ReactNative app that uses redux, redux-persist and a HeadlessJS task. This task needs to have access to the store. As the task fires without booting the entire app (and so has no access by default), we thought we could simply create the store inside the task as well so that it would be rehydrated by redux-persist. It turns out, however, that the store created in this way is different from the one in the app: after running, they contain different values. We tested this in several ways and it seems indeed a problem with the stores (and not with the actions for instance)
How should we access a Redux store from an HeadlessJS task?
Relevant code:
store/configure.js:
configureStore = (client) => {
  const middleware = createMiddleware(client);
  const finalCreateStore = applyMiddleware(thunk, middleware, logger)(createStore);
  const store = finalCreateStore(rootReducer, undefined, autoRehydrate());

  return store;
};

In use (both in the app and in the service):
const client = new ApiClient();
const store = configureStore(client);
client.setStore(store);
persistStore(store, {
  storage: AsyncStorage,
}

In the app we simply use the Provider from react-redux to use the store, in the service we use store.dispatch.

A: For people looking for solution. I have found the solution in here.
The idea is to bind the store to async method.
https://github.com/react-native-kit/react-native-track-player/issues/63
Copy pasting the solution here.
// index
const store = ...
....registerHeadlessTask('TrackPlayer', () => require('event-handler.js').bind(null, store));
// event-handler.js
module.exports = async (store, data) {
    if(data.type == '...') {
        store.dispatch(...);
    }
};

A:
simply create the store inside the task as well so that it would be rehydrated by redux-persist.

This did indeed happen.
You created two stores (not advisable with redux) which were both hydrate, but not linked, as there is no such thing as linked redux stores.
Every time you run createStore, it's a new store. And every time you dispatch, you do that on a specific store.
Unfortunately async or multithreaded issues are not directly addressed by redux.
It would be possible though with middleware and / or store listeners to keep the two stores in sync.
But redux is also just not a mean for communication between threads (which I assume these tasks are, or you could just give the task a reference to the store once it was created or give the main app the store reference from the task).
It's more a form of Command-Query-Separation and centralized state.

A: You can access your store directly as reference.
Let's say you have your headless set in index.js, then you can just simply use store there like this:
    import { AppRegistry } from 'react-native';

    import Store from './src/Redux/Store';
    import { someAction } from './src/Redux/Actions/someActions';

    import App from './App';
    import { name as appName } from './app.json';

    const HeadlessTask = async () => {
      console.log('Receiving HeadlessTask');
      const someParam = await Store.getState().Something.someParam;

      if (someParam) {
        Store.dispatch(someAction(someParam));
      } else {
        Store.dispatch(someAction());
      }
    };

    AppRegistry.registerHeadlessTask('HeadlessTask', () => HeadlessTask);

    AppRegistry.registerComponent(appName, () => App);


text:
Q: If the kernel (cokernel) of a morphism $f$ is trivial, then is $f$ injective (surjective), or mono (epi)? Define a monomorphism (epimorphism) as a left-cancellative (right-cancellative) morphism, in some category.
The Wikipedia page on cokernels says that a morphism is injective (surjective) iff its kernel (cokernel) is trivial. The category being discussed seems to be that of vector spaces.
Now, in many categories, being an injection (surjection) is equivalent to being a monomorphism (epimorphism), but, if this is not the case --ie. monomorphisms are not injective (epimorphisms are not surjective)--, does the above result generalize to such monomorphisms (epimorphisms)?
Namely, is the following true? A morphism is a monomorphism (epimorphism) iff its kernel (cokernel) is trivial.

A: As Qiaochu notes, kernels and cokernels don't make sense in an arbitrary category: you need a zero object to even define what these should be (and even with a zero object, they aren't guaranteed to exist).
If you have a category with a zero object, then a monomorphism $f$ has zero kernel: $f\circ\ker f = 0 = f\circ 0\implies \ker f = 0$. This doesn't show that the kernel actually exists, just that if it does, it must be equal to zero. However, it is not difficult to verify that $0$ satisfies the universal property of the kernel in this case. Reverse all the arrows to get the dual statement for cokernels.
However, the converse is false: consider the category with four objects $A$, $B$, $C$, and a zero object $0$ and morphisms
\begin{align*}
\operatorname{Hom}(X,X) &= \{0, id_X\}\quad\textrm{for each object }X\\
\operatorname{Hom}(B,C) &= \{0, f\}\\
\operatorname{Hom}(A,B) &= \{0,g,h\}\\
\operatorname{Hom}(A,C) &= \{0, fg = fh\}\\
\operatorname{Hom}(C,A) &= \operatorname{Hom}(C,B) = \operatorname{Hom}(B,A) =\{0\}.
\end{align*}
By construction, $g\neq h$, $fg = fh$, and you can verify that $\ker f$ exists and is equal to $0 : 0\to X$.

A: I just wanted to supplement the existing answer to this question with another example of a category with a zero object and kernels, where a morphism with trivial kernel need not be monic. The category I have in mind is the category $\mathbf{Set}_*$ of pointed sets, whose objects are sets $X$ with a labelled element $*\in X$, and morphisms are functions that preserve the labelled element. This category has a zero object as well as kernels (in fact, all limits and colimits). The zero object is the singleton set $\{*\}$, and the kernel of a morphism $f\colon X\rightarrow Y$ is the preimage of $*\in Y$, with its labelled element being the same as in $X$. The monomorphisms in $\mathbf{Set}_*$ are exactly the injective functions.
Morphisms in $\mathbf{Set}_*$ with trivial kernel need not be monic. The simplest example is to take the function $f\colon\{*,x,y\}\rightarrow\{*,z\}$ sending $*$ to $*$ and $x$ and $y$ to $z$. This has trivial kernel but is not monic.


text:
Q: Division error in python, result is incorrectly rounded I am trying to make a BMI calculator function. I am learning python at pyschools.
This is my code:
# Note: Return a string of 1 decimal place.
def BMI(weight, height):
    x = weight /(height*height)
    g = round(x,1)
    return g

And pyschools shows me that these are the right answers:
With 110 = weight and 2 = height I am supposed to get a BMI of 27,5.
But I instead get 27.
Then it does a second check to make sure I wrote the code right and tells me 24,2 is the right answer but my program did return 24,2. But it still marks my answer in red and says "my" 24,2 is wrong and the website's is right.
If someone has a better site or anything to learn python it would also be appreciated since this website seems to be kind of wrong sometimes. And I am looking for free online resources. No books please.

A: To fix it for all cases, add this line to the top:
from __future__ import division  # Make division work like in Python 3.

in Python 2, / means integer division.

With this in mind, in Python 2 if you pass intgers into division, it will give you an integer back. Anything that would have been a float is floored*. Therefore another option to get the desired result is to pass a float in, so instead of:
weight / (height*height)

do:
float(weight) / (height*height)  # float in means float out.

*This means that only full times that the divisor goes in are counted. So 1/2 will get 0 because 2 goes fully into 1 0 times.

A: def BMI(weight, height):
    x = float(weight) /(height*height)
    g = round(x,1)
    return g

see Python division
and Binary arithmetic operations

A: The issue lies with your division.
Division as we intrinsically know it is floating point division, or division where 1 / 2 evaluates to a fraction, 0.5. In standard programatic division, the 1, 2 are ints() and therefore cant be fractions, or floats() as the type is called in python. The expression, 1 / 2 therefore evaluates as 0, as 2 as a whole integer cant go into one entirely any times.
Ex:
In [1]: 1 / 2
Out[1]: 0

# Explicitly what is going on, since 1 and 2 are ints.
In [2]: int(1) / int(2)
Out[2]: 0

#fixed with floating division
In [3]: float(1) / float(2)
Out[3]: 0.5

# protip: only one of the divisors needs to be a float for python to divide correctly.
In [4]: 1 / float(2)
Out[4]: 0.5

Use x = weight / float((height*height)) to get the results you expect.
# Note: Return a string of 1 decimal place.
def BMI(weight, height):
    x = weight / float((height*height))
    g = round(x,1)
    return g


text:
Q: Android doesn't show on Android Studio So I've been trying to debug my phone and at first it worked but later when I disconnected the phone and tried later it stopped working, it just wasn't showing up and the question: "Do you grant permission...." stopped showing up too. I also checked USB debugging is on I don't know what could cause this problem, it worked before why not again?
I checked if USB debugging is on, I also watched youtube videos on how to fix this and it wasn't helpful.

A: First:
I recommend disabling and enabling USB debugging again
Second:
Try to revoke USB Debugging authorizations
Third:
If the problem still persists, Try to play with those options [FIRST, SECOND]


text:
Q: Subsonic Delete multiple records I have a table which has a two fields, userid and degreeid. A user can have multiple degreeds in this table. When a user select their degree I want to delete any degree id already in the database but un-selected by user. How should do it? I try to use something like this with no luck.
repo.DeleteMany(x=>x.MeetingAttendeeUserID==userID && x.EducationDegreeID userDegreeList)
Thanks,
Lewis

A: Could you do something like this?
repo.DeleteMany(x =>
    x.MeetingAttendeeUserId == userID &&
    x.EducationDegreeID != selectedDegreeId
);

Edit: Or this.
repo.DeleteMany(x =>
    x.MeetingAttendeeUserId == userID &&
    userDegreeList.Contains(x.EducationDegreeID))
);

A: I have tried
SubSonicRepository<ReportDatum> repo = new SubSonicRepository<ReportDatum>(db);
repo.DeleteMany(x => x.ReportID == Convert.ToInt32(reportID));

and it does nothing, not even an error.
Addendum for someone that comes across this:
don't convert in the delete call, convert your variables beforehand.
int deleteKey = Convert.ToInt32(reportID)
SubSonicRepository<ReportDatum> repo = new SubSonicRepository<ReportDatum>(db);
repo.DeleteMany(x => x.ReportID == deleteKey);

and it fired fine.

A: I would recommend if you dont know Lamda expression. Create your own stored procedure and call use it.
This will not restrict you using lamda expression if you don't have time to learn it.
Ultimately you wanted to done your job.


text:
Q: How do I list all instantiated objects in Python? I have a long running processes which may have a resource leak.  How can I obtain a list of all instantiated objects (possibly only of a particular class) in my environment?

A: Try gc.get_objects():
>>> import gc
>>>
>>> class Foo: pass
...
>>> f1 = Foo()
>>>
>>> [o for o in gc.get_objects() if isinstance(o, Foo)]
[<__main__.Foo instance at 0x2d2288>]
>>>
>>> f2 = Foo()
>>>
>>> [o for o in gc.get_objects() if isinstance(o, Foo)]
[<__main__.Foo instance at 0x2d2288>, <__main__.Foo instance at 0x2d22b0>]

A: There's a few ways that you pretty much have to combine. I've used this module in the past to check for exactly that, memory leaks
https://mg.pov.lt/objgraph/
It can make your process use a TON more memory and be pretty slow though, depending on how you use it.

A: All instantiated objects (I'm assuming just for Python itself in a single module):
globals().keys().
For all of these that are instances only of a particular class:
filter(lambda x: isinstance(x, some_class), globals().keys()).


text:
Q: Running Rails App Downloaded from GitHub (database.yml) I'm a newb to rails, so please excuse this question but I've been searching everywhere for how to do it. I have a github project I cloaned that I'm going to have to eventually work on, but need to view it now in the browser (will be crash coursing to get up to speed the next couple months). I've downloaded the directory and ran bundle install. Now I'm trying to start the rails server and I get this:
    Chriss-MacBook-Pro:chris cgood$ rails server
/usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/railtie/configuration.rb:85:in `method_missing': undefined method `active_record' for #<Rails::Application::Configuration:0x007fc07b649c48> (NoMethodError)
    from /Users/cgood/event/chris/config/application.rb:69:in `<class:Application>'
    from /Users/cgood/event/chris/config/application.rb:25:in `<module:ChrisGood>'
    from /Users/cgood/event/chris/config/application.rb:24:in `<top (required)>'
    from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands.rb:53:in `require'
    from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands.rb:53:in `block in <top (required)>'
    from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands.rb:50:in `tap'
    from /usr/local/rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

Any help would be really appreciated! I've been pulling out hair for hours tackling error message after error message. This one has me stuck as hard to find anything on the internet about it.
I have xcode, rails installer, homebrew and postgreSQL installed. Thanks.

A: 2 things:

*

*upgrade rails!! there's a post about the dangers of using 3.2.11

*your app needs a file called database.yml, read this and this to find out what to put in it

Normally your app would have that file in it already, but since it usually contains sensitive data, like database user passwords, people tend to leave it out of their github repos. So you just need to make your own one.


text:
Q: What happend when I create a Stream in Dart but not close it When I create a Stream object in Flutter (Dart), I got a warning message that I should close this Stream after used it. I wonder that have any problem when I create a new Stream but not close it. (Seem like memory leak)
I used memory tool for finding memory leak in that's case but fail. Why should I close the Stream. May I miss anything about stream in Dart?
P/s: In my application, I have to create many Stream object and share it with many widget. It's easy to code if I don't need to manage the Stream instance.


text:
Q: Matplotlib - format with subscript and superscript How to write this number format, please?

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(14, 8))
a = 2
b = 5
c = 5
plt.text(5, 400, "${}^+^{}_-_{}$ d.".format(a, b, c))
plt.show()

A: I have found the solution:
fig, ax = plt.subplots(figsize=(14, 8))
a = 2.003
b = 5.551
c = -6.661
plt.text(0.5, 0.5, "${0:f}^{{{1:+f}}}_{{{2:f}}}$".format(a,b,c))
plt.show()


text:
Q: Export xml string to dataframe I have an XML string of the type:
<data>

    <name>a</name>

  <row>
    <Date>2021-04-20</Date>
    <Name>One</Name>
    15689
    <code2>Y</code2>
    <code3>38</code3>
  </row>
  <row>
    <Date>2021-04-20</Date>
    <Name>Two</Name>
    16890
    <code2>Y</code2>
    <code3>92</code3>
  </row>
</data>

And I am trying to parse this in a pandas data frame using this method:
dfcols = ['Date','name','code','code2','code3']
etree = et.fromstring(xml_str)

#xml_str is the xml string of the type mentioned above
rows = etree.findall('.//row')

xml_data = [[i.get('date'),i.get('name'),i.get('code'),i.get('code2'),i.get('code3')] for row in rows]

df = pd.DataFrame(xml_data, columns=dfcols)
print(df)

As a result, I get a data frame full of None values.
Can someone please help me?

A: You're almost there. Just change
rows=etree.findall('.//row)

to
xml_data =[]
for row in etree.findall('.//row'):
    xml_data.append([element.text for element in row.findall('.//*')])

Output:
         Date name   code code2 code3
0  2021-04-20  One  15689     Y    38
1  2021-04-20  Two  16890     Y    92

A: In Pandas v1.3 (estimated release by end of May 2021), the new read_xml makes this even easier with either lxml or etree parser:
df = pd.read_xml("Input.xml", xpath=".//row", parser="etree")


text:
Q: Real time plotting of EKG sensor data not working in small interval < 600ms i hope you're safe and healthy.
I'm working on my graduation project and in the last minute the professor required me to do real time plotting of ECG sensor data which is captured at 200Hz frequency (every 5ms) and after some research I found Dash which seemed to be a great tool that's gonna save me a lot of time that I really don't have…
the problem I'm having is that whenever I use the update interval to a value <600ms the whole screen starts flickering and redrawing the whole plot instead of updating (adding more values to) the plot.
It seems to work just fine with an update interval that's >=600ms.
here's the code I'm working with:
sig = []
with open("test_data7_ms.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for lines in csv_reader:
        sig.append((lines[0]))

# sig is an array created from a file that contains the sensor readings
# just to simulate the work of the sensor without the hassle with cables and everything
sig_iter = iter(sig)
x = deque(maxlen=5)
x.append(1)
Y = deque(maxlen=5)
Y.append(next(sig_iter, 400))
app = dash.Dash()

app.layout = html.Div(
    [
        dcc.Graph(id='ecg-graph',
                  animate=True),
        dcc.Interval(
            id='ecg-graph-update',
            interval=500,
            n_intervals=0
        ),
    ]
)

@app.callback(Output('ecg-graph', 'figure'),
    [Input('ecg-graph-update', 'n_intervals')])
def update_ecg(n):
    x.append(x[-1]+1)
    Y.append(next(sig_iter, 400))

    trace = go.Scatter(
        x=list(x),
        y=list(Y),
        name='Scatter',
        mode='lines'
    )
    return {'data': [trace], 'layout': go.Layout(xaxis=dict(range=[min(x), max(x)]),
                                                 yaxis=dict(range=[100, 900]),)}

if __name__ == "__main__":
    app.run_server(debug=True)

If anyone knows how to solve this problem or have any suggestions concerning Dash or other framework/library I'd really appreciate the help.


text:
Q: Griddler gem throwing exception while parsing an incoming email I have integrated Sendgrid incoming parse Webhook API, and it is correctly posting the email object to my rails app. On app I'm using griddler gem to catch and do further processing of email data. But I'm getting following exception:
Sent mail to chandan@exmaple.com (77.6ms)
F, [2014-11-14T17:48:05.851336 #24799] FATAL -- :
NoMethodError (undefined method `process' for #<EmailProcessor:0x0000000a2ad5f0>):
  griddler (1.1.0) app/controllers/griddler/emails_controller.rb:19:in `public_send'
  griddler (1.1.0) app/controllers/griddler/emails_controller.rb:19:in `process_email'
  griddler (1.1.0) app/controllers/griddler/emails_controller.rb:4:in `block in create'
  griddler (1.1.0) app/controllers/griddler/emails_controller.rb:3:in `each'
  griddler (1.1.0) app/controllers/griddler/emails_controller.rb:3:in `create'
  actionpack (4.1.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.1.4) lib/active_support/callbacks.rb:113:in `call'

Where as I have the process instance method in /mailer/email_processor.rb
class EmailProcessor
  def initialize(email)
    @email = email
    puts "initialized Email Processor\n\n\n\n\n\n\n\n" # Should see this line in log
  end

  def process
    user = User.find_by_email(@email.from[:email])
    puts @email.inspect and return if user.blank?

    puts "############### @email = #{@email.inspect}###############\n\n\n\n\n\n\n"
  end
end

Here is config/initializer/griddler.rb
Griddler.configure do |config|
  config.processor_class = EmailProcessor
  config.processor_method = :process
  config.reply_delimiter = '-- REPLY ABOVE THIS LINE --'
  config.email_service = :sendgrid
end

Here is the version of gem I'm using:
#Process incoming mail from sendgrid smtp server
gem 'griddler', "~> 1.1.0"
gem 'griddler-sendgrid', "~> 0.0.1"

This is based on documentation available on griddler github
Can anyone please help me with what I'm missing here. Also, why I don't see following line in log ?
"initialized Email Processor\n\n\n\n\n\n\n\n"

Following is the line to define route
mount_griddler

EDIT: As far as I know, rails doesn't add any such class directly.
Strangely I'm able to see the 'process' method available for 'EmailProcessor' class in 'rails console':
2.1.4 :005 > x = EmailProcessor.new(1)
initialized Email Processor\n\n\n\n\n\n\n\n
 => #<EmailProcessor:0x007fc6ae5aee08 @email=1>
2.1.4 :006 > x.methods
 => [:process, :blank?, :present?, ...
2.1.4 :014 > EmailProcessor.instance_methods(false)
 => [:process]

Thanks

A: The issue was, the EmailProcessor class was not being loaded with rails application startup. Adding following lines to application.rb did the magic:
 config.autoload_paths += %W(#{config.root}/app/mailers/email_processor.rb)

NOTE: You'll need to restart your server, every time you make changes to email_processor.rb.
Thanks to Joel Oliveira (Author of Griddler) to responding to my personal email and pointing out the issue :)


text:
Q: Default icons I can use in android? I want to have a list and in each item I want to have a small icon that signifies success/failure.
Is there anything build-in to android e.g. default icons that I can use to display that?
I assume I need to declare an ImageView and as android:src add some image that is part of the installation?
How can I do this?

A: Use android:src="@android:drawable/btn_plus"
but I don't think it's a good way, it would be better for you to copy the images to your drawables folder, even the documenation says so it advises not to use any icon directly from android.R.drawable
say for example, you are using btn_plus icon provided by the android.R.drawable and in near future say in API 25 they stop using btn_plus, your application may crash.

A: yes you can use android icon whith this code:
            imgView.setImageResource(android.R.drawable.ic_menu_myplaces);

In fact, these icons are on the path android.R.drawable.icons and try to find your Favorite Icons

A: Okay...You can get a set of Material Design Icons pack,all you have to do is install this plugin Android Material Design Icon Generator
MAC:

Preference > Plugins > Browse repositories, then search material.

Linux or Windows:

File > Settings... > IDE Settings > Plugins > Browse repositories,
  then search material.

After installing restart your IDE and right click on your drawable folder
select New->Material design icon

A: you can use
android.R.drawable.xxx

(use autocomplete to see whats in there)
Use this link to donwload the icons.

A: Yes you can use android default icon in your application
imageView.setImageResource(android.R.drawable.ic_delete);

Also you can check in Android SDK for different icons with below path
android-sdk/platforms/android-19/data/res/


text:
Q: How to get current input language c++? How can I get the current input language in c++ systemwide. If I switch to another window and change input language there, how do I know that the language has changed and to which language?

A: I think it depends on OS, and in windows,try following codes:
char szBuf[25];
double thId;
HANDLE hCurrentKBLayout;

hCurrentKBLayout = GetKeyboardLayout(0);
memset(szBuf, 0x00, 25);

ImmGetDescription(hCurrentKBLayout, szBuf, 50);
if(String(szBuf).Length()==0)
    strcpy(szBuf,"系统默认");
ShowMessage("current input language is:" + String(szBuf));

A: Officially, the locale "" is supposed to correspond to an
implementation defined locale, which typically should correspond
to what the user wants his language to be.  Whether this works
in practice depends a lot on the implementation;
std::locale().name() seems to always return "C" on my
Windows machine (even though I'm not running a US version of
Windows).
More generally, there may not be a single "language".  Input,
for example, is, at the system level, generally language
neutral; the key factors are how the keyboard is set (but
I've often entered French or German from a US keyboard), and
once the characters are in your program, how you interpret them
(and presumably, what you want to know is how to interpret them,
according to what conventions).  If you want to know the
conventions other programs, or the OS use, you'll have to find
some OS specific means; it is a sort of standard that
environment variables like LANG, LC_CTYPE, etc. contain this
information, but how the different conventions are encoded
varies (although I think recent versions of Windows also support
the Posix standard forms), and OS's other than Unix often use
other means as well, so you'll need something OS specific here.


text:
Q: Radio Button Struts 1.3 I would like to create a radio button to select the values displayed on a jsp page.
how can I use radio buttons  to select values from this JSP page ?
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<%! int i=0; %>

DOCUMENT INFORMATION CENTER

Employee ID	Document ID	Topic	Text	Files

<% int j=(Integer)session.getAttribute("i");
HttpSession session2=request.getSession();
for(i=0;i<j;i++)
{ out.println("
"+session.getAttribute("eid"+i)+"	"+session2.getAttribute("id"+i)+"	"+session2.getAttribute("topic"+i)+"	"+session2.getAttribute("text"+i)+"	"+session2.getAttribute("files"+i)+"
");
}

%>

A: You can use struts logic tags for this purpose. If the session logic present set the value of particular radio button as true. For iterating purpose also you can use logic:iterate tag. Following piece of code may help you.
<logic:present name="i" scope="session">
<logic:equal value="1" name="i" scope="session">

</logic:equal>
</logic:present>

Let me know if this helps..


text:
Q: Pack & unpack node_modules of an Electron Native application to be patched First of all, I am generating an electron native application using electron-builder, npm and npx.
The next commands/steps are being executed to compile and generate the electron native application:

*

*npm run build -- --prod --build-optimizer (to compile app)

*npx electron-builder build --windows (to generate an electron windows app)

Later, I obtain a myApp folder which contains:
/win-unpacked
electron-builder-effective-config.yaml
myApp.exe

My application uses the node_modules folder which contains all node dependencies used in my application.
My question is: are there any way to unpack the native application or similar and patch new changes inside node_modules?
After perform an investigation, I have discovered that node dependencies are packed in system cache inside an app.asar file which contains a dist folder with some .js files.
In developer tools:

Inside app.asar:

Are there any way to "deploy" node modules folder with the aim to perform patch operations of each package and change the code inside node modules folders?
I will appreciate any kind of help.

A: Asar is a read only archiv format, so you cant patch any files in the archive.
But what you can do is to disable the asar option in your build config.
So in your package.json define it like this:
"build": {
    "appid": "........",
    "win":   {........},
    "asar":  false
}

if you build this, there is no asar archive anymore and you can overwrite any file...
what you can also do is using asar programatically. So you can unpack the asar archive, updating files and package new archive. See here how you can use it

A: Contrary to what is being said here, patching a .asar archive is totally possible. I have published a library on NPM called patch-asar that does specifically this.


text:
Q: requiring a file from laravel facade file I have a facade 'CustomMage', but from which I'm not able to include magento api.
<?php namespace Bond\CustomMage;

class CustomMage {

    /* Using mage configurations*/
    public static function changeIsActive($table, $id, $status){
        $api_path = \Config::get('api.mage_soap_api_path');
        require_once("{$api_path}app/Mage.php");

        /*umask(0);
        Mage::app('default');
        $quote = Mage::getModel('sales/quote')->load($id);
        $quote->setIsActive($status)->save();*/
    }

}

I'm getting this error,

[2018-02-07 08:47:09] local.ERROR: exception 'ErrorException' with
  message 'include(Bond\CustomMage\Mage.php): failed to open stream: No
  such file or directory' in
  /var/www/html/FootballTicketPad/ecomm/lib/Varien/Autoload.php:93

But this code is ok if i use it in app/helpers.php.

function GetModal($table, $id){
    $api_path = \Config::get('api.mage_soap_api_path');
    require_once("{$api_path}app/Mage.php");
    umask(0);
    Mage::app('default');
    return Mage::getModel($table)->load($id);
}


text:
Q: Is this sentence, 'try to relieve her by lightening her mood', correct? Is this sentence, "try to relieve her by lightening her mood", correct, and if so, what is the difference here between lighten and relieve?

A: Yes, that sentence is correct.

Relieve: to free from anxiety, fear or pain.
Lighten: to cause to become cheery or glad.

"Lighten" is a synonym of "cheer up". And "relieve" is a synonym of "alleviate".
The difference is pretty clear since relieve does not imply to have a good mood, while lighten does.


text:
Q: How to analyse the ratio of two continuous variables sampled repeatedly over time I am measuring reproductive hormones in dolphins over time to look at seasonal changes.  The sample type (respiratory vapour) that I am using suffers from variable water dilution that cannot easily be quantified (an artefact of normal respiratory processes).  For this reason, absolute concentrations are not a consistent measure; however, dilution will affect all analytes in respiratory vapour equally, therefore comparing the ratio of key hormones, which are biologically important, will indicate when/how changes are occurring over time.
This is an example of my experimental design, where XX is progesterone (ng/mL)/oestradiol (ng/mL)
e.g.
Dolphin ID        Sex         Time point         Progesterone:oestradiol
 1                  F              1                     XX

My sample size will be small (i.e. 12 animals) and sampling will occur over 4 time periods.  For this reason, I don't think I will have the statistical power to analyse these using standard parametric tests (mixed effects model with repeated measures).
Any information in regards to what kind of statistical analysis would be useful or any transformations of this ratio data to conform to traditional tests would be greatly appreciated.


text:
Q: What does it mean "getavg must return value" in this program? I am in an introductory programming class and am having problems solving a problem. It would be greatly appreciated if anyone could help.
The program should display the average number of pounds of coffee ordered. The number of pounds ordered are stored in the pounds array. Complete the program using the while statement.
//Introductory22.cpp - displays the average number of pounds ordered
//Created/revised by <your name> on <current date>

#include <iostream>
#include <iomanip>
using namespace std;

//function prototype
double getAvg();

int main()
{
   double pounds[6] = {10, 15.5, 17, 18.5, 11, 12.5};
   double average = 0.0;

   average = getAvg();
   cout << fixed << setprecision(2);
   cout << "Average number of pounds ordered: " << average << endl;
   return 0;
}   //end of main function

//*****function definitions*****
void getAvg()
{
   int x = 0;
   do // begin loop
   {
      cout << pounds[6] << endl;
      x += 1 pounds[sub];
   } while (x < 6);
   return static_cast<double>(total) / numElements;
}   //end of getAvg function

That is my code and I get error C4716 - getavg must return a value.
What simple way could I fix this?

A: Your function declaration and function definitions have different signatures. You need to change your definition to return a double.


text:
Q: Is this Wikipedia pseudocode for in-order generic tree traversal correct? Wikipedia states that the following algorithm works for any tree (not necessarily binary trees)

*

*Perform pre-order operation

*For each i (with i = 1 to n) do:

*

*Visit i-th, if present

*Perform in-order operation

*Perform post-order operation

  where n is the number of child nodes.

The pre-order and post-order parts make sense. The in-order one does not make sense to me however. By performing this algorithm I would perform the in-order operation on the same node several times. Basically, if I have a node with 5 child nodes, then I will perform the in-order operation on the node 5 times, once after visiting each child node. This does not make sense to me. Isn't a tree traversal supposed to go through each node once?
Actually, does an in-order traversal even make sense for generic trees? Doesn't it only apply to binary trees, or trees where the "order" is not ambiguous?

A: In the algorithm you provided, although it is true that the same in-order operation is performed in the same node multiple times, it is still ran once for each node and each node is visited only once.
Note that this isn't a "in-order" tree traversal, you can't make such a traversal on a ntree, it just doesn't make sense. This is simply a deep-first traversal and the in-order operation is something that is ran after the node has been visited. It has nothing to do with the "in-order functions" that are mentioned elsewhere in on the page.
Maybe I should add, visit is the recursive call in this case, not the in-order operation.


text:
Q: Reducing file size of QGIS PDF export? I've created a layout printed to PDF (A4, 1:1000) which shows an area of OS mapping (vector data) and this prints to over 8MB - is there a way to reduce the output size of the pdf?
I've tried removing all the unnecessary layers and this helps but only slightly.


text:
Q: AR Multiplayer: How to share the position of the 3D object, relative to the image target? I'm trying to implement a very basic ARCore-ARKit multiplayer in Unity. I can use markers to place 3D content over them using Vuforia or ARKit/ARCore image recognition.
But how can I store and share across several devices (iOS and Android) the position of the 3D object, relative to the image target?
I can't find any useful tutorial on this topic.

A: You can make the 3D objects child objects of your image anchor and share the local position. For the sharing you can use Unity networking


text:
Q: Custom post type - displaying sets of data if selected on Worpdress back end I am trying to extend a custom wordpress plugin that displays sets of data stored on the Wordpress database when an option is setup on the backend via a custom metabox on a custom post type.
At the moment it is displaying two custom sets of data but I need to add a third one. I think my php skills are obviously not up to scratch for this one as I keep getting the error below:
Parse error: syntax error, unexpected end of file  on line 103
<?php if ($contestedby2013 == true || $contested2013 == true) { ?>

Older election data

                <?php if($contested2005 == true) {echo '
2005 full election results
';}?>
                <?php if($contestedby2008 == true) {echo '
2008 by-election results
';}?>
                <?php if($contested2009 == true) {echo '
2009 full election results
';}?>
                <?php if($contestedby2009 == true) {echo '
2009 by-election results
';}?>
                <?php if($contested2010 == true) {echo '
2010 by-election results
';}?>
                <?php if($contested2013 == true) {echo '
2013 full election results
';}?>
                <?php if($contestedby2013 == true) {echo '
2013 by-election results
';}?>

Older election result data for <?php echo $electoral_area_title; ?> area

Before the 2005 election, county level electoral boundaries in Warwickshire were slightly different. Because of this difference, data isn't displayed alongside the 2005, 2009 and 2013 results - but it is still available to view and download through the opendata.warwickshire.gov.uk website.

                <?php include('tab-logic-2005-full.php');?>
                <?php include('tab-logic-2008-by.php');?>
                <?php include('tab-logic-2009-full.php');?>
                <?php include('tab-logic-2009-by.php');?>
                <?php include('tab-logic-2010-by.php');?>
                <?php include('tab-logic-2013-full.php');?>
                <?php include('tab-logic-2013-by.php');?>

<?php if ($contestedby2014 == true || $contested2013 == true) { ?>

Older election data

                <?php if($contested2005 == true) {echo '
2005 full election results
';}?>
                <?php if($contestedby2008 == true) {echo '
2008 by-election results
';}?>
                <?php if($contested2009 == true) {echo '
2009 full election results
';}?>
                <?php if($contestedby2009 == true) {echo '
2009 by-election results
';}?>
                <?php if($contested2010 == true) {echo '
2010 by-election results
';}?>
                <?php if($contested2013 == true) {echo '
2013 full election results
';}?>
                <?php if($contestedby2014 == true) {echo '
2013 by-election results
';}?>

Older election result data for <?php echo $electoral_area_title; ?> area

Before the 2005 election, county level electoral boundaries in Warwickshire were slightly different. Because of this difference, data isn't displayed alongside the 2005, 2009 and 2013 results - but it is still available to view and download through the opendata.warwickshire.gov.uk website.

                <?php include('tab-logic-2005-full.php');?>
                <?php include('tab-logic-2008-by.php');?>
                <?php include('tab-logic-2009-full.php');?>
                <?php include('tab-logic-2009-by.php');?>
                <?php include('tab-logic-2010-by.php');?>
                <?php include('tab-logic-2013-full.php');?>
                <?php include('tab-logic-2014-by.php');?>

<?php } ?>

<?php } else { ?>

Older election data

                <?php if($contested2005 == true) {echo '
2005 full election results
';}?>
                <?php if($contestedby2008 == true) {echo '
2008 by-election results
';}?>
                <?php if($contested2009 == true) {echo '
2009 full election results
';}?>
                <?php if($contestedby2009 == true) {echo '
2009 by-election results
';}?>
                <?php if($contested2010 == true) {echo '
2010 by-election results
';}?>
                <?php if($contested2013 == true) {echo '
2013 full election results
';}?>

Older election result data for <?php echo $electoral_area_title; ?> area

Before the 2005 election, county level electoral boundaries in Warwickshire were slightly different. Because of this difference, data isn't displayed alongside the 2005, 2009 and 2013 results - but it is still available to view and download through the opendata.warwickshire.gov.uk website.

                <?php include('tab-logic-2005-full.php');?>
                <?php include('tab-logic-2008-by.php');?>
                <?php include('tab-logic-2009-full.php');?>
                <?php include('tab-logic-2009-by.php');?>
                <?php include('tab-logic-2010-by.php');?>
                <?php include('tab-logic-2013-full.php');?>

<? php } ?>

Any thoughts?


text:
Q: How can I simulate a click event in my AngularJS directive test? I've tried following the format of the ng-directive-testing repo for a directive I've written. The directive basically renders an overlay when the user clicks on an element. Here's the directive (simplified):
mod.directive('uiCopyLinkDialog', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var $elm = angular.element(element);
            element.bind('click', function(event) {
                $elm.addClass('test');
            });
        }
    };
});

The test I'm writing looks like this:
describe('pre-compiled link', function () {

    beforeEach(mocks.inject(function($compile, $rootScope) {
        scope = $rootScope;
        element = angular.element('');
        $compile(element)(scope);
        scope.$digest();
    }));

    it("should change the class when clicked", function () {
        element.click(); // this returns "'undefined' is not a function"
        element[0].click(); // so does this
        $(elm).click(); // this uses jquery and doesn't *seem* to fail
        waits(500); // hack to see if it was a race condition
        expect(elm.className).toContain('test'); // always fails
    });

});

You can see in the test that I try several ways to trigger the click() event on the link, with most of them giving an undefined error.
Can anyone tell me what I'm doing wrong here? Reading the examples this sounds like it's the correct syntax but my test runner (Karma via Grunt) doesn't want to play ball.

A: You can use triggerHandler, part of JQLite.
I used this to trigger a click event on a directive...
element = angular.element("

");
compiled = $compile(element)($rootScope);
compiled.triggerHandler('click');

Full example available on this blog post:
http://sravi-kiran.blogspot.co.nz/2013/12/TriggeringEventsInAngularJsDirectiveTests.html

A: I've had trouble with this also. It seems as though click() doesn't seem to work at all for me with PhantomJS for any element I compile. It always returns undefined.
Though not really as good as an actual click, you could access the directive's function in ng-click to simulate a click through it's isolate scope:
var element = $compile('Click me')(scope);
var isolateScope = element.isolateScope();
isolateScope.myfunc();
scope.$digest();

/* check that things changed ... */

A: So my solution to this was to actually append the element to the body. Since the root problem is that phantomJs doesn't fire events for elements in memory, it seemed simpler to append each element so that the events work for real.
afterEach(function(){
    $('body').empty();
});

it('should do something when clicked', function(){
    element = $compile('

')($scope);
    $('body').append(element);

    // fire all the watches, so the scope expressions will be evaluated
    $rootScope.$digest();

    $(element).find('.my-input').click();
});

A: So this turned out to be a problem with PhantomJS: some events that act on elements don't seem to fire when the elements aren't actually on a document anywhere, but just in memory (that's my theory, anyway). To work around this I had to use this function to trigger click events on elements:
define(function () {
    return {
        click: function (el) {
            var ev = document.createEvent("MouseEvent");
            ev.initMouseEvent(
                "click",
                true /* bubble */, true /* cancelable */,
                window, null,
                0, 0, 0, 0, /* coordinates */
                false, false, false, false, /* modifier keys */
                0 /*left*/, null
            );
            el.dispatchEvent(ev);
        }
    };
});

This worked, although other things were harder: I also wanted to write a test that ensures a given form input has focus, but getting this value was almost impossible using PhantomJS since I guess the browser can't make something focused if it has no onscreen representation. Anyone needing this could have a look at CasperJS which offers a simple API for some of these requirements.

A: You can use angular-test-runner library and test will look like:
const testRunner = require('angular-test-runner');

describe('directive', () => {
    let app;
    const {expectElement, click} = testRunner.actions;

    beforeEach(() => {
        app = testRunner.app(['mod']);
    });

    it("should add class when clicked", function () {
        const html = app.runHtml('');

        html.perform(
            click.in('.foo')
        );

        html.verify(
            expectElement('.foo').toHaveClass('test')
        );
    });

});

A: How about including angular-scenario and then using browserTrigger(element, 'click')?


text:
Q: Xcode/Git Repository Error: "Please verify that the working copy is reachable and try again." Here are the steps I take.

*

*I open Xcode (4.3.3) organizer and select Checkout or Clone Repository

*I choose the location https://MyUsername@bitbucket.org/MyUsername/myrepo.git

*Press Clone button and it successfully clones it on my local disk

*So I open the local copy of the project and perform some changes to it.

*When I try to commit changes (or do any other git related operation) I get the following error:

The working copy "MyAppName" could not be reached.
Please verify that the working copy is reachable and try again.

However I can perform commits (and other types of git operations) without any issues from the Terminal app using command lines.
I've tried restarting my computer, deleting all Xcode settings, but nothing helped.
Update: I tried it again today and it works fine now. Maybe it's some sort of an intermittent bug in Xcode.

A: Whenever this happens to me (and it happens often) I do the following:
1-Close the project
2-Open the organiser
3-Go into the repositories tab.
If your current working copy has been added to the list already, then within the organizer navigate to it, and double-click on the .xcodeproj project.
This will re-open the project in XCode, and you'll find that now SCM operation will work fine.
If your current working copy hasn't been added to the list, press the + button in the bottom left corner, select "Add Working Copy", navigate to the folder containing the .xcodeproj and open this folder.
Now double click on the .xcodeproj file, the project will open in XCode.
And it's all working fine again...
No idea why this make things work... but it does

A: I have the same problem. It happens if you have ~/ in the path to project. Works fine, when you open your project from organizer.

A: It's a bug of Xcode! When you search the xxx.xcodeproj from your Home folder of the dialog box  directly, Xcode will use the ~/xxx/xxx as the SVN/Git path which is completely wrong.
So you should avoid this, and search from the "/" path instead.

A: This is not exactly the answer you might be looking for, but I ran across similar problems when using Remote git repository (Github) and Xcode.
I ended up using a GUI tool "SourceTree", a good and easy to use tool to pull/push your code from Local Git to Remote Git Repository. Try it out http://sourcetreeapp.com/


text:
Q: Elasticsearch - ElasticRestHighLevelClient Filtering Values with partition How to create a query like bellow with ElasticRestHighLevelClient:
I can not add this part to my query.
"include": {
               "partition": 0,
               "num_partitions": 20
            }

Here is what I need:
GET /_search
{
   "aggs": {
      "expired_sessions": {
         "terms": {
            "field": "account_id",
            "include": {
               "partition": 0,
               "num_partitions": 20
            },
            "size": 10000,
         }
      }
   }
}

Here is my java code.
        AggregationBuilder AggregationBuilder = AggregationBuilders
                .terms("CONTACT_ID")
                .field("CONTACT_ID")
                .size(10000);

A: This is what you are looking for:
  IncludeExclude includeExclude = new IncludeExclude(0, 20);

  AggregationBuilder aggrBuilder = AggregationBuilders
                           .terms("expired_sessions")
                           .field("account_id")
                           .includeExclude(includeExclude)
                           .size(10000);

  searchSourceBuilder.aggregation(aggregationBuilder);

The corresponding JSON:
"aggregations":{
      "expired_sessions":{
         "terms":{
            "field":"account_id",
            "size":10000,
            "include":{
               "partition":0,
               "num_partitions":20
            }
         }
     }
}


text:
Q: Ruby on rails implementing "repost" action for Post's model I have a Userand Post model  with the association one-to-many. I tried to implement a repost action, add a link has_and_belongs_to_many through a table reposts.
But I was faced with the following challenges:
1) Post to feed loaded as follows:
followed_users="SELECT  followed_id FROM relationships WHERE follower_id = :user ";
replics_posts="SELECT micropost_id FROM replics_users WHERE user_id = (:user)"
reposts="SELECT post_id FROM reposts WHERE user_id = (:user)"

where("user_id IN(#{followed_users}) OR user_id= (:user) OR id IN(#{replics_posts}) OR id in (#{reposts})", user: user);

and sorted by date modified. Repost similarly sorted, from which there is a situation that is repost in the middle  feed.
2) No additional effort, followers do not see reposts user.
These problems can be solved through the auxiliary array with the need to fast, but it looks ridiculous and non-optimal solution.
How can I get out of the situation?
P.S. I think the solution can be found by reference in the field "Content" in the Post model on the same field, another object. Then repost action will not need a separate table and will consist only of a new Post object with a pointer to the contents of the original post. But I do not know how to do this in Ruby on Rails.
Thank you for your help!

A: I corrected as follows:
1)  In the Post model added a new field repost_id and reference to yourself:
has_many: reposts, class_name: "Post", foreign_key: "repost_id", dependent:: destroy;

(relation to the model User not changed)
2) Added to Post's controller method repost
  def repost
    orig_post=Micropost.find(params[:id]);
    if(orig_post)
      Micropost.create(user_id:current_user.id,
        content: orig_post.content,
        repost_id:orig_post.id);
      respond_to do |format|
        format.js
      end
    end
  end

(Do not forget to realize meets both the route and validations creation of the post)
The result is a correct model of behavior actions repost with dependencies and correct display in the feed. But sadly, this approach involves storing duplicate data in the table Posts in the "Content" field.


text:
Q: Soldering Nichrome wire to Stainless steel and steel to PCB Is it possible to solder Nichrome wire (30AWG) to stainless steel and then the steel to a PCB?

A: Nichrome is very refractory- it melts at around 1400°C- so that's not a problem.
Both stainless steel and Nichrome have oxide layers that render them impossible to soft solder. It's possible to silver solder (braze) them with high temperatures (eg. a propane torch), silver solder and brazing flux but that's not a lot of use if you want to connect to a PCB since the stainless steel is not soft solderable (the silver solder itself is soft solderable, if I recall correctly).
Pressure contact is one possibility (a terminal strip or a threaded stud) or you could spot weld or silver solder the Nichrome wire to a copper wire that could then be soft soldered.


text:
Q: What SQL query does stackoverflow use to retrieve a question and all its answers in order? According to this, stackoverflow uses one table for both questions and answers. This design seems somewhat unusual.
What SQL query does stackoverflow use to retrieve question #123456 and all its answers?
What is the advantage of this design compared to having separate tables for questions and answers?

A: You probably won't get the exact SQL query, since only the SE team knows that. However, the basic form probably looks something like
SELECT * # Replace the actual fields
FROM posts
WHERE (Id = {POST_ID}) OR (ParentId = {POST_ID})
ORDER BY PostTypeId ASC, Score DESC

The reason one table is used is because questions and answers are actually very similar. Both can be voted upon, have authors and editors, etc.. Keeping it in one table makes things easier for the DBAs.
In theory, it might also save a JOIN, but since SE redirects to a question page even if you pass an answer ID as a question ID, it might not necessarily do so.


text:
Q: How can I make my lines not cross with Turtle? This is part of my code (not ready yet). I need to make lines of the circles not cross, pretending to be overlaying objects. I'd like not to fill in the blank circles. Thanks in advance!
# G7
for i in range (140,0,-20):
    turtle.up()
    turtle.sety(160)
    turtle.setx(i)
    turtle.down()
    turtle.setheading(90)
    turtle.circle(i)

# G8
for i in range (160,0,-20):
    turtle.up()
    turtle.sety(0)
    turtle.setx(i)
    turtle.down()
    turtle.setheading(90)
    turtle.circle(i,180)

A: The obvious way seems to be using fill:
import turtle

turtle.color('black', 'white')
turtle.speed('fastest')

for i in range(140, 0, -20):
    turtle.up()
    turtle.setposition(i, 160)
    turtle.down()
    turtle.setheading(90)
    turtle.circle(i)

for i in range(160, 0, -20):
    turtle.up()
    turtle.setposition(i, 0)
    turtle.down()
    turtle.setheading(90)
    turtle.begin_fill()
    turtle.circle(i, 180)
    turtle.end_fill()

turtle.hideturtle()
turtle.mainloop()

But since you indicate you don't want to use fill, another approach is to use stamping:
from turtle import Turtle, Screen

CURSOR_SIZE = 20

screen = Screen()

turtle = Turtle('circle', visible=False)
turtle.color('black', 'white')
turtle.penup()

turtle.sety(140)

for i in range(240, 0, -40):
    turtle.shapesize(i / CURSOR_SIZE)
    turtle.stamp()

turtle.sety(0)

for i in range(280, 0, -40):
    turtle.shapesize(i / CURSOR_SIZE)
    turtle.stamp()

turtle.sety(-10)

turtle.begin_poly()
turtle.circle(10, 180, 12)
turtle.end_poly()

screen.register_shape("semicircle", turtle.get_poly())
turtle.shape("semicircle")

turtle.sety(-160)

for i in range(320, 0, -40):
    turtle.shapesize(i / CURSOR_SIZE)
    turtle.stamp()

screen.mainloop()

But if neither of those appeals to you, you could simply draw the image by calculating where the starting point of each arc is on the circle below it to avoid the overlapping lines.  I.e. do the math.


text:
Q: Mathematica crashes in for loop My Mathematica (both version 10.4 and the new 11) crash in the following loop:
count = 0;

findConnectedNodes[start_] := Module[{positions, i},

count++;
positions = adjmatrix[[start]] // ArrayRules // Keys;
positions = positions[[1 ;; -2]] // Flatten;

For[i = 1, i <=  Length[positions], i++,

 If[Not[MemberQ[connectedNodes, positions[[i]]]],
  findConnectedNodes[positions[[i]]]];

 AppendTo[connectedNodes, positions[[i]]];
 connectedNodes = connectedNodes // DeleteDuplicates;

 ]

];

findConnectedAddresses[1];

The variable adjmatrix is a SparseArray and this code is to find all connected nodes in an adjacency matrix.
Interestingly the code works very well up to about 14'000 "counts" (the variable count) and after that Mathematica just crashes.
$RecursionLimit is set to Infinity.
Thank you very much for your help. And also any other suggestions for the code are much appreciated.

A: Although you set the variable $RecursionLimit to infinity all programming languages can only recurse until so much. If I can assume correctly the Mathematica compiler is throwing you a "Stack Overflow" error which happens when the current local "stack memory" overflows (or surpasses) the maximum stack memory size.
Based on what I am inferring I would recommend force/manually initialise the Mathematica garbage collector at the end of each recursion to destroy the unwanted variable references created from previous recursions. If you can provide the error message given when your loop crashes, I or other people will be able to get you a more constructive or grounded response.

A: Thank you very much for all the tips and ideas.
My solution was to add the new nodes that were found to a intermediate variable and loop on that variable. In that way I did not go "deeper" into the loop and always stayed at one level.
If anyone has a similar (or the same) problem I will write the whole code. But for now I hope the "text-version" is self explanatory.


text:
Q: how to set textview below view pager inside relatvielayout in android <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="2"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="55dp"
        android:paddingRight="55dp"
        android:paddingTop="55dp">

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pager"
            android:fontFamily="sans-serif"
            android:gravity="center_horizontal"
            android:lineSpacingExtra="6sp"
            android:paddingTop="30dp"
            android:text="@string/label_businesscard_title"
            android:textColor="#3e4360"
            android:textSize="16sp"
            android:textStyle="normal" />

        <com.viewpagerindicator.CirclePageIndicator
            android:id="@+id/indicator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:paddingTop="15dp"
            app:centered="true"
            app:fillColor="#1ebad6"
            app:pageColor="#c6caca"
            app:snap="false" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="40dp">

    </RelativeLayout>

</LinearLayout>

this is my xml i want set textview below viewpager and indicator below textview i hae put feature layout below but its not working please suggest me what i m doing wrong. my expected screen is like below.
https://pasteboard.co/GSuVsth.jpg  but not able to do please suggest me.

A: Here try this out I hope it will help you. The problem is you are giving too much padding Top. So either you have to remove that or you have to use scrollview and then use this layout to fullfill your requirements or use more space.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="2"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:paddingLeft="55dp"
    android:paddingRight="55dp">

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/indicator"
        android:fontFamily="sans-serif"
        android:gravity="center_horizontal"
        android:lineSpacingExtra="6sp"
        android:text="@string/label_businesscard_title"
        android:textColor="#3e4360"
        android:textSize="16sp"
        android:textStyle="normal"
        android:id="@+id/textView" />

    <com.viewpagerindicator.CirclePageIndicator
        android:id="@+id/indicator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        app:centered="true"
        app:fillColor="#1ebad6"
        app:pageColor="#c6caca"
        app:snap="false" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="40dp">

</RelativeLayout>

A: Try this
    <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="2"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="55dp"
android:paddingRight="55dp">

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView"
    android:layout_marginTop="5dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/indicator"
    android:fontFamily="sans-serif"
    android:textAlignment="center"
    android:layout_margin="7dp"
    android:gravity="center_horizontal"
    android:lineSpacingExtra="6sp"
    android:textColor="#3e4360"
    android:textSize="16sp"
    android:text="helllllllllllll"
    android:textStyle="normal"
    android:id="@+id/textView" />

   <com.viewpagerindicator.CirclePageIndicator
    android:id="@+id/indicator"
    android:layout_margin="5dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    app:centered="true"
    app:fillColor="#1ebad6"
    app:pageColor="#c6caca"
    app:snap="false" />
    </RelativeLayout>

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="40dp">


text:
Q: Embed expression in Report Builder for control of multiple objects? I have a status type report where I'm using multiple colors to indicate who is where.  To control the colors, I'm using a long expression that matches an ID number to an assigned color.  Then I'm repeating this over 25 times for each particular Tablix which represents a location.
What I'm wondering is:  Would it be possible to embed the expression in a textbox, and then refer to the textbox in order to control each fields' fill color?
It seems that I would need something like
=ReportItems!FillControl.Value
in the Background Color property, with FillControl.Value being something like
=IIF(IsNothing(Fields!ProviderEmpID.Value) OR (Fields!PtOrder.Value) <> "1", "Black", "White")
, but it doesn't calculate.
By doing this, then I can duplicate the location fields multiple times, and only have to update the control once when changes need to be made.


text:
Q: ssh config change user for one host I would like to connect to each server using the root user and to machin server using me user.
I edit .ssh/config
 User root
 Host machin
 Hostname machin
 User me

When I type
 ssh machin

I get
 root@machin's password:

What is wrong with my config?

A: According to the ssh_config manual page:

Since the first obtained value for each parameter is used, more
  host-specific declarations should be given near the beginning of the
  file, and general defaults at the end.

You should change the order of your configuration values, first set the host-specific ones then the general ones:
Host machin
Hostname machin
User me
User root


text:
Q: Replaced UIWebView with WKWebView, but still same error from Apple I have removed the UIWebView from my app. But when I uploaded the iOS app on iTunes I still got the same message "Re: ITMS-90809: Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView APIs"
I have searched for UIWebView globally in the project and there are no search results. That simply means UIWebView is removed.
I have updated the pods too.
I have verified the presence of UIWebView in the app archive using below code:
grep -r "UIWebView" .

The response is
./BCSymbolMaps/F4DBB519-4BC9-3C29-B017-4C0BD603D250.bcsymbolmap:l_OBJC_PROTOCOL_$_UIWebViewDelegate
./BCSymbolMaps/F4DBB519-4BC9-3C29-B017-4C0BD603D250.bcsymbolmap:l_OBJC_LABEL_PROTOCOL_$_UIWebViewDelegate
./BCSymbolMaps/F4DBB519-4BC9-3C29-B017-4C0BD603D250.bcsymbolmap:-[Crashlytics monitorErrorsForUIWebView:]
./BCSymbolMaps/F4DBB519-4BC9-3C29-B017-4C0BD603D250.bcsymbolmap:CLSWebViewIsUIWebViewAlreadyMonitored
./BCSymbolMaps/63FADF77-FD8F-31A1-9B4E-2799F044786E.bcsymbolmap:l_OBJC_PROTOCOL_$_UIWebViewDelegate
./BCSymbolMaps/63FADF77-FD8F-31A1-9B4E-2799F044786E.bcsymbolmap:l_OBJC_LABEL_PROTOCOL_$_UIWebViewDelegate
./BCSymbolMaps/63FADF77-FD8F-31A1-9B4E-2799F044786E.bcsymbolmap:-[Crashlytics monitorErrorsForUIWebView:]
./BCSymbolMaps/63FADF77-FD8F-31A1-9B4E-2799F044786E.bcsymbolmap:CLSWebViewIsUIWebViewAlreadyMonitored
Binary file ./dSYMs/Eureka.framework.dSYM/Contents/Resources/DWARF/Eureka matches

How can I check the code that is still causing the error of UIWebView?

A: How can I check if the UIWebView is completely removed from the project or not?
Solution is:

*

*Open terminal. Open your project root folder in terminal.

*Run Command: grep -r "UIWebView" .

*This command will list all the pods that contains "UIWebView". No either update these pods or remove these pods and ren the step 2 command again. Repeat till all "UIWebView" matches are not removed.

Below are some steps that will guide you to update existing UIWebView to WKWebView.
Import the "WebKit" class to the Controller.
Suppose you are using a UIWebView named "webViewMain". Then go to your storyboard and simply replace the UIWebView with UIView. Make sure that you have added the same constraints to UIView that were added to UIWebView. Draw @IBOutlet from the new UIView to existing @IBOutlet of UIWebView.
Here you need to change the class of @IBOutlet from UIWebView to UIView because you have replaced the UIWebView with UIView.
Older Code: @IBOutlet weak var webViewMain: UIWebView!
New Code: @IBOutlet weak var webViewMain: UIView!
Then create a new variable to create a new WKWebView.
CODE: var webView : WKWebView!
Add below code where you load request/html in the UIWebView:
// WKWebView
            // init and load request in webview.
            webView = WKWebView(frame: self.webViewMain.frame)
            webView.navigationDelegate = self
            self.webView.load(request)
            self.webViewMain.addSubview(webView)
            webView.translatesAutoresizingMaskIntoConstraints = false
// Adding constraints from webView(WKWebView) to webViewMain (UIView)
            webView.leadingAnchor.constraint(equalTo: webViewMain.leadingAnchor, constant: 0).isActive = true
            webView.trailingAnchor.constraint(equalTo: webViewMain.trailingAnchor, constant: 0).isActive = true
            webView.topAnchor.constraint(equalTo: webViewMain.topAnchor, constant: 0).isActive = true
            webView.bottomAnchor.constraint(equalTo: webViewMain.bottomAnchor, constant: 0).isActive = true
            // WKWebView

Till now you have replaced UIWebView with WKWebView .
Now comes the delegate methods.
UIWebView has delegate class: UIWebViewDelegate
WKWebView has delegate class: WKNavigationDelegate
Replace UIWebViewDelegate with WKNavigationDelegate.

Now comes delegate method comparison for UIWebView vs WKWebView:
UIWebView: func webViewDidFinishLoad(_ webView: UIWebView)
WKWebView: func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
UIWebView: func webViewDidStartLoad(_ webView: UIWebView)
WKWebView: func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
UIWebView: func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool
Here we return true/false to load/cancel the navigation.
WKWebView: func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
Here we returndecisionHandler(.allow)/decisionHandler(.cancel) to load/cancel the navigation.
To Scale aspect fit content of the webView (WKWebView).
var scriptContent = "var meta = document.createElement('meta');"
    scriptContent += "meta.name='viewport';"
    scriptContent += "meta.content='width=device-width';"
    scriptContent += "document.getElementsByTagName('head')[0].appendChild(meta);"
    webView.evaluateJavaScript(scriptContent, completionHandler: nil)

To set the height of the webView:
webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
    self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: {     (height, error) in
     self.constraintWebViewProductDescriptionHeight.constant = height as! CGFloat
    })
}
})


text:
Q: Try line still fire after an exception is thrown I'm trying to trouble shoot a try/throw/catch structure between two of my php files. I have die and dump lines in to narrow down where my errors are coming from, i.e. the die(var_dump(...)) line is not normally there.
Here's my try/catch block:
public function sendWelcome(){
    try{

        $this->welcome->sendWelcomeforAllNewUsers();
        die(var_dump(["here", __FILE__ , __LINE__]));

    }catch(\Exception $exception){

        Session::flash('error', $exception->getMessage());
        return Redirect::to('main');

    }

    Session::flash('success', "Welcome emails have been sent");
    return Redirect::route('admin.importedAccounts');
}

And here's my method that could throw an exception:
protected function sendWelcomeToNewUsers(){

    if(empty($this->newUsers)){
        throw new \Exception('There are no new users to send welcome emails to.');
    }

    foreach($this->newUsers as $user){
        $this->sendWelcome($user->getLogin());
    }
}

I'm firing the block now knowing that $this->newUsers is empty (definitely evaluates as true), but I'm still hitting my die and dump line which is the next line in the try block.
I added a die and dump line to the if that throws the exception just to be sure it's firing:
    if(empty($this->newUsers)){
        die(var_dump(["here", __FILE__ , __LINE__]));
        // when I add this in and try it in the browser I definitely die here.
        throw new \Exception('There are no new users to send welcome emails to.');
    }

Is there something I'm doing wrong here? Is there something that would allow a try to still fire even if an exception has been thrown?


text:
Q: python dictionary question All,
This is the request from the template that i get
u'subjects': [u'7', u'4', u'5', u'3', u'2', u'1']

In my views how to extract the values like 7 4 5 3 2 1
How do i extract the above sequence from
new_subjects=request.POST.get('subjects')

Thanks.

A: Something like the following:
try:
    int_subjects = [int(x) for x in new_subjects]
except ValueError:
    #There was an error parsing.

A: request.POST is an instance of QueryDict which have a method named getlist that returns a list of values for the given key.
Example:
>>> new_subjects = request.POST.getlist('subjects')
>>> print new_subjects
[u'7', u'4', u'5', u'3', u'2', u'1']

See gnibbler's response for converting the list items to integers.

A: try:
    int_subjects = map(int, new_subjects)
except ValueError:
    #There was an error parsing.

Using timeit in ipython shows that map is slightly faster than the comprehension in this case
In [99]: timeit map(int,new_subjects)
100000 loops, best of 3: 7.81 µs per loop

In [100]: timeit [int(x) for x in new_subjects]
100000 loops, best of 3: 8.8 µs per loop


text:
Q: Warning initialization makes pointer form integer without a cast I am getting the warning initialization makes pointer form integer without a cast when I try to test my code using this
#include <stdio.h>
#include <string.h>
#include "List.h"
#include "List.c"
int main()
{
    int k;
    // make list
    ListP r = newlist();
    //check if empty
    k = isEmptyList(r);
    if(k=0)
    {
        printf("this list is empty");
    }
    else
    {
        printf("List not empty");
    }
    //display
    displayList(r);
    //insert
    insertItemList(r, "shuan");
    //check if empty
    k = isEmptyList(r);
    if(k=0)
    {
        printf("this list is empty");
    }
    else
    {
        printf("List not empty");
    }
    //display
    displayList(r);
    return 0;
}

The error says it in the line with the newList() call the function for the new list is
typedef struct List
{
    struct Node* head;
    int size;
}List;

typedef struct Node
{
    char *info;
    struct Node* next;
}Node;
typedef struct Node *NodeP;
typedef struct List *ListP;

//makes a list
ListP newList()
{
    List *p;
    ListP g;
    p = (List*) malloc(sizeof(List));
    if(p == NULL)
    {
        fprintf(stderr, "Memory allocation failed!\n");
        exit(1);
    };
    p->size = 0;
    p->head == NULL;
    g = p;
    return g;
};

Does this mean that the function is exiting 1 because malloc isn't allocating memory for the list and is not in the right syntax or is there another problem with the code? Any insight would be greatly appreciated.

A: Probably you should get also a warning about 'unknown' function. That means that there is a problem with function newList and compiler assumes the unknown function returns int, and continues on..
Possible reason: the function is named newList but you use
ListP r = newlist();
             ^

You should double check if proper headers are included and names are correct, and that the function is declared before it's used. Search case sensitive (grep is by default case sensitive so something like
grep -r "newlist" .  // verify
grep -r "newList" .  // again...

will work) in your project root dir for "newlist" & for "newList". You shouldn't also
#include "List.c"

but only
#include "List.h"

Then correct also comparison p->head == NULL; to assignment p->head = NULL;


text:
Q: Coverting PCM 16bit LE to WAV I'm trying to write a program in C that converts a captured Raw 16kHz PCM 16-bit file to a 16-bit WAV.
I've read some posts and people recommended using libsox. Installed it and now i'm really struggling with understanding the man-page.
So far (by reading the example in the source dist) I've figured out that the structs:

*

*sox_format_t

*sox_signalinfo_t

can probably be used to describe the data I'm inputting. I also know how much info i'm processing (time) if that is somehow necessary?
Some guidance is appreciated!

A: Well, It worked out as the question is answered. However I'll post the code here so that people can analyze it or just use it in their own projects.
The link provided by both "simonc" and "Nickolay O." was used. Search the web for more info on the individual fields.
struct wavfile
{
    char        id[4];          // should always contain "RIFF"
    int     totallength;    // total file length minus 8
    char        wavefmt[8];     // should be "WAVEfmt "
    int     format;         // 16 for PCM format
    short     pcm;            // 1 for PCM format
    short     channels;       // channels
    int     frequency;      // sampling frequency, 16000 in this case
    int     bytes_per_second;
    short     bytes_by_capture;
    short     bits_per_sample;
    char        data[4];        // should always contain "data"
    int     bytes_in_data;
};

//Writes a header to a file that has been opened (take heed that the correct flags
//must've been used. Binary mode required, then you should choose whether you want to
//append or overwrite current file
void write_wav_header(char* name, int samples, int channels){
    struct wavfile filler;
    FILE *pFile;
    strcpy(filler.id, "RIFF");
    filler.totallength = (samples * channels) + sizeof(struct wavfile) - 8; //81956
    strcpy(filler.wavefmt, "WAVEfmt ");
    filler.format = 16;
    filler.pcm = 1;
    filler.channels = channels;
    filler.frequency = 16000;
    filler.bits_per_sample = 16;
    filler.bytes_per_second = filler.channels * filler.frequency * filler.bits_per_sample/8;
    filler.bytes_by_capture = filler.channels*filler.bits_per_sample/8;
    filler.bytes_in_data = samples * filler.channels * filler.bits_per_sample/8;
    strcpy(filler.data, "data");
    pFile = fopen(name, "wb");
    fwrite(&filler, 1, sizeof(filler), pFile);
    fclose(pFile);
}

A: I would recommend to write WAV header and data manually, it is really very simple for PCM :
https://web.archive.org/web/20080706175634/https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
Update: original link https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ became invalid.


text:
Q: Animate a div from offscreen, without absolute positions? I have a scoreboard... This scoreboard is a series of inline-block divs to keep it horizontal:

0

KDZaster

Grand Finals

DarthArma

0

I have included a jsFiddle: https://jsfiddle.net/Lsxhmky7/
This page has a whole bunch of animations that I am doing with both CSS and jQuery (which are not included in the jsFiddle)... I've got all the animations working, except one.
One of the things I would like to do is so that the two score arrows on the left and right sides slide in from the edges of the screen.
I know I can do this with absolute positioning, but this grid doesn't have anything else in absolute positions, and I don't want it to be. I want it to be inline so that if widths of certain elements have to change, the page moves with it.
Is there a way I can animate the moving of these two elements from offscreen, while maintaining the inline positioning of all other blocks?

A: Fairly simple with transform: translate();
Move the arrow offscreen by default using transformX, then animate it moving back into position.
animation: slideInLeft 2s 1 forwards;
animation: [name] [length] [iterations] [end]
This runs the animation only once, for 2 seconds then stops at the end state.
.score1 {
    width: var(--score-width);
    -webkit-clip-path: polygon(
        0 0,
        0 calc(var(--main-height) / 2),
        0 var(--main-height),
        calc(var(--score-width) - var(--arrow-width)) var(--main-height),
        var(--score-width) calc(var(--main-height) / 2),
        calc(var(--score-width) - var(--arrow-width)) 0
    );
  transform: translateX(-100px);
  animation: slideInLeft 2s 1 forwards;
}

@keyframes slideInLeft {
  from { transform: translate(-100px); }
  to { transform: translateX(0); }
}

Reverse for the right arrow.

:root {
 --main-color0: rgba(000,000,000,0.5);
 --main-color1: rgba(255,000,000,0.5);
 --main-color2: rgba(000,255,255,0.5);
 --main-color3: rgba(255,255,255,0.5);

 --main-height: 50px;
 --main-gutter: -10px;
 --main-padding: 10px;
 --main-border: 4px;

 --font-family: 'Franklin Gothic';
 --font-color: #FFFFFF;
 --font-large: 24px;
 --font-small: 14px;
 --font-shadow: 1px 1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, -1px -1px 0 #000;

 --arrow-width: 15px;
 --round-width: 180px;
 --player-width: 300px;
 --score-width: 50px;

 --out-speed: 0.5s;
 --in-speed: 2s;
}

body {
 color: var(--font-color);
 font-family: var(--font-family);
 font-size: var(--font-large);
 text-shadow: var(--font-shadow);
 line-height: var(--main-height);

 margin: 10px 0;
 text-align: center;
 background-color: #ccc;
}

.slow { transition: all var(--in-speed) ease; }
.fast { transition: all var(--out-speed) linear; }
.inline { display: inline-block; vertical-align: middle; margin: 0 -7px; }
.inner { -webkit-clip-path: inset(var(--main-border) 0); }

.color0 { background-color: var(--main-color0); }
.color1 { background-color: var(--main-color1); }
.color2 { background-color: var(--main-color2); }
.color3 { background-color: var(--main-color3); }

.title {
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
 padding: 0 10px;
}

.round {
 font-size: var(--font-small);
 text-transform: uppercase;
 width: var(--round-width);
 -webkit-clip-path: polygon(
  var(--arrow-width) 0,
  0 calc(var(--main-height) / 2),
  var(--arrow-width) var(--main-height),
  calc(var(--round-width) - var(--arrow-width)) var(--main-height),
  var(--round-width) calc(var(--main-height) / 2),
  calc(var(--round-width) - var(--arrow-width)) 0
 );
}

.player1 {
 width: var(--player-width);
 -webkit-clip-path: polygon(
  0 0,
  var(--arrow-width) calc(var(--main-height) / 2),
  0 var(--main-height),
  var(--player-width) var(--main-height),
  calc(var(--player-width) - var(--arrow-width)) calc(var(--main-height) / 2),
  var(--player-width) 0
 );
}
.player2 {
 width: var(--player-width);
 -webkit-clip-path: polygon(
  0 0,
  var(--arrow-width) calc(var(--main-height) / 2),
  0 var(--main-height),
  var(--player-width) var(--main-height),
  calc(var(--player-width) - var(--arrow-width)) calc(var(--main-height) / 2),
  var(--player-width) 0
 );
}
.player1 .title { padding: 0 20px; text-align: right; }
.player2 .title { padding: 0 20px; text-align: left; }

.score1 {
 width: var(--score-width);
 -webkit-clip-path: polygon(
  0 0,
  0 calc(var(--main-height) / 2),
  0 var(--main-height),
  calc(var(--score-width) - var(--arrow-width)) var(--main-height),
  var(--score-width) calc(var(--main-height) / 2),
  calc(var(--score-width) - var(--arrow-width)) 0
 );
  transform: translateX(-100px);
  animation: slideInLeft 2s 1 forwards;
}

@keyframes slideInLeft {
  from { transform: translate(-100px); }
  to { transform: translateX(0); }
}
.score2 {
 width: var(--score-width);
 -webkit-clip-path: polygon(
  var(--arrow-width) 0,
  0 calc(var(--main-height) / 2),
  var(--arrow-width) var(--main-height),
  var(--score-width) var(--main-height),
  var(--score-width) calc(var(--main-height) / 2),
  var(--score-width) 0
 );
}

.score1 .title { padding: 0 20px 0 0; text-align: right; }
.score2 .title { padding: 0 0 0 20px; text-align: left; }

0

KDZaster

Grand Finals

DarthArma

0

A: You can do this with good ol' position: relative:
.score1 {
    position: relative;
    right: calc(var(--score-width) + var(--arrow-width));
}

Using transition/animation you can also do without jQuery.
Alternatively you can use transform: translate(...), or even better translateX(...) which triggers 3D transformations and thus the load will probably end on the GPU rather than the CPU, possibily yielding better performances.