text:
Q: How to fix This "All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes)" I am creating an app that uses firebase authentication for login and registration but I keep getting sudden crashes as soon as I run the application. I'm getting a warning in my Gradle.build file at the app level. The warning says

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:support-media-compat:26.1.0

I've tried changing com.android.support:appcompat-v7:28.0.0 to v7:26.0.1 and 27.1.0 but none of them solved the problem.
My build.gradle file is as follows:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.project.tck.rescueme_responder"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.google.firebase:firebase-auth:16.1.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
}
apply plugin: 'com.google.gms.google-services'

I expect a login that authenticates using FireBase when I run the application but then the application crashes each time I run it.

A: There is a similar question here
I guess the problem is in the transitive dependencies of the direct dependencies you use since I don't see them explicitly referenced in your build.gradle file. Some of them use one version (28.0.0) while some another (26.1.10).
The above referenced answer provides some workarounds. Furthermore, depending on the Gradle version you use (if it is >=4.6), you may be able to add constraints for those transitive dependencies in your build.gradle file to be sure they use the version you want.


text:
Q: Calculations between nested forms, Gravity Forms I'm using Gravity Forms & Nested Forms.
I'd like to add numbers up between child entries but unsure on how to enable the merge tags on the parent form so I can do Calculations based on the Numbers entered in the child forms.
My Parent Form
I'd like to calculate a Total Chargeable Time as seen in the screenshot.

A: The merge tags must be manually entered on in the formula setting a calculation-enabled Number or Product field on the parent form. It sounds like you're looking for the :count modifier (i.e. {Nested Form:1:count}).
Full documentation here:
https://gravitywiz.com/documentation/gravity-forms-nested-forms/
Support here:
http://gravitywiz.com/support/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Specifics of List Membership How does Python (2.6.4, specifically) determine list membership in general?  I've run some tests to see what it does:
def main():
    obj = fancy_obj(arg='C:\\')
    needle = (50, obj)
    haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle]

    print (1, fancy_obj(arg='C:\\'),) in haystack
    print needle in haystack

if __name__ == '__main__':
    main()

Which yields:
False
True

This tells me that Python is probably checking the object references, which makes sense.  Is there something more definitive I can look at?

A: From (An Unofficial) Python Reference Wiki:
For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.
So in your example, if the fancy_obj class stored the value of arg in an instance variable and were to implement an __eq__ method that returned True if the two fancy_objs being compared had the same value for arg then (1, fancy_obj(arg='C:\\'),) in haystack would be True.
The relevant page of the Standard Library reference is: Built-in Types, specifically 5.6 Sequence Types

A: Here is code from the Python SVN:
static int
list_contains(PyListObject *a, PyObject *el)
{
    Py_ssize_t i;
    int cmp;

    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
        cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
                                           Py_EQ);
    return cmp;
}

so basically it uses the == with the object and each object in the list.

A: Python is using the (equivalent of) the == operator.  If the fancy_obj class does not define __eq__ (or the crufty old __cmp__, still supported for backwards compatibility) then equality, ==, "falls back" to identity, is, and that appears to be what's happening here.
The relevant docs are here, and I quote:
x in s    True if an item of s is equal to x, else False
and "equal to" means == is true.


text:
Q: Dividir texto em partes Preciso pegar um pedaço específico de um aquivo .txt que esteja entre <tag> e </tag>.
Porém preciso pegar todas as linhas onde isso acontece.
Exemplo:
<tag1>titulo</tag1>
<tag2>subtitulo</tag2>

texto...

<tag2>subtitulo</tag2>
texto...

<tag1>titulo</tag1>
<tag2>subtitulo</tag2>
texto...

Eu quero pegar o texto entre essas tags e salvar.

A: Tente esse código:
var pattern = /<tag.*?>(.*?)<\/tag.*?>/g; //Padrão que a regex vai dar Match
var reader = new FileReader(); //Leitor do arquivo txt
var output = ""; //Variável de texto onde será carregado o conteúdo do txt
reader.onload = function (e) {  //Função para leitura após o carregamento do reader
            output = e.target.result;
            displayContents(output);
        }; //Fim da função
        reader.readAsText(filePath.files[0]); //insira o path para seu txt
var m;

do {
    m = pattern.exec(output); //executa o padrão da regex e armazena os val em m
    if (m) {
        console.log(m[1]); //mostra o resultado no console do browser
    }
} while (m);

Explicação do código:

*

*A função a seguir carrega o arquivo txt através de um FileReader

*Passa seu conteúdo para a variável output.

*Imprime o conteúdo que deu match na regex no console do browser.
Explicação da regex:
/<tag.*?>(.*?)<\/tag.*?>/g;

*

*<tag Encontra a sequencia exatamente igual a <tag

*.*?> Prossegue (sem capturar) por todos os caracteres até a primeira ocorrência do >.

*(.*?)<\/tag Captura todo o conteúdo no grupo de captura 1 até a primeira ocorrência de </tag

*.*?> Prossegue (sem capturar) por todos os caracteres até a primeira ocorrência do >.

*/g É um modificador da regex, indica que deve continuar tentando dar match até o fim da sequencia de texto.


text:
Q: limit access to unc server to the program I am connecting to an unc server (\blablub\share) from my program (written in c++). Right now i am using WNetUseConnection Function to connect to the server. Now i want to limit the access only to the program. Because right now it is possible to access the unc server using the explorer after the connection has been established. But i want to limit the access (especially for file write operations) only to the program.  How do i do that?

A: Use WNetAddConnection3 and leave NETRESOURCE::lpLocalName 0. This does the heavy work of WNetUseConnection but doesn't add a drive letter. Therefore, you'll still need to use \\Server\Share\File names in your program.
Don't forget to WNetCancelConnection2 when your program exits. Of course, while your program runs, the connection exists. That's intentional. Security works at user level, not program level. If you really, really don't want this, you'll have to impersonate the user account you use in WNetAddConnection3.


text:
Q: Swap multiple value columns of dataframe in spark I need to swap the value of multiple columns based in a condition of one of them and using the API instead sparkQL
I have a DataFrame with columns [A,B,C,X,Y,Z] and it has rows with this pattern:

(1,2,3,null,null,null),
  (3,3,3,null,null,null),
  (null,null,null,5,3,2),
  (3,1,1,null,null,null),
  (null,null,null,3,4,1)

I would like to achieve swapping the values between the groups of columns (a,b,c) and (x,y,z) when any row has the condition that the value in column A is null. So after the execution, the table should only have values in the columns [A,B,C]. I have tried to do something like
val result = df.withColumn("A", when(col("A").isNull, col("X")).withColumn("X", when(col("A").isNull,lit(null)).withColumn("B", when(col("A").isNull, col("Y")).withColumn("Y", when(col("A").isNull,lit(null)).withColumn("C", when(col("A").isNull, col("Z")).withColumn("Z", when(col("A").isNull,lit(null)).

Surprisingly executing only this:

val result = df.withColumn("A", when(col("A").isNull, col("X")).withColumn("X", when(col("A").isNull,lit(null))

I got the expected result for the the column swapping I defined with that line "(5,null,null,null,3,2)". But when I add the operations "withColumn" for the other 2 columns I ended up with rows like this "(5,null,null,null,3,2)"
Any help would be appreciated.

A: After you swap "A" and "X", "A" is not null any more. Therefore, the subsequent operations don't work.
I strongly suggest that you use a flag column to help achieve this.
val result = df
.withColumn("flag", when(col("A").isNull, true).otherwise(false)
.withColumn("A", when(col("flag") === true, col("X"))
.withColumn("X", when(col("flag") === true, lit(null))
.withColumn("B", when(col("flag") === true, col("Y"))
.withColumn("Y", when(col("flag") === true, lit(null))
.withColumn("C", when(col("flag") === true, col("Z"))
.withColumn("Z", when(col("flag") === true, lit(null)).


text:
Q: How to Create Custom Stored Procedures Using Code First Fluent API There are many articles that show how to create Insert, Update, Delete procedures using Code First like this one.
How about custom procedure like this simple select statement:
Select * from Customers

I could make changes to the Up and Down Migration methods, but is there a way to create custom procs using Fluent API directly.

A: Here is a solution which I don't recommand but If you want to use DbContext.Database, here it is:
using(var db = new MyDbContext(connectionString))
{
    db.Database.ExecuteSqlCommand("CREATE PROCEDURE MyProcedure ... END;");

    var command = "EXEC MyProcedure;";
    IEnumerable<Customer> customers = db.Database.SqlQuery<Customer>(command, null);
}


text:
Q: Google Script can't find file for one user but can for owner I have an app script which should pull a file from a shared folder in google drive. It has worked in the past but recently stopped working after no changes. The code runs fine when I execute it, however when another user runs the program it errors.
the error given is TypeError: Cannot read property 'hasNext' of undefined
To pull the file I am using
var file;
[other code]
file=DriveApp.getFilesByName("file.pdf")
if(file.hasNext()){
    var attachment=file.next()
}

A: Google recently changed security policies which changed ownership of files. Simply reopening the files fixed the problem


text:
Q: How to set a custom widget size/position to it's parent layout in kivy? I am trying to add a custom widget to a GridLayout, but the size and position don't dynamically scale to fit the parent layout. My goal is to add one of these CustomWidgets to the GridLayout by pressing a button. I am able to achieve the results I want if I copy+paste the contents of my .kv files' <CustomWidgets> class directly into the .kv GridLayout (left image), but this sidesteps the purpose of the button.
I've linked an image to help clarify my expected vs actual outcome. The left image shows my desired result of pressing the "Add Activity" button three times. The right image shows the actual outcome when I try adding a custom widget by pressing the "Add Activity" button three times.

My guess is this problem can be solved if the 'size_hint_x: self.x' is set after adding it to the GridLayout. I've tried to set the CustomWidget 'size_hint_x' to fit the parent layout within the .kv GridLayout by setting it after building
    CustomWidgets:
        size_hint_x: self.x

with no luck. I am able to set a number value as the width of the CustomWidget but then it doesn't dynamically change to fit the size of the window.
DemoApp.py
class CustomGridLayout(GridLayout):

    def add_list_item(self):
        print("add list item - CustomGridLayout")
        self.ids['list_layout'].add_widget(CustomWidgets())
    pass

class CustomWidgets(Widget):
    pass

class DemoApp(App):
    def build(self):
        underlying_layout = CustomGridLayout()
        return underlying_layout

if __name__ == "__main__":
    DemoApp().run()

demo.kv
<CustomGridLayout>:
    id: underlying_layout
    orientation: 'vertical'
    cols: 1
    row: 2

    ScrollView:
        GridLayout: #<- This is the GridLayout I want to add custom widgets to
            id: list_layout
            cols: 1
            height: self.minimum_height
            row_default_height: 60
            size_hint_y: None
            Label:
                height: 20
                text: 'List:'

    AnchorLayout:
        size_hint_y: .4
        Button:
            text: 'Add List Item'
            on_press: root.add_list_item()

<CustomWidgets>
    StackLayout:
        cols: 3
        rows: 1
        orientation: 'lr-tb'
        #size_hint: self.x , None   #<-- Is there a size_hint I can provide that will adjust size once widget is added?
        height: 80
        Button:
            size_hint: .25, None
        TextInput:
            size_hint: .5, None
        Button:
            size_hint: .25, None

A: I think it will work better if you have your CustomWigets extend StackLayout instead of containing a StackLayout, like this:
class CustomWidgets(StackLayout):
    pass

Then, in your kv file:
<CustomWidgets>
    orientation: 'lr-tb'
    size_hint: 1.0 , None   #<-- Is there a size_hint I can provide that will adjust size once widget is added?
    height: 80
    Button:
        size_hint: .25, None
    TextInput:
        size_hint: .5, None
    Button:
        size_hint: .25, None

the size_hint: 1.0 , None will keep the CustomWidgets width equal to its parents width.
When your CustomWidgets extended Widget and contained a StackLayout, then the size_hint of the contained StackLayout indicates a fraction of its parent, which was the CustomWidgets itself. And the Widget class ignores size_hint, only Layout classes and Window use it.


text:
Q: multiple MX pointing to the same server I need help for a mail server configuration.
I would like to know if it's possible to have multiple MX with different pub IP, pointing to the same local server.
this is because in my environment exist 2 gateway (multiple services providers), a watchguard t30 (local 10.0.0.254) that manage 12.12.12.5 and a watchguard t35 (local 10.0.0.253) that manage 12.12.12.6, for failover purpose. they share the same isp router has the 12.12.12.0/28.
watchguard t35 - loc 10.0.0.254 - pub 12.12.12.5
watchguard t30 - loc 10.0.0.253 - pub 12.12.12.6
zone mycompany.com:
mycompany.com. MX 5 mail.mycompany.com
mycompany.com. MX 15 samemail.mycompany.com
mycompany.com. TXT "v=sfp1 a mx ip4:12.12.12.5 ip4:12.12.12.6 ~all"
mail.mycompany.com. A 12.12.12.5
samemail.mycompany.com A 12.12.12.6

zone 12.12.12.in-addr.apra:
5.12.12.12.in-addr.arpa. PTR mail.mycompany.com.
6.12.12.12.in-addr.arpa. PTR samemail.mycompany.com.

on firewall1: nat 12.12.12.5 - 10.0.0.1 commons mail ports
on firewall2: nat 12.12.12.6 - 10.0.0.1 commons mail ports
MAILSERVER nic config
ip: 10.0.0.1
subnet mask: 255.0.0.0
gw 10.0.0.254 metric 2
gw 10.0.0.253 metric 50

In this way when the first gateway goes down, all the request start comes (and goes out) from 10.0.0.253 (12.12.12.6) on common ports (25..443..) instead of the gateway with metric 2.
or maybe I could assign another NIC to the mail server and change all rules on firewalls, and then works with INTERFACE metrics, like in the example:
MAILSERVER NIC1
10.0.0.1
255.0.0.0
10.0.0.254
nic metric 2

NIC2
10.0.0.2
255.0.0.0
10.0.0.253
nic metric 50

I would like to know if there is any contraindication in using this method, or if there are alternatives..
other infos, the mailserver is Mdaemon.
every help is appreciable!
edit:
If I use the configuration with two gateways and different metrics, my server will always use the one with the lowest metric 10.0.0.254 (12.12.12.5) until it finds it online. Unless I set some particular route, the server will not be able to use the secondary 10.0.0.253 (12.12.12.6), not even port 25 and the other common ports will listen. I did a test, I launched a continuous query on port 25 on 12.12.12.5 and on 12.12.12.6, in the meantime of this test I turned off the firewall 10.0.0.254 (12.12.12.5), the server has therefore stopped listening on it, and began to listen on the secondary firewall in metric. are there scenarios where my server could start communication not using the 10.0.0.254 when it is online?
test fw1 down

A: Hi this configuration will not do what you suppose it would to do :-(. Mainly the DNS records would be for the domain (the most probably you have this correct but for the readers to have it visible correctly)...
zone mycompany.com:
mycompany.com. MX 5 mail.mycompany.com
mycompany.com. MX 15 samemail.mycompany.com
mycompany.com. TXT "v=sfp1 a mx ip4:12.12.12.5 ip4:12.12.12.6 ~all"
mail.mycompany.com. A 12.12.12.5
samemail.mycompany.com A 12.12.12.6

zone 12.12.12.in-addr.apra:
5.12.12.12.in-addr.arpa. PTR mail.mycompany.com.
6.12.12.12.in-addr.arpa. PTR samemail.mycompany.com.

From the DNS point of view it is correct but the issue may be the routing on server side. Based on the network setting you have post, it is not behave internally as two independent network connection on server side but all the time it is preferred to use 10.0.0.254 / 12.12.12.5 even in case the communication has been started using 10.0.0.253 / 12.12.12.6 (for any reason). In some cases it may work but in other cases it will not work (like in case other side has utilized e.g. Cisco ASA - at that moment it will not be recognized as related communication and it will be terminated).
To have it working it would be better to utilize some HA options on gateway side and - e.g. Virtual IP, Stand-by gateway,... And on dns side to use one MX record. As it is "ending" on the same router of ISP it would not be an issue. The mail server would have at that moment also just one interface.
In case you would insist on two interfaces on mail server it may be possible but you need to make sure that the response will follow the same gateway which would be used to established the connection. The easiest way would be sNAT on gateway / firewall but in case of mail server it is not good idea as you are loosing the track of source IP (e.g. spam check based on source IP) so some other (more complicated approach would be selected).


text:
Q: Nodejs- Manipulating properties while destructuring I am looking for a smart way to manipulate data while I'm destructuring an object.
Take a look on the following code:
let employee =  {
   name: 'John Doe',
   birthday: '1980/01/01', // yyyy/MM/dd format
   department: 'R&D'
}

const { name, birthday, department } = employee

console.log(`${name} is working under ${department} and their birthday is on ${birthday}.`)

Let's say I want to adjust this to show their age instead of their birthday, I have a method that calculates how old they are, which is called calcAge.
I'm expecting the code to revolve around this (or equivalent to):
let employee =  {
   name: 'John Doe',
   birthday: '1980/01/01', // yyyy/MM/dd format
   department: 'R&D'
}

// Option 1: Current state:
const { name, birthday , department } = employee
const age = calcAge(birthday)

// Option 2: Required state:
// const { name, age: calcAge(birthday), department } = employee
// Note this:    ^^^^^^^^^^^^^^^^^^^^^^

console.log(`${name} is working under ${department} and they are ${age} years old.`)

Hope this makes sense, if you have any questions please feel free to ask.

A: Unfortunately, it's not possible to manipulate the data while you are destructuring an object. The only purpose of the assignment destructuring is to be able to assign values and not manipulate them.
Also, manipulate data during the assignment destructuring could lead to confusion and hard readability.


text:
Q: Difficult integral with trigonometric substitution: $\int\frac{\sqrt{1-x}}{\sqrt x}dx$ This is the integral I am talking about
$$\int\frac{\sqrt{1-x}}{\sqrt x}dx$$
As you can tell I tried substitution $u = \sqrt x$, and from there I went to $u = \sin{\theta}$ like here.

$$\newcommand{\dd}{\; \mathrm{d}}
\int \frac{\sqrt{1-x}}{\sqrt x} \dd x=
\begin{vmatrix} u=\sqrt x \\ \dd u = \frac1{2\sqrt x}\end{vmatrix} =
2\int \sqrt{1-u^2} \dd u =
\begin{vmatrix} u=\sin\theta \\ \theta = \arcsin u \\ \dd u = \cos\theta \dd\theta \end{vmatrix} =
2\int \sqrt{1-\sin^2\theta} \cos\theta \dd\theta =
2\int \cos^2\theta \dd\theta=
2\int \frac{1+\cos2\theta}2 \dd\theta =
\int \dd\theta + \int\cos2\theta \dd\theta =
\theta + \frac12 \sin2\theta + C =
\arcsin u +  \frac12 \sin(2\arcsin u) + C =
\arcsin \sqrt x +  \frac12 \sin(2\arcsin \sqrt x) + C
$$

Anyways, you can see I entered this answer and was wrong and I have no idea why. I even tried to go back and substitute in cosine instead of sine since in this case they were equivalent and I still got the answer wrong, any help is appreciated thank you!

A: Consdering, just as you apparently did, $$I=\int \frac{\sqrt{1-x}}{\sqrt{x}}\,dx$$ First $$x=u^2\implies dx=2u\,du\implies I=2\int \sqrt{1-u^2}\,du$$ Second $$u=\sin(t)\implies du=\cos(t)\,dt \implies I=2\int \cos^2(t) dt=\int (1+\cos(2t))\,dt$$ $$I=t+\frac{1}{2} \sin (2 t)+C$$ Now, back to $x$ $$t=\sin^{-1}(u)=\sin^{-1}(\sqrt x) \implies I=\sin ^{-1}(\sqrt x)+\frac 12\sin ^{-1}\left(2\sin ^{-1}(\sqrt x)\right)+C$$ which could simplify to $$I=\sqrt{(1-x) x}+\sin ^{-1}\left(\sqrt{x}\right)+C$$

A: $$
I:=\int \frac{\sqrt{1-x}}{\sqrt{x}} d x
$$
Since $0 <x<1$, therefore let $x=\sin ^{2}\theta$, then  $d x=2 \sin \theta \cos \theta d\theta.$
$$\begin{aligned}
I &=\int \frac{\sqrt{\cos ^{2} \theta}}{\sqrt{\sin ^{2} \theta}} \cdot 2 \sin \theta \cos \theta d \theta =\int 2 \cos ^{2} \theta d\theta =\int(1+\cos 2 \theta) d \theta \\&=\theta+\frac{\sin 2 \theta}{2}+C=\theta+\sin \theta \cos \theta +C =\boxed{\sin ^{-1} \sqrt{x}+\sqrt{x(1-x)}+C}\end{aligned}
$$


text:
Q: android - google play services 7.3.0 causes crash I was using google play services 6.5.87 until now but I wanted to use Android place picker in my app. This requires play services version 7.0.0 and above.
I changed google play services version to 7.3.0(latest, tried 7.0.0 as well), but this started causing crash on kit kat and below devices. Following are the errors that came up:

*

*The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

*NoClassDefFoundError

*java.lang.VerfiyError

I tried googling for solution. Someone suggested changing jdk from 1.8 to 1.7(tried but didn't work). But when we change play services version from 7.x.x to 6.5.87 everything works just fine.
Somewhere I read that wear doesn't support 7.3.0 so that could be the reason. I tried specifying screen sizes, and that didn't help.
Any lead will be of immense help.

A: I think I have found the root cause for it, in your build.gradle(app) file

*

*inside defaultConfig, set multiDexEnabled flag to true (MultiDex)

*Put compile dependency compile 'com.android.support:multidex:1.0.0' under dependencies

Now, in your Application class, add this
@Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
This works.


text:
Q: How to slice some part of Google Map and show the sliced one in a div? I want to slice some part of Google Map and want to show it in a div. How can I do that? Is there any google apis?
I don't have any code but below example shows my requirement.

From the above map I want to slice below red color part and I want to put it in separate div.

Is it possible? If it is, then how can I do that? Any APIs?

A: To the best of my understanding, Google maps does not separate regions into layers. One solution I can think of is using Open Street Maps to export your desired region into an SVG and using illustrator to remove the unnecessary content.


text:
Q: Get Current Fragment for Back button Event in FragmentTagManger I use a FragmentTagManager and now I want to access the currently active Fragment and call a method when the Back button is pressed.
The Fragment that I want to get is a container. Because I am changing Fragments dynamically inside the tabs I need to access the container and call a method from its superclass and cant just pop() from the FragmentStack directly.
How can I access the current Fragment that is displayed in a Tab?
Right now I have this
Main.java
    private FragmentTabHost mTabHost;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

        mTabHost.addTab(
                mTabHost.newTabSpec(TAB_1).setIndicator(getString(R.string.music), null),
                MusicListContainerFragment.class, null);
        mTabHost.addTab(
                mTabHost.newTabSpec(TAB_2).setIndicator(getString(R.string.devices), null),
                DeviceChooserFragment.class, null);
        mTabHost.addTab(
                mTabHost.newTabSpec(TAB_3).setIndicator(getString(R.string.musicplayer), null),
                MusicPlayerFragment.class, null);
}
    @Override
    public void onBackPressed() {
        System.out.println(mTabHost.getCurrentTab());
        if(mTabHost.getCurrentTab() == 0){
            System.out.println(getFragmentManager().findFragmentByTag(TAB_1));//NULL
            System.out.println(getFragmentManager().findFragmentById(R.id.container));// NULL

        }
    }

Basecontainer.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout>

ContainerFragment
public class MusicListContainerFragment extends BaseContainerFragment {
    private boolean mIsViewInited;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.base_container, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsViewInited) {
            mIsViewInited = true;
            initView();
        }
    }

    private void initView() {
        replaceFragment(new MusicListFragment(), false);
    }
}

A: I hope you found a solution in the meanwhile since your question was posted 3 months ago. Nevertheless I was facing the same problem and came up with this solution.
If you want to override the <- Button in the Actionbar use
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // this takes the user 'back', as if they pressed the left-facing triangle icon on the main android toolbar.
            // if this doesn't work as desired, another possibility is to call `finish()` here.
            if (getFragmentManager().findFragmentById(R.id.activity_profile) instanceof FragmentOfYourChoice) {
                onBackPressed();
                return true;
            }
            else
                super.onOptionsItemSelected(item);

        default:
            return super.onOptionsItemSelected(item);
    }
}

I assume that if you get to the point where is no Fragment in your Backstack you want to trigger the activity pop off your backstack. This is what triggers the "else" branch.
If you want to get the same effect on pressing the actual "Back-Button" (Triangle) you have to override the onBackPressed() method like that.
@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 1)
        getFragmentManager().popBackStack();
    else
        super.onBackPressed();
}

A: Maybe you can use OnBackStackChangedListener to know when there is a fragment stack change, regardless of the method that sets/unsets the fragment stack, as shown:
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            //TODO: Handle your stacks changes here
            Log.d(Constants.TAG,"Stack Entry Count: "+getSupportFragmentManager().getBackStackEntryCount());
        }
    });

Regards.-


text:
Q: Angular2, how i can pass attributes from parent to child I have a custom component "SuperField"

    <input name="super" />
    <input name="field" />

is called so:
<super-component [disabled]="true" [superDirective]="control"></super-component>

and i want to pass custom & default attribute directives from parent to child without explicit define them and this directives should be removed from the host (in the DOM):

    <input name="super" [disabled]="true" [superDirective]="control" />
    <input name="field" [disabled]="true" [superDirective]="control" />

so i can pass every ng2 attribute directive without define them in the ts-file, like:
@Input() disabled: boolean;
@Input() superDirective: any;

Can i do this? And if yes, how?

A: I am not able to figure out that why you want to do this against Angular's basic feature to keep components independent. By doing this it would be tightly coupled.
Defile a service and keep value objects for your both the directives. Set both of these in parent class and later access it from the child class.
valObjCls
{
disabled:boolean;
superDirective:any;
}

ParentClass{

constructor(VO:valObjCls){}
VO.disabled = false;
VO.superDirective = 'parentControl';
}

ChildClass{
constructor(VO:valObjCls)
console.log(VO.disabled);
console.log(VO.superDirective);
}


text:
Q: one to many and many to many in Typeorm I have project with typeorm and express.In this project i have user and tweet.
I have problem, why i create a new tweet, in user automatic add new userId.
My relation:
Tweet:
``
// create tweet
export const store = async (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<any> => {
  try {
    const { tweet, userId } = req.body;
    const { userName } = req.body;
    const user = await User.create({ userName }).save();
    const tweets = await Tweet.create({
      tweet,
      userId: user.id,
    }).save();
    return res.status(201).json({
      message: "created tweet succesfully",
      data: [tweets],
    });
  } catch (error) {
    next(error);
  }
};

// get all tweet
export const index = async (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<any> => {
  try {
    const tweet = await Tweet.find({ relations: ["user"] });
    return res.status(200).json({
      message: "get tweet succesfully",
      data: tweet,
    });
  } catch (error) {
    next(error);
  }
};

User:
``   // create user
export const store = async (
req: Request,
res: Response,
next: NextFunction
): Promise => {
try {
const { userName } = req.body;
const user = await User.create({
userName,
});
await user.save();
return res.status(201).json({
message: "created user succesfully",
data: [user],
});
} catch (error) {
next(error);
}
};
// get all data
export const index = async (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<any> => {
  try {
    const user = await User.find({ relations: ["tweets"] });

    return res.status(200).json({
      message: "get user succesfully",
      data: user,
    });
  } catch (error) {
    next(error);
  }
};


text:
Q: SQL LISTADO EMPLEADOS Obtener utilizando una consulta SQL el listado de departamentos que tienen 2 o mas empleados. Indicar el nombre del departamento (campo nom_depart) y la cantidad de empleados, ordenado por el nombre del departamento de forma ascendente.
Tablas:

*

*APPX_employee (id,department_id)

*APPX_department (id, nom_depart)

Tengo esto pero pues como se muestra en la imagen no es lo que se solicita:
select dept.nom_depart,
       cant.department_id
from APPX_department as dept
inner join APPX_employee as cant where (dept.id=1
AND cant.department_id=2) OR (dept.id=2 AND cant.department_id=2)
group by dept.nom_depart

LA SALIDA ESPERADA ES:

A: select d.nomDpto, count(e.idDpto) as TotalEmp
from departamentos d
inner join empleados e
on d.id = e.idDpto
group by d.nomDpto
having count(e.idDpto) >= 2
order by d.nomDpto

Se usa la clausula inner join para relacionar las dos tablas por un campo en común, posteriormente se emplea la cláusula group by para agrupar los registros por el campo nomDpto de la tabla departamentos y entonces vendría la cláusula having que se usa para filtrar los agrupamientos que se hacen con la clausula group by, después vendría el ordenamiento por el campo deseado y por último vendría la proyección de los campos a través de la cláusula select mostrando el nombre del departamento y usando la función de agregación count para contar todos los campos idDpto de la tabla empleados que tienen el mismo idDpto.
Nota: Yo pongo nombres genéricos a los campos y tablas quizá tus nombres sean diferentes a los que uso.

A: Te comento:
Dado el contexto de la pregunta, la consulta podría quedar de esta forma:
SELECT APPX_department.nom_depart, COUNT(APPX_employee.department_id) AS Total
FROM APPX_department
INNER JOIN APPX_employee ON APPX_department.id = APPX_employee.department_id
GROUP BY APPX_department.nom_depart
HAVING Total >= 2;

Te comento que:

*

*No debes colocar en el SELECT la columna de la llave foránea, dado que según lo que expones ese valor no es el esperado, si no un conteo de las veces que esta aparece como referencia de un empleado asignado a un X departamento, lo que si puedes hacer es usar una función de agregación tal como COUNT y pasarle la FK

*Posterior dado que necesitas el conteo de empleados por departamento deberás agrupar, de otro modo todo se reducirá a una sola fila.


text:
Q: Getting problems while changing the name of a long table in latex While trying to rename a long table from 'Table 11' (automatically assigned by latex) to 'Table A.5' I got problems while using \renewcommand{\thetable}{A.5}. The problem is that the caption text is out of bound and Latex reports the error " Misplaced not align" and "Misplaced omit".
While hoping to sufficiently clearly explain the problem, Could You please help me to solve this issue?
Thanks in advance.
I report a screenshot of my code to help You understand the problem. Note that of course at the end of the long table I coded: "end{\longtable}.

A: Next time please help us to help you by providing a MWE in text form not as screenshot so that we can copy the code and try our answer.
This looks like a xy problem to me.
Could it be that you are actually trying to reset the table counter every time another counter is incremented and use both counters to reference the table?
If so the newfloat package can help you.
In the following example the table counter is reset at the end of each section and both the section counter and table counter are printed by \caption.
Please note that I have redefined \thesection instead of \thetable to match the format requested while avoiding an inconsistency between using sometimes numbers and sometimes letters for the same counter.
\documentclass{article}
\usepackage{longtable}
\usepackage[within=section]{newfloat}
% see https://en.wikibooks.org/wiki/LaTeX/Counters#Counter_style
\renewcommand{\thesection}{\Alph{section}}

\begin{document}
    \section{Abcdef}
    \begin{longtable}{ll}
        \caption{Abc}
    \end{longtable}
    \begin{longtable}{ll}
        \caption{Def}
    \end{longtable}

    \section{Ghijkl}
    \begin{longtable}{ll}
        \caption{Ghi}
    \end{longtable}
    \begin{longtable}{ll}
        \caption{Jkl}
    \end{longtable}
\end{document}

As a side note I would recommend taking a look at the booktabs package documentation which gives a few recommendations on how to format tables.

To answer the question that you have asked:
The problem is that \renewcommand inserts unexpandable tokens before \caption.
If you really want to change the numbering of a single table only (which I would discourage without knowing the context) redefine \thetable before the table and keep the definition local with an explicit \begingroup ...\endgroup:
\documentclass{article}
\usepackage{longtable}

\begin{document}
    \begingroup
    \renewcommand{\thetable}{A.5}
    \begin{longtable}{ll}
        \caption{Abc}
    \end{longtable}
    \endgroup

    \begin{longtable}{ll}
        \caption{Def}
    \end{longtable}
\end{document}


text:
Q: Как перебрать массив объектов и суммировать значения? Есть arrayOfSizez массив объектов следующего вида:

[{height: 12312, offset: 21}, {height: 12312, offset: 21}, {height: 12312, offset: 21}.....]

Мне нужно суммировать все height и offset отдельно. Как это сделать?
Следующий вопрос:
цикл этого вида:

for (let i = 1; i < arrayOfSizes.length; i++) {
          if (arrayOfSizes[i].offset < arrayOfSizes[i - 1].offset) {
            offset += arrayOfSizes[i].offset;
          }
        }

Нужно переписать через reducer, примерно такого вида:

const offset = arrayOfSizes.reduce(
          (prev: any, val: any, i: any, arr: any) =>
            val.offset < arr[i].offset ? prev + val.offset : prev,
          0,
        );

Пока что то не так, помогите пожалуйста

A: Не совсем понятно в каком виде Вам его нужно вернуть. Например так собрать все суммы в один объект.
const result = arrayOfSizez.reduce((acc, el) => {
   acc.height += el.height;
   acc.offset += el.offset;
   return acc;
})

console.log(result);

Если нужно сохранить нетронутым исходный массив можно сделать так:
const result = arrayOfSizez.reduce((acc, el) => {
   acc.height = acc.height ? acc.height+el.height : el.height;
   acc.offset = acc.offset ? acc.offset+el.offset : el.offset;
   return acc;
}, {})

Или так:
const result = JSON.parse(JSON.stringify(arrayOfSizez)).reduce((acc, el) => {
   acc.height += el.height;
   acc.offset += el.offset;
   return acc;
})

A: Думаю данное решение будет оптимальным:

const values = [
  { height: 12312, offset: 21 },
  { height: 12312, offset: 21 },
  { height: 12312, offset: 21 },
];

const getHeightAndOffsetSums = (items) => items
  .reduce((acc, { height, offset }) => {
    acc.heightSum += height;
    acc.offsetSum += offset;

    return acc;
  }, { heightSum: 0, offsetSum: 0 });

console.log(getHeightAndOffsetSums(values));


text:
Q: Deserialize mongo document property which implements Inteface base on condition I'm using Mongo database with C# driver in my ASP.Net Core application.
For now I'm having a document User :

public class User
{
    public Guid Id{get;set;}

    public int Role {get;set;}

    public IVendor Vendor {get;set;}
}

My Vendor in User class can be FoodVendor or FoodDeliveryVendor which implements the same IVendor interface and deserialized base on User role.
I have tried searching for interface deserialization in Mongo database, the only solutions I can find were about deserializing interface to a specific class which implements it.
Any solutions about deserializing interface property to specifc class base on specific conditions ?
Thank you.


text:
Q: Wrong setting value in constructor using interfaces I get json which I need to parse to object with GSON:
"product":{
"product_type":"assignment",
"id":717,
    "product_profile":{
    "title":"new Order from java",
    "info":"Some special info",
    "dtl_expl":true,
    "special_info":""
    }
}

"product_profile" will be different object depend on what I get in "product_type". I created classes for each of that objects - Assignment and Writing. They are child of ProductType class. I implement interface in Product class which should return right object - Assignment or Writing depend on what value is in "product_type". My Product class
public class Product implements IProductType{
    ProductAssignment prodAss;
    ProductWriting prodWr;
    ProductType returnState;

    @SerializedName("id")
    int id;
    @SerializedName("product_type")
    String product_type;
    @SerializedName("product_profile")
    ProductType product_profile;
    public Product()
    {

    }
    public Product(int id, String product_type, ProductType product_profile)
    {
        this.id = id;
        this.product_type = product_type;
        this.product_profile = product_profile;
    }
    public int getProductId()
    {
         return this.id;
    }
    public String getProductType()
    {
         return this.product_type;
    }
    public ProductType getProduct()
    {
         return this.returnObject(product_type);
    }
    public void setProductId(int id)
    {
        this.id = id;
    }
    public void setProductTitle(String product_type)
    {
        this.product_type = product_type;
    }
    public void setProduct(ProductType product_profile)
    {
        this.product_profile =  this.returnObject(product_type);
    }
    @Override
    public String toString() {
        return "id=" + id + " " + "title=" + product_type
                + " " + "profile=" + product_profile  +  "}";
    }
    @Override
    public ProductType returnObject(String res)
    {

        System.out.println("Product");
        System.out.println(product_profile);
        if (res.equals("assignment"))
        {
            this.product_profile = new ProductAssignment();
            System.out.println("I'm going to parse Assignment");
        }
        else if  (res.equals("writing"))
            this.product_profile =  new ProductWriting();

        return product_profile;

    }

}

But when I try to parse json to object like this:
  Gson gson = new Gson();
  Product product = gson.fromJson(res,Product.class);

I get such a product object:
id=447 title=assignment profile=ProductType@e49f9fa

so "id" and "product_type" parse correctly, but it is not Assignment object in ProdutType.
My ProductType class:
   public class ProductType implements IProductType{
    String product;

    static ProductType productType;
    static ProductAssignment productAssignment;
    static ProductWriting productWriting;
    IProductType component;

    ProductType returnState;
    ProductAssignment prodAss;
    ProductWriting prodWr;
    public ProductType()
    {
    }
    public ProductType(IProductType c)
    {
         component = c;
    }
    public ProductType getProductType()
    {
        return this.returnState;
    }
    public void setProductType(ProductType returnState)
    {
        this.returnState = returnState;
    }
    @Override
    public ProductType returnObject(String product_type)
    {
        if (product_type.equals("assignment"))
        {
            this.returnState = new ProductAssignment();
            System.out.println("I'm going to parse Assignment");
        }
        else if  (product_type.equals("writing"))
            this.returnState =  new ProductWriting();

        return returnState;
    }
    @Override
    public String toString()
    {
        return returnState.getClass().getName();
    }

}

A: Looks fine. To get correct output you need to override toString() in the ProductType class.


text:
Q: How do I distract the receptionist in Tidy Park? While investigating Jerome's disappearance in the Tidy Park clubhouse, Lara asks you to distract the manor's receptionist so you can grab a laundry token out of her cash register.
I've tried talking to the lady multiple times, but I can't seem to get her attention.

How do I distract the receptionist in Tidy Park's manor?

A: Get the ring bell from the soda bar room and replace the non-working bell at the receptionist's desk with it


text:
Q: Ionic does not accept animation attribute in ion-view I have ion-view template which is referenced from main menu of the app.
In second view i have attribute:
<ion-view title="Settings" animation="slide-in-up">

But page is loaded with default animation.
I tried to remove attribute animation from body tag, but without luck, animation is still same (i tried it in several browsers and android devices).
<body ng-app="starter" animation="slide-left-right-ios7">

Could somebody tell me how can i set animation by right way?
Thanks for any help.

A: I don't know if this is all of what you're looking for, but I was able to find $ionicAnimation documentation. It also sounds like the Ionic team has been doing some major work that effects transitions, which might be why the docs have been down.


text:
Q: Parse Query on Nested Keys with Spaces We need to perform analytics on custom objects stored within Parse.Object's. These objects have keys with spaces. Normally I would just use dot notation: query.equalTo("metaData.custom_key", "custom value"); However, dot notation is not working in a case with spaces, as it would with a native MongoDB query.
Bad Queries with syntax error:

*

*With spaces: parseQuery.equalTo("metaData.key with spaces", "some value")

*With escape: parseQuery.equalTo("metaData.key\ with\ spaces", "some value")

*With replace: parseQuery.equalTo("metaData.key_with_spaces", "some value")

*With replace: parseQuery.equalTo("metaData["key with spaces"]", "some value")

*With replace: parseQuery.equalTo("metaData.'key with spaces'", "some value")
These all result in errors like:
ParseError {
  code: 105,
  message: 'Invalid key name: metaData.\'key with spaces\'' }

E.g. ParseClass.metaData:
{
  "key with spaces":"some value",
  "key 2": "value 2"
}

These solutions are not preferable:
 1. Changing the metaData schema so there are no spaces in keys, because we have millions of objects in production using this format and production write scripts are risky.
 2. Using mongoose or native MongoDB queries, because Parse.Pointer's are stored in MongoDB as strings but we need relations.
3. Post-processing the metaData after a full query (inefficient; last resort).
The final result we need is to count the values for each unique key in the metaData object.
Any thoughts?


text:
Q: pandas series sum shows extra precision I am trying to sum a simple pandas series, and i am getting extraneous results ( by way of extra precision).
Here is the scenario:
import pandas as pd
prices = [2.99, 4.45, 1.36]
s = pd.Series(prices)
s.sum()

shows the output:
8.8000000000000007

I have tried this:
pd.set_option('display.precision',2)  # No use - still the same result

as well as this:
np.set_printoptions(precision=2)  # no use

pd.show_versions()

gives this output:
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.6.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 61 Stepping 4, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.23.1
pytest: 3.0.5
pip: 9.0.1
setuptools: 39.1.0
Cython: 0.25.2
numpy: 1.13.3
scipy: 0.19.1
pyarrow: None
xarray: None
IPython: 5.1.0
sphinx: 1.5.1
patsy: 0.4.1
dateutil: 2.6.0
pytz: 2016.10
blosc: None
bottleneck: 1.2.1
tables: 3.4.3
numexpr: 2.6.2
feather: None
matplotlib: 2.2.2
openpyxl: 2.4.1
xlrd: 1.0.0
xlwt: 1.2.0
xlsxwriter: 0.9.6
lxml: 3.7.2
bs4: 4.5.3
html5lib: 0.9999999
sqlalchemy: 1.1.5
pymysql: None
psycopg2: None
jinja2: 2.9.4
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 0.6.0

Can anyone help me understand how the result came to be 8.8000000000000007  and how do I display only two decimal digits.
I have tried this aswell - no use:
round(s.sum(),2)

A: If you are okay working with DataFrame then this can be easily achieved with-
import pandas as pd
prices = [2.99, 4.45, 1.36]
s = pd.DataFrame(prices)
with pd.option_context('display.precision', 2):
    print(s.sum())

Will output-
8.81

EDIT:
Or if you insist on using Series, then you could finally use the numpy function around as follows -
>>> import numpy as np
>>> np.around(s.sum(), 2)
0    8.81


text:
Q: Is it posible to get the position of point on an excel graph axis I'm not sure this is possible but thought this was the best place to ask.
Is it posible to get the position of a series value on a graph in excel?
For example,  if I have a line graph in excel that has time along the x axis, is it possible to (using VBA) get the position of a specific point on that axis.
What I am trying to do is have a vertical line that is can be positioned based on a date entered by the user.
like this

Where the green line could be positioned by entering in a date (rather than just being manually moved)  (or also it could be set to automatically move to the current date etc).
I was then thinking that if the position is on the graph is queryable, then I can just access the line object and move it to any position I wanted through VBA.
Any Ideas?  or is this just not possible?

A: The "cleanest" way to do this is to add the line to the chart as a new series.  In that way, Excel handles all of the positioning and your work is simplified.  To get a vertical line on a chart, there are a number of options.  I prefer this route:

*

*Create a small 2x2 area with two dates and two values

*Add in the date or x-axis value you want the line at (E3 in image).  You can use =TODAY() here or some manually entered value.

*Set the second x-axis value equal to the first

*Use MAX and MIN on the data to get the values for each date.  You can also use 0 and 1 and a secondary axis, but I think MAX/MIN is easier.

*Add the data to the chart and format as a marker with straight line.

Formulas

*

*E3: =TODAY()

*E4: =E3

*F3: =MIN(C3:C27)

*F4: =MAX(C3:C27)
Result and chart data series for vertical line


text:
Q: Save checkbox state in TableView Cell? Background: I want to create an app that lists some books that someone might be collecting which they can use as a checklist. I want to get a test working properly before I launch into it completely and I've managed to get the following working so far.
Using a plist, UITableView and a UITableCell I can populate a table. The cell consists of a thumbnail, the book title and its second-hand price. There's also a 'checkbox' button which the user can toggle if they've already got the book or not. What I want to do is save the state of the checkbox toggle on exit. Maybe store a value into the .plist (which I've copied over to the Documents directory so it's editable if necessary)? Or is there another way? I could do it using NSUserDefaults, but how could I get that to relate to each cell (book)?
Screenshot of the test app in action (excuse the rudimentary graphics for now):

And here's the cell layout and associated .h file:

Here's the code for the main ViewController .m file:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Find out the path of books_star.plist

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory =  [paths objectAtIndex:0];

    // Load the file content and read the data into arrays

    NSString *myListPath = [documentsDirectory stringByAppendingPathComponent:@"books_star.plist"];
    tableData = [[NSArray alloc]initWithContentsOfFile:myListPath];
    NSLog(@"%@",tableData);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *books_starTableIdentifier = @"booksCell";

    booksCell *cell = (booksCell *)[tableView dequeueReusableCellWithIdentifier:books_starTableIdentifier];
    if (cell == nil)

    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"booksCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    cell.titleLabel.text = [[tableData objectAtIndex:indexPath.row]objectForKey:@"title"];
    cell.thumbnailImageView.image = [UIImage imageNamed: [[tableData objectAtIndex:indexPath.row]objectForKey:@"thumbnail"]];
    cell.priceLabel.text = [[tableData objectAtIndex:indexPath.row]objectForKey:@"price"];

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 96;
}

@end

And here's the code for the Cell .m file:
#import "booksCell.h"

@implementation booksCell

@synthesize titleLabel = _titleLabel;
@synthesize priceLabel = _priceLabel;
@synthesize thumbnailImageView = _thumbnailImageView;
@synthesize checkBoxButton;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {}
    return self;}

- (void) awakeFromNib {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    checked = [defaults boolForKey:@"boxIsChecked"];
    [self checkTheBox];
}

- (IBAction)checkButton:(id)sender {

        if (!checked) {
            [checkBoxButton setImage:[UIImage imageNamed:@"check_on.png"] forState:UIControlStateNormal];
            checked = YES;

            NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile:@"books_star.plist"];
            [plist setObject:[NSNumber numberWithBool:YES] forKey:@"check"];
            [plist writeToFile:@"books_star.plist" atomically:YES];
        }

        else if (checked) {
            [checkBoxButton setImage:[UIImage imageNamed:@"check_off.png"] forState:UIControlStateNormal];
            checked = NO;

        }
        }

- (void) checkTheBox {
        if (!checked) {
            [checkBoxButton setImage:[UIImage imageNamed:@"check_off.png"] forState:UIControlStateNormal];
        }

        else if (checked) {
            [checkBoxButton setImage:[UIImage imageNamed:@"checkBox_on.png"] forState:UIControlStateNormal];}
        }

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

And finally here's the .plist file:

A: You may want to look at using Core Data going forwards, but your plist will work. I would recommend a number of changes to the plist though:

*

*I'd make the root an array (this is a list of books)

*I'd make each item a dictionary (with title, price and thumbnail)

Now, all of your data for each book is in the same container. But, more importantly, you have the option to add to that container - so you have somewhere to store the selected status.

A: You should change the way how you keep your data in plist.
It should be like that:

For table view you select objectAtIndex of current [indexPath row].
You make you UITableViewCell configurable from those "book NSDictionary" - you can add to those objects "checked" property if necessary and easily modify it.
It is much better approach if you want to delete / edit / create objects in your system.
With that approach you don't have a problem of missing indexes for selected objects etc.
Once you have NSDictionary in your UITableViewCell you can add that property like that:
[dict setValue:[NSNumber numberWithBool:YES] forKey:@"checked"];

To get value:
[[dict valueForKey:@"checked"] boolValue];


text:
Q: inserting jpg in word 2007 - jpg became small I would like to know how to have a jpg file appears to be a little bit clearer and bigger if I insert it on word 2007.
I used snag it to capture a file and it looks good actually but if I paste it on word, then it became small. Any idea?

A: Word inserts the image in the size the image has. When you make a screenshot and the tool you are using specifies in the image a resolution of 300 dpi, then it's going to be quite small in print. Word uses exactly that information.
Furthermore, if an image would be larger than the current bounds of the paper it will be made smaller as well to fit.
In both cases you don't lose any image information. The whole image is still there, just a little smaller. Word does not reample the image, just chooses a display dize. So you can always go back and resize the image to your liking.
The thing is a little different once you export to PDF with the built-in support, though. Then all images are stored as JPEG and resampled to (I think) 150 dpi.
Side note: For screenshots I'd rarely use JPEG. My HDD isn't that full yet that I cannot afford PNG for things I like clear and readable :-)

A: In Word 2003 you can right-click on an image after inserting it and select Format Picture... on the pop-up context menu. In the Format Picture dialog box that appears there's a Size tab with various controls. There's also a Picture Toolbar which, if visible, had a Format Picture button on it. Word 2007 probably has similar functionality, as well as a Help menu...


text:
Q: How Can I Convert My new Byte Array To an Image i have write this code for extracting bitplane1 of my image . but i have exceptions.
actually i get an image and convert it to a byte array so after i change this byte array i want to convert this new byte array to image ? could you please give me some advice ? best regards
(actually i want extract bitplane1 of my image)
any suggestion ?
my code is :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace bitplane
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)

    {
      //  Image grayImage;
        OpenFileDialog o = new OpenFileDialog();
        o.ShowDialog();

        byte[] x = File.ReadAllBytes(o.FileName);

        byte maskbyte1 = 2;
        int [] newpix= new int [x.Length];
    for (int i = 0; i < x.Length; i++)
       {

           newpix[i] = x[i] & maskbyte1;

           string px=newpix[i].ToString();

          x[i] = Convert.ToByte(px);

    }
        MemoryStream ms = new MemoryStream(x);
        Image myImage = Image.FromStream(ms);

    myImage.Save(@"C:\Users\Public\Pictures\Sample Pictures\New folder\fgh.jpg");
    }
    }
}

my exception is for this line :
Image myImage = Image.FromStream(ms);
System.ArgumentException was unhandled
 Parameter is not valid.

A: Well, I think the first exception you may get int this code is because of this:
o.ShowDialog();
byte[] x = File.ReadAllBytes(o.FileName);

Note that doesn't matters what happenes to the open file dialog, the byte[] x = File.ReadAllBytes(o.FileName); will always be executed once even if its value is null. I think you should first edit your code to sthg like this:
if (o.ShowDialog() == DialogResult.OK)
{
    byte[] x = File.ReadAllBytes(o.FileName);
    //...  and all other codes
}

Now the code will only be executed when the o object returns OK, which means a file was selected.
The second thing is, that in your code there are a lot of places where an exception could be thrown, and in this case it's better and safer to use methods that are already exist. Here's a method that calls one:
public Image ConvertByteArrayToImage(byte[] bytes)
{
    System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
    return Image.FromStream(stream);
}

This code does almost all the work that your code already contains.
But there are cases when this code throws exceptions either, so the most safe way is to put all the stuff in a try-catch block:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace bitplane
{
    public partial class Form1 : Form
    {
        public byte[] x;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (o.ShowDialog() == DialogResult.OK)
                {
                    OpenImage(o.FileName);
                    SaveImage(ConvertByteArrayToImage(x), @"C:\Users\Public\Pictures\Sample Pictures\New folder\fgh.jpg");
                }
            }
            catch
            {
                MessageBox.Show("error");
            }
        }

        public void OpenImage(string path)
        {
            x = File.ReadAllBytes(path);
        }

        public void SaveImage(Image image, string path)
        {
            image.Save(path);
        }

        public Image ConvertByteArrayToImage(byte[] bytes)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
            return Image.FromStream(stream);
        }
}

I inserted some methods to your code, so you can call them from anywhere, and don't have to do it inside only one event, but it does the same thing.
Hopefully helps a bit! :)


text:
Q: Alexa skills console returns null I've written simple aws lambda code to output on the alexa skills kit console, but I'm constantly getting an output of null. I've made sure to paste the arn from aws lambda into the endpoint of the skill. Not sure why this is happening.
aws lambda code
alexa skills json output

A: You need to properly form your responses to see them working on the Alexa Skill Kit Console. Passing a single string to the alexa service will not work. You could potentially use console.log outputs to see that the lambda call is working properly. You can also test under lambda's built-in test. A string output returns null because the alexa skill kit console requires a properly JSON formatted output. I'd suggest you to start with a sample hello world skill example


text:
Q: Error: Unable to guess the MIME type as no guessers are available (have you enabled the php_fileinfo extension?) I'm having this problem with Laravel:
Unable to guess the MIME type as no guessers are available (have you enabled the php_fileinfo extension?)

I tried to solve this error by enabling extension in php.ini
from this ;extension=php_fileinfo.dll to this extension=php_fileinfo.dll


text:
Q: How to assign and match land cover type from Corine to a dataframe with a set of lon lat coordinates? I'm trying to find out the land use type for a set of coordinates that define the location of plant species across Europe. However I'm stuck in the process of assigning the land use to the respective coordinates. Any advice would be more than welcome!
First, I download the land use raster file from here: https://land.copernicus.eu/pan-european/corine-land-cover
#Read raster file (year 2006 but could be any)
clc <- raster("U2006_CLC2000_V2020_20u1.tif")

Then, I read the Corine land use classes and rename the levels of the raster file with this classes
#Read Corine classes
clc_classes <- foreign::read.dbf("CLC_1990/DATA/U2006_CLC2000_V2020_20u1.tif.vat.dbf",
                                 as.is = TRUE) %>%dplyr::select(value = Value,landcov = LABEL3)

This is a small subset of coordinates from my full list of coordinates (over 200.000 in total):
lon <- c("51.105", "51.195", "51.188", "51.239")
lat <- c("4.392", "4.395", "4.896", "4.468")
sp <- c("sp1","sp2", "sp3","sp4")
#Create minimal dataframe
d <- data.frame(lon,lat,sp)

But now I really do not know how to proceed and create the final dataframe with land use type given the matching with the raster file
My intention is to add a 4th column as follows after the matching of my coordinates with the land use type of the raster file.
#Example of how this fourth column would be like:
d$land_use <- c("Olive groves", "Olive groves", "Vineyards", "Pastures")

A: The data (another file from the same website).
library(terra)
r <- rast("U2018_CLC2018_V2020_20u1.tif")

As you can see, r knows about the class labels.
r
#class       : SpatRaster
#dimensions  : 46000, 65000, 1  (nrow, ncol, nlyr)
#resolution  : 100, 100  (x, y)
#extent      : 9e+05, 7400000, 9e+05, 5500000  (xmin, xmax, ymin, ymax)
#coord. ref. : ETRS_1989_LAEA (EPSG:3035)
#source      : U2018_CLC2018_V2020_20u1.tif
#color table : 1
#categories  : LABEL3, Red, Green, Blue, CODE_18
#name        :                  LABEL3
#min value   : Continuous urban fabric
#max value   :                  NODATA

head(cats(r)[[1]])
#  Value                                     LABEL3       Red     Green      Blue CODE_18
#1     1                    Continuous urban fabric 0.9019608 0.0000000 0.3019608     111
#2     2                 Discontinuous urban fabric 1.0000000 0.0000000 0.0000000     112
#3     3             Industrial or commercial units 0.8000000 0.3019608 0.9490196     121
#4     4 Road and rail networks and associated land 0.8000000 0.0000000 0.0000000     122
#5     5                                 Port areas 0.9019608 0.8000000 0.8000000     123
#6     6                                   Airports 0.9019608 0.8000000 0.9019608     124

Here are some example points for use with extract
pts <- matrix(c(3819069, 3777007, 3775822, 2267450, 2302403, 2331431), ncol=2)
extract(r, pts)
#                        LABEL3
#1                Sea and ocean
#2 Complex cultivation patterns
#3           Natural grasslands

Or with your lon/lat points (you had the names reversed!), first transform these to the coordinate reference system of the land use raster:
lat <- c(51.105, 51.195, 51.188, 51.239)
lon <- c(4.392, 4.395, 4.896, 4.468)
xy <- cbind(lon, lat)
v <- vect(xy, crs="+proj=longlat")
vv <- project(v, crs(r))

extract(r, vv)
#  ID                                     LABEL3
#1  1               Complex cultivation patterns
#2  2 Road and rail networks and associated land
#3  3                                   Pastures
#4  4             Industrial or commercial units

If you want the land use code instead
activeCat(r) <- "CODE_18"
extract(r, vv)
#  ID CODE_18
#1  1     242
#2  2     122
#3  3     231
#4  4     121

A: The answer from Robert was really great helping someone with no clues like me.
However when I try to achieve the same, I get unexpected results.
When I run
library(terra)
data <- rast("2018_CLC2018_V2020_20u1.tif")
data

I get no labels:
class       : SpatRaster
dimensions  : 46000, 65000, 1  (nrow, ncol, nlyr)
resolution  : 100, 100  (x, y)
extent      : 9e+05, 7400000, 9e+05, 5500000  (xmin, xmax, ymin, ymax)
coord. ref. : ETRS_1989_LAEA (EPSG:3035)
source      : U2018_CLC2018_V2020_20u1.tif
name        : U2018_CLC2018_V2020_20u1
min value   :                        1
max value   :                       48

And therefore the results from the extraction are in the 1 - 48 range.
This is the only file I found at the website that matches the naming.
I'm sorry for adding this as an answer but I couldn't comment.


text:
Q: How to use Spring Profiles in configuring a Spring Job I need to run a Spring batch job. My requirement is to run a few steps in sequence/parallel depending on the spring profile
I placed the Job config to run steps in parallel in a spring config file parallel.xml
<job id="job" xmlns="http://www.springframework.org/schema/batch"
incrementer="incrementer">

<step id="step1" next="step2">
    <tasklet ref="tasklet" />
</step>

<split id="step2" task-executor="assetStepAsyncTaskExecutor">
    <flow>
        <step id="split1">
            <tasklet ref="tasklet" />
        </step>
    </flow>
    <flow>
        <step id="split2">
            <tasklet ref="tasklet" />
        </step>
    </flow>
</split>
<listeners>
    <listener ref="listener" />
</listeners>
</job>

and the Job config to run steps in sequence in a spring config file default.xml
<job id="job" xmlns="http://www.springframework.org/schema/batch"
incrementer="incrementer">

<step id="step1" next="step2">
    <tasklet ref="tasklet" />
</step>
<step id="step2" next="step3">
            <tasklet ref="tasklet" />
</step>
<step id="step3">
    <tasklet ref="tasklet" />
</step>
<listeners>
    <listener ref="listener" />
</listeners>
</job>

And I am toggling between the job configs using Spring profile.
<beans profile="parallel">
<import resource="classpath:/spring/parallel.xml" />
</beans>

<beans profile="default">
<import resource="classpath:/spring/default.xml" />
</beans>

I am loading the config files through the contextConfigLocation context-param in web.xml.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
// other config files
classpath*:/spring/default.xml
classpath*:/spring/parallel.xml
</param-value>
</context-param>

I am passing the profile details as context-params
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>default</param-value>
</context-param>

<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>parallel</param-value>
</context-param>

If I don't include the files in contextConfigLocation it doesn't load the spring beans in default.xml and parallel.xml and because of this I get a NoBeanFoundException
Error creating bean with name 'controller' defined in class path resource [config.xml]: Cannot resolve reference to bean 'batchJob' while setting bean property 'job'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'batchJob' is defined
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) [spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) [spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3339) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:3780) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
    at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
    at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
    at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [rt.jar:1.8.0_121]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_121]
    at org.jboss.threads.JBossThread.run(JBossThread.java:122)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'batchJob' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1083) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:274) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) [spring-beans-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    ... 26 more

If I include both the config files. I get a DuplicateJobException.
12/21/2017 17:00:58,971 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/]] (ServerService Thread Pool -- 85) JBWEB000287: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener: java.lang.IllegalStateException: org.springframework.batch.core.configuration.DuplicateJobException: A job configuration with this name [batchJob] was already registered
    at org.springframework.batch.core.configuration.support.AutomaticJobRegistrar.start(AutomaticJobRegistrar.java:164) [spring-batch-core-2.1.8.RELEASE.jar:]
    at org.springframework.batch.core.configuration.support.AutomaticJobRegistrar.onApplicationEvent(AutomaticJobRegistrar.java:128) [spring-batch-core-2.1.8.RELEASE.jar:]
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:97) [spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:303) [spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:911) [spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:428) [spring-context-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
    at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3339) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:3780) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
    at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
    at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
    at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [rt.jar:1.8.0_121]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_121]
    at org.jboss.threads.JBossThread.run(JBossThread.java:122)
Caused by: org.springframework.batch.core.configuration.DuplicateJobException: A job configuration with this name [batchJob] was already registered
    at org.springframework.batch.core.configuration.support.MapJobRegistry.register(MapJobRegistry.java:52) [spring-batch-core-2.1.8.RELEASE.jar:]
    at org.springframework.batch.core.configuration.support.DefaultJobLoader.doLoad(DefaultJobLoader.java:152) [spring-batch-core-2.1.8.RELEASE.jar:]
    at org.springframework.batch.core.configuration.support.DefaultJobLoader.load(DefaultJobLoader.java:114) [spring-batch-core-2.1.8.RELEASE.jar:]
    at org.springframework.batch.core.configuration.support.AutomaticJobRegistrar.start(AutomaticJobRegistrar.java:161) [spring-batch-core-2.1.8.RELEASE.jar:]
    ... 19 more

What am I missing?

A: Spring Batch each job name has to be unique which is defined as id="job" while configuring the job. Above configuration trying to setup two jobs with same job name as "batchJob" which is why you are seeing the exception.
To achieve what you need you do this.
 <job id="jobA" xmlns="http://www.springframework.org/schema/batch"
incrementer="incrementer">

<step id="step1" next="step2">
    <tasklet ref="tasklet" />
</step>

<split id="step2" task-executor="assetStepAsyncTaskExecutor">
    <flow>
        <step id="split1">
            <tasklet ref="tasklet" />
        </step>
    </flow>
    <flow>
        <step id="split2">
            <tasklet ref="tasklet" />
        </step>
    </flow>
</split>
<listeners>
    <listener ref="listener" />
</listeners>
</job>

<job id="jobB" xmlns="http://www.springframework.org/schema/batch"
incrementer="incrementer">

<step id="step1" next="step2">
    <tasklet ref="tasklet" />
</step>
<step id="step2" next="step3">
            <tasklet ref="tasklet" />
</step>
<step id="step3">
    <tasklet ref="tasklet" />
</step>
<listeners>
    <listener ref="listener" />
</listeners>
</job>

From you controller you can call either jobA or jobB based on the context parameter.

A: As @lzagkaretos Suggested in the comments, the issue was with the Spring version. Updating the version to 3.2.2.RELEASE resolved the issue for me.


text:
Q: Unable to write entire output in a text file In the below function after doing some operations to print few words after some processing,i wish to print all the output words in a file,however rather than 4 words which are being produced as output only 2 are being written in the file words.txt.
def morsePartialDecode(inputStringList):
    with open('words.txt','w') as wordfile:
        message_received = inputStringList
        message_received = ' '.join(inputStringList)
        for i in range(len(message_received)):
            x = 'x'
            y = '.'
            message = message_received.replace(x, y)
        message1 = message.split(",")
        message_conv = morseDecode(message1)
        print message_conv
        print >> wordfile, (message_conv)

        for i in range(len(message_received)):
            x = 'x'
            y = '-'
            message = message_received.replace(x, y)
        message2 = message.split(",")
        message_converted = morseDecode(message2)
        print >> wordfile, (message_converted)
    wordfile.close()
    return message_converted

As an output of the function i am getting the the words:
EESE
TTDT
SAIFE
DMNCT

However in the file only SAIFE and DMNCT are written.Where did it went wrong.Any help would be appreciated.

A: You don't need to close the file if you're using a with statement if python.
You're opening the file in "w" mode, which means that every time you open it, the whole file will be destroyed. Try opening it in append mode.
edit:
Also, I would take a look at the CSV module. It has some great use cases here.


text:
Q: dlmSmooth increases fluctuations I am currently working with State Space models for the first time and am trying to estimate an error correction model with an unobserved I(2) process, $\mu_t$. I have specified a model in R using the package dlm. My model has the form:
$$ \Delta s_t = \alpha_1 s_{t-1} + \alpha_2 p_{t-1} + \mu_{t} + \kappa_0 \Delta p_{t} + \kappa_1 \Delta p_{t-1} + \omega_1 \Delta s_{t-1} + \epsilon_t $$
$$ \mu_{t} = \mu_{t-1} + \Delta \mu_{t}$$
$$ \Delta \mu_t = \Delta \mu_{t-1} + \eta_t$$
where $\Delta s_t, s_{t-1}, p_{t-1}, \Delta p_t, \Delta p_{t-1}, \Delta s_{t-1}$  are data-observations, $\alpha_1, \alpha_2, \kappa_0, \kappa_1, \omega_1$ are constant unknown parameters and $\mu_t$ is an unobserved I(2) process.
I am mainly interested in estimating the unknown parameter values $\alpha_1$ and $\alpha_2$ and the unobservered process $\mu_t$.
Implementing the model in R, I first specify the model by the following code and obtain the filtered parameter values. Hereafter I obtain the smoothed values.
dlmmodel2 <- function(alfa) {dlm(
  FF=matrix(c(1,1,-1,1,1,1,0),nr = 1),
  GG=matrix(c(1,0,0,0,0,0,0,  0,1,0,0,0,0,0,  0,0,1,0,0,0,0,  0,0,0,1,0,0,0,  0,0,0,0,1,0,0,  0,0,0,0,0,1,0,  0,0,1,0,0,0,1), nr = 7),
  V = alfa[1],
  W =matrix(c(0,0,0,0,0,0,0,   0,0,0,0,0,0,0,  0,0,0,0,0,0,0,  0,0,0,0,0,0,0,   0,0,0,0,0,0,0,  0,0,0,0,0,0,0,  0,0,0,0,0,0,alfa[2]), nr = 7),
  m0 = matrix(c(1,1,1,1,1,1,1),nr = 7),
  C0 = matrix(c(0,0,0,0,0,0,0,   0,0,0,0,0,0,0,  0,0,5,0,0,0,1,  0,0,0,0,0,0,0,   0,0,0,0,0,0,0,  0,0,0,0,0,0,0,  0,0,1,0,0,0,5), nr = 7),
  X=F_matrix, # F_Matrix contains the data observations (col 3 and 7 are empty)
  JFF=matrix(c(1,2,0,4,5,6,0), nr=1)
)
}

#initial values
init1 <- c(2.1,1)

#model
model <- dlmMLE(y_vector,init1,dlmmodel2) #yvector contains Delta_s_t
model
parameter_results2 <- dlmmodel2(model$par)

#filter and smooth
filtered<- dlmFilter(y_vector, parameter_results2)
smoothed <- dlmSmooth(filtered)

My problem arise as I try to obtain the smoothed values. The obtained values range from 3 e+209 to -1 e+191 though my filtered values are in a much lower range.
My question is: why is my smoothed values so (numerically) large? (see output below)
> plot(filtered$m)
> filtered$m
Time Series:
Start = 1999
End = 2017
Frequency = 1
          [,1] [,2]        [,3] [,4]      [,5]     [,6]        [,7]
1999 1.0000000    1  1.00000000    1 1.0000000 1.000000  1.00000000
2000 1.0283483    1  1.22242633    1 0.9961995 1.012915  0.54457382
2001 0.9213248    1  0.21543516    1 0.8005188 1.007066 -0.35293323
2002 0.9299682    1  0.53160130    1 0.8180312 1.007189  0.02261221
2003 0.9328907    1  1.01496822    1 0.8239033 1.007241  0.26599504
2004 0.9324971    1  1.15266894    1 0.8231204 1.007232  0.19794457
2005 0.9319144    1  0.94703263    1 0.8219661 1.007218 -0.01607025
2006 0.9314988    1  0.30847832    1 0.8211416 1.007209 -0.34454848
2007 0.9315001    1 -0.03187562    1 0.8211442 1.007209 -0.34235386
2008 0.9313951    1 -0.14680378    1 0.8210130 1.007191 -0.26428162
2009 0.9310889    1 -0.72624693    1 0.8205843 1.007147 -0.48839884
2010 0.9319146    1  0.43896849    1 0.8217332 1.007266  0.37800888
2011 0.9317131    1  0.17669692    1 0.8214527 1.007237  0.02991360
2012 0.9316768    1 -0.19409593    1 0.8214027 1.007232 -0.18156016
2013 0.9316803    1 -0.60983462    1 0.8214079 1.007232 -0.30928727
2014 0.9316748    1 -0.54629135    1 0.8214003 1.007231 -0.10740577
2015 0.9316805    1 -0.25928590    1 0.8214087 1.007232  0.10678342
2016 0.9316611    1  0.52341814    1 0.8213816 1.007229  0.48246605
2017 0.9316605    1  0.84370534    1 0.8213807 1.007229  0.39923137
>

> smoothed$s
Time Series:
Start = 1999
End = 2017
Frequency = 1
               [,1]           [,2]           [,3]           [,4]           [,5]           [,6]
1999   1.000000e+00   1.000000e+00 -9.466652e+231   1.000000e+00   1.000000e+00   1.000000e+00
2000  3.439619e+209  6.190332e+197  1.701729e+213  3.255033e+196  1.000790e+212 -2.029970e+211
2001 -1.013215e+191 -1.003954e+177 -7.431703e+191 -5.630027e+175 -2.226889e+191 -7.003334e+189
2002 -9.117334e+175 -6.378055e+161  1.064459e+176 -5.483632e+160 -1.467380e+176 -7.720378e+174
2003  3.317407e+159 -1.130269e+146  4.784756e+161 -1.657647e+144  6.221140e+159  9.835280e+157
2004  6.630620e+145 -2.177203e+132  9.128879e+147 -2.182155e+130  6.581938e+145  7.359108e+143
2005  7.807999e+133  1.845376e+120  4.883447e+135  5.325280e+117  9.771700e+133  1.344280e+133
2006  3.443877e+120 -1.712517e+108 -2.018727e+123 -2.481098e+105  2.988215e+120  1.008803e+120
2007 -1.940769e+108  -3.597062e+95 -7.471470e+111  -6.241203e+94 -3.494084e+108 -2.497683e+107
2008  -4.174798e+95  -2.506133e+83  -3.241887e+98   6.105502e+82  -2.704219e+96  -2.974656e+95
2009   5.170978e+84  -1.197459e+72   1.458495e+87  -5.988552e+70   6.800202e+84   9.838138e+83
2010  -1.007168e+72  -2.888476e+60   2.190879e+75   1.197968e+59  -2.637143e+72  -1.420613e+71
2011   5.463719e+60  -7.203329e+48  -6.079742e+63   5.655312e+47   3.452379e+60   2.101814e+60
2012   3.870811e+48   9.011218e+36  -7.816310e+51   3.313523e+33   6.043987e+48  -3.248771e+48
2013   1.559516e+38   7.271353e+27  -1.127496e+43  -1.021232e+26   6.176949e+38  -6.562388e+37
2014  -2.202694e+27   1.420512e+16  -2.248650e+31  -2.071048e+14   2.786972e+27  -6.745094e+26
2015   2.775447e+16   1.235690e+04   5.069440e+19  -6.768663e+02   4.426600e+16   3.470204e+15
2016  -4.283332e+04   1.000000e+00   1.373019e+05   1.000000e+00  -1.779131e+04  -4.499139e+03
2017   9.316605e-01   1.000000e+00   8.437053e-01   1.000000e+00   8.213807e-01   1.007229e+00
               [,7]
1999 -6.761894e+231
2000  1.136702e+213
2001 -1.183163e+191
2002  2.204284e+175
2003  2.729704e+161
2004  3.381939e+147
2005  1.976811e+135
2006 -9.824642e+122
2007 -5.034451e+111
2008  -8.683889e+98
2009   1.006174e+87
2010   1.349258e+75
2011   1.247445e+64
2012   2.416943e+52
2013  -4.594289e+42
2014  -8.923618e+30
2015   2.568447e+19
2016  -4.045394e+04
2017   3.992314e-01
>

If I run the same code on a larger sample (1968-2017 instead of 2000-2017), I can estimate the filtered values but get the following error code when trying to obtain the smoothed values.
> smoothed <- dlmSmooth(filtered)
Error in dlmSmooth.dlmFiltered(filtered) :
  error code 6 from Lapack routine dgesdd

Does anyone know whether this can be fixed in any other way than reducing the time span?
Any help would be greatly appreciated.
Thanks in advance.

A: I cannot quite relate your code to your problem statement. When I print your GG matrix I get:
> matrix(c(1,0,0,0,0,0,0,  0,1,0,0,0,0,0,  0,0,1,0,0,0,0,  0,0,0,1,0,0,0,  0,0,0,0,1,0,0,  0,0,0,0,0,1,0,  0,0,1,0,0,0,1), nr = 7)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    0    0    0    0
[2,]    0    1    0    0    0    0    0
[3,]    0    0    1    0    0    0    1
[4,]    0    0    0    1    0    0    0
[5,]    0    0    0    0    1    0    0
[6,]    0    0    0    0    0    1    0
[7,]    0    0    0    0    0    0    1

It looks like $\mu_t$  is in the third position of the state vector and $\Delta\mu_t$ in the seventh, but why there is a $-1$ in the third position in FF rather than a 1? It wouldn't matter (a change of sign in the latent process), but make me fear that I am misunderstanding something.
You set only two variances in V and W, but make no provision to ensure that they are non-negativa an remain so along the maximum likelihood estimation: try to replace by something like exp(alpha[1])  or alpha[2]^2 (and modify the initial values accordingly).
Don't you say that you have five unknown parameters (other than the variances of the noises that I gather are alpha[1] and alpha[2])?
If you want to estimate these parameters --which you need to in order to run your filter-- you should replace them in the proper places inside function dlmmodel2. If you intend these five parameters to be the five  elements of the state vector not already taken by $\mu_t$ and $\Delta\mu_t$, you should initialize them properly: it seems that you are giving them initial value 1 (in m0) and variance 0 (in C0). Is that what you intend?  How were the non-zero elements in C0 chosen?
I seem to recall that I have had some trouble passing time series to some function in dlm. Try to pass plain matrices.

A: Thank you so much for your response.
Yes you are right that the third position in FF should be a 1 in order to match the model I have presented. This is a mistake on my behalf as I have simplified the model slightly in order to present it here.
So far, my estimates of the two variances have been positive, hence, I have not felt the need to restrict the parameters but on your recommendation I have now done so.
With regards to my five unknown parameters, you are right that I would like to obtain estimates of these. I have been unsure of how to include them properly in dlmmodel2 and hence I have chosen to include them as element 1,2,4,5,6 in my state vector. In this example I initialize them to 1, but I am continuously trying different initial values.
I see now that I have misinterpreted c0, and as my parameters are unknown c0 should in fact have a strictly positive diagonal. Changing this in my R code seems to do the trick and the two errors I previously got are now gone.
Thank you very much for your answer.


text:
Q: Project in C won't work I need to do a project, and so far I've done this:
#include<stdio.h>
#include<malloc.h>
typedef struct
{
    char Name[10];
    char Address[10];
    long Phone_number;
}Phonebook;
void main()
{
    int Counter, Number = 0;
    long Number_of_residents;
    Phonebook *Information = (Phonebook*)malloc(sizeof(Phonebook));
    scanf("%ld", &Number_of_residents);
    for (Counter = 0; Counter < Number_of_residents; Counter++)
    {
        Information = (Phonebook*)realloc(Information, sizeof(Phonebook)*(Counter + 1));
        gets(Information[Number].Name);
        Number++;
        gets(Information[Number].Address);
        Number++;
        scanf("%ld", &Information[Number].Phone_number);
        Number++;
    }
}

What did I do wrong here?
It doesn't work at all.

A: You don't need do Number++ after every gets()
There are also couple of bugs in the code, the correct code will looks like. Please note that we don't need to realloc array every time as we know it size before reading each element.
Also using gets() is unsafe and if you start using scanf() it's better to continue use it.
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  char Name[10];
  char Address[10];
  long Phone_number;
}Phonebook;

int main() {
  int Counter, Number = 0;
  long Number_of_residents;
  Phonebook * Information;
  scanf("%ld", &Number_of_residents);
  Information = (Phonebook*)malloc(Number_of_residents * sizeof(Phonebook));
  for (Counter = 0; Counter < Number_of_residents; Counter++) {
    scanf("%10s", Information[Counter].Name);
    scanf("%10s", Information[Counter].Address);
    scanf("%ld", &Information[Counter].Phone_number);
  }

  return 0;

}

A: Try this:
#include<stdio.h>
#include<malloc.h>
typedef struct
{
    char Name[10];
    char Address[10];
    long Phone_number;
}Phonebook;
void main()
{
    int Counter;
    long Number_of_residents;
    scanf("%ld", &Number_of_residents);
    getchar();
    Phonebook *Information = (Phonebook*)malloc(Number_of_residents * sizeof(Phonebook));
    for (Counter = 0; Counter < Number_of_residents; Counter++)
    {
        gets(Information[Counter].Name);
        gets(Information[Counter].Address);
        scanf("%ld", &Information[Counter].Phone_number);
        getchar();
    }
}

The changes made:

*

*As said in the existing answer, Number++ was incorrect. In fact, you don't need Number at all. You can simply use Counter.

*scanf() has issues with \n being taken as the next input, so I have added getchar() after every scanf() to take care of that.

*I am not sure why you had that realloc() statement. I removed it, and now this code snippet that I have posted works on my computer.


text:
Q: how can I use the fileupload helper when it is loaded in another page using the load jquery method? I have the following problem, one page load in one of his div using the Load method from Jquery Ajax another page that use the FileUpload Asp.net Helper. Alone that page Works fine, but inside this div the upload button apparently calls the hosting page, not the page that original has the helper.
In consecuence, How can correctly use the helper loaded from another page?
In a scheme I think that this is happening:

And I want this to happen, but don't know how to do it:

A: The upload button submits the form. It will be submitted to whatever location is specified in the action attribute of the form. Therefore you should set the action attribute value to the page that you want the form to post to.
This will be easier to manage if you set includeFormTag to false. It is true by default:
@FileUpload.GetHtml(
    initialNumberOfFiles: 1,
    allowMoreFilesToBeAdded: false,
    includeFormTag: false,
    uploadText: "Upload",
    name: "Upload1"
)

You will then need to provide your own form tag. Make sure you include the correct enctype for managing file uploads:
<form action="somePage" method="post" enctype="multipart/form-data">
...


text:
Q: jQuery Validation Plugin remote check for password with Django I have a "Reset Password" form being validated by the jQuery Validation plugin. Everything works fine except that I can't get the "remote" part to work with Django. What I'm trying to do is to have remote send an ajax request to my Django backend to check that the "Old Password" is correct as part of validation.
What I'm not sure about is how to set up my url.py and views.py to return what jQuery.validation needs
Login is required, so there will be a request.user
My Code:
    $("#changePassword").validate({
    rules:
    {
        oldPassword:
        {
            required: true,
            remote:
            {
                url: "profile/password/check/",
                type: "post",
                data:
                {
                    oldPassword: function()
                    {
                        return $("#oldPassword").val();
                    }
                }
            }
        },
        newPassword: "required",
        confirmPassword:
        {
            equalTo: "#newPassword"
        }
    }
});

Help is much appreciated, thank you :)

A: All you need to do is map the URL ^profile/password/check/ to a view, and within that view, fetch the value for the key oldPassword in the request.POST dictionary, do with it what you will, and return either true or false. For example:
def check_profile_password(request):
  response_str = "false"
  if request.is_ajax():
    old_password = request.POST.get("oldPassword")
    if old_password:
       # Apply whatever logic you want to apply
       response_str = "true"

  return HttpResponse("%s" % response_str)

A: Okay I ended up figuring it out myself, thanks though to everyone who offered help.
From the jQuery.Validation side, I think perhaps my methods weren't getting through or being added to the Validation modeul properly, so there was never anything wrong with Django.
I ended up simply putting "remote:" into my input tag, like so:
<input id="oldPassword" name="oldPassword" type="password" remote="/profile/password/check/" size="25" class="required" minlength="2" />

Then to apply validation, in a  tag:
$("#changePassword").validate();

Then in Django:
old_password = request.GET.get("oldPassword")
request_user = User.objects.get(id=request.user.id)
if(request_user.check_password(old_password) == True):
    response_str = "true"
return HttpResponse(response_str)

A: Hmm i did something like that in my django project. since im not behind the computer where i program and dont have access to my code i can only describe what i did.
I urls py i have set up some url like
/profile/save/, which calls saveProfile view. You could set up url like ^pwdvalidate/$ and call matching view.
In saveProfile view i do check
if the request.is_ajax() and if request is get. then check request.user's existing password and do all other checks you need. Return it with simplejson dumps:
return HttpResponse(simplejson.dumps(some_python_obj))
js request do with jquery.ajax
I understand its quite vague and generic, but hope it helps.
Edit: Check out this example : http://webcloud.se/article/AJAX_in_Django_with_jQuery/

A: A word of note: remote validation DOES NOT work in older version of jQuery.
For me I could get it to work only in version 1.6.1 and above.
It will also help if you set the remote validation to execute 'synchronously', default being 'asynchronous'.
remote: { url:"validate.php", async:false }