text:
Q: Getting django signals to work between applications I have a Django app called receipt_printer which should be printing an order when it is received using a signal. There are two apps here called: Orders and receipt_printer.
However, whenever an order is processed and fully charged I can't get the signals to work. The example below just prints out something to the console for simplicity. If I do everything inside the models.py in the Orders app it works fine.
receipt_printer/apps.py
from django.apps import AppConfig

class ReceiptPrinterConfig(AppConfig):
    name = 'receipt_printer'

    def ready(self):
        from . import signals

receipt_printer/signals.py
from django.db import models
from saleor.order.models import Order
from django.db.models.signals import post_save

def order_fully_paid_signal(sender, instance, created, **kwargs):
    if instance.get_payment_status() == "fully-charged":
        print("This signal is working for fully paid order")
    else:
        print("This signal won't working for fully paid order")
post_save.connect(order_fully_paid_signal, sender=Order)

receipt_printer/init.py
default_app_config = 'receipt_printer.apps.ReceiptPrinterConfig'

UPDATE, also tried the below - didn't work:
@receiver(post_save, sender=Order)
def order_fully_paid_signal(sender, instance, created, **kwargs):
    if instance.get_payment_status() == "fully-charged":
        print("This signal is working for fully paid order")
    else:
        print("This signal won't working for fully paid order")

A: Not entirely sure what the issue is here but below is a post_save pattern I use that does work cross-app without any changes needed to apps.py nor init.py:
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=<Model>, dispatch_uid='<model>_post_save')
def <model>_post_save(sender, instance, **kwargs):

    ...

A: I needed to add the following line to the bottom of my models.py for the Orders app:
from saleor.saleor_package.receipt_printer.signals import order_fully_paid_signal


text:
Q: Adobe DTM: Multiple Event rule in a page having issue I have created 3 different event based rule in a page to track 3 different buttons in a page. When I click on the first link it is fine. But when the second link is clicked it fires 2 times with the value I set for the 1st button and the current button.
When I click the third button it fires again 2 times with the previous click event and the present one. Can you please let me know how to stop this?
This the code that I have.

THIS

xxx

              Play Video

The selector used is #hero a.js-loadVideo
The other button that I have on the same page is
Register Now

If I click on Register Now it is firing the value that I have set for the top button.

A: This sounds like something I have had trouble with this in the past. I used the following to get this to fix:

*

*Search your s_code for the following plugin/utility by searching for "clearVars":
/* Utility manageVars v1.4 - clear variable values (requires split 1.5)*/
/* */
/* editing out code not relevant to question */
    s.clearVars=new Function("t","var s=this;s[t]='';");
/* editing out code not relevant to question */

*In the Criteria section of all your event-based rules select "Custom" and add the following code:
s.manageVars("clearVars","events,",1)
return true;

If you are missing the s_code piece you can get it by downloading a more recent s_code file from Adobe

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to show infowindow in google map mvc i am show the info window but not show the info window..how to resolve this problem..
only show the title .but .not show the info window..
only show the title .but .not show the info window..
@model  IEnumerable

    <title>Show/Add multiple markers to Google Maps in asp.net website</title>

    <form id="form1">

    </form>

A: An InfoWindow displays content (usually text or images) in a popup window above the map, at a given location. The info window has a content area and a tapered stem. The tip of the stem is attached to a specified location on the map.
The content of the InfoWindow may contain a string of text, a snippet of HTML, or a DOM element. To set the content, either specify it within the InfoWindowOptions or call setContent() on the InfoWindow explicitly.
If you wish to explicitly size the content, you can put it in a
 element and style the
 with CSS. You can use CSS to enable scrolling too. Note that if you do not enable scrolling and the content exceeds the space available in the info window, the content may spill out of the info window.
You can check this example on how to use info window. Just take note that this example is using javascript.


text:
Q: Covering projection is monomorphism Let $p:(E,e_0) \rightarrow(X,x_0)$ be a covering projection. Show that $p \sharp: \pi_{1}(E,e_0) \rightarrow \pi_{1}(X,x_0)$ is a monomorphism.
I was wondering here do I need to prove this is a homomorphism?
As I'm confused as I know you have to prove that it is an injection. Which is just by considering what is in the kernel of $\pi_{1}(E,e_0) \rightarrow \pi_{1}(X,x_0)$, something that is homotopic to the constant map, then you just lift the homotopy to the covering space to get something homotopic to the constant map in $(E,e_0)$.
However, is this enough or do you need to show homomorphism? How would you show a homomorphism? would you need to do concatenation of loops?

A: If you are not sure about it being a homomorphism, what you should try and prove is that for any map of topological spaces $p:X \to Y$ the induced map $p_*:\pi_1(X,x) \to \pi_1(Y,p(x))$ is a homomorphism. What is this map?
Let $[f]$ be a class in $\pi_1(X,x)$. Then the induced map is $p_*([f]) = [p \circ f]$ where $p \circ f$ is the composite $f:I \to X$ with $p:X \to Y$. Then check that this map is a homomorphism. Recall if we have paths $f:x \to y$ and $g:y \to z$ then $g \cdot f$ is the map obtained by 'going twice as fast' and that this passes through equivalence class via $[g]\cdot[f] = [g \cdot f]$.
The fact that the induced map of a covering space is injective is a consequence of the homotopy lifting property as you say.


text:
Q: How do I pass a state object to a screen in React Native? **     i want to pass the setScreen object to Signup screen
     please tell me how do i pass it so i could change the screen state from Signup screen**
import React, { useState } from 'react';
import 'react-native-gesture-handler';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import AccountScreen from './src/screens/AccountScreen';
import SigninScreen from './src/screens/SigninScreen';
import SignupScreen from './src/screens/SignupScreen';
import TrackCreateScreen from './src/screens/TrackCreateScreen';
import TrackDetailScreen from './src/screens/TrackDetailScreen';
import TrackListScreen from './src/screens/TrackListScreen';

const Stack = createStackNavigator();
const TrackStack = createStackNavigator();
const Tab = createBottomTabNavigator();

const TrackScreenStack = () => {
  return (
    <TrackStack.Navigator initialRouteName="TrackList">
      <TrackStack.Screen
        name="TrackList"
        component={TrackListScreen}
      />
      <TrackStack.Screen
        name="TrackDetail"
        component={TrackDetailScreen}
      />
    </TrackStack.Navigator>
  )
}

**   here i have declared the state object
     and i wish to pass it in Signup screen
     so that i could switch between screen stacks**
const App = () => {
  const [screen, setScreen] = useState(true);
  return (
    <NavigationContainer>
      {screen ? (
        <Stack.Navigator initialRouteName="Signup">
          <Stack.Screen
            name="Signup"
            component={SignupScreen}
          />
          <Stack.Screen
            name="Signin"
            component={SigninScreen}
          />
        </Stack.Navigator>
      ) :
        <Tab.Navigator>
          <Tab.Screen
            name="Track"
            component={TrackScreenStack}
          />
          <Tab.Screen
            name="Account"
            component={AccountScreen}
          />
          <Tab.Screen
            name="TrackCreate"
            component={TrackCreateScreen}
          />
        </Tab.Navigator>
      }
    </NavigationContainer>
  )
}

export default App;


text:
Q: cakePHP3 prefix routing and same name for controller / subcontroller I have (more precisely "want") the following structure and i try to build the routes:
src/Controller/OrdersController.php
src/Controller/Orders/PositionsController.php

So the routes are:
/orders > OrdersController
/orders/details/1 > OrdersController:details
/orders/positions/details/1 > PositionsController:details

The solution is prefix routing, so far, so good. But it only works with fixed routes before the prefix routing.
So this works:
Router::scope('/', function (RouteBuilder $routes)
{
    $routes->connect('/orders/details/*', [
        'controller' => 'Orders',
        'action' => 'details'
    ]);
    $routes->prefix('orders', function (RouteBuilder $routes)
    {
        $routes->fallbacks(DashedRoute::class);
    });
    $routes->fallbacks(DashedRoute::class);
});

But I want it more flexible and don't define every route. Can i use the ":action" flag to define the routes.
Best case would be to have multiple level like:
src/Controller/OrdersController.php
src/Controller/Orders/PositionsController.php
src/Controller/Orders/Positions/CommentsController.php

Is it possible?
This would be more "structure" instead of OrdersController, OrdersPositionsController and OrdersPositionsCommentsController, ...

A: I could solve it by myself:
Router::scope('/', function (RouteBuilder $routes)
{
    $routes->prefix('orders', [], function (RouteBuilder $routes)
    {
        // -- order positions
        $routes->connect('/positions', [
            'controller' => 'Positions',
            'action' => 'index'
        ]);
        $routes->connect('/positions/:action/*', [
            'controller' => 'Positions'
        ]);

        $routes->prefix('positions', [], function (RouteBuilder $routes)
        {
            $routes->connect('/comments', [
                'controller' => 'Comments',
                'action' => 'index'
            ]);
        });

    });

    $routes->fallbacks(DashedRoute::class);

});


text:
Q: Routing Error Rails, dont undertand Are all correct but the error persists, i make the all codes to all you see
Routing Error

No route matches {:controller=>"posts", :user_id=>#<Post id: 1, title: "sa", content: "sasa", created_at: "2013-01-06 00:25:03", updated_at: "2013-01-06 00:25:03", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, user_id: 1>, :action=>"edit"}
Try running rake routes for more information on available routes.

My routes are:
  get "painel/index"

 resources :posts

  resources :user  do
    resources :posts,:comments

      end

and my models is:
user.rb

  attr_accessible :email, :password, :password_confirmation,:username
  has_many :posts
  has_many :comments

post.rb

  attr_accessible :content, :title  ,:image
  has_many :comments
  belongs_to :user

A: 1) Check 'rake routes'
2) use the url or path you get in routes list. That will solve your error
If that does not solve your error,
paste your routes file and link_to call which is returning error.


text:
Q: how to generate dynamic tooltips with data from MYSQL using PHP I have a PHP script that retrieves a number of random fields from one column in MYSQL and echos them to a page. What I want to be able to do is hover mouse over any of the echoed results and display a tooltip which shows additional information from my databse- such as info from two relevant fields in two separate columns in MYSQL database
Would I have to include these extra colums in my SQL select statement and some how pass these to javascript to display tooltip or is there a way to do it with PHP alone?
I'm fairly new to PHP and my javascript knowledge is thin. The idea sounds simple but I have a feeling it's going to be very difficult to do.
Anyway, here is my code which has been helped out by mmmshuddup (cheers for that). I realise that I haven't protected against SQL injections yet. But I will!
Thanks.
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="db"; // Database name
$tbl_name="sentence"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sn=$_POST['numberofsentences'];

$query="SELECT line FROM `sentence` ORDER BY rand() LIMIT $sn";
$result = mysql_query($query);

$count = 0;
while ($row = mysql_fetch_array($result)) {
    // do something with $row. The following echos the results and adds a space after each sentence.
    echo $row['line'], "&nbsp";
    if ($count >= 4) {
        echo '
    ';
        $count = 0;
    } else {
        $count++;
    }
}
// Close the database connection
mysql_close();

 ?>

A: Their is list of built in tooltip plugins, you can use any one just like
1- load first time all information to multiple divs with seprate ids
2- show and hide on based upon time or what so ever you want
here is one example of tooptip that i have used it, found it suited my need link here.

A: If you don't want to go down the route of using Javascript, you can use the HTML title tag like so:
<a href="whatever.php" title="<?php echo $tooltip; ?>">some link

That should give you a simple tooltip. For anything fancier though you'll need to use Javascript.


text:
Q: VS.NET - Multiple Find All References Result Windows? Visual Studio has a "Find All References" tool that is great in navigating the codebase to find out where a function is called or where a variable is used. When navigating a large code base, I tend to do find all references multiple times to find the top level of where a function is called.
Imagine we have the following:
A1() calls B1(), B1() calls C()
A2() calls B2(), B2() calls C()
My problem:
If I do find all references on C(), I find both B1() and B2(), which is great.
Now, I try to find out where B1() is called. I find A1() calls B1(). Great!
However, I run into an issue when I want to back track and find out what calls B2(), but I lost track of B2()! By default, VS.NET only has window for the "Find All References" result. Since I found all references for B1() just now, I lost track of where C() was called. I now have to find all references to C(), and then find all references to B2(). I'm working in a large code base, and finding all references can easily take more than a minute for a function. It would be nice if I could save the results of a search, and future find all references would open a new window instead of overwriting the existing search.
Is there a setting in VS.NET 2008 or a free addon that would allow me to have multiple "Find All References" windows?
On a related note, VS.NET has 2 Find result windows for searching for text. Is there a way to have more?

A: I know this question is old, but apparently you can persist a results tab and get new results in a new tab, by using the "Keep Results" button at the panel's header (VS2017).

A: I don't know about studio, but Resharper does this for you.  It will keep track of all your previous searches when you use the "Find Usages" function.  You also have some good flexibility for hte scope of hte search (Current File, Project, Solution, etc), as well as options for searching (usages of base types, etc).
They do have a free trial, so see if that meets your needs.

A: Another useful trick is Ctrl+K+K (setting a bookmark) or Ctrl+K+N (traverse to next bookmark).  These get stored in the *.suo (user file) for Visual Studio.  This is also useful if you're searching large code bases and you get a million file tabs in Visual Studio.  If you keep the bookmark of where you're actually coding, you can flip back to that file tab in a blink of an eye.


text:
Q: type casted call to postgres stored procedure not matching I created a stored procedure via pgAdmin, logged in as 'postgres' (the only user, and an admin):
CREATE OR REPLACE PROCEDURE public."spCreateMeet"(
    "_MeetName" character varying,
    "_MeetBannerDescription" character varying,
    "_MeetDate" date)
LANGUAGE 'sql'
AS $BODY$
INSERT INTO public."tblMeet"
("MeetName", "MeetBannerDescription", "MeetDate")
VALUES ("_MeetName", "_MeetBannerDescription", "_MeetDate")
RETURNING "MeetId";
$BODY$;

Here's my call, being made directly in pgAdmin, logged in as same user that created it:
CALL spCreateMeet('TestMeet'::character varying,'blah'::character varying,'2021-06-01T00:00:00.000Z'::date)

It is properly type cast, and I've tried qualifying with 'public.', so why am I getting:
ERROR:  procedure spcreatemeet(character varying, character varying, date) does not exist

LINE 1: CALL spCreateMeet('TestMeet'::character varying,'blah...
             ^

HINT:  No procedure matches the given name and argument types. You might need to add explicit type casts.

A: First of all don't use upper case or camel case in column, table, function etc. names in postgresql because it is case sensitive. If you do that then it will create a problem every time.
you can see the error where it is showing the procedure name in small case. If you will not surround the names with double quote then it will treat it as small case only so the solution is surround the names with double quote.
Try this:
CALL "spCreateMeet"('TestMeet'::character varying,'blah'::character varying,'2021-06-01T00:00:00.000Z'::date)


text:
Q: How to update spinner2 whenever spinner1 is changed? I've got numbers from 1 to 12 in spinner1, and another spinner2 that I'd like to be controlled by what the user picked in the former.
Whenever user selects a number between from 1 to 6 in spinner1, spinner2 should show numbers from 1 to 31.
Whenever user selects a number between from 7 to 12 in spinner1, spinner2 should show numbers from 1 to 30.
I've managed to come up with this code, but it does not seem to work as above. Could help me in finding what's wrong?
package com.example.spinners;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {
Spinner sp1, sp2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sp1 = (Spinner) findViewById(R.id.SP1);
    sp2 = (Spinner) findViewById(R.id.SP2);

      List<String> list = new ArrayList<String>();

    list.add("1");  list.add("2");  list.add("3");  list.add("4");
    list.add("5");  list.add("6");  list.add("7");  list.add("8");
    list.add("9");  list.add("10"); list.add("11"); list.add("12");

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp1.setAdapter(dataAdapter);

    //
    sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long    id) {

           // userSelectedIndex = position;
        }

        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    //

    if (sp1.getSelectedItem().equals("1") || sp1.getSelectedItem().equals("2")
        || sp1.getSelectedItem().equals("3") || sp1.getSelectedItem().equals("4")
        || sp1.getSelectedItem().equals("5") || sp1.getSelectedItem().equals("6")) {

            //
          List<String> list2 = new ArrayList<String>();

            list2.add("1"); list2.add("2"); list2.add("3"); list2.add("4"); list2.add("5");
            list2.add("6"); list2.add("7"); list2.add("8"); list2.add("9"); list2.add("10");
            list2.add("11"); list2.add("12"); list2.add("13"); list2.add("14");
            list2.add("15"); list2.add("16"); list2.add("17"); list2.add("18");
            list2.add("19"); list2.add("20"); list2.add("21"); list2.add("22");
            list2.add("23"); list2.add("24"); list2.add("25"); list2.add("26");
            list2.add("27"); list2.add("28"); list2.add("29"); list2.add("30");
            list2.add("31");

            ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list2);
            dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sp2.setAdapter(dataAdapter2);

       } else if(sp1.getSelectedItem().equals("7") || sp1.getSelectedItem().equals("8") || sp1.getSelectedItem().equals("9") || sp1.getSelectedItem().equals("10") || sp1.getSelectedItem().equals("11") || sp1.getSelectedItem().equals("12")) {
    /////////////////////////////////////////////////////////

    //
      List<String> list2 = new ArrayList<String>();

    list2.add("1"); list2.add("2"); list2.add("3"); list2.add("4"); list2.add("5");
list2.add("6"); list2.add("7"); list2.add("8"); list2.add("9"); list2.add("10");
list2.add("11"); list2.add("12"); list2.add("13");  list2.add("14");
list2.add("15"); list2.add("16");   list2.add("17"); list2.add("18");
list2.add("19"); list2.add("20");   list2.add("21"); list2.add("22");
list2.add("23"); list2.add("24");   list2.add("25"); list2.add("26");
list2.add("27"); list2.add("28");   list2.add("29"); list2.add("30");

    ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list2);
    dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp2.setAdapter(dataAdapter2);
       }
    //
}

}

A: The problem in your code is, that you are checking the selected value only once, before the window has even opened. You need to check it every time a user changes the value. So you need that logic in your onItemSelectedListener. Here the revised code, with a few improvements (untested, but it should work).
public class MainActivity extends Activity {
    private Spinner sp1, sp2;

    private List<Integer> firstList = new ArrayList<Integer>();
    private List<Integer> secondList = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp1 = (Spinner) findViewById(R.id.SP1);
        sp2 = (Spinner) findViewById(R.id.SP2);

        for (int i = 1; i <= 12; i++) {
            firstList.add(i);
        }

        ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, firstList);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp1.setAdapter(dataAdapter);

        sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int currentValue = firstList.get(position);

                if(currentValue <= 6){
                    for (int i = 1; i <= 30; i++) {
                        secondList.add(i);
                    }
                } else {
                    for (int i = 1; i <= 31; i++) {
                        secondList.add(i);
                    }
                }

                ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(MainActivity.this, android.R.layout.simple_spinner_item, secondList);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                sp2.setAdapter(dataAdapter);
            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
}


text:
Q: Interval of Convergence of $\arctan(\frac{x}{\sqrt{2}})$ I am asked to find the power series of the function $f(x)=\arctan(\frac{x}{\sqrt{2}})$. I first found the derivative of this function which is: $f'(x)=\frac{\sqrt{2}}{2+x^{2}}$. Then I found the power series of $f'(x)$ which is: $\sum_{n=0}^{\infty }\frac{1}{\sqrt{2}}(-1)^{n}\left ( \frac{1}{2} \right )^{n}x^{2n}$. Then to get the power series of $f(x)$, I just integrated the previous power series term by term to get: $\sum_{n=0}^{\infty }\frac{1}{\sqrt{2}}(-1)^{n}\left ( \frac{1}{2} \right )^{n}\frac{x^{2n+1}}{2n+1}$. Now to find the radius of convergence, I found $-\sqrt{2}\leqslant x\leqslant \sqrt{2}$. However, when I entered this answer in the software, it doesn't accept this answer as a valid answer. Can anybody tell me where the problem is? Because I checked and I found that the series is convergent at the end points of my interval of convergence. Thanks!

A: The ratio test tells you the series converges if $-\sqrt{2}<x<\sqrt{2}$ and diverges if $x<-\sqrt{2}$ or $x>\sqrt{2}$.
But what happens when $x=\text{exactly }\sqrt{2}$ or $-\sqrt{2}$?

A: The radius of convergence of a power series is a non-negative number, that can have the value of $\infty$. You should try putting $R = \sqrt{2}$ into the software. Note that you should integrate power serieses only within the radius of convergence. Your answer is still correct event though strictly speaking not correctly established.


text:
Q: Deform a 2D shape from the shapes of the 3D object I have a 2D shape and a 3D object.
I would like to be able to deform the 2D shape from the shapes of my 3D object.
How could I do that?

Here is my 2D file

Here is my 3D file
I want to restructure the curves of my 3D shape on my 2D shape.
Basically deform my 2D from the 3D shapes


text:
Q: Best way to move an internal pointer of array in PHP Consider my following array
for($i=0;$i<10;$i++) $arr2test['a'.sprintf('%s',$i)]='arr # '.($i+1);

Now, I can access $arr2test by index. Like, I can echo $arr2test['a3'] to show the fourth element of this array.
My requirement is to get fifth element of this array. Let, I don't know the index of fifth element. I just know the fourth element index i.e. a3
I know I can do it by a foreach loop like code below -
$keyOfNextElement=null;
foreach($arr2test as $k=>$v){
    if(isset($a3Found)){
        $keyOfNextElement=$k;
        break;
    }
    if($k=='a3') $a3Found=true;
}
if(!is_null($keyOfNextElement)) echo arr2test[$keyOfNextElement];
else echo "Next element NOT found!!!";

Please consider a array that contain a lot of data like thousand or even more data.
So, in this case the above solution is not perfect one. Specially when I need to do such operation frequently.
Another note, I don't know weather its fourth or fifth element. I just know the index "a3" and I want the next element of "a3"

A: You can use array_keys().
$keys = array_keys($arr2test);
$index4 = array_search('a3', $keys);
$index5 = $keys[$index4+1];
$element5 = $arr2test[$index5];

A: Use array_slice:
$a4 = array_slice($arr2test, 4, 1);

A: I think this is a faster way to getting the index of fifth element
reset($arr2test);
for($j=1;$j<5;$j++){
    next($arr2test);
}
echo current($arr2test);


text:
Q: how to modify the value without updating it and then matching it with the element in mongodb? I have an element which whose value I am getting dynamically to match.
The only difference is the value in DB is concatenated with an underscore and the value I am getting is without underscore. So is there any way to modify the value according to what I am getting and apply "find".
Collection:
    "name": {
      "age": 23,
      "firstname": "sweta",
      "secondname": "sharma"},
      "hobbyImages": [
         0: "0_abc_0.jpg",
         1: "1_def_1.jpg"
      ]
    }

Query:
db.find({ "name.age": 23, "hobbyImages": imageName });

I am having an image name as abc.jpg
Expected Result:
The collection which I have mentioned above but I am not getting anything.
Does anyone have any idea how to remove the '_' and '0' and then check the element value?

A: You can try match the image with $regex.
const [name, ex] = imageName.split('.');
const regex = new RegExp(`\\d_${name}_\\d.${ex}`, "gi")
db.users.find(
   { "name.age": 23, "hobbyImages": { "$elemMatch": { "$regex": regex } } }
)


text:
Q: Year and month conversion in sql server I have convert this 1452361874 value into 2016-01-09 17:51:14 by using below code on sql server.
CONVERT (nVarchar(32), DATEADD(s, nDateTime, '01/01/1970'), 20)

Now,someone help me to find out individual month and year in different column.
Example:
January 1970

A: I have declared one variable to set value, and tried something like this.
To check output - execute below lines in your SQL,
DECLARE @nDateTime AS INT=1452361874
SELECT DATENAME(MONTH,CONVERT(NVARCHAR(32) ,DATEADD(s ,@nDateTime ,'01/01/1970') ,20)) MonthN,YEAR(CONVERT(NVARCHAR(32) ,DATEADD(s ,@nDateTime ,'01/01/1970') ,20)) YearN

As per your query you should write like below,
SELECT DATENAME(MONTH,CONVERT(NVARCHAR(32) ,DATEADD(s ,nDateTime ,'01/01/1970') ,20)) MonthName,YEAR(CONVERT(NVARCHAR(32) ,DATEADD(s ,nDateTime ,'01/01/1970') ,20)) YearName

A: you can select them as follows
SELECT DATENAME(month,MONTH( DATEADD(s, nDateTime, '01/01/1970'))) as [month],YEAR( DATEADD(s, nDateTime, '01/01/1970')) as [year]

A: DECLARE @dateval DATETIME

SET @dateval = CONVERT(NVARCHAR(32), DATEADD(s, 1452361874, '01/01/1970'), 20)

SELECT (CONVERT(VARCHAR(40), datename(month, month(@dateval))) + ' ' +
convert(VARCHAR(40), YEAR(@dateval))) AS 'Date'

A: Using a cross apply allows you to use the column alias ("cDateTime") in columns of the select clause.
select
     CONVERT(nVarchar(32), ca.cDateTime , 20) as nDateTime
   , DATENAME(MONTH, ca.cDateTime)
   + ' ' + CONVERT(nVarChar,YEAR(ca.cDateTime)) as mnth_yr
from yourtable
cross apply (
    select DATEADD(s, nDateTime, '19700101')
  ) ca (cDateTime)


text:
Q: What do "steady" and "steadily" mean here?
"To fall in love is easy, even to remain in it is not difficult; our human loneliness is cause enough. But it is a hard quest worth making to find a comrade through whose steady presence one becomes steadily the person one desires to be."

—   Anna Louise Strong

A: Putting in simple words,

Humans fall in love too easily because they're lonely. But it is hard to find someone who stays by your side and lets you be who you want to be. It's hard but it is worth it.

Interpretation always implies in different views. That is mine. Hope it helps you.

A: Falling in love is easy, and staying in love is also easy because people are afraid of being lonely. The difficult part [quest=the search] is finding that special someone who helps you become the person you want to be (i.e. a better person) in life. But it's worth it in the end.


text:
Q: Настроить запуск приложения в определенное время в iOS с проигрыванием музыки? Приложение должно срабатывать как будильник. В исходном состоянии приложение в бекграунде (1 случай) или выгружено из памяти (2 случай).
В назначенное время оно должно проснуться и запустить проигрывание звукового файла (либо музыкального потока с удаленного сервера)
Каким образом можно реализовать такое поведение (в iOS 10+, Swift 4)? Точно можно сделать - видел такие будильники в приложениях-радио.


text:
Q: Too few arguments to function route(), I am trying to use the index method of a resource controller but I get this error.
Too few arguments to function route(), 0 passed in D:\xampp\htdocs\SistemaHNF\storage\framework\views\c3a3dac715e2000606fb9805bd8426410ba15b72.php on line 14 and at least 1 expected (View: D:\xampp\htdocs\SistemaHNF\resources\views\gestionEspecialidades.blade.php)

I'm going to post the code in the view that tries to access the method and the code of the index method in the controller.
View Code (this is in app.blade)

                        {{ __('Gestion especialidades') }}

Controller code
public function index(){
   $especialidades = Especialidades::all();
   return view ('gestionEspecialidades',compact('especialidades'));
}

I dunno why I get the error if the index method doesn't require any parameters, the route is a resource route
Route Code
Route::resource('/especialidades', EspecialidadesController::class);

I'm new in Laravel so I don't have any idea what is giving me this error.
What I'm trying to do with that navbar is when I click in Gestionar Especialidad to run the index method to show all the values in a table in the view gestionEspecialidades, going to post the code of the view that I want to use the index method.
Second View code
    @extends('layouts.app')

@section('content')

Gestión Especialidades

            Nombre

        @foreach ($especialidades as $especialidad)

                {{$especialidad->nombre}}

        @endforeach

@endsection

What can be the cause of the error? Help will be appreciated. (English is not my main language so sorry for any mistakes, if you need more details or more code I can gladly update the question.)
Framework/view code
<?php $__env->startSection('content'); ?>

Gestión Especialidades

            Nombre

        <?php $__currentLoopData = $especialidades; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $especialidad): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>

                <?php echo e($especialidad->nombre); ?>
                <a href="<?php echo e(route()); ?>"> Editar
                 <a href="<?php echo e(route(/*Ruta para formulario Eliminar */)); ?>"> Eliminar

        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

    Registrar especialidad

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH D:\xampp\htdocs\SistemaHNF\resources\views/gestionEspecialidades.blade.php ENDPATH**/ ?>

A: Please try with route:
Route::resource('especialidades', 'EspecialidadesController');


text:
Q: How to set initial value for select element in AngularJS? I write dependent comboboxes and faced such problem - how to set initial value? For example, I have a form for adding new records:
Controller.js:
...
$http({
     url: '/api/address/fill',
     method: 'POST'
}).success(function (data) {
     $scope.itemsForLevelOne = data
}).error(function(errorData) {
   ...
});

$scope.updateOne = function() {
    $http({
         url: '/api/address/change',
         method: "POST",
         data: {'tobId' : $scope.itemOne.id}
    }).success(function (data) {
         $scope.itemsForLevelTwo = data;
    }).error(function(errorData) {
       ...
    });
};
...

View.html:
...
Level One
<select class="form-control m-b"
        data-role="listview"
        data-inset="true"
        ng-options="someValue as someValue.tobName for someValue in itemsForLevelOne"
        ng-model="itemOne"
        x-ng-change="updateOne(itemOne)">
</select>

Level Two
<select class="form-control m-b"
        data-role="listview"
        data-inset="true"
        ng-options="someValue as someValue.tobName for someValue in itemsForLevelTwo"
        ng-model="itemTwo"
        x-ng-change="updateTwo(itemTwo)">
</select>
...

From the controller I can make call to the server- side (Play Framework in my case) and then extract data from the database and save them.
In the forms of editing and deleting records I should to set the initial values for all select elements.
How can I do it?

A: AngularJS uses bidirectional  binding. The selected option is stored in the ng-model attribute when a selection is made, and it's also read from the ng-model attribute on order to display the correct selection.
So you pick the element to select from the array of options, and initialize the variable corresponding to the ng-model of the select. For example, to have the first element selected, you do
$scope.itemOne = $scope.itemsForLevelOne[0];

A: You should use ng-repeat instead of ng-options
<select>
        <option ng-repeat="someValue as someValue.tobName for someValue in itemsForLevelTwo"  ng-selected="expression_to_be_evaluated"
</select>

ng-repeat with the option tag, gives you more control than ng-options.

A: What JB said, but remember it is IMPERATIVE that the values match between the object that you pass to the ng-model and the list values themselves; In your case:
$scope.itemOne = someValue;
$scope.itemTwo = someValue2;

someValue and someValue2 NEED to match up with a corresponding option value, or else you will end up with the dreaded empty first box.
Another solution would to add a default chooser option which instructs the user to choose an option:
...
Level One
<select class="form-control m-b"
        data-role="listview"
        data-inset="true"
        ng-options="someValue as someValue.tobName for someValue in itemsForLevelOne"
        ng-model="itemOne"
        x-ng-change="updateOne(itemOne)">
    <option>Please Select An Item</option>
</select>
...

This way, the person filling out the form will never select an option involuntarily. This default option, because it has no value, will disappear when a selection is made.


text:
Q: Are mass and charge manifistations of the same thing? Even though mass and charge are two different physical properties of matter, have there been any attempts at unifying them? say, by defining a physical property of matter such that mass and charge are naturally derived from it, and are regarded as different manifestations of the same physical phenomenon?
Kind of like how the electric and magnetic fields are related by Maxwell's equations (also the fact that a magnetic field is basically an electric field in a different reference frame), or how mass and energy are related.

A: Yes, there have been attempts to unify these concepts. The earliest was done by Kaluza and Klein, who imagined that we lived in a $5$ dimensional universe, and the electromagnetic field was really a manifestation of gravity in the extra, fifth dimension.
Gravity, which is a manifestation of the curvature of spacetime, is described by the metric of spacetime $g_{\mu\nu}$, a $4\times 4$ matrix. In this five dimensional universe, we have a five dimensional metric $\tilde{g}_{ab}$, a $5\times 5$ matrix, parametrized by
$$\tilde{g}_{ab}=\begin{pmatrix}g_{\mu\nu}+\phi^2A_{\mu}A_{\nu} && \phi^2 A_{\mu}\\ \phi^2 A_{\nu} && \phi^2 \end{pmatrix}$$
Where $g_{\mu\nu}$ is a four dimensional metric, $A_{\mu}$ is a four dimensional vector potential, which describes the electromagnetic field, and a scalar field $\phi$. If $\phi$ is constant, the five dimensional Einstein field equations
$$\tilde{R}_{ab}-\frac{1}{2}\tilde{g}_{ab}\tilde{R}=0$$
miraculously reproduce both the four dimensional Einstein field equations, and Maxwell's equations.
And so in this five dimensional universe, charge is just a different manifestation of the five dimensional energy-momentum tensor $\tilde{T}_{ab}$ that would appear on the RHS of the above equation.


text:
Q: Mongoose - Cast to ObjectId failed, Multiple IDs return new SavedMember({
    id: member.id, // ID of the user
    guildId: member.guild.id // ID of the guild
}).save();

gives error:
  message: 'Cast to ObjectId failed for value "218459216145285121" at path "_id" for model "member"',
  name: 'CastError',
  model: Model { member }

member.ts
const memberSchema = new Schema({
    _id: Types.ObjectId,
    id: String,
    guildId: String,
    xpMessages: { type: Number, default: 0 },
    warnings: { type: Array, default: [] }
});
...
export const SavedMember = model<MemberDocument>('member', memberSchema);

Repo: https://github.com/theADAMJR/2pg-dashboard

A: Based on this other answer here:
Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.
So, when you try to add a new document, the id property refers to _id


text:
Q: function for word frequency + dictionary I am trying to create a function to take in a string and return how many times a word in it has been used (with the word) as a dictionary. I also want it to look for a specific list of words to search up the string when provided and return the frequency of the words in the given list found in the string.
Example,
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc))

should return
{'i':1 , 'went':1, 'to':2, 'school':1, 'today':1, 'learn':1}
And,
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc,wordlist=["I", "feel", "Great"]))

should return
{'i':1, 'feel':0, 'great':0}
This is what I have so far
def wordfunc(stringfunc,wordlist=[]):
    count_dict = dict()
    stringfunc=stringfunc.lower()  # i want it to be case insensitive
    word = stringfunc.split()
    for i in range(len(word)):
        x =  ord(word[i][-1]) # in the next few lines I am trying to get rid of special characters
        if (not(x>=97 and x<=112) or (x>=65 and x<= 90)):
            word[i]=word[i][:-1] # if a word ends with , or ! i want it to discount last character
    for i in wordlist:
        if (i not in word):
            count_dict[i]=0
        else:
            count_dict[i]=word.count(i)
    return count_dict

When I try
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc,wordlist=["I", "feel", "Great"]))

I get
{'I':1, 'feel':0, 'Great':0} # i can't get a lower case i don't know why
and when I try
stringfunc = "I went to school today, to learn!"
print(wordfunc(stringfunc))

I get an empty dictionary {}
Can you help me identify my error? Thanks!

A: You "can't get lower case" because you didn't program it.  If the input supplies wordlist, then you blithely accept whatever is there.  In the given case, you have two words capitalized, so that's what comes out.  Instead, you need to convert every element of wordlist to lower case, just as you did with the input string.
BTW, do not give misleading names to variables: stringfunc is not a function.
The main loop will be much easier to read if  you quit playing games with ASCII code values.  Instead, simply use isletter.  If this is new to you, then I strongly recommend that you repeat your tutorial on string processing; you missed some useful things that you will now recognize.
That said, also look up the collections package, notably the Counter type.  Once you've cleaned out all but letters and spaces in your input string, you can do the main processing with
count_dict = Counter(stringfunc.split())


text:
Q: Mongoose find query with populate returns error on Azure MongoDB after query results hit 500+ I'm pretty new to MongoDB, Mongoose, also Azure Environments. I'm having trouble with a specific query which worked fine. But it generates error after the expected query results is 500+. The results is the accumulated report which can have maximum 1200 records. And the results is generated from 2 collections with population. Following is my node.js/express api function that generates the results.
index: (req, res, next) => {
    Store.find({isChecked: true}).batchSize(1200)
    .populate('lastCheckResult').exec(function (err, stores) {
      if (err) {
        console.log(err);
        return next(err);
      }
      else {
        res.locals.stores = stores;
        return next();
      }
    });
  },

And the following is the error from Azure Web app(node.js).

"Message: {"errors":[{"severity":"Error","location":{"start":0,"end":75279},"code":"SC3004","message":"The SQL query exceeded the maximum number of 'OR' operators. The allowed limit is 500."}]} ActivityId: 96ebe198-0000-0000-0000-000000000000, Request URI: /apps/32fe74cb-f1dd-4433-bfbf-ba15991cdee1/services/d914c6a9-eb86-43d8-9108-4ee395d25345/partitions/aa7a586e-7f30-4a02-99e4-8a21d2dc8295/replicas/131759772120608879s, RequestStats: ResponseTime: 2018-07-30T10:54:11.9018240Z, StoreReadResult: StorePhysicalAddress: rntbd://10.0.0.48:14000/apps/32fe74cb-f1dd-4433-bfbf-ba15991cdee1/services/d914c6a9-eb86-43d8-9108-4ee395d25345/partitions/aa7a586e-7f30-4a02-99e4-8a21d2dc8295/replicas/131759772120608879s, LSN: 2965, GlobalCommittedLsn: 2964, PartitionKeyRangeId: 0, IsValid: True, StatusCode: 0, IsGone: False, IsNotFound: False, IsInvalidPartition: False, RequestCharge: 1, ItemLSN: -1, ResourceType: Document, OperationType: Query , SDK: Microsoft.Azure.Documents.Common/2.0.0.0"

Anyone help me how to fix or workaround this kind of problem?

A:
The SQL query exceeded the maximum number of 'OR' operators. The
  allowed limit is 500.

Based on your error log, I presume that you are using Cosmos DB Mongo API. In fact, CosmosDB is an independent server implementation that does not directly align with MongoDB server versions and features.
CosmosDB supports a subset of the MongoDB API and translates requests into the CosmosDB SQL equivalent. CosmosDB has some different behaviours and results. But the onus is on CosmosDB to improve their emulation of MongoDB.
I suggest you you could split the number of your query data per batch to temporarily avoid this limitation. I also searched similar case related to limitation:The SQL query text exceeded the maximum limit of 30720 characters in Azure CosmosDB.
Certainly, you could add feedback here to get official assistance or consider using MongoDB Atlas on Azure if you'd like full MongoDB feature support.
Hope it helps you.


text:
Q: SchemaToolTask not found in datanucleus-rdbms.jar I have started with data nucleus a couple of days ago.
I have downloaded the jdo tutorial and am trying to run it.
I have collected all the jar files related to the tutorial here .
I am using ant for building. "compile" and "enhance" tasks work fine. The "createschema" task is spitting the following error out!

C:\datanucleus\datanucleus-samples-jdo-tutorial-3.0\build.xml:123:

taskdef clas
      org.datanucleus.store.rdbms.SchemaToolTask
  cannot be found

I have checked datanucleus-rdbms.jar for the SchemaToolTask and I didn't find that class in the jar file.
I downloaded it from here .
Why is that class not there?? Am I using the wrong jar file?

A: Why would you download 3.0 and use it with a tutorial for v 1.0?

A: In version 3.x the location of the SchemaToolTask changed from:
org.datanucleus.store.rdbms
to:
org.datanucleus.store.schema
reflecting the fact that the Schema tool is datastore agnostic.

A: Found that I was using source jar files instead of the binaries.
[Closing the question by marking this as the answer]


text:
Q: Error instalar Urllib2 desde terminal: ERROR:Could not find a version that satisfies the requirement urllib2 Estoy intentando installar urllib2 desde la terminal usando el comando:
pip install urllib2

El error que me aparece es el siguiente

ERROR:Could not find a version that satisfies the requirement urllib2
ERROR: No matching distribution found for urllib2

Gracias

A: Resumiendo:
No necesitas instalar urllib2 en absoluto.
urllib2 era un paquete incluido en Python 2. En Python 3 ese mismo paquete se separó en varias partes. Según la propia documentación:

The urllib2 module has been split across several modules in Python 3
named urllib.request and urllib.error.

Comento esto porque si te has visto en la necesidad de instalar urllib2 sospecho que estás intentando trabajar con algo pensado para Python 2 en Python 3.
De ser así tienes varias opciones:

*

*utilizar urllib.request en lugar de urllib2

*utilizar el paquete requests

*migrar tu script de Python 2 a Python 3 con 2to3
Opciones que NO deberías plantearte:

*

*Utilizar Python 2


text:
Q: How can C read chinese from console and file I'm using ubuntu 12.04
I want to know how can I read Chinese using C
  setlocale(LC_ALL, "zh_CN.UTF-8");
  scanf("%s", st1);
  for (b = 0; b < max_w;b++)
  {
    printf("%d ", st1[b]);
    if (st1[b] == 0)
        break;
  }

For this code, when I input English, it outputs fine, but if I enter Chinese like"的",it outputs
Enter word or sentence (EXIT to break): 的
target char seq :
-25 -102 -124 0

I'm wondering why there is negative values in the array.
Further, I found that the bytes of a "的" in file read using fscanf is different from reading from the console.

A: UTF-8 encodes characters with a variable number of bytes. This is why you see three bytes for the 的 sign.
At graphemica - 的, you can see that 的 has the value U+7684 which translates to E7 9A 84 when you encode it in UTF-8.
You print every byte separately as an integer value. A char type might be signed and when it is converted to an integer, you can get negative numbers too. In your case this is

*

*-25 = E7

*-102 = 9A

*-124 = 84

You can print the bytes as hex values with %x or as an unsigned integer %u, then you will see positive numbers only.
You can also change your print statement to
printf("%d ", (unsigned char) st1[b]);

which will interpret the bytes as unsigned values and show your output as
231 154 132 0

A: There's no need (and in fact it's harmful) to hard-code a specific locale name. What characters you can read are independent of the locale's language (used for messages), and any locale with UTF-8 encoding should work fine.
The easiest (but ugly once you try to go too far with it) way to make this work is to use the wide character stdio functions (e.g. getwc) instead of the byte-oriented ones. Otherwise you can read bytes then process them with mbrtowc.


text:
Q: Shared ADBannerView from AppDelegate - how to get the ad from the delegate I have done a fair bit of reading around on have found a few SO questions below:
using shared instance of ADBannerView across app with UITableViews
How to make a single shared instance of iAd banner throughout many view controllers?
AdBannerView shared across multiple views, including the rootviewcontroller, how?
I would like to have a single ADBannerView that is loaded in my AppDelegate class in the didFinishLoading method. The hope is that this ADBannerView can then be retrieved by all of the relevant ViewControllers (by importing the AppDelegate.h) and then just displayed accordingly when the user moves between VC's.
The code that I have implemented is the following:
AppDelegate.h
    @interface AppDelegate : UIResponder
@property (strong, nonatomic) IBOutlet ADBannerView *adView;
@property (nonatomic, assign) BOOL bannerIsVisible;

- (ADBannerView *)sharedAdBannerView;

AppDelegate.m
ADBannerView *adView;
BOOL bannerIsVisible;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions(NSDictionary *)launchOptions
{
    // create the iAdBannerView
    adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
    adView.frame = CGRectOffset(adView.frame, 0, -50);
    adView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
    adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
    adView.delegate=self;
    self.bannerIsVisible=NO;

    // Override point for customization after application launch.
    return YES;
}

#pragma begin of iAdBannerView Delegate Methods
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{

    if (self.bannerIsVisible)
    {
        [UIView beginAnimations:@"animateAdBannerOff" context:NULL];
        banner.frame = CGRectOffset(banner.frame, 0, -50);
        [UIView commitAnimations];
        self.bannerIsVisible = NO;
    }

}

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{

    if (!self.bannerIsVisible)
    {
    [UIView beginAnimations:@"animateAdBannerOn" context:NULL];
    // banner is invisible now and moved out of the screen on 50 px
    banner.frame = CGRectOffset(banner.frame, 0, 50);
    [UIView commitAnimations];
    self.bannerIsVisible = YES;
    }

}

- (ADBannerView *)sharedAdBannerView
{
    return adView;
}

I have also tried a variation using the [NSNotificationCenter defaultCenter] postNotificationName: methods but in the end I am faced with the same issue:
Problem:
In the ViewController I want to display the ADBannerView how do I retrieve it from the AppDelegate?
I have currently:
ADBannerView *banner = [[UIApplication sharedApplication] sharedAdBannerView];
[self.view addSubview:banner];

But I am getting a multitude of errors and cannot seem to get around it.
Error: No visible @interface for UIApplication declares the sector sharedAdBannerView.
I'm sure I'm missing something pretty fundamental.
Any help would be greatly appreciated... Thanks, James

A: You've to import ADBannerView.h in your AppDelegate.m.
By the way, have a look at Apple sample project "iAd Suite"

A: Creating a shared iAdBannerView is one of these topics, were you can read for days and in the end either give up or write the few lines of code necessary. I've chosen the second way and created this few lines of code.
import UIKit
import iAd

// Used thrughout the applcation to show banner when possible
private let applicationADBannerView = ADBannerView(adType: ADAdType.Banner)

// Simple base class for controllers to share one banner view.
// To use this class, inherit a view controller from it and add
// a UIView as container for the banner. The size of the
// container is used as banner size
internal class BaseViewControllerWithBanner: UIViewController, ADBannerViewDelegate {
    private var bannerContainer: UIView?

    internal func viewDidLoad(bannerContainer: UIView) {
        super.viewDidLoad()
        self.bannerContainer = bannerContainer
    }

    internal func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
        log(error)
        applicationADBannerView.delegate = nil
        applicationADBannerView.removeFromSuperview()
    }

    internal override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        applicationADBannerView.delegate = self
        applicationADBannerView.frame = bannerContainer?.frame ?? CGRectZero
        bannerContainer?.addSubview(applicationADBannerView)
    }

    internal override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        applicationADBannerView.delegate = nil
        applicationADBannerView.removeFromSuperview()
    }
}

To use this class simply inherit and override the viewDidLoad method like in this example.
import UIKit

internal class BanneredViewController: BaseViewControllerWithBanner {
    @IBOutlet weak var bannerViewContainer: UIView! // Position and link this in the xib or storyboard

    internal override func viewDidLoad() {
        log("BanneredViewController: viewDidLoad")
        super.viewDidLoad(bannerViewContainer)
        ... do all other stuff ...
    }
}

And it works perfectly: 100% of all Requests get filled in all countries, that support iAd's.


text:
Q: cPanel Email Pipe Program I want to run a PHP program when receiving emails, and so far, I've had no luck. I have this code in the "Set Default Address" page on cPanel:

mailhandler.php contains the following PHP code:
#!/usr/local/lib/php -q
<?php

  $DataBase = array(
                      'host' => 'localhost',
                      'port' => 3306,
                      'username' => 'dbusername',
                      'password' => 'dbpassword',
                      'database' => 'dbdatabase',
                    );

  // Establish secure database connection
  $DB = @new mysqli($DataBase['host'], $DataBase['username'], $DataBase['password'], $DataBase['database'], $DataBase['port']);

  $DB->query("INSERT INTO test (text) VALUES('Mail received!')");
?>

I've tried running the PHP script from the browser, and the text "Mail received!" is stored into the table. However, when I send a mail, nothing happens. I receive the email on my email account, but nothing is inserted into the database.
Edit: I am receiving the following mail when trying to send a mail to my server:

This message was created automatically by mail delivery software.
A message that you sent could not be delivered to one or more of its
  recipients. This is a permanent error. The following address(es)
  failed:
pipe to |/home/MY USERNAME HERE/public_html/mailhandler.php
      generated by MY EMAIL HERE
      local delivery failed
The following text was generated during the delivery attempt:
------ pipe to |/home/MY USERNAME HERE/public_html/mailhandler.php
         generated by MY EMAIL HERE ------
Could not exec '/home/MY USERNAME HERE/public_html/mailhandler.php'
------ This is a copy of the message, including all the headers. ------
Return-path:  Received: from
  mail-qa0-f67.google.com ([209.85.216.67]:64353)
          by SERVER URL HERE with esmtps (TLSv1:RC4-SHA:128)
          (Exim 4.82)
          (envelope-from )
          id 1WeXDD-0006Pe-Nn
          for MY EMAIL HERE; Mon, 28 Apr 2014 02:06:17 +0400 Received: by mail-qa0-f67.google.com with SMTP id dc16so744105qab.2
          for ; Sun, 27 Apr 2014 15:06:28 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
          d=gmail.com; s=20120113;
          h=mime-version:date:message-id:subject:from:to:content-type;
          bh=uuzTLjs2Sa8uqU2HBL4i1frXIc2i13Cxtg9X0Mykahg=;
          b=A/0fGQwjV6g1G+TBL12DIASjLqcl9h7jD9LOFKEm6MX0YL4uFa3ZRJ9zdou9dio9Hf
           yjPJv+yTFjV3W7mzydQc7pvkyTSRpHPbxN/B7yySagzB5PPMbrhebLGJoNTBSrtFaidS
           4Zax/qtOoj/GRnNf9srmtq8IQS4Np1EKJWn+uiKTxDBj2IPU3p2ng8ufkW8cKehHVJFR
           A7DOm9v26JZq3NRpNt8ct7yuSsOp8Nwqwe49p9703FvoePXvu6on2GZwiNTlD6fcJjf5
           /wtwHpMqu8YVZ0Ehx0GXNgqDtpsINrmgIAil9dPfdTF7VtJiIIq9x9sm6yAPzUtTQTBw
           9gUA== MIME-Version: 1.0 X-Received: by 10.140.26.243 with SMTP id 106mr11307188qgv.91.1398636388049;  Sun, 27 Apr 2014 15:06:28
  -0700 (PDT) Received: by 10.224.131.198 with HTTP; Sun, 27 Apr 2014 15:06:28 -0700 (PDT) Date: Mon, 28 Apr 2014 00:06:28 +0200 Message-ID:

  Subject: heeei From: MY NAME HERE  To:
  MY EMAIL HERE Content-Type: multipart/alternative;
  boundary=001a11c00c9814689304f80d6998
--001a11c00c9814689304f80d6998 Content-Type: text/plain; charset=UTF-8
test
--001a11c00c9814689304f80d6998 Content-Type: text/html; charset=UTF-8

  test

  --001a11c00c9814689304f80d6998--

A: 'Could not exec' likely means you don't have the permissions set correctly on that PHP file.  You need to make sure that PHP file is executable.  755 should be good.
I realize this is an old thread but I recently did all of this and figured I'd post in case someone else ran across it.


text:
Q: Limit of infinity times 0 I have a question regarding a specific step in the proof of the theorem that 'differentiability implies continuity'.
The proof in my calculus book asserts that if $h\to0$ then:
$$\frac{f(x+h)-f(x)}{h}=f'(x)$$
Therefore:
$$f(x+h)-f(x)=f'(x)h=f'(x)0=0$$
I can imagine cases where $f'(x)$ may be infinite, such as in the case of $g'(0)$ when $g(x)=x^\frac{1}{3}$
Question: how can one be sure that $f'(x)0$ is always $0$, even in the case of an infinite slope?

A: The key point ultimately boils down to:

If $\lim_{n\to\infty} a_n$ and $\lim_{n\to\infty} b_n$ exist, then $\lim_{n\to\infty} a_nb_n$ exists and equals $\left(\lim_{n\to\infty} a_n\right)\left(\lim_{n\to\infty} b_n\right)$.

Recall that existence of a limit (within $\Bbb R$) means specifically that the limit is a real number, so finite.

A: Note that the hypothesis of the theorem is differentiability; hence the theorem is not applicable to non-differentiable functions. A function $f$ not differentiable at a point $c$ is by definition such that $\lim_{h \to 0}[f(c+h) - f(c)] /h$ does not exist. The function $x \mapsto x^{1/3}$ is, for example, not differentiable at $0$; for we have
$$
h^{1/3}/h = h^{-2/3} \to \infty
$$
as $h \to 0.$


text:
Q: How to randomly initialize layers in pretrained model? I am using Xception model with pre initialized weights trained on ImageNet as so:
model = keras.applications.Xception(
    weights='imagenet',
    input_shape=(150,150,3)
)

Now I Would like to take specific layer (by its name, using model.get_layer(layerName)) and then reinitialize its weights to completely random one.
What is the simplest way to do so, and if it is even possible?

A: You could use a reinitialize function like this:
def reinitialize_layer(model, initializer, layer_name):
    layer = model.get_layer(layer_name)
    layer.set_weights([initializer(shape=w.shape) for w in layer.get_weights()])

Instead of layer_name you could also work with the layer index. You could also extend the function such that it takes a list of layer names, if you like to reinitialize more than one layer.
Usage example:
import keras

model = keras.applications.Xception(
    weights='imagenet',
    input_shape=(299,299,3)
)

# zeros as illustrative example, change to something else
initializer = keras.initializers.Zeros()

# check pretrained weights
print(model.get_layer("predictions").get_weights())

# change "predictions" to whatever layer name you like to use instead
reinitialize_layer(model, initializer, "predictions")

# check weights after reinitialization
print(model.get_layer("predictions").get_weights())

model.compile(...)
model.fit(...)


text:
Q: Basic VS extension to run snippet and render out results (similar to watch) I'd like to develop an extension for Visual Studio that runs a small snippet of code during runtime once a breakpoint's been hit.
To add some clarity, I pretty much want to call some code just as I would by manually writing it in the immediate window and render the results nicely (preferably a tree view).
I was reluctant to post this question since it seems pretty broad at first glance, but I'm fairly certain there aren't many different ways to achieve this.
I did originally look into Roslyn, but I believe that's for compile-time only if I'm not mistaken?
I have the code to do this already, and it runs perfectly in the immediate window, but I want to box it up as a feature since it's a bit cumbersome to manually enter it, and navigating it isn't easy either. what I need is somewhere between a 'watch' and an 'immediate' feature.
Question
Which platform/technology allows me to extend Visual Studio in a way I can run snippets of code 'ad hoc' during runtime and display the results nicely?

A: I suggest looking into this:

*

*Aspect-oriented programming

*Castle DynamicProxy

*And perhaps CSharpScript.EvaluateAsync to evaluate code snippets in runtime

A: Q: Which platform/technology allows me to extend Visual Studio in a way I can run snippets of code 'ad hoc' during runtime and display the results nicely?
I would approach this as follows:

*

*Create a visual studio extension with your new window. This involves installing the Visual Studio SDK (it's shipped with VS nowadays) and then creating a window the usual way. As an example, you can check my project https://github.com/atlaste/CPPCoverage -> CoverageExt which has some code for that. There's also a lot of examples on https://github.com/Microsoft/VSSDK-Extensibility-Samples .

*To do that, first create a tiny C# file in a temp folder.

Basically you create a function as follows:
// Add some convenient using's.

public class EvaluationClass {
  public static object Evaluate() {
    return /* paste the evaluated expression here */;
  }
}

The good thing about this method is that results are automatically boxed/casted to object, which is fine. The only issue here is that you might want to make a second compile run for the void case, which will fail because it cannot be boxed/casted to object.
Next,

*Use csc.exe to compile a DLL. Handle errors accordingly. CSC is located in your .NET framework folder (c:\windows\microsoft.net\framework[x]\...)

*Use reflection to load the DLL and execute the method in the extension.

The basic trick is as follows:
try {
  var assembly = Assembly.Load(tempDllName);
  // TODO: check if assembly is null --> compilation error

  var eval = assembly.GetType("EvaluationClass").GetMethod("Evaluate");
  // TODO: check if eval is null --> compilation error

  var result = eval.Invoke();

  // Draw result on window
}
catch (Exception ex) {

  // Handle exception appropriately
}

*Improve on this... the most useful thing here would be to grab the top stack frame from the debugger and pass the this object as value to the method... I haven't looked into how to do that; it should be available in the API somewhere though...


text:
Q: How to get smart tabs ("indent with tabs, align with spaces") behavior in Xcode? I used to use tabs for indentation and spaces for alignment.
Like so (arrows show tabs and dots show spaces).

In QtCreator you can set such coding style in standard preferences.
I can't find the way to achieve the same goal in Xcode. Could you please tell me if it is possible?
May be there is a plugin for that?
UPDATE:
Here is how it can be achieved in QtCreator:

P.S. Please, don't try to persuade me that using spaces only/tabs only is better, otherwise this question will turn into another holywar :)
Once more about what I'm trying to achieve: Indent with tabs, align with spaces. Vim Tips Wiki.
UPDATE 2: I've just submitted an Apple Radar bug-report (enhancement) rdar://22285639. Here it is on the open radar.
UPDATE 3: I received an answer from Apple. My bug is a duplicate of rdar://8165023.

A: In Xcode > Preferences (⌘,):

If I understand your question correctly, this should do it for you.

A: If you want to remap the standard Xcode's ⌘+[ to TAB, you can do the following:

*

*Install a program called "Karabiner".

*Go to Preferences ~> "Misc and Uninstall"

*In "Custom Setting" section click on the "Open private.xml" button

*Open the file and replace its content with the following code:
<?xml version="1.0"?>
<root>
    <item>
        <name>Tab instead of Command+[</name>
        <identifier>private.swap_tab_and_cmnd+[</identifier>
        <autogen>
            __KeyToKey__
            KeyCode::TAB, ModifierFlag::NONE,
            KeyCode::BRACKET_RIGHT, ModifierFlag::COMMAND_L | ModifierFlag::NONE
        </autogen>
    </item>
</root>

*Go to Preferences ~> "Change Key" ~> click on "Reload XML" button

*Put a tick in the checkbox which is called "Tab instead of Command+["

*Enjoy

PS: Please note that this setting works globally on your machine, not just in Xcode. However, I am sure that google might help you to find a solution how to customize it even further, applying the changes only to Xcode.

A: In XCode
Xcode > Preferences or use ⌘ , to open Preferences
now click on the Text Edit tab and then there is sub tab bar click on Indentation and you can change setting of the Indentation as you need


text:
Q: R Shiny - Editing a data table inside a dynamically created bsModal The app below contains an actionButton Add data that inserts a UI element each time it is clicked. Each UI element is a box that contains one selectInput Select data and an actionButton Edit that opens a modal when clicked.
Each modal contains:

*

*A data table with two columns: Parameter and Value (this column is editable).

*An actionButton Apply, which applies any changes made to the Value
column.

When the user selects a dataset inside box x, a reactiveValue is created to store the corresponding parameters in a data.frame x_paramset (where x is the id of the box inserted via insertUI) and add a val column which has the same value as default (see list at the top of code below). I then use renderDataTable to add the Value column (which contains the numericInput) - this data table is displayed inside the modal.
To update the data.frame to apply any changes the user may have made in the modal, I use an observeEvent that listens for the Apply button and updates the val column in the data.frame x_paramset with the values inside the numericInputs in the Value column.
Here is the app (the bsModal has been commented out and replaced with a shinyWidgets::dropdownButton):
library(shiny)
library(shinydashboard)
library(shinyjs)
library(shinyWidgets)
library(DT)
library(tidyverse)

all = list(p1 = list(a = list(id = "a", default = 10)),
           p2 = list(x = list(id = "x", default = 20)))

# UI ----------------------------------------------------------------------

ui<-fluidPage(shinyjs::useShinyjs(),

              tags$head(
                tags$script("
                            $(document).on('click', '.dropdown-shinyWidgets li button', function () {
                            $(this).blur()
                            Shiny.onInputChange('lastClickId',this.id)
                            Shiny.onInputChange('lastClick',Math.random())
                            });

                            ")
                ),

              box(title = "Add data",
                  column(width = 12,
                         fluidRow(
                           tags$div(id = 'add')
                         ),
                         fluidRow(
                           actionButton("addbox", "Add data")
                         ))
                  )
              )

# SERVER ------------------------------------------------------------------

server <- function(input, output, session) {

  rvals = reactiveValues()

  getInputs <- function(pattern){
    reactives <- names(reactiveValuesToList(input))
    name = reactives[grep(pattern,reactives)]
    }

  observeEvent(input$addbox, {
    lr = paste0('box', input$addbox)
    insertUI(
      selector = '#add',
      ui = tags$div(id = lr,
                    box(title = lr,

                        selectizeInput(lr, "Choose data:", choices = names(all)),

                        shinyWidgets::dropdownButton(inputId = paste0(lr, "_settings"),
                                       circle = F, status = "success", icon = icon("gear"), width = "1000px",
                                       tooltip = tooltipOptions(title = "Click to edit"),

                                       tags$h4(paste0("Edit settings for Learner", lr)),
                                       hr(),
                                       DT::dataTableOutput( paste0(lr, "_paramdt") ),
                                       bsButton(paste0(lr, "_apply"), "Apply")
                        ) # end dropdownButton

                        )

      ) #end tags$div
    ) # end inserUI

    # create reactive dataset
    rvals[[ paste0(lr, "_paramset") ]] <- reactive({

      do.call(rbind, all[[ input[[lr]] ]]) %>%
        cbind(., lr) %>%
        as.data.frame %>%
        mutate(val = default)

    }) # end reactive

    # render DT in modal
    output[[ paste0(lr, "_paramdt") ]] <- renderDataTable({

      DT <- rvals[[ paste0(lr, "_paramset") ]]() %>%
        mutate(
          Parameter = id,
          Value = as.character(numericInput(paste0(lr,"value",id), label = NULL, value = default))) %>%
        select(Parameter:Value)

      datatable(DT,
                selection = 'none',
                #server = F,
                escape = F,
                options = list(preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
                               drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))

    }) # end renderDT

    # Apply changes
    observeEvent(input$lastClick, {

      # replace old values with new
      rvals[[ paste0(lr, "_paramset") ]](rvals[[ paste0(lr, "_paramset") ]]() %>%
                                           mutate(
                                             val = input$box1valuea
                                             )
                                           )
    }) # end apply changes observeEvent

  }) #end observeEvent
}

shinyApp(ui=ui, server=server)

I encounter errors when I try the following:

*

*Add data >> Edit >> make some change to numericInput >> Apply - this
resets the numericInput inside the modal back to its default whereas
I would like the user-specified value to persist upon applying
changes or closing the modal.

*The app crashes when I try:
Add data >> Edit >> Apply >> close modal >> Add data OR
Click Add data twice and then click Edit in either box.

I am not sure where my server logic is failing. I know Shiny does not support "persistent use" modals (https://github.com/rstudio/shiny/issues/1590) but I was wondering if there was a workaround? I am also not sure what inside the insertUI observeEvent is causing the app to crash in the cases described above. Any help you can offer would be greatly appreciated!


text:
Q: Any lib can manipulate attributes of the HTML code while keeping original data Suppose if I have below code. As you can see, I have some script or data wrapped with "%%[" and "]%%". And normally it is illegal. That's the original data I want to keep. Meanwhile I want to Add/Change/Remove the attributes in the
. Then output the code after modified.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

%%[
Sever Language data here
]%%
<title>%%=v(@variable)=%%</title>

        <custom name="opencounter" type="tracking">

            Something here

I've tried lots of way to work on this. I've tried Beautifulsoup. But it will change some special character like "—" to "&mdash". I want to keep the special character if it's not coded as escaped character. Beautifulsoup also change the order of the attribute. For the <custom> tag, it will convert it to <custom></custom>. I think Beautifulsoup is a lib good at parsing data not manipulating data.
I also tried jsdom long ago, it was working fine I think. But it still have some trouble with <custom> issue. It will have some trouble with changing  to . Not sure if jsdom will keep the illegal data. And it's working very slow...
I've also tried to use jQuery in browser to output with .html() function. But it will change the order of the attribute. And for the
 tag, it will insert
 in it which isn't what I want.
So suppose I want to change the cellpadding to 10. The code should looks like below. Maybe I can allow the different order of the attribute. Does anyone have any idea on what lib I can use or what kind of thing I can do to work on this requirement. Welcome any comments!!! BTW, I'm not sooo familiar with regular expression. I think it will makes me frustrating...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

%%[
Sever Language data here
]%%
<title>%%=v(@variable)=%%</title>

        <custom name="opencounter" type="tracking">

            Something here

A: jQuery I believe should do what you want, but not with the .html() function. Keep the table as-is, then use jQuery to select it and modify the attributes.
I am not sure what attributes you want to add/ change/ remove, but code like the following would work:

Of course, you should add a class or id to your table to make it easier to select by jQuery.
Parsers like BeautifulSoup work by parsing the XML into objects that it understands. When it writes out the HTML, it writes out the data in the objects, not the original string that was parsed.

A: The only answer to your requirements is, to use string manipulation:
text = text.replace('cellpadding="0"', 'cellpadding="10"')


text:
Q: Grab only Dates from timestamp, automatically format once the new data is populated from a google form I want to grab only the dates from timestamps. Now I have this formula =ArrayFormula(if(len(A2:A),int(A2:A),IFERROR(1/0)))
However, when the new date is entered, the dates becomes something like this 42338
then I have to format it everytime when a new data is entered.
This is what it looks like now. http://i.stack.imgur.com/y3zZn.png
I tried using =text(A2:A,"yyyy-mm-DD")), it solves my problem but my query in another sheet won't recognize this formate as dates.
Please help! Thank you

A: You could use an arrayformula within your query dataset to convert the dates to numbers.
This example sheet contains a couple of approaches using QUERY and SUMIFS: https://goo.gl/JXunQB


text:
Q: Formula for consecutive heads or tails in x coin flips. If I flip a coin 3 times it is simple to show that

*

*At least 1 is head or tail  = 1.0 # obvious

*At least 2 consecutive are head or tail = 0.75

$6 / 8 = 0.75$

*

*At least 3 consecutive are head or tail = 0.25

$2 / 8 = 0.25$

Calculating when at least x consecutive are head or tail is not so easy when you start flipping a lot of coins as the number of posibilities is $2^n$ where n is the number of coin flips.
I thougth the problem was interesting enough to deserve writing a programme for it.
Still after looking to the outputs of the programme I can not find a formula / procedure that will give me the answer without needing to enumerate all the possibilities.
Can you please give me a motivated formula (I mean a formula and an intuitive explanation of it) that having as the input:

*

*$a$ = number of coin flips

*$b$ = so many consecutive heads or tails

will tell me the probability of how many times that happens?
(Ex. $f(3,2)$ => 0.75 )


text:
Q: Materialize Center Buttons Horozontally on grid I'm working on https://rapptor.co . I have used Materialize as the framework and I'm making a login modal, I'm trying to center the buttons at the bottom of the modal with center-align, however It's not working.

Login Details

                person
                <input id="first_name" type="text" class="validate">
                Username/Email

                security
                <input id="first_name" type="password" class="validate">
                Password

                Close

                Help

                Login

Can anyone suggest anything for me to try?
Thanks!

A: remove float:right; and insert try following css at line no:13
.row .col.m4 {
    width: 33.3333333333%;
    margin-left: auto;
    left: auto;
    right: auto;
    text-align: center;
}

A: change your modal footer like this way, just run this snippet you can see the difference, hope this will help you

.modal-footer {
 text-align:center;
}
.modal-footer a {
 display:inline-block;
 margin:0 15px;
 float:none; /*if you set float already */
}

    Close
    Help
    Login

if you set this you button show like this picture

i dont know this is what you need , thats why i put an image here


text:
Q: Add custom params to prometheus scrape request We have metrics endpoint enabled in our application to get metrics. It requires custom parameter, how to configure prometheus.yaml to send custom param as part of each metrics scrape
Below is my prometheus.yml configuration
# Sample METRICS
- job_name: 'sys-metrics'
metrics_path: '/sys/metrics'
# Optional HTTP URL parameters.
params:
-user-id: ['myemail@email.com']
scrape_interval: 3s
static_configs:
- targets: ['dev.devhost.domain.com:12345']

When I start server, I get marshal error
 parsing YAML file prometheus.yml: yaml: unmarshal errors:\n  line 37: field -user-id not found in type config.plain"
Any help appreciated

A: under params, user-id is child element, add tab to resolve. as I defined at same level, prometheus expected to be one of pre-defined config.
params:
    -user-id: ['myemail@email.com']

Issue solved


text:
Q: Problema con clases abstractas Resulta que debo crear el juego Ahorcado, entonces ya apliqué todo el código pero resulta que quiero generar palabras aleatorias, claro que palabras ya definidas y agarrar todo en un arreglo donde con la clase Math.Random() poder generar números aleatorios dentro del rango del arreglo y así poder tomar palabras aleatorias para que el juego sea más didáctico. He aquí parte del código que aún no sé manejar clases abstractas, es por ello que pido su ayuda:
public abstract class Palabras
{
    private String nombre;
    private String Descripcion;
    public abstract void setNombre(String nombre);
    public abstract void getNombre();
}
public class PlatosTipicos extends Palabras
{
    //...
}

Entonces esa es mi duda, no sé como proseguir.

A: Las clases abstractas sirven para compartir métodos y atributos de una clase superior, y que no debe ser implementable, (no puedes crear un objeto de ella), por ejemplo, tu tienes tu getter y setter en la clase Palabras, por lo que en PlatosTipicos deberás implementar ese setNombre(String nombre) y getNombre() y al hacer esto como el atributo lo tienes en privado, no podrás acceder de el de forma sencilla. (Se puede vía reflect).
Las clases abstractas te permiten abstraer en lo posible tu problema, ahorita tu problema es generar nueva palabra, por lo que yo haría algo así.
public abstract class Palabras{ //por favor es Java no C o C# las llaves en Java suelen escribirse en la firma de la clase o método.
   //Podrías hacer que nombre y descripción esten dentro de un constructor.

    public Palabras(String nombre, String descripcion){
        this.nombre=nombre;
        this.descripcion=descripcion;
    }

    private String nombre;
    private String Descripcion;
    public void setNombre(String nombre){
         this.nombre=nombre;
    }
    public String getNombre(){
         return nombre;
    }
    public abstract String obtenerPalabra();
}
public class PlatosTipicos extends Palabras{
    public String obtenerPalabra(){
    //Tu algoritmo de obtener aleatoriamente la palabra.
    }
}

Y ya para la ejecución sería algo así
Palabras palabra = new PlatosTipicos("nombre","descripcion");
palabras.obtenerPalabra();

A: Estoy entendiendo mal o lo que queres hacer es heredar de Palabras a otros tipos de palabras?
Si estoy en lo correcto, debo decirte, que no se si vale la pena crear varias clases para diferentes tipos de palabras, podrias usar alguna estructura que te permita guardar varios tipos de cosas, como por ejemplo ArrayList de ArrayList.
Por como hiciste eso parece mas orientado a una interfaz-implentando que a una herencia. Las interfaces son como las clases abstractas pero con la diferencia de que únicamente pones adentro los metodos que obligas a implementar.
ej:
public interfaz observable
{
    public void mostrarDatos();
}


text:
Q: pyplot: dotted background and dotted rectangle Is there any way to get a dotted background like the following picture?

The only method I know is to upload a picture of dots and fill in the plot with that picture according to this post:Adding a background image to a plot with known corner coordinates

A: For instance, with this ugly hack you can have dots wherever you want:
import matplotlib.pyplot as plt
import numpy as np

y = np.random.randn(100) * 100
x = np.arange(len(y))

for xi in x:
    ybg = np.arange(np.int(y.min())-1, np.int(y.max()+1))
    xbg = np.repeat(xi, len(ybg))
    plt.plot(xbg, ybg, '.k', alpha = 0.25)

plt.plot(x, y, 'b', lw = 3)

Controlling xbg and ybg you can control where your dots will be plotted so you don't have to mind about an image background.


text:
Q: Expected response to be a <:redirect> but was <200> I've got an issue with my rspec tests and having looked through previous questions I haven't been able to resolve it. The test fails with the above error but the code works in practice, does anyone know how to resolve this?
Rspec:
describe "authentication of edit/update pages" do

    before(:each) do
        @user = Factory(:user)
    end

    describe "for non-signed in users" do
        it "should deny access to 'edit'" do
            get :edit, :id => @user
            response.should redirect_to(signin_path)
        end

        it "should deny access to 'update'" do
            put :update, :id => @user, :user => {}
            response.should redirect_to(signin_path)
        end
    end
end

Sessions Helper:
def deny_access
    redirect_to signin_path, :notice => "Please sign in to access this page."
end

Users Controller
class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
  private
    def authenticate
        deny_access unless signed_in?
    end
end

A: I guess you should change your code a bit:
def deny_access
  redirect_to signin_path, :notice => "Please sign in to access this page." and return
end


text:
Q: Infopath Form use in SharePoint Module Need License? I Created Custom State Machine Workflow in that workflow having Infopath Custom Form Module so we are going to deploy in production server. This Application access number end users in that time we need any Infopath License Please help............

A: I wish I could understand what you are asking about. License (or free license) is used and needed even for freeware products.
Infopath is part of Microsoft Office that is commercial product and generally not free. Though, the cost of license has nothing to do with the need of having licenses for software usage, be they free or not, in Sharepoint module or not.
Update:
Please check my answer on Sharepoint - Infopath licensing and usage
Once more, the licensing depends on how you usу Infopath forms with Sharepoint:

*

*are you using Sharepoint Online or own your own enterprse Sharepoint server

*restrict the usage of Infopath forms to filler/client (non-browser-enabled forms) or use browser-enabled forms

*publish to Sharepoint server or to client machines using free Sharepoint Foundation

*etc.

Anyway, with enterprise, standard Sharepoint server or "free" Sharepoint Foundation, with client Infopath or through IPFS, one cannot avoid purchasing Microsoft licenses since it is hooked to using Windows operating system on every client machine. Additional options with Sharepoint and Infopath depend.
Your question is impossible to answer without knowing your details or requirements


text:
Q: Paging with IndexedDB cursor I have an IndexedDB data store with a few hundred objects in it.  I'd like to grab items 40-59 from it based on the ordering in one of my indexes on that store.  Is there a way to do that without simply calling cursor.continue() 39 times before starting to consume data?  It seems pretty wasteful in terms of processing time.

A: I had the same problem and cursor.advance(40) is what you want to use.
One thing that took me a while to figure out so may be useful to others is if you want to advance the cursor and iterate through the results you will either need to call them in separate openCursor().onsuccess handlers, or implement some kind of tracking to prevent them both being called in the same request or an InvalidStateError exception with be thrown. This can be done like so:
Separate Handlers
// advance first
store.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    cursor.advance(40);
};

// then iterate
objectStore.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    cursor.continue();
});

Same Handler
// create flag for advancing
var advancing = true;

store.openCursor().onsuccess = function(event) {

    var cursor = event.target.result;

    // advancing
    if (advancing === true) {

        cursor.advance(40);

        // set advancing flag to false so we don't advance again
        advancing = false;

    }
    // continuing
    else {

        cursor.continue();

    }

}

Spec reference: http://www.w3.org/TR/IndexedDB/#widl-IDBCursor-advance-void-unsigned-long-count
MDN Reference with example: https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor.advance

A: I believe you can call cursor.advance(40)
Spec reference: http://www.w3.org/TR/IndexedDB/#widl-IDBCursor-advance


text:
Q: SPFX Webpart stalls Chrome? I have the below code being used in a SPFX webpart that I created which displays Social Media icons and a company name. Everything works fine, but when using Chrome if the webpart attempts to load while not being visible on the user's screen, they get a "Loading spfx-social-links" overlay on the screen which prevents them from interacting with SharePoint.
If they scroll down the screen to where the webpart is located, it finishes loading properly and they are then able to interact with SharePoint.
Is there something missing from my code that can prevent this issue from occurring? This webpart was created with the intent of being at the bottom of the page similar to this site's Blog, FaceBook, Twitter, and LinkedIn links.
public render(): void {

SPComponentLoader.loadCss('https://use.fontawesome.com/releases/v5.0.6/css/all.css');
var fbVar = (this.properties.showFb) ? styles.show: styles.hide;
var tVar = (this.properties.showTwitter) ? styles.show: styles.hide;
var inVar = (this.properties.showInstagram) ? styles.show: styles.hide;
var ytVar = (this.properties.showYt) ? styles.show: styles.hide;
var liVar = (this.properties.showLi) ? styles.show: styles.hide;

this.domElement.innerHTML = `

    ${ escape(this.properties.description) }

`;
}

A: Pull the loadCss function out of the render() call or call it only the first time using this.renderedOnce, e.g.:
public render(): void {

if (this.renderedOnce === false) {
  CPComponentLoader.loadCss('https://use.fontawesome.com/releases/v5.0.6/css/all.cs');
}
var fbVar = (this.properties.showFb) ? styles.show: styles.hide;
var tVar = (this.properties.showTwitter) ? styles.show: styles.hide;
var inVar = (this.properties.showInstagram) ? styles.show: styles.hide;
var ytVar = (this.properties.showYt) ? styles.show: styles.hide;
var liVar = (this.properties.showLi) ? styles.show: styles.hide;

this.domElement.innerHTML = `

    ${ escape(this.properties.description) }

`;
}


text:
Q: How to enable or disable -updates, -security, -backports, -proposed repositories from commandline? Let's assume that we are using Ubuntu 18.04 LTS (Bionic Beaver).
I know GUI ways to enable or disable the following repositories:

*

*Important security updates  (bionic-security)

*Recommended updates (bionic-updates)

*Pre-released updates (bionic-proposed)

*Unsupported updates (bionic-backports)

In KDE user may want to open Software & Updates (or software-properties-kde) and navigate to Updates tab.
In GNOME, MATE, Xfce user should open Software & Updates (or software-properties-gtk) and navigate to Updates tab for -security, -updates and -backports and Developer options tab for -proposed.
But how to enable or disable -updates, -security, -backports, -proposed repositories from commandline?
Note: I need a solution without direct editing of /etc/apt/sources.list.
Update: I created discussion and poll named "Does Ubuntu need console alternative for software-properties-gtk / software-properties-kde?" on community.ubuntu.com.

A:
Note: I need a solution without direct editing of /etc/apt/sources.list.

Would using find and sed to comment out the lines be considered direct editing?
To disable these lines:
find /etc/apt -type f -name '*.list' -exec sed -i 's/\(^deb.*-backports.*\)/#\1/; s/\(^deb.*-updates.*\)/#\1/; s/\(^deb.*-proposed.*\)/#\1/; s/\(^deb.*-security.*\)/#\1/' {} +

Alternatively, we can just delete them:
find /etc/apt -type f -name '*.list' -exec sed -i '/-backports/d; /-updates/d; /-proposed/d; /-security/d' {} +

To enable them again:
find /etc/apt -type f -name '*.list' -exec sed -i 's/^#\(deb.*-backports.*\)/\1/; s/^#\(deb.*-updates.*\)/\1/; s/^#\(deb.*-proposed.*\)/\1/; s/^#\(deb.*-security.*\)/\1/' {} +

A: Best way to do this is:
sudo nano /etc/apt/sources.list

And uncomment the lines/sources you need.