text:
Q: with fragment google maps api v2 I'm trying my hand and Android Application Development. I'm currently using Eclipse (I can't remember the version, whatever the newest is). I've crossed a bridge where I just can't seem to grasp what I'm doing wrong. I'm attempting to use the Google Maps V2 API. I've been through several documents and tried several techniques, all of which lead to the same error
 `Binary XML file line #11: Error inflating class fragment``
I've tried so many different answers from questions similar to mine, but to no avail. :( I can usually figure these things out, but maybe I'm just too overloaded.
<uses-sdk
    android:minSdkVersion="17"
    android:targetSdkVersion="17" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVISES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="---my key----" />
</application>

`
<fragment
    android:id="@+id/map"
    android:name="com.testing.svma.MainActivity"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

`public class MainActivity extends FragmentActivity {
    private GoogleMap  map;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
}`

A: Try this,
Change the map fragment name as follows,
android:name="com.google.android.gms.maps.MapFragment"

And put these in to your manifest file also,
 <uses-library android:name="com.google.android.maps" />

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />


text:
Q: Invoke Instance Method Reference On Instance Argument In Java is it possible to, given a non-static method reference, and an instance of the class, somehow communicate that you would like that class instance to invoke that method?
Pseudo example:
public Object methodApply(Function<Object,Object> method, Object instance, List<Object> args) {
    return instance.method(args);
}

A: You cannot declare a method that invokes any method on an object declared with any class but if you use reflection.
The drawback  of a reflection approach is you may get exceptions at runtime if the method/access are not valid.
With Java 8, you may pass any method reference but only to implement a functional interface (it is so just an alternative to a lambda expression).
The limitation is that this method reference must be in accordance with the functional interface descriptor.

If you want really to use Java 8 and benefit from type safety to implement your need, you should take advantage that you can invoke method references on a variable that doesn't make part of the lambda.
But note also that the number of argument that a functional interface accepts is not variable.
So you should so overload your generic method to accept different number of arguments.
For example if you want to pass one argument to the invoked method, methodApply() should have a Function<T,R> parameter :
public static <T, R> R methodApply(Function<T, R> function, T arg) {
  return function.apply(arg);
}

But if you want also to to able to pass two arguments to the invoked method, methodApply() should be overloaded and have so a BiFunction<T, U, R> parameter :
public static <T, U, R> R methodApply(BiFunction<T, U, R> function, T argOne, U argTwo) {
  return function.apply(argOne, argTwo);
}

If you need to pass more parameters, you can of course create your own functional interfaces : TriFunction, QuadriFunction and overload the method in the same way.
Here is a sample working code that illustrates that :
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;

public class FunctionHelper {

    public static void main(String[] args) {

      System.out.println("methodApply() with Function" + System.lineSeparator());
      // String.concat
      String oneString = "hello";
      String concatenated = methodApply(oneString::concat, " world");
      System.out.println("concatenated="+ concatenated);

      // List add/remove
      List<String> list = new ArrayList<>();
      methodApply(list::add, concatenated);
      System.out.println("after adding, list="+list);
      methodApply(list::remove, concatenated);
      System.out.println("afer removing, list="+list);

      System.out.println("---------------------------"+ System.lineSeparator());

      System.out.println("methodApply() with BiFunction" + System.lineSeparator());
      // String.substring
      oneString = "hello world";
      System.out.println("substring=" + methodApply(oneString::substring, 0, 6));
    }

    public static <T, R> R methodApply(Function<T, R> function, T arg) {
      return function.apply(arg);
    }

    public static <T, U, R> R methodApply(BiFunction<T, U, R> function, T argOne, U argTwo) {
      return function.apply(argOne, argTwo);
    }

}

Output :

methodApply() with Function
concatenated=hello world
after adding, list=[hello world]
afer removing, list=[]

methodApply() with BiFunction
substring=hello

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why won't a:active work in sidebar widget? I have the following in my css:
.categories-widget li a:hover {
text-decoration: underline;
}

.categories-widget li a:active {
text-decoration: underline;
}

and this in my sidebar.php:

Categories

   <?php
   global $parent_id;
   wp_list_categories('show_count=1&title_li=&child_of='.$gateway_parent_id.'&show_count=0&hide_empty=0'); ?>

The a:hover works, but not the a:active. Is there a reason for this? What can I do to fix it?

A: it wont work since you have:
.categories-widget li a:hover {
text-decoration: underline;
}

.categories-widget li a:active {
text-decoration: underline;
}

and the :active pseudo selector will match when an element is currently being pressed down on by the mouse cursor. so it is doing the same thing..
try :
.categories-widget li a:hover {
    text-decoration: underline;
    }
.categories-widget li a:active {
position:fixed;
padding-top:1px;
color:red;
}


text:
Q: Confusion with explicit constructor invocation In the code that I have provided the overloaded constructor with argument which makes a call to the no-args constructor, which inturn should call the constructor of the object class in this case. So how does using the this() keyword execute the program correctly but not a direct call to the constructor.
public class S {

    S() {
        System.out.println("S()");
    }

    S(int i) {

        this();
        S();// The method S is undefined for type S
        System.out.println("S(int i)");
    }

    public static void main(String[] args) {
        S obj1 = new S();
        System.out.println("----------");
        S obj2 = new S(10);
        System.out.println("----------");

    }

}

A: Syntactically, S() is a method invocation, but you do not have a method called S.
this(); is special syntax for using another constructor in the same class.
To illustrate this point, I added:
void S() {
  System.out.println("Method S()");
}

It now compiles, and the output is:
S()
----------
S()
Method S()
S(int i)
----------

A: A constructor is defined to initialize (construct) objects, therefore you can't call it.
S s = new S();//Correct
S(); //Incorrect, you are calling a method not a constructor.
new S();//Correct

*

*this() is used to to pass arguments to constructor of the same class.

*super() is used to pass arguments to parent constructor.

This is called explicit constructor invocation.
Note that when invoking a constructor from another constructor, it must be the first statement of the constructor else it won't compile.

A: How to invoke other constructors of the same class is defined by The Java Language Specification, section 8.8.7.1 Explicit Constructor Invocations:

• Alternate constructor invocations begin with the keyword this
  (possibly prefaced with explicit type arguments). They are used to
  invoke an alternate constructor of the same class.
• Superclass constructor invocations begin with either the keyword
  super (possibly prefaced with explicit type arguments) or a Primary
  expression. They are used to invoke a constructor of the direct
  superclass.


text:
Q: Is it right for me to say Java forces programmers to use OOP while C++ does not? Java appears to force a programmer to use OOP the way I see it, while C++ does not so far as I am concerned....
I wish to know whether this is syntactically true for Java and C++

A: That is like saying Haskell forces programmer to use recursive calls. You can program procedurally in Java, and you can program with OOP mindset in C++. So neither answer is correct. But the concept is that in Java you should use OOP at all times and in C++ not, only if you wish so, but there is no one that can enforce it on you. (Maybe your boss by firing you, or SO being mean to you)
It is like firing a gun. You can either fire with the muzzle pointing at someone else (using OOP in Java) or look straight into the barrel while pulling the trigger (not using OOP in Java)


text:
Q: How to replace my power supply safely? If something is powered from a 9 V and 1 A supply, you can replace it with a 9 V and 1 or more amp supply. How would one calculate if it is safe to replace it with a less voltage and less amperage supply, lets say,

A:
How would one calculate if it is safe to replace it with a less voltage and less amperage supply

do not do it
You'd need to know specifications / test all components and need deep electric knowledge.


text:
Q: how to validate a same form in different button click using jquery edit-txt,updatePassword are two buttons in a single form superAdminDetailsForm . i want to valide this form in both button click. I wrote form validation on each button click .but it doesn't work. edit-txt button is type of text and update password is type of button
    $().ready(function() {$('#edit-txt').on('click', function() {
        $("#superAdminDetailsForm").validate({

                    rules: {
                        superadminEmail:{
                            required:true,
                            email:true
                        },
                    },
                    messages: {
                            superadminEmail:"Please enter your Email id"
                    },
                    submitHandler: function(){
                    var formData =$("#superAdminDetailsForm").serialize();
                        $.ajax({
                            url:'/accounts',
                            type:'post',
                            datatype: 'json',
                            data: formData,
                            success : function(response){
                                if(response == "true"){
                                    window.location='/accounts';
                                } else {
                                     alert("false")
                                }
                            },
                            error: function (request,status, error) {
                            }
                        });
                    return false;
                }
            });

    });

    $('#updatePassword').on('click', function()  {$("#superAdminDetailsForm").validate({

            rules: {
                oldPassword:"required",
                newPassword:"required",
                confirmpassword:{
                    require :"true",
                    equalTo : "#oldPassword"
                }
            },
             messages: {
                 oldPassword:"Please enter Old Password ",
                 newPassword: "Please enter New Password",
                 confirmpassword:"Retype password is incorrect"
             },
            submitHandler: function(){//to pass all data of a form serial
                 var formData =$("#superAdminDetailsForm").serialize();
                        $.ajax({
                            url:'/changePassword',
                            type:'post',
                            datatype: 'json',
                            data: formData,
                            success : function(response){
                                if(response == "true"){
                                    window.location = '/accounts';
                                } else {
                                    alert("password incorrect");
                                }
                            },
                            error: function (request,status, error) {
                            }
                        });
                    return false;
                }

        });
    });
});


text:
Q: Has the map $f:S^2 \to \mathbb{R} $ an antipodal point with the same image? The problem says that if $f:S^2 \to \mathbb{R} $ is continuous, then there exists a point $q\in S^2 $ such that $f(q)=f(-q)$.
I don't know how to prove it. Any help is welcome!

A: The B-U Theorem is hard to prove in dimension $2$ and greater, but simple in dimension $1$.  Here's how to get your result using the dimension $1$ version.
Borsuk-Ulam, $1$-dim:  If $g: S^1 \to \mathbb{R}$ is continuous then there is a point $x_0 \in S^1$ with $g(x_0) = g(-x_0)$.
Proof:  Suppose not, so that $g(x) \neq g(-x)$ for all $x$.   Define $h: S^1 \to \{\pm 1\}$ by the formula
$$
h(x) = \frac{g(x)-g(-x)}{|g(x)-g(-x)|}.
$$
This is well-defined because the bottom is never $0$.  Moreover, $h$ is clearly continuous and onto, but this contradicts the connectedness of $S^1$.  $\Box$
For your problem, embed $S^1$ into $S^2$ by the equator by the inclusion $i: S^1 \to S^2$.  Now apply the above theorem to $g=f \circ i$ where $f$ is your map $f: S^2 \to \mathbb{R}$.

A: It's a direct consequence of the Borsuk-Ulam theorem. Apply it to
$$g:S^2\to\mathbb{R}^2$$
$$g(v)=\big(f(v), 0\big)$$

A: When I read Randall's elegant and short proof, I realized that we can easily prove the follwing more general result:
Let $X$ be a nonempty connected topological space with a continuous involution $\iota : X \to X$ (which means that $\iota \circ \iota = id_X$). Then for any continuous $g : X \to \mathbb{R}$ there exists a point $x \in X$ such that $g(\iota(x)) = g(x)$.
We may apply this to $X = S^n$ and $\iota(x) = -x$.
Define $h : X \to \mathbb{R}, h(x) = g(\iota(x)) - g(x)$. This is a continuous map such that $h(\iota(x)) = -h(x)$ for all $x \in X$. We conclude
$(1) \phantom{.}$ If $y \in h(X)$, then also $-y \in h(X)$.
Define $U = h(X) \cap (-\infty,0)$ and $V = h(X) \cap (0,\infty)$. These are open subsets of $h(X)$ and $(1)$ implies
$(2) \phantom{.}$ If $h(X) \ne \{ 0 \}$, then $U, V \ne \emptyset$.
Assume $0 \notin h(X)$. Then $h(X) = U \cup V$ and $U, V \ne \emptyset$ by $(2)$. Therefore $h(X)$ is not connected which contradicts the fact that continuous images of connected spaces are connected.
Therefore $0 \in h(X)$ which proves the assertion.


text:
Q: time-column cleanup with substitutions I'm probably working with one of the craziest databases in the world, and I need to format exported time columns for a report. The problem is, the times in this column is imported from multiple sources, some with proper sql date format (2017-03-01 01:45:00.000), and some with the date set to server default, with only the time properly recorded (1900-01-01 00:45:00.000).
For example:
df$Date = c("2017-02-01 00:00:00.000", "2017-03-01 00:00:00.000", "2017-01-01 00:00:00.000")
df$Time = c("1900-01-01 03:30:00.000", "2017-03-01 04:45:00.000", "1900-01-01 05:50:00.000")

I need a result of:
properdatetime<- c("2017-02-01 03:30:00.000", "2017-03-01 04:45:00.000", "2017-01-01 05:50:00.000" )

I tried a mixture of chron & gsub, but no dice:
library(chron)
tmp <- c(df$Date)
tmp<-gsub('$.{1}', '', tmp2)

tmp2 <- c(df$Time)
tmp2<-gsub('^.{1}$', '', tmp2) #regex - keep last portion of column

df$properdatetime<- chron(dates.=tmp,times.=tmp2, format=c('y-m-d','h:m:s'))

I keep getting this error:
'Error in convert.dates(dates., format = format[[1]], origin. = origin.) :
  format y-m-d may be incorrect'

A: I basically used the regmatches + gregexpr combo to extract the dates from Date and times from Time and concatenated them to create propDateTime
Date = c("2017-02-01 00:00:00.000", "2017-03-01 00:00:00.000", "2017-01-01 00:00:00.000")
Time = c("1900-01-01 03:30:00.000", "2017-03-01 04:45:00.000", "1900-01-01 05:50:00.000")

Dates = regmatches(Date, gregexpr("^[[:digit:][:punct:]]+\\>", Date))
Times = regmatches(Time, gregexpr("\\<[[:digit:][:punct:]]+$", Time))

propDateTime = paste(Dates, Times)
propDateTime = as.POSIXct(propDateTime, format = "%Y-%m-%d %H:%M:%S")

# "2017-02-01 03:30:00 EST" "2017-03-01 04:45:00 EST" "2017-01-01 05:50:00 EST"

Here I used a as.POSIXct to store the data as a "DateTime" object, which preserves the hours, minutes and seconds. Notice that the datetime created is in the EST time zone. You can use the zone = argument to specify a difference time zone if it makes a difference.


text:
Q: Как передать переменную из JS скрипта в шаблон Django мой шаблон Django создает таблицу из модели:
'''

 {% for status in device_statuses  %}

      {{ status }}

 {% endfor %}

'''
При нажатии на  у меня открывается модальное окно вот таким кодом:

        <button type="button" class="close" data-dismiss="modal">×Close</button>

На просторах интернета я нашел, как передать значение из JS текстом:
$('#myModal').on('show.bs.modal', function (event) {
            // получить кнопку, которая его открыло
            var button = $(event.relatedTarget)
            // извлечь информацию из атрибута data-content
            var content = button.data('content')
            // вывести эту информацию в элемент, имеющий id="content"
            $(this).find('#content').text(content);
        });

Но никак не могу найти инфу, как мне передать из кода JS переменную, которую я могу использовать в форме? ну, например, передать {{status.id}} во всплывающее окно, чтобы там я мог сделать там форму и, к примеру, передать этот {{status.id}} во View.
заранее спасибо!


text:
Q: Rx .Net trigger an action based on objects datetime property (ie date passes from future to past) I'm fairly new to the reactive world so please forgive my ignorance.
I have an Observable stream of objects (coming from a DynamicData cache if that has any bearing) and I want to be able to trigger an action to update this object when a DateTime on this object elapses.
So for an example object:
    class TestObject
    {
        public DateTime TriggerDate { get; set; }

        public void SomeUpdate(string avalue) => Debug.WriteLine($"{DateTime.Now:HH:mm:ss} {avalue}");
    }

The best I can come up with is this and I'm not sure if it's the best way to do it, it feels a bit messy?
        var testobjects = new List<TestObject>
        {
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(4) },
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(8) },
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(12) },
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(16) },
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(20) },
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(24) },
            new TestObject{ TriggerDate = DateTime.Now.AddSeconds(28) },
        }.ToObservable();

        testobjects
            .Select(x =>
            {

                // return an observable (with the one item) that I can delay and subscribe on
                var updateStatus = Observable.Return(x)
                    .Delay(x.TriggerDate - DateTime.Now) // delay until the time passes
                    .Select(test =>
                    {
                        test.SomeUpdate("hi");

                        return test;
                    })
                    .Do(
                        _ => Debug.WriteLine("onNext"),
                        ex => Debug.WriteLine($"onException {ex.Message}"),
                        () => Debug.WriteLine("onComplete"))
                    .Subscribe();

                // needed ?
                //_cleanup.Add(updateStatus);

                return x;
            })
            .Subscribe();

A: What are you trying to do with that .Do section?
This code is nearly equivalent, with improved subscription handling, to what you have. The one difference is the 'onNext' message happens before the 'Hi':
testobjects
    .SelectMany(t => Observable.Return(t)
        .Delay(t.TriggerDate)
        .Do(
            _ => Debug.WriteLine("onNext"),
            ex => Debug.WriteLine($"onException {ex.Message}"),
            () => Debug.WriteLine("onComplete")
        )
    )
    .Subscribe(t => t.SomeUpdate("Hi"));

Edit:
SelectMany flattens whereas Select doesn't. In this case, if you were to use Select, your type going into the Subscribe would be IObservable<IObservable<TestObject>>: For each original TestObject in the observable, we create an observable that has a single TestObject. SelectMany flattens that into IObservable<TestObject>. You could accomplish the same effect with Merge. Select(f).Merge() is roughly equal to SelectMany(f).
Regarding Subscribe actions: I'm guessing you mis-read something; I would recommend the opposite. Observables should have pure-functional code; subscriptions are the best place for side-effects.


text:
Q: In VUE2, the WangEditor rich text editor is used to probabilistically trigger unknown errors in the parent component When opening the rich text editor in the parent component, an error is probably, only the click behavior, and the rich text content and other behaviors are not modified
[enter image description here][1]
[enter image description here][2]
The error message is
[Vue warn]: Error in mounted hook: "Error: Cannot find a descendant at path [0,1] in node: {"children":[{"type":"paragraph","children":[{"text":"给定以下 JSP 代码片段:"}]},{"type":"pre","children":[{"type":"code","language":"","children":[{"text":"<% int x = 1; %>\n<%! int x = 10; %>\nx = <%=x++%>"}]}]},{"type":"paragraph","children":[{"text":"有"},{"text":" 2 "},{"text":"个客户依次浏览该"},{"text":" JSP"},{"text":",且每个客户只浏览一次,则第"},{"text":"2 "},{"text":"个客户会看到浏览器显示()"}],"indent":"28px"},{"type":"paragraph","children":[{"text":""}]}],"operations":[{"type":"merge_node","path":[0,1],"position":4,"properties":{}},{"type":"merge_node","path":[0,1],"position":9,"properties":{}}],"selection":null,"marks":null,"id":"wangEditor-1","isDestroyed":false,"isFullScreen":false,"history":{"undos":[[{"type":"merge_node","path":[0,1],"position":4,"properties":{}},{"type":"merge_node","path":[0,1],"position":9,"properties":{}}]],"redos":[]}}"

vue.runtime.esm.js?2b0e:3047 Error: Cannot find a descendant at path [0,1] in node: {"children":[{"type":"paragraph","children":[{"text":"给定以下 JSP 代码片段:"}]},{"type":"pre","children":[{"type":"code","language":"","children":[{"text":"<% int x = 1; %>\n<%! int x = 10; %>\nx = <%=x++%>"}]}]},{"type":"paragraph","children":[{"text":"有"},{"text":" 2 "},{"text":"个客户依次浏览该"},{"text":" JSP"},{"text":",且每个客户只浏览一次,则第"},{"text":"2 "},{"text":"个客户会看到浏览器显示()"}],"indent":"28px"},{"type":"paragraph","children":[{"text":""}]}],"operations":[{"type":"merge_node","path":[0,1],"position":4,"properties":{}},{"type":"merge_node","path":[0,1],"position":9,"properties":{}}],"selection":null,"marks":null,"id":"wangEditor-1","isDestroyed":false,"isFullScreen":false,"history":{"undos":[[{"type":"merge_node","path":[0,1],"position":4,"properties":{}},{"type":"merge_node","path":[0,1],"position":9,"properties":{}}]],"redos":[]}}
at Object.get (index.esm.js?cb23:2487:1)
at Object.first (index.esm.js?cb23:2416:1)
at Object.path (index.esm.js?cb23:1648:1)
at Object.nodes (index.esm.js?cb23:1474:1)
at nodes.next (<anonymous>)
at eval (index.esm.js?cb23:4568:1)
at Object.withoutNormalizing (index.esm.js?cb23:2243:1)
at Object.mergeNodes (index.esm.js?cb23:4522:1)
at normalizeNode (index.esm.js?cb23:380:1)
at o.normalizeNode (index.esm.js?cb23:17547:1)

I didn't find the error on the Internet, so I used Props in the sub-component for parent-child component communication, listen through the watch function, and destroyed the editor
<Editor
  :style="editorStyle"
  v-model="html"
  :defaultConfig="editorConfig"
  :mode="mode"
  @onCreated="onCreated"
  @onChange="onChange(html)"
/>

beforeDestroy() {
  const editor = this.editor
  if (editor == null) return
  editor.destroy()
},
watch: {
  html(newValue) {
    this.$emit('input', newValue)
  },
  value(newValue) {
    this.html = newValue
  }
}

When opening the form while editing, variables are assigned values through encapsulated Axios requests
  <WangEditor v-model="form.content"
      :editorStyle="{ height: '220px' }"
      @itemUpdate="uploadQuestionInfoImage"
      ref="itemWE"></WangEditor>

  this.form.content = questionData.content


text:
Q: How to recognize if there are any categorical variables that should be encoded as factors in a data.frame? I have the following data.frame. How can I recognize if there is any categorical variable that should be encoded as factors in a data.frame?
  YEAR  PBE  CBE  PPO  CPO  PFO DINC  CFO RDINC RFP
1  1925 59.7 58.6 60.5 65.8 65.8 51.4 90.9  68.5 877
2  1926 59.7 59.4 63.3 63.3 68.0 52.6 92.1  69.6 899
3  1927 63.0 53.7 59.9 66.8 65.5 52.1 90.9  70.2 883
4  1928 71.0 48.1 56.3 69.9 64.8 52.7 90.9  71.9 884
5  1929 71.0 49.0 55.0 68.7 65.6 55.1 91.1  75.2 895
6  1930 74.2 48.2 59.6 66.1 62.4 48.8 90.7  68.3 874
7  1931 72.1 47.9 57.0 67.4 51.4 41.5 90.0  64.0 791
8  1932 79.0 46.0 49.5 69.7 42.8 31.4 87.8  53.9 733
9  1933 73.1 50.8 47.3 68.7 41.6 29.4 88.0  53.2 752
10 1934 70.2 55.2 56.6 62.2 46.4 33.2 89.1  58.0 811
11 1935 82.2 52.2 73.9 47.7 49.7 37.0 87.3  63.2 847
12 1936 68.4 57.3 64.4 54.4 50.1 41.8 90.5  70.5 845
13 1937 73.0 54.4 62.2 55.0 52.1 44.5 90.4  72.5 849
14 1938 70.2 53.6 59.9 57.4 48.4 40.8 90.6  67.8 803
15 1939 67.8 53.9 51.0 63.9 47.1 43.5 93.8  73.2 793
16 1940 63.4 54.2 41.5 72.4 47.8 46.5 95.5  77.6 798
17 1941 56.0 60.0 43.9 67.4 52.2 56.3 97.5  89.5 830

Is this a correct answer?
yes! factor(beef$PBE) has 14 levels, factor(beef$PPO) has 16 levels, factor(beef$CFO) has 15 levels, and the rest cannot be encoded as factor because they have complete 17 levels.

A: Your exact question is: "How can I recognize if there is any categorical variable that should be encoded as factors in a data.frame?". Use of "should" here is the crucial part. Why do we encode things as factors anyway?
Factors are used when data are restricted to a number of discrete levels, such as "red", "orange",  or "green" for the colour of a traffic light (yes, some countries have "red+orange", or "flashing orange" as well, add these to the levels of your factor). An ordered factor is used when data is categorical but has a defined order, such as "small", "medium", "large, or "extra large".
If your data is numbers, it is most likely that it should remain as numbers, unless it is already a numerical coding for an underlying category (eg 1=male, 2=female). There's very few reasons to convert anything else numeric into factors unless you have only a few values and statistical analysis using categorical methods makes more sense than continuous numerical methods.

A: Spacedman makes some very good points that it is in general not desirable to create factors from numeric data willy-nilly. For visualization or some modeling approaches it can be useful, though. I use the utility function below to replace columns with few distinct entries in a data.frame by (ordered) factors, I post it below with an example:
make_factors <- function(data, max_levels=15) {
    # convert all columns in <data> that are not already factors
    # and that have fewer than <max_levels> distinct values into factors.
    # If the column is numeric, it becomes an ordered factor.

    stopifnot(is.data.frame(data))
    for(n in names(data)){
        if(!is.factor(data[[n]]) &&
                length(unique(data[[n]])) <= max_levels) {
            data[[n]] <- if(!is.numeric(data[[n]])){
                 as.factor(data[[n]])
            } else {
                 ordered(data[[n]])
            }
        }
    }
    data
}

# create dataset with one numeric column <foo> with few  distinct entries
# and one character column <baz> with few  distinct entries :
data <- iris
data <- within(data, {
     foo <- round(iris[, 1])
     baz <- as.character(foo)
})

table(data$foo)

## 4  5  6  7  8
## 5 47 68 24  6

str(data)

## 'data.frame':    150 obs. of  7 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ baz         : chr  "5" "5" "5" "5" ...
##  $ foo         : num  5 5 5 5 5 5 5 5 4 5 ...

str(make_factors(data))

## 'data.frame':    150 obs. of  7 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ baz         : Factor w/ 5 levels "4","5","6","7",..: 2 2 2 2 2 2 2 2 1 2 ...
##  $ foo         : Ord.factor w/ 5 levels "4"<"5"<"6"<"7"<..: 2 2 2 2 2 2 2 2 1 2 ...


text: Q: Where can I see log from pub/sub api error for specific method? I'm installing a pipeline with Terraform on GCP. The pipeline is not working but I'm not seeing any errors being logged. However when looking at Cloud Pub/Sub API service details I can this that the error rate for the following method google.pubsub.v1.Subscriber.StreamingPull is at 100%. How can I have access the detail of these errors?


text:
Q: Can't boot into ubuntu after installing I just installed Ubuntu at my HP Pavillion H8 computer with 8gb RAM and a Intel Core i7 CPU, and for some reason I can't boot into Ubuntu. When looking in the msconfig boot menu, the only OS listed is Windows 7. Also I can't seem to find the "OS selection screen" in my boot menu. When the HP logo appears, I press esc to interrupt normal boot, and I get this screen with a lot of options. I tried all of them, and none of them seems to have a "OS Selection Screen".
I installed Ubuntu 12.04.2 using a CD.
Thanks in advance.
EDIT: I read this article, which said that Ubuntu made itself the default OS when installed. That's not the case here. I can't even get into it. http://www.psychocats.net/ubuntu/bootmenu
EDIT2: I've just checked my remaining space in the C: drive in Windows. And yes, the partition were successfull, I have less space for Windows (which means more space for Ubuntu, I think). So from that I can conclude that my installation weren't cancelled.

A: *

*Download Boot repair disk ISO. Link for boot repair disk: http://sourceforge.net/projects/boot-repair-cd/files/

*Using universal USB installer create bootable USB with Boot repair disk ISO. Universal USB installer link: http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/

*Restart the computer with the USB flash drive. Keep pressing F8/12 or ESC depending on your computer and select boot option.

*Select USB flash.

*Computer will be booted with boot repair disk. Select the option for repairing grub.

*Restart your computer, it will be ok.


text:
Q: Is there any easy way to generate sequencial IDs starting from one based on another ID using spring boot? I have used Spring Boot's SequenceStyleGenerator to generate custom formatted IDs.
For example ORG0001, USR0001, VEH0001, etc. They work perfectly but independently.
I need to create a hierarchical ID flow like this.
The top of the hierarchy is Organization.
(Organization ID can be ORG0001. This can be achieved using Spring's SequenceStyleGenerator.)
Every other object ID's should automatically get its ID sequence number based on the organization. The first child object that relates to the organization must start from 1.
For Example, let's say, IDs of user objects and vehicle objects of each organization should start from 1 and continue. Like below.
ORG0001 - USR0001, USR0002, USR0003

        - VEH0001, VEH0002, VEH0003

ORG0002 - USR0001, USR0002

        - VEH0001, VEH0002, VEH0003

Any Clue is appreciated!


text:
Q: How to select random value from iOS picker wheel using Selenium I am performing my automation in real IOS device.
In one of the aspect I have to automate a picker wheel

xpath:
//UIAApplication[1]/UIAWindow[1]/UIAPopover[1]/UIAPicker[1]/UIAPickerWheel[1]

I would like to select a random value from picker. I can able to do the by sending static value using SendKeys. Instead of the I want to select a random value.
Can I please know how can I do that using java??

A: Two ways to do this :

*

*Randomise the UIAPickerWheel[1] index while you are using the x-path to access the elements.

*You can put all possible static values into an ArrayList and use a random element from amongst them to input using the sendKeys() in way some-what like this :
ArrayList<String> list = new ArrayList<String>();
list.add("value1");
list.add("value2"); // so on for all your values
Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
element.sendKeys(random);

A: Not sure if anyone would still need this. But just in case this could help somebody out there...
Here's an adaptation of the code in Nexial Automation:
val index = RandomUtils.nextInt(0, 7)
// index = 3

val picker = driver.findElement(By.xpath("//XCUIElementTypePickerWheel"))
val currentPickedValue = picker.getAttribute("value")
val pickerId = picker.id

// if picker already has selection, we'll swipe to top of the dropdown first
if (StringUtils.isNotBlank(currentPickedValue))
    driver.executeScript(
        scriptScript,
        mapOf<String, Any>("element" to pickerId, "direction" to "down", "velocity" to 250))

// magic number 25 (per dropdown option)
val scrollAmount = 25.0 / picker.size.height

for (i in 0 until index)
    driver.executeScript(
        scriptSelectPickerValue,
        mapOf<String, Any>("element" to pickerId, "order" to "next", "offset" to scrollAmount))

The code is written in Kotlin. If you know Java/JavaScript/C#, then the above should be reasonably comprehensible.
The magic number is derived via some online research and trial-and-error. Seems to work fine so far.
I randomized index as an integer between 0 to 7. Feel free to change index to something else.
This code has only been tested on XCUITest driver.

A: Consider moving your view interaction methods to Appium iOS Gestures which does pretty much the same as you did in your script but 'from the box'
Pickerwheel gesture


text:
Q: Object properties updating between instances C# I have got 4 instances of a service class within a WPF application that is updating all 4 instances when one of the complex properties change, the same changes are applied to all the instances.
The class looks like this:
public class ExampleClass
{
    private IEnumerable<SomeComplexType> _status;
    public int InstanceNumber { get; set; }

    public IEnumerable<SomeComplexType> Status
    {
        get { return _status; }
        set { _status = value; }
    }

    public Task DoSomeWork()
    {
        var t = Task.Run(() =>
        {
            var random = new Random();
            int i = 1;
            foreach (var item in Status)
            {
                item.SomeValue = random.NextDouble();
                item.ItemNumber = (InstanceNumber*i);
                i++;
            }
            UpdateInterface();
        });
        return t;
    }

    public void UpdateInterface()
    {
        var message = new UpdateMessage {InstanceNumber = InstanceNumber, Status = Status};
        Messenger.Default.Send(message);
    }
}

With the supporting types being similar to the following:
    class SomeComplexType
{
    public double SomeValue { get; set; }
    public int ItemNumber { get; set; }
}

class  UpdateMessage
{
    public int InstanceNumber { get; set; }
    public IEnumerable<SomeComplexType> Status { get; set; }
}

Now when the DoSomeWork() method is called on instance 1, it works as expected.
Same when the DoSomeWork() method is then called on instance 2, but after instance 2 has updated, the UpdateInterface() function on instance 1 returns the status value of instance 2, even though the correct instance number is returned.
Can anyone explain this behavior?
The calling code is a simple function triggered by a button press:
public ICommand OnTestClickCommand
{
    get { return _onTestClickCommand ?? (_onTestClickCommand = new RelayCommand(ButtonTestClick); }
}

private async void ButtonTestClick()
{
    await ExampleClass.DoSomeWork;
}

EDIT:
The problem was in the ctor of each class, which looked like this:
    public ExampleClass(SomeDefaultClass default)
    {
        Status = default.Status;
    }

The same default variable was passed in when creating each instance. Should have included that in the original ask. This only passes the reference as stated in the comments.


text:
Q: Short film where man repeats a few minutes of his life in a loop I remember seeing, years ago, a short film about a guy who gets stuck in a time loop and is forced to relive the same few minutes of his life over and over.
In one iteration, he talks to his smart aleck secretary. In another, he meets a woman in the park. He uses each iteration to find out more about what's going on. I think he even finds the scientist responsible for his problems. Eventually, he goes nuts and I think he kills himself.
What short film was this?

A: The 1990 film, 12:01 PM involves a man stuck in an hour-long time loop who confronts the scientist responsible, confronts his secretary, and tries to exit the loop by shooting himself. There was a 1993 remake, 12:01 involving a 24 hour time loop. They're both based on a short story, 12:01 PM by Richard A. Lupoff.
You can view both versions below (no guarantees that the links will stay up):
12:01 PM

12:01


text:
Q: Simple Harmonic Motion: Relation between angular motion and linear to and from motion What is angular frequency in simple Harmonic Motion?
If simple harmonic motion is a linear to and fro motion then whose angular frequency are we talking about? A linearly moving body cannot have an angular frequency right? I know that we compare it with uniform circular motion, but then how can we associate angular quantities for linear translation? Is the frequency associated to the air particle/surrounding particles that disturbed due to that SHM?
And why was the motion compared to UCM only?

A: Simple harmonic motion is not just to and fro motion - it is to and fro motion where the displacement from the central position over time follows a sine wave. There are other types of to and fro motion which are not simple harmonic motion - for example, where the displacement from the central position over time follows a triangle wave rather than a sine wave.
The connection with uniform circular motion is that simple harmonic motion is the projection on the x-axis of the position of an object moving with uniform circular motion in the x-y plane. If the object is moving in a circle of radius $R$ with frequency $f$ then at time $t$ its position is
$\left(R\sin (2\pi f t), R\cos (2\pi f t)\right)$
so the projection of its position on the x-axis is $R \sin(2\pi f t)$. A particle moving with simple harmonic motion $x(t)=R \sin(2\pi f t)$ is said to be moving with frequency $f$ because it takes $\frac 1 f$ seconds to move from one extreme point $x=R$ to the opposite extreme point $x=-R$ and back again.

A: Simple harmonic motion is a clockwise rotation about the unit circle in the scaled phase space coordinates $(x/x_{xmax},\quad v/x_{max}\omega)$.   If the oscillator is a mass $m$ on a spring constant $k$, then $\omega=\sqrt{\frac{k}{m}}$.
$$
\begin{align}
x &=x_{max}\quad\cos(\omega t) \\
v=\frac {dx}{dt} &=-x_{max}\omega\quad sin(\omega t) \\
\end {align}
$$
Notice that
$$
 (\frac{x}{x_{max}})^2 + (\frac{v}{x_{max}\omega})^2=1 \\
$$
$$
\begin{bmatrix}
x/x_{max}\\
v/x_{max}\omega\\
\end{bmatrix}_t=
\begin{bmatrix}
cos(\omega t) & sin(\omega t) \\
-sin(\omega t) & cos(\omega t)  \\
\end{bmatrix}
\begin{bmatrix}
1\\
0\\
\end{bmatrix}_{t=0}
$$


text:
Q: postfix in a jail how to notify blacklistd running in main host I have postfix compiled with blacklistd support running in a jail.
On the main host (FreeBSD 12.1) blascklistd is running with this config:
# Blacklist rule
# adr/mask:port type    proto   owner           name    nfail   disable
[local]
submission      stream  *       *               *       2       24h

How to configure postfix to notify blacklistd running on the main host?

A: Just add another socket to blacklistd in base
vim /etc/rc.conf
blacklistd_enable="YES"
blacklistd_flags="-r -s /var/run/blacklistd.sock"
blacklistd_jails="jail1 jail2"
for i in ${blacklistd_jails}
do
        blacklistd_flags="${blacklistd_flags} -s /jail/${i}/var/run/blacklistd.sock"
done

The programs in the jails (postfix, sendmail, sshd) just report to the default socket.


text:
Q: Special symbols used in syntax definition I always see syntax definition of sql clauses as the following:
http://msdn.microsoft.com/en-us/library/ms174123.aspx
ALTER TABLE table_name
ALTER COLUMN column_name
   {
    type_name[({precision[.scale]})][NULL|NOT NULL]
   {DROP DEFAULT
   | SET DEFAULT constant_expression
   | IDENTITY [ ( seed , increment ) ]
   }
| ADD
   { < column_definition > | < table_constraint > } [ ,...n ]
| DROP
   { [ CONSTRAINT ] constraint_name
   | COLUMN column }
] }
< column_definition > ::=
   { column_name data_type }
   [ [ DEFAULT constant_expression ]
      | IDENTITY [ ( seed , increment ) ]
   ]
   [ROWGUIDCOL]
   [ < column_constraint > ] [ ...n ] ]
< column_constraint > ::=
   [ NULL | NOT NULL ]
   [ CONSTRAINT constraint_name ]
   {
      | { PRIMARY KEY | UNIQUE }
      | REFERENCES ref_table [ (ref_column) ]
      [ ON DELETE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ]
      [ ON UPDATE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ]
   }
< table_constraint > ::=
   [ CONSTRAINT constraint_name ]
   { [ { PRIMARY KEY | UNIQUE }
      { ( column [ ,...n ] ) }
      | FOREIGN KEY
        ( column [ ,...n ] )
        REFERENCES ref_table [ (ref_column [ ,...n ] ) ]
      [ ON DELETE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ]
      [ ON UPDATE { CASCADE | NO ACTION | SET DEFAULT |SET NULL } ]
   }

I know the basic meanings of the signs like "|", but where I can get a full explanation of all these signs such as "{", "[", etc?

A: It's called Backus Naur form, or more specifically Extended Backus Naur form, which is meant to be more human readable and less formal.
http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form goes over it thoroughly.

A: *

*Pipe means "or"

*Curlies mean "block can be repeated"

*Squares mean "clause is optional"

*Parens are real SQL


text:
Q: Worksheet_Calculate() - Record dates when a cell's value is changed I am a beginner in VBA.
I have a Column "AA" can have multiple values, driven by formula of which 2 are "Impact Assessed" or "Ready for retesting".
Problem Statement - I want to record the dates when cell's value is changed to Impact Assessed and Ready for Retesting in 2 separate columns - Column B and Column C, respectively. I also want the ability of the macro to run if I copy-paste more than 1 cells triggering the change in my Column AA.
Below is my code -
Private Sub Worksheet_Calculate()

Dim rng As Range
  If Target.CountLarge > 1 Then Exit Sub
Set rng = Application.Intersect(Me.Range("AA:AA"), Target)

If Not rng Is Nothing Then
    Select Case (rng.Value)
        Case "2 - Impact Assessed": rng.Offset(0, 1).Value = Date
        Case "4 - Ready for retesting": rng.Offset(0, 2).Value = Date
    End Select
End If

End Sub

A: Something like this:
Private Sub Worksheet_Calculate()

    Dim rng As Range, c As Range, v

    'get all cells with formulas
    On Error Resume Next
    Set rng = Me.Range("A:A").SpecialCells(xlCellTypeFormulas)
    On Error GoTo 0

    'got some cells - loop over each cell
    If Not rng Is Nothing Then
        For Each c In rng.Cells
            'make sure there's no error
            If Not IsError(c.Value) Then
                Select Case c.Value
                    Case "2 - Impact Assessed"
                        AddDateIfEmpty c.Offset(0, 1)
                    Case "4 - Ready for retesting"
                        AddDateIfEmpty c.Offset(0, 2)
                End Select
            End If
        Next c
    End If
End Sub

'utility sub: add date only if not already present
Sub AddDateIfEmpty(c As Range)
    If Len(c.Value) = 0 Then c.Value = Date
End Sub


text:
Q: How can I get MATLAB to display radians in terms of pi? I am trying to make a programme to convert cartesian coordinates to polar coordinates.
My calculator returns arctan(1) as pi/4.
MATLAB on the other hand returns atan(1) as 0.7854.
How can I get MATLAB to return numbers like this as expressions of pi?

A: As you've stated this is just for a quick visual check, I would just divide by pi:
n = 0.7854;
disp(['n in terms of pi: ', num2str(n/pi), '*pi']);
>> n in terms of pi: 0.25*pi

If this was something you wanted to often do, I would define some function on your local path like so
function [val, str] = wrtpi(n)
% Returns the value of n with respect to pi
    val = n/pi;
    % Could include some rounding checks here if you wanted to complicate things
    % ... *checks* ...
    str = ['n in terms of pi: ', num2str(n/pi), '*pi'];
end

Then
n = 0.7854;
[val, str] = wrtpi(n)
>> val = 0.25
   str = n in terms of pi: 0.25*pi

You also say this is just for identifying radian quadrants, aside from learning them, you could also just have a simple function
function q = quadrant(n)
    Qs = pi*[0, 1/2, 1, 3/2];               % Quadrants
    q = find(Qs <= mod(n,2*pi), 1, 'last'); % Index within the quadrants
    % You could make this accept vector inputs using:
    % q = arrayfun(@(x) find(Qs <= mod(x,2*pi), 1, 'last'), n)
end

Then
quadrant(2*pi - 0.0001) % >> 4
quadrant(0.2)           % >> 1
quadrant(1.6)           % >> 2

Note that using the symbolic math toolbox for something as simple as this will likely cause more complications and slowdown than it helps!

A: For some particular values of pi you can use symbolic numbers, for example:
atan(sym(1))
ans =
pi/4

asin(sym(3^.5/2))
ans =
pi/3

Note that this requires the Symbolic Math Toolbox.


text:
Q: update fork to upstream regularry I have the fork of some very huge and actively developed project. Usually I update to upstream every 2 month, but this process very painful - it takes a week, work stops, and after merge many bugs appear.
At fist I tried just git rebase but there ware a lot of conflicts on every commit, so I decided squash all my changes to 1 commit and rebase it on upstream, but I loose my commit history.
Are there any approach to make this process less painful?

A: I don't know but:

Usually I update to upstream every 2 month, but this process very painful - it takes a week, work stops, and after merge many bugs appear.

I think, that if you are 2 months behind on an actively developed master you are begging for trouble.

*

*I suggest you make smaller features. Perform smaller merges more often. But this might not be feasible if you can't split your features.

*Or, merge master into your feature branch to test it, then update upstream.
You have to test it anyway. That way the bugs appear with you, and not with the maintainers.

A: If you have to maintain own patches over fast changing project there is no magic button. git rebase is a right tool for this because does good job of bookkeeping but it cannot resolve conflicts by itself. There are some things which may help you. They are mostly irrelevant to technology you use.

*

*(as suggested by other answer) try to update more often, and add unit tests

*make your changes smaller, do not try to fix upstream coding style etc. Disable in your IDE automatic reformatting. Sometimes it makes sense to violate the style regarding for example indentation.

*structure carefully your changes. Divide it into commits like:

*

*non-functional refactoring of the upstream code, which is going to prepare project for your features inclusion. They will conflict almost always but you can redo them relatively easily from scratch if you have high-level description around (like "extract X functionality into function with Y name")

*pieces of logic which is exclusive to you features implemented in new files added by you. Then they would never conflict.

*inclusion of your features into the project by adding or changing couple of lines here and there. They would sometimes conflict but should be easy to redo.

*contribute your changes upstream, fully or partly


text:
Q: vba/Office: How to get the server name as a string from an "Application" object? Is there a way to get the server name as a string from an "Application" object using vba?
An example of code is:
Option Explicit
Sub Test()
    Dim SrvrName As String
    SrvrName = Application.ServerName 'Pseudocode
End Sub

An example of output is: "Excel.Application", "Outlook.Application", "Word.Application", etc.
I have need to pass this string to an external vbscript file. This string must change dynamically depending on the application in use.

A: I think you're after the TypeName() function.
Sub test()
Dim oExcelApp as Variant
Set oExcelApp = Application
MsgBox TypeName( oExcelApp ) 'Outputs: "Application"
End Sub


text:
Q: When will an object fail to cast to its parent class in Java? I'm having the same issue as ClassCastException in ant schemagen task using jaxb-ri-2.2.7. However, my biggest question is not about the issue itself, but the exception in the error log:
java.lang.ClassCastException: com.sun.tools.javac.api.JavacTrees cannot be cast to com.sun.source.util.Trees

By looking into the problem, I found that JavacTrees is a child class of DocTrees, and DocTrees is a child class of Trees. Specifically, the class definitions are:
public class JavacTrees extends DocTrees {
    // ...
}

public abstract class DocTrees extends Trees {
    // ...
}

public abstract class Trees {
    // ...
}

The above ClassCastException basically means that an object failed to cast into its parent class. I don't remember anything like that in any textbook I read.
Can somebody explain this exception to me? Thanks.

A: Thanks @OHGODSPIDERS for the hint about ClassLoaders. I checked the class loaders of JavacTrees and Trees using a debugger, and here's the results:

*

*com.sun.tools.javac.api.JavacTrees was loaded by java.net.FactoryURLClassLoader

*com.sun.source.util.Trees was loaded by org.codehaus.plexus.classworlds.realm.ClassRealm
Therefore, the 2 classes are loaded by different ClassLoaders. Hence it will fail to cast from JavacTrees to Trees, even though Trees is the parent class of JavacTrees.


text:
Q: Wordpress 4 and wp_editor() Not Showing Visual/Text tabs I use wordpress a lot, i develop for it a lot too!
I have a client website that i have added 10 custom meta boxes to the post edit screen in functions.php . All the meta boxes have an editor using wp_editor()
This all worked find in wordpress 3.8 and 3.9 but now the site has been upgraded to wordpress 4 the editor is refusing to show the visual/text tabs on the editor pane.
I have verified this by deactivating all plugins on my development copy, and the issue persisted. I then installed a second copy of wordpress but 3.9 and the tabs came back!
Any idea why this is happening on wordpress 4?

A: Yes as per @Nibbr Web Development, TinyMCE editor IDs cannot have brackets. Which is the html field ID, so what we will do is create a different but similiar name for the ID attribute and still use our desired name in for the text area field name, like so.
$content = $options['textareafield'];
// editor_id cannot have brackets and must be lowercase
$editor_id = 'textareafield';
// textarea_name in array can have brackets!
$settings = array('media_buttons' => false, 'textarea_name' => 'my_options[textareafield]');
wp_editor($content, $editor_id, $settings);

This should solve this problem. Also for those of you that have problems with the popup windows such as inserting a link.

A: Just in case anyone else is having this problem, I've found that a pretty reliable way to get your visual editor tab back after upgrading to Wordpress 4.0 is:

*

*disable all plugins

*Change the theme to one of the defaults (e.g. TwentyFourteen)

*Go to "my profile" and check the "disable visual editor" box.

*Save

*Go back to "my profile" and uncheck the "disable visual editor" box.

*Save

Voila, your edit posts and pages screens should now have the editor tabs back. You can now swap themes back to whichever you want to use.

A: Another reason can be using custom user agent. WP does not recognise it as supported browser, and so these buttons are disabled. So check if $_SERVER['HTTP_USER_AGENT'] value is correct.
Also you can force using rich editor buttons with user_can_richedit filter.
add_filter('user_can_richedit', 'user_can_richedit_custom');
function user_can_richedit_custom($value){
    $value = true;
    return $value;
}


text:
Q: If $\int _1^{\infty }f\left(x\right)dx$ converges absolutely then $\int _1^{\infty }\sin \left(x\right)f\left(x\right)dx$ exists I'm in need of some assistance with a homework question (I'm doing some calculus work by myself and have gotten stuck on this question):
"Prove or give a counter-example of of the following statement:
Let there be a continuous function $f :[0,\infty) \rightarrow \mathbb{R}.$
If $\int _1^{\infty }f\left(x\right)dx$ converges absolutely then
$\int _1^{\infty }\sin \left(x\right)f\left(x\right)dx$ exists"
OK so I know how to disprove the statement if it would have been prove if exists then exists. (Using $\frac{\sin \left(x\right)}{x}$ ) but I can't seem to make any progress for what they actual ask regarding converges absolutely.
Any help is appreciated. Thx!

A: Note that $\int_1^\infty |f(x)sin(x)|dx\leq \int_1^\infty |f(x)|dx<\infty$, hence the integral $\int_1^\infty f(x)sin(x) dx$ converges absolutely and exists.


text:
Q: "Manually" invoke expose event on gtk.DrawingArea I'm creating a small tool for data visualization.
The GUI is created with Pygtk and very simple. After the user has entered a filename he can press the button "calc" to see the output. The output is rendered by pycairo and presented in a gtk.DrawingArea.
The application works as following:
When the button is pressed the file is processed and its content is stored in a special class. This class is a custom container: It's instantiated together with the gui and either empty or filled. The DrawingArea's expose event is linked to a drawing function that reads the container and draws its content. As long as the container is empty the DrawingArea remains empty but after calc has been clicked and a file was loaded the DrawingArea should be filled with my visuals.
The problem is:
Everything works fine, except of updating the DrawingArea. I can't figure out how to manually invoke expose. After pressing calc I have to resize the window to see the result.
More specific:
I've copied this code from a tutorial and don't know how to provide the parameter event myself:
def do_expose_event(self,event):
    # Create the cairo context
    cr = self.window.cairo_create()

    # Restrict Cairo to the exposed area; avoid extra work
    cr.rectangle(event.area.x, event.area.y,
            event.area.width, event.area.height)
    cr.clip()

    self.draw(cr, *self.window.get_size())

A: In order to have your widget refreshed, you need to tell GTK+ that it needs to be redrawn, typically using gtk.Widget.queue_draw() (called as self.queue_draw()), which invalidates your entire widget and schedules a redraw (by emitting expose events) that will take place after your program returns to the main loop.
If you need more control over the region being redrawn, you can always use gtk.Widget.queue_draw_area() to specify an area to invalidate, or go all the way down to gtk.gdk.Window.invalidate_rect().

A: You've written a event callback, which you need to connect to the expose event like so:self.connect("do_expose_event", self.expose) in the __init__ method of your object.

A: Call self.draw() from the calc handler and forget about making a fake event structure to pass to expose.
But if you insist on misusing do_expose_event() by calling it directly, you don't need to create an entire event structure, just call it with the one element it references (event.area) set to the window geometry so that nothing gets clipped.


text:
Q: interface method where T2 : T Check out this snippet
public interface IExample<T>
{
    IExample<T> Exposes<TInclude>()
        where T : TInclude;
}

I'm looking to compile time enforce that T is castable to TInclude.  Could do a runtime check, but would prefer it to be compile time.
The above complains that T isn't defined.
Any suggestions?  Is what I'm trying to do possible with C# generics?

A: Rephrasing your question:

It is possible to make a where clause that enforces the constraint that TInclude is T or any type derived from T. I'm looking to enforce the "opposite direction" constraint: that TInclude is T or any "base type" of T. Is this possible?

No. C# doesn't support that kind of constraint. Sorry.

Any suggestions?

Scala supports that kind of constraint I think. As does Java, though the way Java does it is a bit odd. But I suppose you don't want to change languages.
Can you describe in more detail the concept you actually want to represent with this interface? If we know what you're trying to do then it will be easier to give you pragmatic advice.

A: You can move the type constraint to the interface level, like that:
public interface IExample<T, U>
    where T : U
{
    IExample<T, U> Exposes();
}

A: It could be implemented someday: see 1.2 Generalized Constraints


text:
Q: Using svyciprop across two variables I have been looking at how to calculate the CI for proportions across two categorical variables. I have seen this answer, which gets close to what I am looking for, but I am wanting the proportions to be calculated between all possible combinations of the two variables. I have gotten it to work using svymeans and confint and this is the output I am looking for, but using svyciprop. This example comes from the api data in the survey package using the apiclus1 data frame.
library(survey)
data(api)
dclus1<-svydesign(id=~dnum, fpc=~fpc, data=apiclus1)
cbind(svymean(~interaction(sch.wide, stype), design = dclus1),
  confint(svymean(~interaction(sch.wide, stype), design = dclus1)))
                                                   2.5 %     97.5 %
interaction(sch.wide, stype)No.E  0.06557377  0.031454436 0.09969311
interaction(sch.wide, stype)Yes.E 0.72131148  0.635732262 0.80689069
interaction(sch.wide, stype)No.H  0.01639344 -0.002458860 0.03524575
interaction(sch.wide, stype)Yes.H 0.06010929  0.018347771 0.10187081
interaction(sch.wide, stype)No.M  0.04371585  0.005196326 0.08223537
interaction(sch.wide, stype)Yes.M 0.09289617  0.050121072 0.13567128

A: thanks for the minimal reproducible example.  there might be a cleaner way to do this, but i think it's what you're after?  thanks
library(survey)

data(api)

dclus1<-svydesign(id=~dnum, fpc=~fpc, data=apiclus1)

# figure out the levels
levels <- svytable( ~ interaction(sch.wide, stype) , dclus1 )

# calculate svyciprop zero/one for each possible level
svyciprop_fun <-
    function( this_level , ci = FALSE , ... ){
        this_formula <- as.formula( paste0( "~as.numeric( '" , this_level , "' == interaction(sch.wide, stype))"))

        res <- svyciprop( this_formula , dclus1 , ... )
        if( ci ) res <- confint( res )
        res
    }

# use the default method
cbind(
    do.call( rbind , lapply( names( levels ) , svyciprop_fun ) ) ,
    do.call( rbind , lapply( names( levels ) , svyciprop_fun , ci = TRUE ) )
)

# use a different method=
cbind(
    do.call( rbind , lapply( names( levels ) , svyciprop_fun , method = 'asin' ) ) ,
    do.call( rbind , lapply( names( levels ) , svyciprop_fun , ci = TRUE , method = 'asin' ) )
)


text:
Q: SQL duplication on colA and colB, where colC exists both zero and non-zero value I have a database relation as such:
House(street, street_number, built_year)
I want to SELECT  entries where exists duplications on both
street and street number,
and exists both zero value and non-zero value on built_year column.
Then for those entries  where street and street number are the same,
 assign non-zero in column built_year to  the column with zero value.
Appreciate for the help. Thanks

A: WITH CTE AS ( SELECT street, street_number, MAX(built_year) AS maxBuiltYear FROM House GROUP BY street, street_number HAVING COUNT(*)>1)
UPDATE House SET built_year = maxBuiltYear FROM House as h INNER JOIN CTE as c ON c.street = h.street and c.street_number = h.street_number WHERE built_year = 0;

The common table expression (CTE) gets all houses that exist more than once considering street and street_number with the highest built_year within those houses that exist more than once. Then you just update those houses whose biult_year is 0 by joining them with the CTE.
Hope it helps.


text:
Q: Best size for PSD website Templates? I have made some websites in Photoshop CS5, but I usually tend to just make them raw in notepad++. I normally make them live on the site, and edit the code and refresh the page to see the changes. I am wanting to move to the more professional method and making the entire template/design in photoshop. The thing holding me back from diving right in, is the very very start lol..
What is a good resolution to use for the template? I have came across different tutorials and they have say different sizes. For instance, my laptop resolution is 1366x768. I have a 22in LCD at my office, and I know it is a really large resolution as well. I would assume the min resolution of most monitors is 1024x768...
When creating a new template in Photoshop to create website templates, what size should I make the image and why?
Also, since we are on the topic, do you guys have any links to good resources of image collections and such that you find helps you the most in creating your templates? I am a programmer, and as we all know, most coders suck at images.. I am just trying to strengthen the other half of my brain :)
Thanks in advance!

A: I would suggest the following course of action:

*

*Take a look at current statistics for the most widely used screen resolutions. As you'll see, 1366x768 is the most popular resolution right now, followed by good old 1024x768 which still has a huge user base. And keep and eye out for mobile resolutions as well.

*Factor in the necessary screen real estate taken by browser chrome and other OS fluff.

*Since designing for multiple screen sizes is becoming more important every day, I would strongly encourage you to pick a few target resolutions rather than only one. This can all be nicely handled by CSS. Even if you're targeting only desktops, it still makes sense to consider different screen sizes.

*Since you're still getting your feet wet with Photoshop, you could start from one of the many grid-based PSD templates available. I know a 960px one and a 1140px one, but you can find many more. You'll probably have to use multiple grids anyway if you decide to support more than one screen size.

And then when you feel like thinking about all this a bit harder, go straight for this article: A tale of two viewports by Peter-Paul Koch.

A: Look at smashing magazine and sign up for their newsletter as well as webdesignerdepot and check out Codrops.net. They have great freebies, tutorials, and standards updates. I LOVE checking my mail to see them.
As for the PSD - their's no set size. I've seen professional wordpress developers mockup at 1100px wide (height is SO variant based on your layout). I wouldn't recommend much more than  1366px wide.
I might do 1366 or 1440 because that is the resolution most people will see. When you send a mockup at 1920 wide people think the website is too small, when the content is still the 940-980 that they all
Edit:
I myself do PSD's at either at 1100px or 1440px wide and the main content is is always 940-980px wide.
I use 1100 when there isn't much to look at graphically in the body background, and 1440 when the background is more crucial to the "feel" of the website.

A: You want to design your website for the most used screen resolution which seems to be 1280px by 720px. Therefore that is what you want your width to be, you can create any type of background and just make sure you fade it to one color or transparently and use CSS to change the background color.
Make sure you have guides that help you keep the content inline, best way, create a new document with the width 960-100px and the height 720px, then drag guides to all four sides.
Then you can change document size to 1280px by 800-960px.
The reason why you have a guide at 720px is because everything above that line is guaranteed to be seen on all resolutions, it's called "above the fold". Good designers take this in account for to ensure the audience will be drawn into exploring the site, a featured content slider is an easy way out.

A: incomepitbull, I understand where you are coming from...
I am also a back end developer who is trying to learn Photoshop..
Many front end designers are ignorant of what goes on on development stage...
Mostly the Photoshop moke up depends on the customer specification...
The height doesn't matter; use 960 px (12col,16col,24col), 980 px (12col,24,col), 1000 px (100 % responsive friendly for those not using grid systems) or 1140 (for webs targeting bigger monitors ie not mobile first px...)
After all, as developers, we fix all this problems; but good mockups are important...


text:
Q: Cardinality of continuous functions $f:\Bbb R\to \Bbb R$
Cardinality of continuous functions $f:\Bbb R\to \Bbb R$.

We know that a continuous function $f:\Bbb R\to \Bbb R$ is completely determined by its values on $\Bbb Q$.
For each rational $q\in \Bbb Q,f(q)$ has $c(=\text{Card }\Bbb R)$ many choices.
Hence the number of such functions becomes $\mathfrak{q^c}= \Bbb N^c$ .
Is it right?Please check.

A: It is not correct. For starters, the expression $q^\mathfrak{c}$ (where $q\in\Bbb Q$) is meaningless; I suspect that you meant $\left|\Bbb Q^\mathfrak{c}\right|$, which is indeed $\left|\Bbb N^\mathfrak{c}\right|$. But note that you do need the cardinality bars.
However, you've got the multiplication principle backwards: you're making a choice amongst $\mathfrak{c}$ real numbers $|\Bbb Q|$ times, so you really want $\mathfrak{c}^{|\Bbb N|}$. Finally, $\mathfrak{c}=2^{|\Bbb N|}$, so
$$\mathfrak{c}^{|\Bbb N|}=\left(2^{|\Bbb N|}\right)^{|\Bbb N|}=2^{|\Bbb N|\cdot|\Bbb N|}=2^{|\Bbb N|}=\mathfrak{c}\;.$$
This actually shows only that there are at most $\mathfrak{c}$ continuous real-valued functions on $\Bbb R$, since it counts all functions from $\Bbb Q$ to $\Bbb R$, not just the ones that are restrictions of continuous functions from $\Bbb R$ to $\Bbb R$. To complete the argument you need to show that there are also at least that many; this is easy, since there are $\mathfrak{c}$ constant functions.
I've answered this in order to respond to the specific problems with your argument. The question itself has been dealt with in detail in the answers to this question.


text:
Q: Typescript error: Property '_myApiUrl' does not exist on type 'Window' I am new to typescript and I run into a problem. I had this method in a Typescript (.ts) file:
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [Service1, Service2]
})

export class AppComponent implements OnInit, OnDestroy {
// more code here
    myMethod() {
       this.isLoading = true;
       const serverPath = 'http://myApiUrl';
       // more code here
    }
// more code here
}

I have replaced http://myApiUrlwith a variable window._myApiUrl and I get the error:
Property '_myApiUrl' does not exist on type 'Window'

myMethod() {
    this.isLoading = true;
    const serverPath = window._myApiUrl;
    // more code here
}

Why does this happen? How can I fix the issue?

A: Typescript doesn't know that variable exists. You can declare it:
declare global {
    interface Window {
        _myApiUrl: string;
    }
}

export class...


text:
Q: Have method wait until JFrame is disposed I have tried and tried and tried and failed at this. I've looked at all related questions on SO and nothing is working for me!
I have a method called from another class.
public void generateObstacles () throws IOException {

new Thread(new Runnable() {
    public void run() {
        Obstacles.NeedyDog windowPet = null;
            try
                {
                    windowPet = new NeedyDog();
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                }
                 windowPet.setBounds(  100, 100, 1000, 400);
                 windowPet.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                 windowPet.setResizable(false);
                 windowPet.setVisible( true );
                 windowPet.pack();
                 windowPet.addWindowListener(new WindowAdapter() {

          @Override
                 public void windowClosed(WindowEvent e) {}
          @Override
                  public void windowClosing(WindowEvent e) {}
          });
                 }
          }).start();

         System.out.println( "Don't move on until it closes" );

}
I need the user to work with NeedyDog's JDialog frame, and for it to dispose before the generateObstacles method moves on to the print statement, but it moves on immediately and prints it onto the console.
Here's my NeedyDog class:
private class NeedyDog extends JDialog implements ActionListener {

public NeedyDog() throws IOException
    super((Window)null);
    setModal(true);
    // Code to setup the JDialog
}

@Override
public void actionPerformed( ActionEvent e )
{
    final JFrame window = (JFrame)SwingUtilities.getRoot(this);

    if (e.getActionCommand().equals("buyball")) {
        user.addCoins( -3 );
        dogTalk.setText(dogTalk.getText() + "\nVery nice. Now I want "
            + "yeh teh play with me!!");
        ball.removeActionListener(this);
        ball.setText("Oops. Try buying something else.");
    }

    else if (e.getActionCommand().equals("buybone"))
    {
        user.addCoins( -5 );
        dogTalk.setText(dogTalk.getText() + "\nWow bone very wow much"
                + " thanks bye.");
        if (dogTalk.getText().contains("Very nice."))
            {
                window.setTitle( "Obstacle overcome!-Dog is happy with"
                    + " a ball AND bone! Closing window...");
            }
            else
            {
                window.setTitle( "Obstacle overcome!-Dog is happy!"
                    + " Closing window...");
            }

        new Thread(new Runnable() {
            public void run() {
                try
                {
                    //Wait 5 seconds before exiting
                    TimeUnit.SECONDS.sleep(5);
                }
                catch ( InterruptedException e )
                {
                    e.printStackTrace();
                }
                    window.dispose();
                }
            }).start();
        }

}

A: The solution is simple: don't use a JFrame but rather use a modal JDialog as this behavior is exactly what the modal dialog has been built for.
And regarding:

I have tried and tried and tried and failed at this. I've looked at all related questions on SO and nothing is working for me!

This question has been asked many many times, most answers with the same or similar solutions. For example
Also check out How to use Dialogs.
If you need more specific code help, then please try to condense your code into the smallest bit that still compiles and runs, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, a minimal example program.


text:
Q: How to pass the cookies get from document.cookie to phantomjs? phantomjs has a parameter --cookies-file and I can point it to a cookie file. Its format is like:
[General]
cookies="@Variant(\0\0\0\x7f\0\0\0\x16QList<QNetworkCookie>\0\0\0\0\x1\0\0\0\x2\0\0\0lBAIDUPSID=9C185C46016DC114CB8ECCDE512C768B; expires=Tue, 10-Nov-2082 20:14:15 GMT; domain=.baidu.com; path=/\0\0\0oBAIDUID=9C185C46016DC114CB8ECCDE512C768B:FG=1; expires=Sat, 15-Oct-2044 17:00:09 GMT; domain=.baidu.com; path=/)"

Here I want to know, if I have the cookies string got from document.cookie on a website, how to pass it to phantomjs --cookies-file? I'm not sure how to convert the format.


text:
Q: Xml parsing with hive I am using hive serDe(https://github.com/dvasilen/Hive-XML-SerDe/wiki/XML-data-sources) for XML parsing and loading it to hive.
Sample XML content:
<records>
<record customer_id="0000-JTALA">
<income>200000</income>
<address type="M">
<Flatno>345</FlatNo>
<Street>ABS</street>
<city>QWW</city>
<country>US</country>
<pin>3235</pin>
</address>
<address type="B">
<Street>ABS</street>
<city>QWW</city>
<country>US</country>
<pin>3235</pin>
</address>
</record>

<record customer_id="0001-JTALA">
<income>200000</income>
<address type="M">
<Flatno>45</FlatNo>
<Street>fgBS</street>
<city>QWW</city>
<country>US</country>
<pin>3235</pin>
</address>
<address type="B">
<Street>ABS</street>
<city>QWW</city>
<country>US</country>
<pin>325</pin>
</address>
<address type="P">
<Street>ABS</street>
<city>QWW</city>
<country>UK</country>
<pin>325</pin>
</address>
</record>
</records>

For every address a row should be created. As per the above sample for first customer 2 records should be created and for second customer 3 records should be created total 5 records, as per my current code only two records are created each for single customer and in address column all the address are concatenated so for the first customer street column has (first address street + second address street).
    Sample query:
CREATE external TABLE msg_details(customer_id STRING, income BIGINT, AType String,Flatno String, Street string,city string,country string,pin string)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES (
"column.xpath.customer_id"="/record/@customer_id",
"column.xpath.income"="/record/income/text()",
"column.xpath.address_type"="/record/address/@type",
"column.xpath.Flatno"="/record/address/Flatno/text()",
"column.xpath.Street"="/record/address/Street/text()",
"column.xpath.city"="/record/address/city/text()",
"column.xpath.country"="/record/address/country/text()"
"column.xpath.pin"="/record/address/pin/text()"
)
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
location '/user/root/serdeinput'
TBLPROPERTIES (
"xmlinput.start"="<record customer",
"xmlinput.end"="</record>"
);

A: One way is to write user defined (custom) serdy for XML parsing.
[ or ]
Write UDF for splitting the Array values containing in the same column values into rows.
The serde which you are using is generic one, which is almost equivalent to the xpath provided by Hive serde, both are having limited features to extract the records only.
I tried 3 other approaches using Lateral view and other ways, but doesn't worked for all the columns in address type.
The only solution for it is to proceed with custom Serde to parse according to your requirements.
create external table msg_details3(customer_id string, income bigint, address_type Array<string>,Flatno Array<string>, Street ARRAY<string>,city ARRAY<string>,country ARRAY<string>,pin ARRAY<string>)
ROW FORMAT SERDE 'com.ibm.spss.hive.serde2.xml.XmlSerDe'
WITH SERDEPROPERTIES (
"column.xpath.customer_id"="/record/@customer_id",
"column.xpath.income"="/record/income/text()",
"column.xpath.address_type"="/record/address/@type",
"column.xpath.Flatno"="/record/address/Flatno/text()",
"column.xpath.Street"="/record/address/Street/text()",
"column.xpath.city"="/record/address/city/text()",
"column.xpath.country"="/record/address/country/text()",
"column.xpath.pin"="/record/address/pin/text()"
)
STORED AS
INPUTFORMAT 'com.ibm.spss.hive.serde2.xml.XmlInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.IgnoreKeyTextOutputFormat'
location '/user/cloudera/data'
TBLPROPERTIES (
"xmlinput.start"="<record ",
"xmlinput.end"="</record>"
);


text:
Q: Automatically resizing images when the browser width/height changes I have a page with many images in divs and the layout looks good only in full size, when the browser window is smaller it's really messy. I found a similar question on stack overflow but their answers don't work for my case.
EDIT: I did everything what you guys advised but it still doesn't work.

<!DOCTYPE html>

A: Let's try another approach. Try not to modify max-width or max-height. Just leave it as it is (or set width: 100% and height: 100%).
And then change  to background: url("url.jpg"); and then just do
.image {
    background-size: cover;
}

or
.image {
    background-size: contain;
}

A: Ok I figured it out! I needed viewport value instead of %. Now images go proportionally with browser size and stay in place.
div.asciigun {
    position: absolute;
    top: 30vw;
    left: 74vw;
    z-index: 1;
    width: 30vw;
    height: 15vw;
}


text:
Q: How do I get rid of error "unrecognized token: "#" " for a search query in rails? This is the error I get:
SQLite3::SQLException: unrecognized token: "#": SELECT "posts"."id" AS
t0_r0, "posts"."title" AS t0_r1, "posts"."content" AS t0_r2,
"posts"."created_at" AS t0_r3, "posts"."updated_at" AS t0_r4,
"posts"."user_id" AS t0_r5, "posts"."course_id" AS t0_r6,
"courses"."id" AS t1_r0, "courses"."name" AS t1_r1,
"courses"."created_at" AS t1_r2, "courses"."updated_at" AS t1_r3,
"courses"."major_id" AS t1_r4, "courses"."user_id" AS t1_r5 FROM
"posts" LEFT OUTER JOIN "courses" ON "courses"."id" =
"posts"."course_id" WHERE (courses.name IN (#{s},#{s}))  ORDER BY
posts.created_at DESC

For this query:
@posts = Post.includes(:course).where("courses.name IN (#{@user.courses.map(&:name).collect { |s| '#{s}'  }.join(',') })").references(:courses).order("posts.created_at DESC")

I dont understand why #{s} doesn't become the strings in the array

A: The reason for your problem is that string interpolation does not work inside single quotes. You need to use "#{s}".
However, as a first improvement, the preferred method of converting a variable to a string is simply to call s.to_s. That said, name sounds like it's already a string, so the entire process of mapping can probably be eliminated.
You also should not be using string interpolation to build a query. Use parameterized queries, give Rails the array of strings, and let it do the work for you:
@posts = Post.includes(:course).where('courses.name IN (?)', @user.courses.pluck(:name))

Note that, to select a single column from a set of results, it's tremendously faster to use pluck(:field) than map(&:field). The map method selects all the columns, instantiates entire ActiveRecord models for the result, and then throws out all that effort when you reduce the collection down to the single field. pluck only selects the required field, and doesn't build AR objects for the result set.

A: Your answer really helped, I had an issue with string iterpolation, the code that worked is
@posts = Post.all.includes(:course).where("courses.name IN (#{@user.courses.map(&:name).collect { |s| "'#{s}'"  }.join(',') })").references(:course).order("posts.created_at DESC")


text:
Q: I need to find a Folder on the Network Share How can I find Folders called BlueMountain when this folder could be nested anywhere in my Users home folder
\\Server\Users\<personsname>\

Ultimately I want to delete the folder but just to be on the safe side. The BlueMountain folder must have one of these subfolder
Certs
Config
Macros
Scripts
Spool
Traces
Transfer

This is what I have so far
Get-ChildItem -Path \\Server\Users -Recurse -Directory -Filter $_.FOLDERNAME | ForEach-Object {
        If $_.FullName --eq "BlueMountain" {

        }

    }

A: You can use -recurse to look for the last thing in your path recursively. So this:
Get-ChildItem \\server\Users\BlueMountain -recurse

Will look in all subfolders of "\server\Users" for anything named "BlueMountain". Then you just need to make sure it has one of your folders.
$SubFolders = 'Certs','Config','Macros','Scripts','Spool','Traces','Transfer'
Get-ChildItem \\server\Users\BlueMountain -recurse | Where{Get-ChildItem "$($_.FullName)\*" -Include $SubFolders}

That should list only the BlueMountain folders found recursively in \server\Users which contain one of the specified subfolders. Then you can just pipe that to Remove-Item -force and call it a day. Or if you want to track things pipe it to tee-object and then to remove-item.

A: try this :
$SubFolders = 'Certs','Config','Macros','Scripts','Spool','Traces','Transfer'
$wordtosearch="BlueMountain"
$SearchPattern= ($SubFolders | %{ "$wordtosearch\\$_" }) -join "|"

get-childitem "\\Server\Users" -directory -Recurse |
    where FullName -match $SearchPattern |
        Split-Path -path {$_.FullName} -Parent |
            remove-item -Recurse -ErrorAction SilentlyContinue


text:
Q: Oracle DB Multiple Instances configuration I am using Oracle database in my local PC. I have 3 instances database running.
My question is, Do i need to specify different listener for each SID in my machine?
or I can just have 1 listener on port 1521 for every SID?
If I need to create each Listener for each SID, what is the pros and cons?
Because I see the blog which create each listener for each SID in the same server.
http://www.snoozingdragon.com/information-technology/tips-and-tricks/multiple-listeners-for-multiple-sid-in-oracle-database-6.html

A: You do not need to have multiple listeners for several databases. Even if you have different versions of Oracle Database software. Listener from upper version (for ex. 12c) supports connections to 12c, 11g, 10g databases
Multiple listeners are used when we need restrict access from some users, or if one listener is not keeping up with too many connections, etc.
I personally have 4 databases on my laptop, and they all use one listener.


text:
Q: Simple slider using jquery I want to implement simple slider.
JSFiddle
The problem is that if there will be more than two slides than it will works fine. But if there are two slides then it cause a issue.
If there are two slides , and we click on previous arrow then it will works fine but when we click on next arrow image will comes after some time thats not look good.
I want to implement same thing by clicking next arrow as it works with previous arrow.
HTML:

  >
  <

SLIDE 1

SLIDE 2

CSS:
#slider {
  position: relative;
  overflow: hidden;
  margin: 20px auto 0 auto;
  border-radius: 4px;
}

#slider ul {
  position: relative;
  margin: 0;
  padding: 0;
  height: 200px;
  list-style: none;
}

#slider ul li {
  position: relative;
  display: block;
  float: left;
  margin: 0;
  padding: 0;
  width: 500px;
  height: 300px;
  background: #ccc;
  text-align: center;
  line-height: 300px;
}

a.control_prev, a.control_next {
  position: absolute;
  top: 40%;
  z-index: 999;
  display: block;
  padding: 4% 3%;
  width: auto;
  height: auto;
  background: #2a2a2a;
  color: #fff;
  text-decoration: none;
  font-weight: 600;
  font-size: 18px;
  opacity: 0.8;
  cursor: pointer;
}

a.control_prev:hover, a.control_next:hover {
  opacity: 1;
  -webkit-transition: all 0.2s ease;
}

a.control_prev {
  border-radius: 0 2px 2px 0;
}

a.control_next {
  right:0;
  border-radius: 2px 0 0 2px;
}

JS:
jQuery(document).ready(function ($) {

    var slideCount = $('#slider ul li').length;
    var slideWidth = $('#slider ul li').width();
    var slideHeight = $('#slider ul li').height();
    var sliderUlWidth = slideCount * slideWidth;

    $('#slider').css({ width: slideWidth, height: slideHeight });

    $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

    $('#slider ul li:last-child').prependTo('#slider ul');

    function moveLeft() {
        $('#slider ul').animate({
            left: + slideWidth
        }, 200, function () {
            $('#slider ul li:last-child').prependTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    function moveRight() {
        $('#slider ul').animate({
            left: - slideWidth
        }, 200, function () {
            $('#slider ul li:first-child').appendTo('#slider ul');
            $('#slider ul').css('left', '');
        });
    };

    $('a.control_prev').click(function () {
        moveLeft();
    });

    $('a.control_next').click(function () {
        moveRight();
    });

});

Please help me.
Thank in advance

A: The difference you get here is :
function moveLeft() {
    $('#slider ul').animate({
        left: slideWidth
    }, 200, function () {
        $('#slider ul li:last-child').prependTo('#slider ul');
        $('#slider ul').css('left', '');
    });
};

function moveRight() {
    $('#slider ul').animate({
        left: slideWidth
    }, 200, function () {
        $('#slider ul li:first-child').appendTo('#slider ul');
        $('#slider ul').css('left', '');
    });
};

You can remove those '+' and '-' in "left" Option.
It makes the difference

A:  Demo
Change your moveRight function to
function moveRight() {
    $('#slider ul').animate({
        right: - slideWidth
    }, 200, function () {
        $('#slider ul li:first-child').appendTo('#slider ul');
        $('#slider ul').css('right', '');
    });
};

A: I don't see why the code works this way, but if you're thinking about putting more than two slides, adding one more slide seems to somehow do the trick: http://jsfiddle.net/ek9bs/
HTML:

>
<

SLIDE 1

SLIDE 2

SLIDE 3

This of course if the two slides you've provided are just examples and you want to add more in general.


text:
Q: Semi-continuity for extended value function Given a topological vector space $(X,\tau)$ a function $f:(X,\tau)\to\overline{\mathbb{R}}:=\mathbb{R}\cup\{\pm\infty\}$ is said to be lower-semicontinuous at $x_0\in X$ if
$$
f(x_0)\le\liminf_{x\to x_0}f(x):=\sup_{V\in\mathscr{V}(x_0)}\inf_{x\in V}f(x),
$$
where $\mathscr{V}(x_0)$ stands for the system of neighborhoods of $x_0$.
Similarly, the upper-semicontinuity at $x_0$ is defined with "$\ge\limsup$" instead of "$\le\liminf$".
My question are: If a function is identically equal to $+\infty$ is it lower and upper semicontinuous everywhere?
Is such a function continuous everywhere? (Continuity requires $f(x_0)\in\mathbb{R}$)
My questions are more about formalism and asks about a discussion on basic definitions. As stated somewhere in a book,  a function is continuous at $x_0$ if and only if it is both upper and lower semi-continuous there.

A: If $f \equiv +\infty$, and $x_0 \in X$ then whatever $V \in \mathscr{V}(x_0)$ is, $\displaystyle \inf_{x \in V} f(x)=+\infty$ and so $f$ is trivially lsc at $x_0$. That $f$ is also usc is checked the same way.
BTW it's perfectly fine to talk about continuity at $x_0$ if $f(x_) = +\infty$. Maybe your text book thinks differently but $\overline{\Bbb R}$ has an (even metrisable) order topology, so continuity can be discussed...


text:
Q: Embedded Cellphone Code What do most cellphones use to run the hardware? C?
I'm just talking about the "common cellphone", not smart phone/android stuff.

A: I work for wireless semiconductor chip provider, and we work on variety of phone platforms from ULC (ultra low cost ) segments to Smart phones.
In our Reference phone design, the entire code (including Protocol stack, Kernel, Middleware, Application and MMI) is written purely in C. AFAIK even first tier customers use C language for their framework, atleast for ULC and Mid category phones, as the memory size tends to be a big requirement.

A: Phones running a variety of the Symbian OS will very likely have all core OS functionality written in C++, as that is the "native" language of Symbian.

A: When talking about cellphones, there are usually two processor components in it.

*

*The "main" processor that covers the user interface.

*The "baseband" processor that powers the cellular modem.  It handles the low-level radio interface, switching towers, etc.

The code for #1 tends to be higher-level (C, C++, Java, etc).  The language used really depends on the OS that it is running (Windows Mobile, Symbian, Linux, something home-grown, etc).  Of course, there is almost always SOME low-level assembly for the boot loader.
The code for #2 is pretty low-level.  Baseband Processors tend to be little more than microcontrollers.  Mostly assembly language and C.  Very unlikely to find anything higher level here.  (Although I have seen a few cell modems with a Python interpreter built-in.)
Usually the Baseband Processor is running some kind of minimal RTOS, or in some cases OS-less.  They are very often running an RTOS called Nucleus from Mentor Graphics.
On some low-cost cell phones, #1 and #2 are joined together to cut costs (only one processor & OS in the system).

A: Hardware things, like setting registers and handling interrupts to run the radio, are all done in C.
Two problems with C++ are, in my opinion, that

*

*It is harder to design efficient programs in it. The CPU may only be a few hundred MHz.

*The compilers for more exotic CPUs barely work in C, so running them in C++ would be a miracle.

A: Phones running Android will use mostly C under the java machine, and the Java in the top layers.
But if you look on most phones they are just like the rest of the embedded market,
it is a lot of c and in some project some c++.
And the smaller they are, the more c you will find.
/Johan

A: Most Cellphones have different layers of Software, Largely we can divide this into three parts.
1.Application Layer : anything like BREW,C++ or Android
2.Middle-layer : Consists of real time OS code : C code[mostly as I have seen]
3.Lower-Layer : Device Drivers : Written in C.
please note :Most Common Cellphones are likely to use C++ as an application layer ,Brew is largely used by CDMA phones for application layer

A: Nokia bought Trolltech, the makers of Qt - a cross-platform application and UI framework for desktop and mobile applications.  Presumably this includes cell phones.  Qt is written in C++.  http://www.qtsoftware.com/developer/getting-started


text:
Q: Could not find which method () to invoke from this list on newInstance in groovy closure I am learning groovy and I am trying to initialize my class dynamically with default values for all fields. So how I am proceeding is, I am taking the list of all the properties and getting the type of that object and create an object of the type, but I am getting error when executing newInstance:
Exception in thread "main" org.codehaus.groovy.runtime.metaclass.MethodSelectionException: Could not find which method <init>() to invoke from this list:
  public java.lang.Boolean#<init>(boolean)
  public java.lang.Boolean#<init>(java.lang.String)
    at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3160)
    at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3097)
    at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1707)
    at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1526)

Below is the code
public static void init() {
        Position position1 = new Position();

        JXPathContext context = JXPathContext.newContext(position1)
        context.createPathAndSetValue('id', '2')

        position1.properties.each { Map.Entry entry ->
            String propertyName = entry.key;
            if (!propertyName.equalsIgnoreCase('class')) {
                Class clazz = position1.class.getDeclaredField(propertyName)?.type
                println "$clazz"
                Object ob = clazz.newInstance()
            }

        }
        Identifier sourceSystemPositionId = new Identifier()

        context.setValue('sourceSystemPositionId/content', 'default-content')
        context.setValue('sourceSystemPositionId/domain', 'default-domain')

        println "$position1"
    }

A: View the java docs for java.lang.Boolean. As you can see in the section Constructor Summary there's no no-arg constructor (and this is what exception message says) for this class. You must either:

*

*invoke it (constructor) with boolean or String argument

*use default value for boolean - which is false

*initialize the value with Boolean.FALSE or Boolean.TRUE


text:
Q: SQLite datatbase data not inserting In my android code I am inserting some data to database from gcm intent.It is working when I am inserting without checking any condition.When I check the first element of the json object received with if statement data are not inserting.I think some error with if condition.please help me
protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message = intent.getExtras().getString("title");

        if (message ==  "instru"){
        String message1 = intent.getExtras().getString("price");
        String message2 = intent.getExtras().getString("price1");
        String message3 = intent.getExtras().getString("price2");
        String message4 = intent.getExtras().getString("price3");
        String message5 = intent.getExtras().getString("price4");
        DatabaseHandler1 db = new DatabaseHandler1(getApplicationContext());
        int count = db.getRowCount_1();
        if(count > 0){
            db.resetTables_1();
        }
        db.addUser_1(message1,message2,message3,message4,message5);
       }
        else if(message == "signal"){
            //else {
            String message1 = intent.getExtras().getString("date");
            String message2 = intent.getExtras().getString("name");
            String message3 = intent.getExtras().getString("buy");
            String message4 = intent.getExtras().getString("stop");
            String message5 = intent.getExtras().getString("tv");
            String message6 = intent.getExtras().getString("tp");
            String message7 = intent.getExtras().getString("res");
            DatabaseHandler1 db = new DatabaseHandler1(getApplicationContext());
            DatabaseHandler1 db = new DatabaseHandler1(getApplicationContext());
            int count = db.getRowCount_2();
            if(count > 0){
                db.resetTables_2();
            }
            db.addUser_2(message1,message2,message3,message4,message5,message6,message7);

        }
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

different json objects recieved
$message = array(
"title" => "instru",
"price" => $trade1,
"price1" => "$trade2",
"price2" => "$trade3",
"price3" => "$trade4",
"price4" => "$date");

$message = array(
        "title" => "signal",
        "date" => $date1,
        "name" => $signal_name,
        "buy" => $price,
        "stop" => $stop,
        "tv" => $trig_value,
        "tp" => $profit,
        "res" => $result,
    );

A: In java, to compare String, You need to use equals() instead of ==
if (message.equals("instru"))

A: Use
message.equals("instru")

instead of
message ==  "instru"

Same goes valid for 'message == "signal"'
Even better
Use
  "instru".equals(message)

Since message can benull` in some situations

A: Don't use
 (message == "signal")

for comparing two Strings.
Using == operator in Java programming for compare two Strings its bad thing. So you need to use equals() or equalsIgnoreCase(). So it will be
message.equals("signal")

or
message.equalsIgnoreCase("signal")