text:
Q: Date shifting by one day in Sparklyr? I am working on a time series forecasting project on R. However I need to fetch my data from the tables located in Hadoop environment. I am using Sparklyr to reach these tables. But I realized a strange problem after finishing data transfer.
My date column shifts by one day and I see 27.03.2017's data in the row representing 26.03.2017.
sc <- spark_connect(master = "yarn-client",
                    spark_home = "/usr/hdp/current/spark2-client/",
                    config = conf)

invoke(hive_context(sc), "sql", "USE mydb")

data <- tbl(sc, 'mydata_raw')
data.df <- data.frame(data)
filter(data.df, date == "2018-05-05")

          date        unit
         <date>       <int>
1        2018-05-04   1111

In my hive tables there is no such problem.


text:
Q: Count file in linux by between date time I would like to ask about how to count the number of files in linux by between two dates and times?
Example I have 10 file like:
Date Modified      Filename
2016101500         1.file
2016101501         2.file
2016101502         3.file
2016101503         4.file
2016101504         5.file

So if I want to count file from time 00.00 to time 03.00, that how many file I have?

A: You can use the find command and specify the time range like this:
find -newerct 2016-10-15T00:00:00 -and -not -newerct 2016-10-15T03:00:01 | wc -l

*

*The -newerct allows you to give a literal timestamp that the change time is compared with.

*The range is build by combining the two times with -and -not.

*Depending on your use case, you might need to adopt the second string like 2016-10-15T04:00:00.

*The matching files are piped to wc -l to get the file count.

There are many more useful tests for timestamps, please refer to the documentation of the find command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does Python interpreter work in dynamic typing? I read this question, but it didn't give me a clear answer:
How does Python interpreter look for types?
How does python interpreter know the type of a variable? I'm not looking how do get the type. I'm here looking at what happens behind the scene. In the example below, how does it associate the class int or string to my variable.
How does it know that is an int:
>>> i = 123
>>> type(i)
<class 'int'>

or that string:
>>> i = "123"
>>> type(i)
<class 'str'>

A: Python variables have no type, they are just references to objects.  The size of a reference is the same regardless of what it is referring to.  In the C implementation of Python it is a pointer, and does have a type, it a pointer to a Python object: PyObject *.  The pointer is the same type regardless of class of object.  Objects, on the other hand, know which class they belong to.
It has been argued that Python has no variables, only names, although that's a step too far for most people.
References in the CPython implementation have an id (identifier) which is actually a virtual address.  The detail and value of this address is not worth pursuing - it can (and probably will) change between versions and is not meant to be used for anything other than a unique number identifying the object.  Nevertheless it can provide interesting pointers (pardon the pun) to what is happening:
>>> x = 42
>>> y = x
>>> id(x)
4297539264
>>> id(y)
4297539264

Note that the id (address) of x and y are the same - they are referencing the same object, an int with the value 42.  So, what happens when we change x, does y change as well?
>>> x = "hello"
>>> id(x)
4324832176
>>> id(y)
4297539264

Thankfully not.  Now x is just referring to a new object of class str with the value "Hello".
When we:
>>> id(y)
4297539264
>>> y = 37
>>> id(y)
4297539104

The id of y changed!  This is because it is now referencing a different object.  ints are immutable, so the assignment y = 37 did not change the original object (42) it created a new one.  The object with the value 42 has its reference count decremented and can now (in theory) be deleted.  In practice it would probably remain in memory for efficiency reason, but that's an implementation detail.
However, let's try this for a list:
>>> a = [1,2,3,4]
>>> b = a
>>> id(a)
4324804808
>>> id(b)
4324804808
>>> a[0] = 99
>>> b
[99, 2, 3, 4]

So changing the list a has changed b! This is because lists in Python (unlike, say in R) are mutable, so they can change in-place. The assignment b = a only copied the reference and thus saved memory (no data was actually copied). Dictionaries are another object with such behavior. See copy in the standard library.

A:
how does it associate the class int or string to my variable

Python doesn't. Variables have no type. Only the object that a variable references has a type. Variables are simply names pointing to objects.
For example, the following also shows the type of an object, but no variable is involved:
>>> type(1)
<class 'int'>
>>> type('foobar')
<class 'str'>

When you use type(variable), the variable part of the expression simply returns the object that name references, passing in the object to the type() function. When using 1 or 'foobar', the expression is a literal producing the object, which is then passed to the type() function.
Python objects are simply datastructures in the interpreter memory; in CPython C structs are used. Variables are merely references (pointers) to those structures. The basic type struct in CPython is called PyObject, and this struct has a ob_type slot that tells Python what type something is. Types are simply more C structures.
If you wanted to follow along in the CPython source code, you'd start at the bltinmodule.c source code (since type is a built-in name), which defines type as the PyType_Type structure. Calling a type (type is a type too) invokes their tp_new function, and PyType_Type defines that as the type_new function. This function handles calls with one argument as follows:
/* Special case: type(x) should return x->ob_type */
{
    const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
    const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);

    if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
        PyObject *x = PyTuple_GET_ITEM(args, 0);
        Py_INCREF(Py_TYPE(x));
        return (PyObject *) Py_TYPE(x);
    }

Here x is the PyObject object you passed in; note, not a variable, but an object! So for your 1 integer object or 'foobar' string object, the Py_TYPE() macro result is returned. Py_TYPE is a macro that simply returns the ob_type value of any PyObject struct.
So now you have the type object for either 1 or 'foobar'; how come you see <class 'int'> or <class 'str'> in your interpreter session? The Python interactive interpreter automatically uses the repr() function on any expression results. In the C structure for PyType_Type definitions the PyType_Type struct is incorporated so all the slots for that type are directly available; I'll omit here exactly how that works. For type objects, using repr() means the type_repr function is called which returns this:
rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);

So in the end, type(1) gets the ->ob_type slot, (which turns out to be the PyLong_Type struct in Python 3, long story), and that structure has a tp_name slot set to "int".
TL;DR: Python variables have no type, they are simply pointers to objects. Objects have types, and the Python interpreter will follow a series of indirect references to reach the type name to print if you are echoing the object in your interpreter.

A: The concept "type" of a variable is "implemented" by using objects of a specific class.
So in
a=float()
an object of type float, as defined by the class float is returned by float().   Python knows what type it is because that's how objects work: you know what type they are.  a is now a float object, with value 0.0.
With builtins, it's the same, it's just that they have shorthands for declaring them.
i=123
is the same as
i=int(123)
int() returns an object of class integer, with value 123.
similarly
i="123"
is the same as
i=str("123")
str("123") returns an object of class str, with value "123"


text:
Q: Are Cross-site scripting attacks relevant with ajax? I'm building a React app, with PHP(Codeigniter) backend.
Being that Codeigniter does't seem to take care of this issue automatically, i started exploring the subject. I understand why user input must be escaped, before rendered in an HTML page, but the question is, whether this should be done in an app that relies solely on AJAX.
I've tried outputting this string inside an HTML element in a React component, after being received via ajax request:
<script>alert('hey');</script>

It ended up as just a literal string in the HTML. Of course, no JS was executed.
Are there some situations, where such a string can be executed, even though it was extracted from an ajax JSON?

A: It is a good practice to escap tags at backend before sending it to frontend.
Lets take an example:
Let us assume you call http://example.com/get.php?userInput=< script >alert('hi');< /script >
Expected output of above request is "< script >alert('hi');< /script >".
Now the ajax call is converting it into string literal and it is not being executed at the place where it is being consumed but if user directly visit the above url it will be rendered as HTML and above script will be executed. In this case attacked might still be able to steal cookie or do other malicious work.

A: I think you take Cross Site Scripting (CSS) differently, CSS could not be prevented automatically by any kind programming language. Actually, in CSS javascript code has been stored in database and get rendered while displaying, stored code may have ajax call and send to data to some other site with your cookies data.
There will not be any problem if you print stored code as it is. If you print your json value like echo json_enocde($apiArray) then your will code not be executed even if your api called without ajax(by hitting url) because script code is getting hidden in browser (you can check it out).
Yes, your code can be executed if you bind your ajax return value as HTML. That's why javascript frameworks print ajax returned values as it is and you have to write code explicitly to bind html code. If you bind your ajax value.
see how to bind html in reactjs in this case your code can be executed.
In php there is - htmlentities($values_that_need_to_be_printed_with_script_tag) function that prints your code as it is, this does not allow the browsers to render javascript code.
The simple thing to prevent CSS(corss site scripting) is print your data as it is - don't allow your browser to render your code stored in database.


text:
Q: Google Map View is leaking very much I've previously used the MapFragment, but it was slow for my needs. The MapView is almost instantly and fits my needs exactly. But there is one thing they both have in common:
Huge memory leaking.
I've 'destroyed' the MapView like I should when exiting the activity and it still leaks. The MapView is in an activity that is frequently opened and closed and opened quickly again. Could that be the issue?
Here are some screeenshots of my hprof files (I'd rather not upload the hprof files, due to possible sensitive information):

I've had multiple leaks, and they al point to the same classes.
However, I am using a custom class, which is unneeded at this moment, and I'll revert back to the default MapView.

A: I am not sure if that's the case, but I did something stupid using Kotlin.
Kotlin got null-safety.
googleMapView?.onDestroy()

I called that in onDestroy() of my Fragment. Guess what? googleMapView was null, that's why it didn't call it's onDestroy()! Wasted around 2 hours on this, because I thought some of my custom classes kept references or other things that led to this...


text:
Q: Как сделать, чтобы на мобильных устройствах рендерилась более мелкая верстка? Здравствуйте. Никому не секрет, что, несмотря на высокое разрешение экранов мобильных девайсов, в браузере мобильных устройств отображается верстка других размеров. Так, к примеру, у 7 айфона с его fullhd экраном отображается верстка на 375 пикселей.
Я сделал сайт и понял, что минимальная ширина моего сайта составляет 533 пикселя. Дальше верстать смысла нет, ибо весь смысл сайта рушится. Таким образом, у меня media only screen and (min-width : 533px) . Но если в браузере (в режиме инспектора) открыть мой сайт в режиме iphone 7, то сайт будет некорректно отображаться, так как у него размер меньше, чем 533.
Подскажите, как сделать, чтобы устройства, у которых при рендеринге (либо своё родное) разрешение меньше 533 отображали верстку на 533?

A: В вашем случае, чтобы устройства нормально отображали вашу вёрстку на экранах с размерами не больше 533-х пикселей, вам нужно писать в @media запросе не min-width : 533px , а max-width : 533px. Это значит, что устройства с максимальной шириной экрана 533 пикселя и меньше, будут читать стили из вашего @media запроса.
Плотность пикселей экрана здесь не играет роли.

A: Здесь чистый Media запрос не поможет. Решается данная задача с помощью костыля:
Добавляем viewport'y ID, а потом добавляем вот такой jquery код.
if (screen.width < 533) {
$('#viewport').attr('content', 'width=533, initial-scale=' + (screen.width / 533).toFixed(4));
});


text:
Q: Array to string conversion during POST only There are questions with the same title but they aren't related to POSTing.
If I submit my form using Symfony I can submit with no problem.  Problem is when I submit my form using Angular using via POST method I created.  It gives me the exception "Notice: Array to string conversion".
I know it has to do with my ManyToMany Relation (owners). If I don't add any owners it works fine. Problem is when I add owners.
Here is my Stack Trace:
Stack Trace:

1. in vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php at line 106

2. at ErrorHandler ->handleError ('8', 'Array to string conversion', '/Applications/MAMP/htdocs/uploader/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php', '106', array('v' => array('id' => '2', 'firstName' => 'Albert', 'lastName' => 'Jankowski', 'username' => 'ajankowski', 'password' => '$2y$13$7lXTaq3w45j3P0HEln71T.ItLxxf8ZX28UkNFpYFPULyR2a7pLW1C', 'email' => 'ajankowski@myemail.com', 'enabled' => true, 'salt' => null, 'usernameCanonical' => 'ajankowski', 'availableRoles' => array('ROLE_USER', 'ROLE_ADMIN'), 'emailCanonical' => 'ajankowski@myemail.com', 'plainPassword' => null, 'lastLogin' => null, 'confirmationToken' => null, 'roles' => array('ROLE_USER'), 'accountNonExpired' => true, 'accountNonLocked' => true, 'credentialsNonExpired' => true, 'credentialsExpired' => false, 'expired' => false, 'locked' => false, 'superAdmin' => false, 'user' => false, 'passwordRequestedAt' => null, 'groups' => array(), 'groupNames' => array())))
in vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php at line 106

3. at ORMQueryBuilderLoader ->Symfony\Bridge\Doctrine\Form\ChoiceList\{closure} (array('id' => '2', 'firstName' => 'Albert', 'lastName' => 'Jankowski', 'username' => 'ajankowski', 'password' => '$2y$13$7lXTaq3w45j3P0HEln71T.ItLxxf8ZX28UkNFpYFPULyR2a7pLW1C', 'email' => 'ajankowski@myemail.com', 'enabled' => true, 'salt' => null, 'usernameCanonical' => 'ajankowski', 'availableRoles' => array('ROLE_USER', 'ROLE_ADMIN'), 'emailCanonical' => 'ajankowski@myemail.com', 'plainPassword' => null, 'lastLogin' => null, 'confirmationToken' => null, 'roles' => array('ROLE_USER'), 'accountNonExpired' => true, 'accountNonLocked' => true, 'credentialsNonExpired' => true, 'credentialsExpired' => false, 'expired' => false, 'locked' => false, 'superAdmin' => false, 'user' => false, 'passwordRequestedAt' => null, 'groups' => array(), 'groupNames' => array()))

4. at array_filter (array(array('id' => '2', 'firstName' => 'Albert', 'lastName' => 'Jankowski', 'username' => 'ajankowski', 'password' => '$2y$13$7lXTaq3w45j3P0HEln71T.ItLxxf8ZX28UkNFpYFPULyR2a7pLW1C', 'email' => 'ajankowski@myemail.com', 'enabled' => true, 'salt' => null, 'usernameCanonical' => 'ajankowski', 'availableRoles' => array('ROLE_USER', 'ROLE_ADMIN'), 'emailCanonical' => 'ajankowski@myemail.com', 'plainPassword' => null, 'lastLogin' => null, 'confirmationToken' => null, 'roles' => array('ROLE_USER'), 'accountNonExpired' => true, 'accountNonLocked' => true, 'credentialsNonExpired' => true, 'credentialsExpired' => false, 'expired' => false, 'locked' => false, 'superAdmin' => false, 'user' => false, 'passwordRequestedAt' => null, 'groups' => array(), 'groupNames' => array())), object(Closure))
in vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php at line 107

My Entity:
/**
 * Company
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CompanyRepository")
 */
class Company
{
  ......
  ......

  /**
   * @var User
   *
   * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User")
   */
  private $owners;

  ......
  ......
}

My Controller:
/**
 * @Route("", name="api_company_create")
 * @Method("POST")
 *
 * @param \Symfony\Component\HttpFoundation\Request $request
 *
 * @return Response $response
 */
public function createAction(Request $request)
{
  // Process the form.
  $company = new Company();
  $form = $this->createForm(new CompanyType(), $company);
  $this->processForm($request, $form, TRUE);

  if (!$form->isValid()) {
    $this->throwApiProblemValidationException($form);
  }

  $em = $this->getDoctrine()->getManager();
  $em->persist($company);
  $em->flush();

  $response = $this->createApiResponse($company, 201);

  $companyUrl = $this->generateUrl(
    'api_company_show',
    ['id' => $company->getId()] );

  $response->headers->set('Location', $companyUrl);

  return $response;
}

/**
 * Process the form.
 *
 * @param \Symfony\Component\HttpFoundation\Request $request
 * @param \Symfony\Component\Form\FormInterface $form
 * @param boolean $removeExtraFields
 * @param Company $currentCompany
 */
private function processForm(Request $request, FormInterface $form, $removeExtraFields = FALSE, $currentCompany = NULL)
{
  $data = json_decode($request->getContent(), true);

  $clearMissing = $request->getMethod() != 'PATCH';
  $form->submit($data, $clearMissing);
}

/**
 * Company
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CompanyRepository")
 */
class Company
{
  ......
  ......

  /**
   * @var User
   *
   * @ORM\ManyToMany(targetEntity="AppBundle\Entity\User")
   */
  private $owners;

  ......
  ......
}

I tried adding __String() to my Company Entity but that didn't help.
  /**
   * Transform to string
   *
   * @return string
   */
  public function __toString()
  {
    return (string) $this->getOwners();
  }

A: I was able to figure this out. It was because Symfony(Doctrine) does not want an entire object back. I created a function in my controller to fix this.
  /**
   * You may receive an entire object for a relation from your api but when
   * saving Doctrine only wants the ids.
   *
   * For Example your API returns:
   *   $data['owners'][0] = array('id' => 1, 'name' => 'Admin');
   *   $data['owners'][1] = array('id' => 2, 'name' => 'User');
   *
   * But it expects:
   *
   *   $data['owners'][0] = 1;
   *   $data['owners'][1] = 2;
   *
   *
   * @param array $data
   * @param string $name
   */
  private function convertRelationToDoctrineSafeArray(&$data, $name)
  {
    if (isset($data[$name]) && $data[$name]) {
      foreach ($data[$name] as $key => $field) {
        $fields[$key] = $field['id'];
      }
      unset($data[$name]);
      $data[$name] = $fields;
    }
  }


text:
Q: how to delete all associated relational model record of a model from laravel? I am using laravel 5.6. i want to delete all child model as long as parent. that means if i delete parent then all child models record should delete self.
check this query.
$d= ParentModel::where('id',2)->with('child_1' ,'child_2','child_3')->first();

here i do not want to define loop and any thing else for delete all record of parent and child table. just want to delete parent and all its child table should also delete self.
I don't know. is this possible to delete all associated  model directly without mentioned.
like this way.
$d-> child_1->delete();
$d-> child_2->delete();
$d-> child_3->delete();
$d-> delete();

A: You can add a foreign key to your child's table migration:
$table->unsignedInteger('parent_id');

$table->foreign('parent_id')
    ->references('id')->on('parent_table_name')
    ->onUpdate('cascade')
    ->onDelete('cascade');

Now when you delete the parent, the child rows will be deleted automatically.
For more information about foreign keys: https://laravel.com/docs/5.6/migrations#foreign-key-constraints

A: Yes you can. Here is deletion code
$parentModel = ParentModel::find($id);
$parentModel->child_1()->delete(); // return deleted record count
$parentModel->child_2()->delete(); // return deleted record count
$parentModel->child_3()->delete(); // return deleted record count


text:
Q: Prevent window.onbeforeunload event from being fired while clicking on hyperlinks I have a page where the user is prompted to confirm the unloading of the page by using the window.onbeforeunload event handler. This message is currently getting fired even when there is a navigation from one page to another as a result of clicking on a hyperlink (anchor tag).
How can I stop the event from being fired when the hyperlink or anchor tag is clicked? My code is provided below:

      Delete

I dont want alert while user click on the anchor tag


text:
Q: Understanding a regular expression in a series extract function in pandas I have the following code:
import pandas as pd
s = pd.Series(['toy story (1995)', 'the pirates (2014)'])
print(s.str.extract('.*\((.*)\).*',expand = True))

with output:
     0
0  1995
1  2014

I understand that the extract function is pulling the values between the parentheses for both series objects. However I do not understand how. What exactly does '.*\((.*)\).*' mean? I think that the asterisks represent wild card characters but beyond that I am quite confused as to what is actually going on with this expression.

A: .*\( matches everything up until the first (
\).* matches everything from ) until the end
(.*) returns everything in between the first two matches

A: .*             Match any number of characters
\(             Match one opening parenthesis
    (.*)       Match any number of characters into the first capturing group
\)             Match a closing parenthesis
.*             Match any number of characters

This notation is called a regular expression, and I guess Pandas uses regexes in the extract function so you can get more precise data. Things inside capturing groups would be returned.
You can learn more about regexes at the Wikipedia page.
Here's a test example using your regex.


text:
Q: geom_tile no longer understands width and height outside aesthetics Since switching to ggplot2 2.0.0 there are problems in defining the width and height of a tile outside the aesthetics.
I used the geom_tile to create some kind of a heatmap and I wanted to have a little space between the tiles, so I used in the older version of ggplot2 the width=.9 and height=.9 parameters, but this fails in the new version.
df <- data.frame(x=letters[1:10], y=rep(LETTERS[1:10], each=10), value=runif(100))
ggplot(df, aes(x, y, fill=value)) + geom_tile()
ggplot(df, aes(x, y, fill=value)) + geom_tile(width=.9, height=.9)

The only way to get this working is by adding columns with width and height into the data frame and use the aesthetics. Is this supposed to work like this? Or do I miss something here?
df <- data.frame(x=letters[1:10], y=rep(LETTERS[1:10], each=10),
                 value=runif(100), w=.9, h=.9)
ggplot(df, aes(x, y, fill=value)) + geom_tile(aes(width=w, height=h))

A: You don't need to add width and height values to dataframe. You can just move those two arguments to aes().
ggplot(df, aes(x, y, fill=value)) + geom_tile(aes(width=0.9, height=0.9))


text:
Q: android.database.sqlite.SQLiteException: Error    android.database.sqlite.SQLiteException: near "TABLEsusParticipants": syntax error (code 1): , while compiling: CREATE TABLEsusParticipants(_idINTEGER PRIMARY KEY AUTOINCREMENT, f_nameVARCHAR(255), m_nameVARCHAR(255));

my SQLite statement given error.i cant figure it out.any Help..
    private static final String DTABASE_NAME = "sport_unleash";
    private static final String TABLE_NAME = "susParticipants";
    private static final int DATABASE_VERSION = 3;
    private static final String ID = "_id";
    private static final String F_NAME = "f_name";
    private static final String M_NAME = "m_name";
    private static final String CREATE_TALBE = "CREATE TABLE" + TABLE_NAME +"("+ID +"INTEGER PRIMARY KEY AUTOINCREMENT, " + F_NAME + "VARCHAR(255), " + M_NAME+ "VARCHAR(255));";

A: you need a space at the end of the "CREATE TABLE" string, and at the start of the "(" string, as the table name doesn't have spaces in, and will be appended directly.
your string should look like:
    private static final String CREATE_TALBE = "CREATE TABLE " + TABLE_NAME +" ("+ID +" INTEGER PRIMARY KEY AUTOINCREMENT, " + F_NAME + " VARCHAR(255), " + M_NAME+ " VARCHAR(255));";


text:
Q: In Clojure, how to unit test an async Pedestal interceptor? I have an async Pedestal interceptor I want to test:
(def my-interceptor
  (io.pedestal.interceptor/interceptor
    {:name  :my-interceptor
     :enter (fn [context]
              (as/go
                (do
                  (Thread/sleep 1000)
                  (assoc context :answer 42))))}))

I first tried a naïve test:
(deftest my-test
  (is (= 42
         (:answer (io.pedestal.interceptor.chain/execute {} [my-interceptor])))))

This doesn't work because chain/execute returns nil when it has async interceptors. I tried another solution adding the test in an interceptor just after the tested one:
(deftest my-test
  (io.pedestal.interceptor.chain/execute
    {}
    [my-interceptor
     (io.pedestal.interceptor/interceptor
       {:name  :test
        :enter (fn [context]
                 (is (= 41 (:answer context))) ; should fail
                 context)})]))

However this doesn't work because the test terminates before the test is executed, and thus succeeds… even if the test fails a second after:
Ran 1 test containing 0 assertions.
No failures.

FAIL in (my-test) (somefile_test.clj:49)
expected: (= 41 (:answer context))
  actual: (not (= 41 42))

In practice my tests suite (using Kaocha) fails because there's a deftest with no assertion in it.
Given that chain/execute returns nil and not a chan, I can't wrap it in a as/<!! to block until it terminates.
At this point I'm stuck. Is there anything I can do to test that kind of interceptors?

A: How about this approach?
(require '[clojure.test :as test])
(require '[clojure.core.async :as async)

(test/deftest async-test []
 (let [c (async/chan)]
      (future (println "Running mah interceptors") (async/>!! c :done))
      (test/is (= :done (async/<!! c)))
      (async/close! c)))

That runs the actual interceptor code in a separate thread. Test code just needs to post something to the c when it is done.


text:
Q: pandas series use gt is not pythonic way? I want to get data with content greater than 3,But the type of content is string
a = [{"content": "1", "title": "刘德华", "info": "", "time": 1578877014},
     {"content": "2", "title": "刘德华", "info": "", "time": 1579877014},
     {"content": "3", "title": "刘德华", "info": "", "time": 1582877014},
     {"content": "24", "title": "苹果", "info": "", "time": 1582876014},
     {"content": "15", "title": "apple", "info": "", "time": 1581877014},
     {"content": "16", "title": "banana", "info": "", "time": 1561877014},
     ]

mycode
index=[i['content'] for i in a]

s=pd.Series(a,index)

re_index=[eval(i['content']) for i in a]
s.index=re_index
res=[]
for i,v in enumerate(s.index.__gt__(2)):
    if v:
        print(i)
        res.append(s.iloc[i])

print(res)

result
[
{'content': '3', 'title': '刘德华', 'info': '', 'time': 1582877014},
{'content': '24', 'title': '苹果', 'info': '', 'time': 1582876014},
{'content': '15', 'title': 'apple', 'info': '', 'time': 1581877014},
{'content': '16', 'title': 'banana', 'info': '', 'time': 1561877014}
]

I think my code is too trivial
how edit my code is pythonic way?

A: Use boolean indexing with convert index to numbers:
out = s[s.index.astype(int) > 2].tolist()
print (out)
[{'content': '3', 'title': '刘德华', 'info': '', 'time': 1582877014},
 {'content': '24', 'title': '苹果', 'info': '', 'time': 1582876014},
 {'content': '15', 'title': 'apple', 'info': '', 'time': 1581877014},
 {'content': '16', 'title': 'banana', 'info': '', 'time': 1561877014}]

A: Try this :
[i for i in a if int(i['content']) >= 3]

[{'content': '3', 'title': '刘德华', 'info': '', 'time': 1582877014},
 {'content': '24', 'title': '苹果', 'info': '', 'time': 1582876014},
 {'content': '15', 'title': 'apple', 'info': '', 'time': 1581877014},
 {'content': '16', 'title': 'banana', 'info': '', 'time': 1561877014}]

You create a list comprehension with an if clause to get values equal to or greater than 3. note the use of int to convert to an integer. I believe you can run the program here without necessarily loading the data into pandas


text:
Q: Save results in YAML file with python I'm stuck in this little problem after an hour of searching previous answer.
I want to store matrices from my code in .yaml file
What I obtain from my code
Matrix
[[  1.00665266e+03   0.00000000e+00   5.08285432e+02]
 [  0.00000000e+00   1.01086937e+03   3.45995536e+02]
 [  0.00000000e+00   0.00000000e+00   1.00000000e+00]]

How I tried to save this matrix (mtx is the shorter name in my code)
fname = "calibrationC300.yaml"

data = dict(
    Matrix = mtx,
)

with open(fname, "w") as f:
    yaml.dump(data, f, default_flow_style=False)

But what I read in my YAML file is totally wrong (just only bad conversion?)
Matrix: !!python/object/apply:numpy.core.multiarray._reconstruct
  args:
  - &id001 !!python/name:numpy.ndarray ''
  - !!python/tuple [0]
  - b
  state: !!python/tuple
  - 1
  - !!python/tuple [3, 3]
  - !!python/object/apply:numpy.dtype
    args: [f8, 0, 1]
    state: !!python/tuple [3, <, null, null, null, -1, -1, 0]
  - false
  - !!binary |
    cWM87e1YkEAAAAAAAAAAAIUEEyb5SH1AAAAAAAAAAACp/Z3yc2qQQFv0vPqb5nZAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAPA/

It is the first time I use Yaml files, what am I doing wrong?
Is there a method to obtain the matrix in the simple form (as I obtain it from the code) in the yaml file?
Thank you in advance

A: The difference is between float and numpy.float64. Yaml uses more sophisticated way to represent numpy.float64. You can change to float if you like more readble yaml. See the following example:
print(yaml.dump({'test': 1, 'data':float(0.2)}, default_flow_style=False))
print(yaml.dump({'test': 2, 'data':numpy.float64(0.2)}, default_flow_style=False))

Output are:
data: 0.2

test: 1

data: !!python/object/apply:numpy.core.multiarray.scalar
- !!python/object/apply:numpy.dtype
  args:
  - f8
  - 0
  - 1
  state: !!python/tuple
  - 3
  - <
  - null
  - null
  - null
  - -1
  - -1
  - 0
- !!binary |
  mpmZmZmZyT8=

test: 2

A: The only thing wrong here seems to be your expectation of how numpy internals can and should be dumped to YAML.
An easy check to see that what you have gotten as YAML is correct, is to load what you dump-ed:
import ruamel.yaml
import numpy
import pprint

mtx = [[1.00665266e+03, 0.00000000e+00, 5.08285432e+02],
       [0.00000000e+00, 1.01086937e+03, 3.45995536e+02],
       [0.00000000e+00, 0.00000000e+00, 1.00000000e+00],]

data = dict(Matrix=mtx)

yaml_str = ruamel.yaml.dump(data, default_flow_style=False)
data = ruamel.yaml.load(yaml_str)
print(data)

which gives:
{'Matrix': [[1006.65266, 0.0, 508.285432], [0.0, 1010.86937, 345.995536], [0.0, 0.0, 1.0]]}

The special types that numpy uses are not dumped as simple (and readable) YAML, there is no guarantee that that could be reloaded. It might be possible for some constructs, although it easily leads to ambiguity, and AFAIK simplification it is not done for any of the numpy types.
Of course you can dump that YAML without having numpy supply its restore information, by doing:
ruamel.yaml.round_trip_dump(data, sys.stdout)

which gives:
Matrix:
- - 1006.65266
  - 0.0
  - 508.285432
- - 0.0
  - 1010.86937
  - 345.995536
- - 0.0
  - 0.0
  - 1.0

much more readable, but not something that will ever become a numpy.multiarray automatically when you load() it again from its YAML representation.

A: I'm not a expert as well, but the produced yaml seems correct. You can see dat the the primitive types are rendered well by default. For the others you might have to take some action. Read here in the  documentation.
Good luck!
(I don't have enough rep. to comment, otherwise I would leave this post as a comment.)


text:
Q: Consuming JSON WCF/asmx service in asp.net MVC 3 I want to consume a JSON/ WCF service in asp.net MVC 3 application. Do I need to use  Jquery AJAX or I can call service methods directly ? Do I need to create two projects in my solution. One for MVC 3 and One for WCF service ?
Please suggest

A: Following two links might be helpful
http://msmvps.com/blogs/theproblemsolver/archive/2011/06/13/using-the-wcf-web-api-in-an-asp-net-mvc-application.aspx
WCF Service with asp.net mvc application


text:
Q: How to compare 2 .csv files and create a new .csv containing parts from both csv files? I am trying to compare two specific parts of CSV files.
JobStart.csv
test1;test2;test3;test4;Val2Compare2;test5;test6;test7....

Datafile.csv
line 1   Val2Compare1; data1;data2;data3;data4;data5;data6
line 2   Val2Compare2; data1;data2;data3;data4;data5;data6
line 3   Val2Compare3; data1;data2;data3;data4;data5;data6

What I want to do is:
Compare values: JobStart.csv Val2Compare2 to
     Datafile.csv          Val2Compare1
                           Val2Compare2
                           Val2Compare3
                           ...

When I got which line is true (in this case line2). Then I want to combine JobStat.csv and Datafile.csv like so:
NEW JOBSTART.CSV

test1;test2;test3;test4;Val2Compare2;test5;test6;test7; data1;data2;data3;data4;data5

I tried to look at:
Compare two csv file using in C#
Comparing specific columns of two csv files
Compare 2 csv files and replace updated values
http://social.msdn.microsoft.com/Forums/vstudio/en-US/3f334045-2ac7-44b9-afaa-bd8d83c8ef27/read-csv-file-and-get-specific-column-from-each-line?forum=csharpgeneral
But couldn't get much help.

A: Try this:
var jobStartLine = File.OpenText(@"JobStart.csv").ReadLine();
var comparisonField = jobStartLine.Split(';')[4];

foreach (var line in File.ReadAllLines(@"Datafile.csv"))
{
    var fields = line.Split(new char[] {';'}, 2);
    if (comparisonField == fields[0])
    {
        File.WriteAllLines(@"NewJobStart.csv", new string[] { jobStartLine + ";" + fields[1] });
        break;
    }
}


text:
Q: In SharePoint 2010 - Does SPSiteCollection.Add create the default groups? Referring to http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/b73dd31b-1ec9-4f44-8cb2-80b2f6796eb5
Does SharePoint 2010 create default groups when site collection is created pro grammatically ?

A: You can use SPWeb.CreateDefaultAssociatedGroups method on your root web to create default Owner and Visitors groups.


text:
Q: python script to assign id based on dataframe fields I'm trying to write an iterative script in python that would see assign an id to a customer based on whether they've met conditions in my lookup table. Normally, I would accomplish this with a sql join, but I need a procedural script that would see whether they've met the conditions that exist in the lookup, then assign them that id. Some attributes are not required or available, so a sql join would not work, since the join would require that all conditions be met. See the example, below:
customers table
customer attr1 attr2 attr3
jerry    a     r     g
tom      q     e     h
cindy    c     f     j

id_lookup table
id attr1   attr2   attr3
1  a       (null)  g
2  (null)  e       h
3  c       f       (null)

final output
customer  id
jerry     1
tom       2
cindy     3

Note that jerry had a match on attr1 and attr3, so met the conditions, thus was assigned 1. The script moves on to the next customer to assign an id procedurally, starting at 1 and moving on in ascending order.
in sql, I would write
select a.customer
   , b.id
from customers a
join id_lookup b
   on ( a.attr1 = b.attr1
   and a.attr2 = b.attr2
   and a.attr3 = b.attr2 )

However, some attributes are not available and since a customer might match many ids, may not be assigned the right once, since the customer should be assigned the id with the lowest value that they qualify for.
Is there a script in python that can accomplish this?

A: You can do that in SQL.
select a.name
     , min(b.id)
from customers a
join id_lookup b
    on ( (a.attr1 = b.attr1 or b.attr1 is null)
    and (a.attr2 = b.attr2 or b.attr2 is null)
    and (a.attr3= b.attr3 or b.attr3 is null) )
group by a.name;

I'm sure you could also solve the problem in Python, but that would either require writing the equivalent in an ORM (and hence any solution would depend on what ORM you are using) or loading the entire tables into Python and processing them there, which would be impractical if your tables were of significant size.


text:
Q: What happens if you leave security rules undefined in Firebase? For example I define security rules for 5 nodes under my root, but not the 6th. If I just leave the 6th's rules blank, what does it default to?
Thanks!

A: I'm assuming you are talking about permissions that look like this:
{
  "rules": {
    "one": {
      ".read": "auth != null",
      ".write": "auth != null",
    },
    "two": {
      ".read": "auth != null",
      ".write": "auth != null",
    }
    ...
    "six": {
    }
  }
}

In the above set of rules, "one" and "two" will have authenticated read/write access, but "six" will not have any permission.
Child locations receive the same permissions that were granted to its parent.  An empty set of permissions do not change that fact.  An empty set of permissions is the same as no explicit permissions.
There is one primary rule that you need to keep in mind.  Once read/write access has been granted to a user at a location, all of its children will also have read/write from that same user. You cannot revoke permission after it has been granted.  If no read/write access has been granted, then users cannot access the location or any of its children.


text:
Q: Is this an adjective? I would like to ask if the words "Grain Honey Nut" in "Grain Honey Nut Cheerios" are adjectives or not. If not please can someone tell me what word class it is?

A: The word "Grain" is part of the two-word adjective "Whole Grain". I don't think there is any such product as "Grain Honey Nut Cheerios".
In a similar way, I would parse the two word phrase "Honey Nut" as a two-word adjective.
So, all told, I'd parse the name of the cereal like this:

          adj                               adj                      noun
[Whole Grain] [Honey Nut] [Cheerios]

Incidentally, when a word that is usually a noun functions as an adjective (as do chicken and paper in the phrases chicken soup or paper clip), this is knows as a noun adjunct.


text:
Q: React/Redux app actions not being dispatched properly I'm trying to set up my first React app using Redux, but I'm currently having some issues with dispatching actions. I have the following files for my actions so far:
constants/AuthActionTypes.js:
export const AUTH_PENDING = 'AUTH_PENDING';
export const AUTH_SUCCESS = 'AUTH_SUCCESS';
export const AUTH_FAIL = 'AUTH_FAIL';

actions/AuthActions.js:
import * as AuthActionTypes from '../constants/AuthActionTypes';

function authPending() {
  return { type: AuthActionTypes.AUTH_PENDING };
}

function authSuccess(response) {
  return { type: AuthActionTypes.AUTH_SUCCESS };
}

export function login(username, password) {
  return dispatch => {
    dispatch(authPending());
    // nothing really happens yet
    dispatch(authSuccess());
  };
}

I've also got a login component containing an HTML form, and a login function that gets called when the form is submitted.
components/Login.js
...

login (e) {
  e.preventDefault();

  var username = ReactDOM.findDOMNode(this.refs.username).value;
  var password = ReactDOM.findDOMNode(this.refs.password).value;

  this.props.dispatch(AuthActions.login(username, password));
}

...

The function is triggered, but... something isn't right. I use redux-devtools, and it only dispatches a single action - surely, it should dispatch the actions from both authPending and authSuccess? In addition, the devtools pane doesn't display any action type, and I get the following warning in the console:

Warning: Failed propType: Invalid prop action of type function
  supplied to LogMonitorEntry, expected object. Check the render
  method of LogMonitor.

What am I doing wrong here? What have I missed? I've primarily looked at the examples at https://github.com/rackt/redux/tree/master/examples/real-world and https://github.com/yildizberkay/redux-example, and I can't see what I'm doing differently that makes my own app break.

A: ... and a couple of minutes later, I've stumbled across the answer: I didn't have the redux-thunk middleware applied to my store. Applied that, and everything works as expected.

A: You can do w/o thunk.
change
this.props.dispatch(AuthActions.login(username, password));

to
this.props.dispatch(AuthActions.authPending());
this.props.dispatch(AuthActions.authSuccess());

Ofcourse, you have to import those two methods/action-creators.


text:
Q: Wrapping a ValidationObserver around a v-for loop I have a v-for loop that allows me to dynamically add new fields to my form. This loop is within a tab which I need to validate before I go onto the next section of my form. It seems as though nothing renders when I place the v-for within my validation observer. Is there another way to accomplish this?
I'm using VeeValidate 3
<template>

    <ValidationObserver :ref="'contact_obs'" v-slot="{ invalid }">

            <BTextInputWithValidation
              rules="required"
              class="col-md-4"
              :label="
                $t('contact_name', { name: applicant.contacts[index].title })
              "
              :name="$t('contact_name')"
              v-model="applicant.contacts[index].name"
              description
              placeholder
            />

            <BTextInputWithValidation
              rules
              class="col-md-4"
              :label="$t('contact_title')"
              :name="$t('contact_title')"
              v-model="applicant.contacts[index].title"
              description
              placeholder
            />

            <BTextInputWithValidation
              rules
              class="col-md-3"
              :label="$t('contact_email_address')"
              :name="$t('contact_email_address')"
              v-model="applicant.contacts[index].email"
              description
              placeholder
            />

     </ValidationObserver>

</template>

A: I believe the problem is here:
v-for="(contact, index) in this.applicant.contacts"

In general you should avoid using the this. prefix to access properties in templates but usually it does no harm. This is one of those cases where it actually does break something. this does not refer to the correct object inside a scoped slot.
I'm surprised you don't see an error in your console.


text:
Q: TypeError: string indices must be integers for JSON I am writing a program in Python to prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below. Here is my code:
import urllib
import json

total = 0
url = open("comments_42.json")
print 'Retrieving', url
#uh = urllib.urlopen(url)
data = url.read()
print 'Retrieved',len(data),'characters'
#print data

info = json.loads(data)
print info
print 'User count:', len(info)

for item in info:
    print item['count']
    total = total + item['count']

print total

The error I am receiving is:
TypeError: string indices must be integers" for "print item['count']

Why do they have to be integers? My instructor on Coursera did a similar thing. Any advice?
The JSON file has this structure:
{
  comments: [
    {
      name: "Matthias"
      count: 97
    },
    {
      name: "Geomer"
      count: 97
    }
    ...
  ]
}

A: The error "TypeError: string indices must be integers" for "print item['count']" says that item is a string; in this case it's a dictionary key.
I haven't seen your JSON but if your "comments_42.json" is this dataset, try the code below:
total = 0
for item in info["comments"]:
    print item['count']
    total += item["count"]

I found it here (maybe someone solved this  challenge or whatever it is and uploaded the solution)

A: It's telling you that item is a string, meaning your JSON structure isn't like the one you used in your course.  For example
info = ['the', 'items', 'inside', 'this', 'list', 'are', 'strings']

for item in info:
    # Items here are strings (the, information, etc)
    print(items) # this will print each word in the list

info = {'sentence': 'the', 'items', 'inside', 'this', 'list', 'are', 'strings'}

for items in info:
    # This is a dictionary, which can be addressed by the key name
    print(items['sentence'])  # this is what you're expecting, because 'sentence' is a dictionary key.

If you add your JSON response to the original question, we can help you understand how to access the items you want.


text:
Q: Implementation of virtual functions from a third party class Summary
I want to design a class which will hold all my problem data so that its member functions can be used to pass information to the third party member functions. How can I do it for the below two functions?
My Problem:
I'm coding a program for scientific computation. To solve my problem I have to use some third party libraries. Currently I'm using Ipopt (for numerical optimization).
To use Ipopt, I have to provide enough information in the following way.
First I need to create a class which should inherit the third party class TNLP.
Then I have to provide implementation to the 8 virtual functions, of which two of them is as below with its implementation.
// MyNLP is the class which I coded to inherit from TNLP.
bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
                           bool init_z, Number* z_L, Number* z_U,
                           Index m, bool init_lambda,
                           Number* lambda)
{
   // Here, we assume we only have starting values for x, if you code
   // your own NLP, you can provide starting values for the others if
   // you wish.
    assert(init_x == true);
    assert(init_z == false);
    assert(init_lambda == false);

   // we initialize x in bounds, in the upper right quadrant
    x[0]=0.5;
    x[1]=1.5;
    return true;
}

and
bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
    // return the value of the objective function
   Number x2 = x[1];
   obj_value = -(x2 - 2.0) * (x2 - 2.0);
   return true;
}

In the above implementations I've provided values to the parameters within the function call directly. Now to make the program more general, instead of directly entering the required information in the above functions, I wish to use a class which contain all the information regarding my problem and use function members in the third party virtual function.
For example, if NLP is the class which hold my problem content and m_nlp is its incident in the class MyNLP then I'll rewrite the virtual functions as below.
bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
                           bool init_z, Number* z_L, Number* z_U,
                           Index m, bool init_lambda,
                           Number* lambda)
{
   // Here, we assume we only have starting values for x, if you code
   // your own NLP, you can provide starting values for the others if
   // you wish.
    assert(init_x == true);
    assert(init_z == false);
    assert(init_lambda == false);

    x = m_nlp->get_initial_values();

}

and
bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
    // return the value of the objective function
    obj_value = m_nlp->get_obj_value();
}

But I cannot do this in the above fashion, since  second function uses x to calculate object_val. How can I design a class to hold all the data and uses its member functions to give required information to Ipopt.
What I thought as a solution:
define a std::vector<Number> values as a member of nlp class and point the x to the first element of the values.
 x = &(m_nlp->get_values()).at(0);

in the second function, I can modify values instead of x and calculate obj_val.

A: You could derive a class from MyNLP.  Or
class NLPWithStuff : public MyNLP {
   //...
   virtual bool get_starting_point(/*...*/)
    {
        // optional boost::signals that do their stuff ??
        // do my stuff, set flags so that no-one touches my stuff
        // don't assert

        return MyNLP::get_starting_point(/*.+.*/);
    }
};

You'll have to declare MyNLP::get_starting_point virtual to make it work.


text:
Q: Join ORC parts and create CSV What is the simplest way to convert an existing ORC store in many parts on HDFS to one CSV file? I can use hive and/or spark, but I want to keep the memory requirements small, so I don't want to spark.read and coalesce.

A: I'm not sure but you can try to export from hive the ORC to an external table in CSV format, setting hive.merge.mapredfiles=true
(https://community.hortonworks.com/questions/92415/how-to-merge-reduce-task-output-to-produce-final-o.html)


text:
Q: Should I save my blood? I have a large amount of blood meals (100+). When questing should I use them at every single opportunity, or should i save them for better areas?
I am currently on the first underground level.

A: There's not a great reason to save them at that point. Blood meals max out at 999 currently.  They could be used to increase your "collections", but their main value is in bringing up skill levels for familiars by doing the 'blood brothers' vaporizing thing.
At 100+, I would try only for long-shot UC chances, as those net you 45 skill points, unless you really need the common variety for boosting.  Given the limit of familiars you can hold, the common ones start to become more trouble than they're worth.  You'll still want to keep some blood meals for events, as they might be useful for catching the tournament type of familiars.

A: In Tower Events, extra event points are earned for "capture" of encountered enemies. Hence by saving all your blood meals till Tower Event you'll have more chances to earn event points. Other than that they are pretty useless.


text:
Q: SAX Parser, how to dynamically ignore & in input xml file for SAXParser.parse I have a scenario where I get an XML from another service and I parse this file and render it to another file.
But, sometimes, we get & in the input file inside any tag and when we try to parse this file we get SAXException.
Is there a way we can dynamically replace &, or we can ignore the & sign while parsing?

A: After doing a bit of research I have come up with following points:

*

*SAX Parser needs a clean XML file without any error, else it will fail and we cannot change characters dynamically in the input. So, we need to check the Input XML file before hand.

*To change characters in the input file with ease use "StringEscapeUtils.escapeXml" provided by Apache in "org.apache.commons.lang.StringEscapeUtils" package. But, this to has its downside, as it will all the occurences of the character. For reference you can check this blog: "http://javarevisited.blogspot.com/2012/09/how-to-replace-escape-xml-special-characters-java-string.html"

*But, my use case scenario was different, I need only particular character to be deleted from the input file. So, for that I had to code from scratch; I had to read file and check for the desired character to delete and delete it and write back to the file again.


text:
Q: Gauss Continued Fraction for Hypergeometric Functions I would like to calculate the Gauss Continued Fraction for this particular Hypergeometric function:
\begin{equation}
_{2}F_{1}\left( 1-\frac{1}{p}, \frac{1}{p}; 1+\frac{1}{p}; x^p \right)
\end{equation}
since it satisfies the transformation:
\begin{equation}
\frac{_{2}F_{1}\left(a+1, b; c+1; z \right)}{_{2}F_{1}\left(a, b; c; z \right)}=\frac{1}{1+\frac{\frac{(a-c)b}{c(c+1)}z}{1+\cdots}}
\end{equation}
for $b=c=-a=1/p$ and $z=x^p, p>1$.
My target is to see whether I could get a good approximation for this function by using this transformation.
I have tried to find a build-in function in Mathematica to calculate this continued fraction, but it was not possible.

I would like to ask if there exists a library where I could possibly find this, or if you could help me write it down on my own.

A: You can use this code to construct the continued fraction expansion to any given order:
    f[a_,b_,c_,n_Integer]:=Module[{k},
       k=Floor[n/2];
       Which[n==1,1,
          EvenQ[n],-((b+k-1)(c-a+k-1))/((c+2k-2)(c+2k-1)),
          OddQ[n], -((a+k)(c-b+k))/((c+2k-1)(c+2k))]]/;n>0;

    cfrac[m_]=ContinuedFractionK[f[a,b,c,n]z^(n-1),1,{n,1,m+1}];

Give it a try.  Just type, for example, "cfrac[4]".  I haven't checked convergence properties for your case of interest.


text:
Q: Add a VLAN tag to specific UDP port traffic I'm running an application in Ubuntu12.04 that I've written that does some remote switch management.
I have only a single NIC connected to the network of managed switches, eth0 which is set with IPv4 10.0.0.1/24. This IPv4 address is the only address that this Ubuntu machine can use since this is the only "globally" routable address assigned to the Ubuntu machine (due to some network administration, not due to technical issues...)
I need the switch management traffic (NetConf over SSH, using UDP port 830) to include a 802.1q VLAN tag with VLAN ID 444), when sending the NetConf frames and the replies will be received also with this tag.
All other traffic (http, ftp, dhcp, snmp, etc.) will use eth0 without the VLAN tag.
I've tried using a VLAN interface eth0.444 on eth0, but is seems the traffic sent doesn't include the VLAN tag.
Can (and how) can I use ebtables/iptables to add a specific VLAN tag to specific UDP port traffic?
Will the ebtables/iptables solution work also for the receive path?
Thank you!
David

A: iptables and ebtables can't set VLAN tags on packets. That's what VLAN sub-interfaces are for.
There's an article on the Ubunut wiki that discusses VLANs that you should probably review. In summary, though, you want to:

*

*Make sure the 802.1q module is loaded with a modprobe 8021q.

*Create the VLAN sub-interface with vconfig add eth0 444.

*Add an IP address and subnet mask from the subnet used in VLAN 444 to the eth0.444 sub-interface with ip addr add x.x.x.x/z dev eth0.444
You'lll also need to configure the switch port to which the server is attached to accept tagged frames for VLAN 444. You don't mention your brand of switch so I can't give much guidance there, but you're probably looking for either a "trunk" or "general" port configured as a tagged member of VLAN 444 and an untagged member of whatever VLAN is used by the subnet assigned to the the eth0 interface.
Be aware that tcpdump can have problems displaying the VLAN tags so don't necessarily assume that frames aren't being tagged if you're just using tcpdump on the host itself to verify that frames are tagged.
Edit:
Typically there's a one-to-one relationship between VLANs and IP subnets. It would be exceedingly atypical if the switch had a management interface in VLAN 444 that was the same IP subnet as whatever VLAN your current eth0 port is located in.

A: 802.1Q tag is inserted into MAC header, and kernel won't decode it if your interface isn't VLAN tagged. So, even if you could mangle outgoing packets, incoming traffic with VLAN tag would stay ignored.
What you need to do is create a VLAN tagged interface, just as you did, and add an IP to it within the same rage the switch IP you're trying to access is in.


text:
Q: Changing single chars to upper or lower case depending on user input in Java I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;

public class LowerUpper {

    public static void main(String[]args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Please enter three letters: ");

        String letters = input.nextLine();

        for (int i = 0; i < letters.length(); i++) {

        char letter1 = letters.charAt(0);
        char letter2 = letters.charAt(1);
        char letter3 = letters.charAt(2);

        if (Character.isUpperCase(letters.charAt(0)) == true)
            System.out.println(Character.toLowerCase(letter1));

        else {
            System.out.println(Character.toUpperCase(letter1));
        }
        if (Character.isUpperCase(letters.charAt(1)) == true)
            System.out.println(Character.toLowerCase(letter2));

        else {
             System.out.println(Character.toUpperCase(letter2));
        }

        if (Character.isUpperCase(letters.charAt(2)) == true)
            System.out.println(Character.toLowerCase(letter3));

        else {
              System.out.println(Character.toUpperCase(letter3));
        }
    }
}
}

When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.

A: The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
   char letter1 = letters.charAt(0);
   if (Character.isUpperCase(letter1)) {
       System.out.println(Character.toLowerCase(letter1));
   } else {
       System.out.println(Character.toUpperCase(letter1));
   }
}

A: The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'.  If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C".  To print the chars in a row, you can simply append each character to a string, and then output that.

A: Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;

public class LowerUpper {

    public static void main(String[]args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Please enter three letters: ");

        String letters = input.nextLine();

        char letter1 = letters.charAt(0);
        char letter2 = letters.charAt(1);
        char letter3 = letters.charAt(2);

        if (Character.isUpperCase(letters.charAt(0)) == true)
            System.out.print("Result: " + Character.toLowerCase(letter1));

        else {
            System.out.print("Result: " + Character.toUpperCase(letter1));
        }

        if (Character.isUpperCase(letters.charAt(1)) == true)
            System.out.print(Character.toLowerCase(letter2));

        else {
             System.out.print(Character.toUpperCase(letter2));
        }

        if (Character.isUpperCase(letters.charAt(2)) == true)
            System.out.print(Character.toLowerCase(letter3));

        else {
              System.out.print(Character.toUpperCase(letter3));
        }
    }
}

A: The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.

To solve your problem. just remove the for loop. 'coz you already
  store each character to the three variables.

You code will look like this now:
import java.util.Scanner;

public class LowerUpper {

    public static void main(String[]args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Please enter three letters: ");

        String letters = input.nextLine();

        char letter1 = letters.charAt(0);
        char letter2 = letters.charAt(1);
        char letter3 = letters.charAt(2);

        if (Character.isUpperCase(letters.charAt(0)) == true)
            System.out.println(Character.toLowerCase(letter1));

        else {
            System.out.println(Character.toUpperCase(letter1));
        }
        if (Character.isUpperCase(letters.charAt(1)) == true)
            System.out.println(Character.toLowerCase(letter2));

        else {
             System.out.println(Character.toUpperCase(letter2));
        }

        if (Character.isUpperCase(letters.charAt(2)) == true)
            System.out.println(Character.toLowerCase(letter3));

        else {
              System.out.println(Character.toUpperCase(letter3));
        }

}
}

A: The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.

A: Replace your for loop with:
System.out.println(letters.toUpperCase());


text:
Q: Управление сторонней запущенной программой Суть такова: есть программа на питоне, написанная с помощью библиотеки pycatia для взаимодействия с программой 3д моделирования CATIA V5. Прога с помощью библиотеки обращается к CATIA вот так:
def catia_application() -> Application:
return Application(Dispatch('CATIA.Application'))

То-есть, прога ищет установленное и запущенное на компе приложение CATIA.Application (которое так же можно увидеть в редакторе реестра).
Но в моем случае CATIA V5 запускается не локально с компа, а подгружается в оперативку с сервера. Вопрос: как обратиться к запущенному с сервера приложению? Работает то CATIA V5 все-таки на компе, должен быть способ взаимодействия с этим процессом (приложением).


text:
Q: Need assistance to understand Power and Ohm's Law Hello I'm looking at a light bar on a vehicle and the specifications say it draws 7.5A at 9-32V and the light bar says it has 36 x 5 Watt LED lights which would make a total of 180 Watts that this device uses is this correct?. My confusion is how can it draw a constant 7.5A at each voltage between 9-32V? If the voltage increase how does affect energy used over time if the current is still flowing to the device at the same speed? and if is powered by 32V at 7.5A this would be a total of 240A which is too much for the device. Would the internal resistance be changing to keep a constant current of 7.5A?
Thank you

A: You're assuming that the current is always 7.5A.  Manufacturers often quote the maximum current draw.  If the light bar contains a switch mode power supply, then the current draw will decrease if you increase the voltage, keeping the wattage approximately constant.
Just because the light bar contains 36 x 5W LEDS, it doesn't mean that each LED is actually being driven at 5W.  Running an LED at less than its rated power makes it easier to keep it cool.  It's also a very good way to fool customers into thinking they are going to get a light that's a lot brighter than it really is.

A: It might have a power supply inside it to drive the LEDs. So there is a good chance the 7.5A is rated nominal value for rated nominal supply, and it will vary according to the applied voltage.
Or it might have a constant current driver so it wastes extra power as heat.
But 180 watts at 7.5A is exactly 24V so they might have rated the consumption at typical 24V usage.

A: The light bar you described seems like it could be using an internal regulator to actually power the lights. It's possible that this has a maximum output power rating regardless of what you provide to the light bar. This regulator will take the 9-32V input and convert it to potentially a 12 / 24V rail that is actually powering the LEDS.
If you could share a link to what LED bar was used that might help us explain what's happening.
Just to clear up your maths and question about Ohm's law, with the provided information you have said that the Light Bar states Max current of 7.5A and an operational voltage range from 9-32V.
The image below shows the equations you should be using to calculate this, to calculate power with the values you have you should do I X V = P. If you want to work out the max current we should do P / V = I. Knowing this we can

Knowing this we can calculate all possible combinations, as shown below,

Assuming the 7.5A limit is used across all voltages you will be current limited at any voltage below 24V meaning the maximum power output would drop as shown.
From my calculations you can see that the Current rating provided lines up perfectly with the 24V @ 7.5A = 180W so it's likely the numbers you are reading are referenced to a 24V supply. This is also quite a common supply rail for LED's so that seems to make sense.


text:
Q: Override plugin option by with a custom theme I'm creating a custom theme and using one of video embedding plugins from the market. There are plenty of options and among them "don't load css style", is there a way how to make it always checked when my theme is active? Author hasn't provided any define value to fix it.
it's stored in option: fve_disable_css
I have tried to update_option(); on init and as well tried a filter pre_option_fve_disable_css but no success, any ideas?
Thanks a lot

A: Plugin can read options on init event or just in code (during loading). All plugins are loaded before theme load. So, using init action can be too late.
Filter pre_option_fve_disable_css doesn't change value of the option. Instead, you have to use option_fve_disable_css filter. But again, it can be also too late.
You should check the handle name in wp_enqueue_script function in plugin code, which enqueues relevant css and deregister this handle in your functions.php during wp_enqueue_script event. This is the right time for such an action.


text:
Q: jQuery hover not functioning properly I dont know whats wrong with this Code. The left hover works properly but the right one doesnt. I mean if you Hover on "L" and then you move the mouse to "R" it doesnt work <.

Here is my JS Fiddle:
http://jsfiddle.net/neoragex/npnHw/5/

A: It's just interfering with the 'Result' label.
Fixed here: http://jsfiddle.net/npnHw/6/

A: This works for me in Chrome. Maybe you are using a different browser?


text:
Q: Recursive Query and INNER JOIN I am stuck with a query that is using recursive and wondering if you guys can help me out.
I have this query below and it is based on the ShipQuantity, then it lists the number of records.  For example, mfgPN "ABC123" has a ShipQuantity of 4, it will list 4 records with a number 1,2,3, 4.
WITH feedInfo
AS (
    SELECT df1.RecID, MfgPN, LinkID, ShipQuantity, 1 AS Number
    FROM EXT_DistributorFeed df1
    WHERE 1 = 1
    AND df1.mfgPN IN ('ABC1', 'ABC2')

    UNION ALL

    SELECT df2.RecID, df2.MfgPN, df2.LinkID, df2.ShipQuantity, feedInfo.number + 1 AS Number
    FROM EXT_DistributorFeed df2
    INNER JOIN feedInfo ON df2.RecID = feedInfo.RecID
    WHERE 1 = 1
    AND number < feedInfo.ShipQuantity
    AND df2.mfgPN IN ('ABC1', 'ABC2')
)
Select feedInfo.*
From feedInfo
OPTION (maxrecursion 20000);

Let's say the result is
RecID   MfgPN   LinkID  ShipQuantity    Number
101     ABC1    L11111  4               1
102     ABC1    L11111  4               2
103     ABC1    L11111  4               3
104     ABC1    L11111  4               4
105     ABC2    L22222  2               1
106     ABC2    L22222  2               2

Now, I have another table "EXT_DistributorFeedDetail" where it may contain serial# (some part# have serial# and some part# don't have).  This table has only two columns: (1) LinkID and (2)SerialNo.  Like this:
EXT_DistributorFeedDetail
LinkID  SerialNo
L22222  S999999
L22222  S888888

I would like to join the feedInfo with EXT_DistributorFeedDetail table to get the result like this:
RecID   MfgPN   LinkID  ShipQuantity    Number  Serial
101     ABC1    L11111  4               1       NULL
102     ABC1    L11111  4               2       NULL
103     ABC1    L11111  4               3       NULL
104     ABC1    L11111  4               4       NULL
105     ABC2    L22222  2               1       S99999
106     ABC2    L22222  2               2       S88888

Any expert out there can help would be greatly appreciated.
Thank you,

A: Looks like you're trying to match up the LinkID and Number from the recursive query to the LinkID and a Row Number in the EXT_DistributorFeedDetail table
WITH feedInfo
AS (
    SELECT df1.RecID, MfgPN, LinkID, ShipQuantity, 1 AS Number
    FROM EXT_DistributorFeed df1
    WHERE 1 = 1
    AND df1.mfgPN IN ('ABC1', 'ABC2')

    UNION ALL

    SELECT df2.RecID, df2.MfgPN, df2.LinkID, df2.ShipQuantity, feedInfo.number + 1 AS Number
    FROM EXT_DistributorFeed df2
    INNER JOIN feedInfo ON df2.RecID = feedInfo.RecID
    WHERE 1 = 1
    AND number < feedInfo.ShipQuantity
    AND df2.mfgPN IN ('ABC1', 'ABC2')
)
Select  fi.*,
        dfd.SerialNo [Serial]
From    feedInfo fi
        LEFT JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY LinkID ORDER BY SerialNo) rn,
                   FROM EXT_DistributorFeedDetail) dfd
           ON dfd.LinkID = fi.LinkID AND dfd.rn = fi.Number
OPTION (maxrecursion 20000);

Depending on what order you want the serial numbers in the EXT_DistributorFeedDetail table to be you would need to change the order by in the Window function ROW_NUMBER() OVER (PARTITION BY LinkID ORDER BY SerialNo)  if you take out the Order by the it would be random and could change.

A: It looks like you want to join the SerialNo in descending order for the number. You can do this by changing the last part of the query to this:
with feedinfo as (
  ....
)

select f.*, e.*
from feedinfo f
left join (
    select *, rn = row_number() over (partition by linkid order by serialno desc)
    from ext_distributorfeeddetail
) e on f.linkid = e.linkid and f.number = e.rn
option (maxrecursion 20000);

A: You have to left join on the EXT_DistributorFeedDetail table to extract serial column. Note that for each recid in the output the serial column will be repeated as many times as the number of entries per linkid in the EXT_DistributorFeedDetail table.
    WITH feedInfo AS
    (
    SELECT df1.RecID, MfgPN, LinkID, ShipQuantity, 1 AS Number
    FROM EXT_DistributorFeed df1
    WHERE df1.mfgPN IN ('ABC1', 'ABC2')

    UNION ALL

    SELECT df2.RecID, df2.MfgPN, df2.LinkID, df2.ShipQuantity,
    feedInfo.number + 1 AS Number
    FROM EXT_DistributorFeed df2
    INNER JOIN feedInfo ON df2.RecID = feedInfo.RecID
    WHERE number < feedInfo.ShipQuantity
    AND df2.mfgPN IN ('ABC1', 'ABC2')
    )
    Select feedInfo.*, e.serial
    From feedInfo
    left join EXT_DistributorFeedDetail e
    on e.linkid = feedinfo.linkid


text:
Q: Accessing remote folders when vpn is connected failed I have a computer that is connected to a remote computer via VPN.
When the VPN connection is up I'm unable to connect to remote shared folders from other local computers defined in my domain (LAN).
Why is that?

A: From Microsoft Support
This occur if you configure the VPN connection to use the default gateway on the remote network. This setting overrides the default gateway settings that you specify in your Transmission Control Protocol/Internet Protocol (TCP/IP) settings.
So This is the default design of VPN. If you want to access LAN/Internet and VPN simultaneously

*

*Go to properties of VPN.

*Click on the Networking tab and double click Internet Protocol Version 4 (TCP/IPv4).

*Click Advanced and uncheck the box for "Use default gateway on remote network.".

This will route all of your local traffic through network you're locally connected, and remote traffic through the VPN assuming that you are not trying to route your internet traffic through the VPN.


text:
Q: How to create directory in nougat 7.0 .. All devices work fine below nougat 7.0 but in nexus 5x not creating directory I put this in manifest
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="true"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

Creating Path Xml in Res
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Java code follows:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("application/pdf");
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Sheep Drench Calculations " );
                shareIntent.putExtra(Intent.EXTRA_TEXT, "Please find attached the report generated from the Sheep Drench App");
                Uri pdfURI = FileProvider.getUriForFile(EmailSend.this,
                        BuildConfig.APPLICATION_ID + ".provider",
                        (new File(pdfDir ,"ResultPDF.pdf")));
                shareIntent.putExtra(Intent.EXTRA_STREAM, (pdfURI));
                startActivity(shareIntent);

More java code:
File pdfDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir");
                    if (!pdfDir.exists()) {
                        pdfDir.mkdir();
                    }

it creates directory but when it go to inside the directory it through exception no such directory or file .
            I tried this one to send email from file but problem is still there ..and director is not created ...

A: Try changing .mkdir() to .mkdirs () and make sure you've  Write External Storage permission in manifest


text:
Q: How do i save dynamically in flask static folder in a python package? I'm trying to build a python package with flask. I am trying to save matplotlib figures into the  static folder of the flask server but based on what i am reading i cannot save files into the package directories. How do I accomplish this task?

A: You can but it is not a good idea to save in your static folder on runtime. You can just create a folder named 'files' and do something like this:
import os
FILES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'files')
.
.

and then save your files in FILES_DIR.


text:
Q: Simple file compression in C I'm new to programming with C, and I need somewhere that I can read up on file compression in C. I only need a simple recognised method. An example would help but mostly somewhere I can read to understand.

A: maybe a good starting point is RLE which is extremely simple but not so trivial to implement. Check it out: http://en.wikipedia.org/wiki/Run-length_encoding

A: The first method I learned in school is Huffman Encoding.  Here is a link: http://en.wikipedia.org/wiki/Huffman_coding
Here is a link to a C implementation:  http://scanftree.com/Data_Structure/huffman-code


text: Q: Customer disconnected when paying My first customer when directed to Paypal to pay got disconnected after submitting payment. Payment was not processed. Any solutions of what may have happened? I did all testing on the sandbox and it worked well. After changing to the live API I was directed to the correct page on Paypal to pay but I never tested out myself because I would be charged. Now my first customer had problems. I am using Woocommerce and setup to use Paypal adaptive payments. My e-commerce is setup for subscriptions with a one time payment and 30 days trial. Customers select the subscription they desire and proceed to cart, then checkout with Paypal. Woocommerce marked the order as completed but I did not receive any payments. Customer said that Paypal got disconnected so they did not try again afraid that they would be charged again.


text:
Q: c# convert a string hex to ascii ? string reading from a csv file I'm trying in C# and visual studio express to convert a very long string of chars that contains hex data names in ASCII words
Example : The file column that I read contain the string

4E 4F 54 49 46 59 .................. (continue)

that means in ASCI  "NOTIFY"
My program is getting this exception when with the method ToHex I try to convert this.
Why appear this exception? Is it caused by the char of space between each two chars of hex ASCII values?

A first chance exception of type 'System.FormatException' occurred in
  mscorlib.dll A first chance exception of type
  'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
  A first chance exception of type
  'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.IO;
using LumenWorks.Framework.IO;
using LumenWorks.Framework.IO.Csv;

//main class
namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public String FirstName { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            ConvertTrace.HexUtf8toAsci();
        }
    }

    //convert service classe
    public class ConvertTrace
    {
        public static String output;
        public static String fine;
        /*this is the method for convert the string that contain the hex spaced couples of chars into a asci readable string*/

        public static string ToHex(String hexString)
        {
            byte[] dBytes = Enumerable.Range(0, hexString.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)).ToArray();

            output = System.Text.Encoding.ASCII.GetString(dBytes);
            return output;
        }

        public static void HexUtf8toAsci()
        {
            // open the file "data.csv" which is a CSV file with headers
            using (CsvReader csv = new CsvReader(new StreamReader("test3pulito.csv"), true))
            {
                int fieldCount = csv.FieldCount;
                string[] headers = csv.GetFieldHeaders();
                while (csv.ReadNextRecord())
                {
                    for (int i = 0; i < fieldCount; i++)
                    {
                        string line2 = null;
                        int line_number2 = 0;
                        using (StreamWriter writer2 = new StreamWriter("test3new.csv"))
                        {
                            System.Text.UTF8Encoding encoding;
                            byte[] dBytes;
                            string ASCIIresult;
                            string utf8result;
                            string corretto;
                            string originale;
                            string risultato;
                            line_number2++;
                            //here I check the column of the file where to get the string to convert
                            if (i>7)
                            {
                                originale = csv[i];
                                Console.WriteLine(originale + "\r");
                                /*here is where I call the convert method*/
                                corretto = ToHex(originale);
                                Console.WriteLine(corretto + "\r");**
                            }
                        }
                    }
                }
            }
        }
    }
}

A: You had the right idea to convert the hex bytes to actual bytes but your approach doesn't work.  Assuming that you're passing in a sequence of valid hex bytes that are space separated, you could do this in your ToHex() method:
var hexBytes = "4E 4F 54 49 46 59";
var bytes = hexBytes.Split(' ')
    .Select(hb => Convert.ToByte(hb, 16)) // converts string -> byte using base 16
    .ToArray();
var asciiStr = System.Text.Encoding.ASCII.GetString(bytes);

A: I've got a more straight forward solution for you, to convert your hex data back into string format.  I've got sample data in here also:
string s = "4E 4F 54 49 46 59"; // Sample data
string hex = "0123456789ABCDEF";
string[] tokens = s.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string token in tokens)
    sb.Append((char)(hex.IndexOf(token[0]) * 16 + hex.IndexOf(token[1])));
string output = sb.ToString(); // The variable output contains your converted text.


text:
Q: Breadth first search simple improvement In most resources implementation of BFS is like this(this is geeks for geeks implementation):
void findpaths(vector<vector<int> >&g, int src,
                             int dst, int v)
{
// create a queue which stores
// the paths
queue<vector<int> > q;

// path vector to store the current path
vector<int> path;
path.push_back(src);
q.push(path);
while (!q.empty()) {
    path = q.front();
    q.pop();
    int last = path[path.size() - 1];

    // if last vertex is the desired destination
    // then print the path
    if (last == dst)
        printpath(path);

    // traverse to all the nodes connected to
    // current vertex and push new path to queue
    for (int i = 0; i < g[last].size(); i++) {
        if (isNotVisited(g[last][i], path)) {
            vector<int> newpath(path);
            newpath.push_back(g[last][i]);
            q.push(newpath);
        }
    }
}

the above implementation suggests that we first add the neighbors to the queue then we will check it that it is our destination or not.
but we can simply check the neighbor is the destination or not when adding the neighbor to the queue (instead of checking it when it is that node's turn) although it is a very minor improvement, it is better than the last one. so why everyone use the previous method for implementing BFS?


text:
Q: How to ensure Wordpress admin dashboard menu item is first I am using WP 3.6.
I am building a theme that only needs a few of the 'native' admin menu items and one menu item I have added using 'add_object_page'.
I would like to make my menu item ALWAYS be the first item.
How can I force it to appear at the top of the list above all plugins and the 'native' menu items?

A: You can use add_menu_page() with last parameter $position.
The position in the menu order this menu should appear. By default, if this parameter is omitted, the menu will appear at the bottom of the menu structure. The higher the number, the lower its position in the menu. WARNING: if two menu items use the same position attribute, one of the items may be overwritten so that only one item displays! Risk of conflict can be reduced by using decimal instead of integer values, e.g. 63.3 instead of 63 (Note: Use quotes in code, IE '63.3').
Default: bottom of menu structure
Positions for Core Menu Items:
 2 Dashboard
 4 Separator
 5 Posts
 10 Media
 15 Links
 20 Pages
 25 Comments
 59 Separator
 60 Appearance
 65 Plugins
 70 Users
 75 Tools
 80 Settings
 99 Separator

For More: visit WordPress Codex

A: If you want the item to appear at the top above the dashboard.
you need to add it as a menu page. with position 1.
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function = '', $icon_url = '', $position = null )

this will make it appear on the top.
when you add it as an object page, it is automatically given the lowest position.
Note: need to use the admin_menu hook.
**=============or===============**,

you can use the custom_menu-order and menu_order hook  and reorder the menu items.
eg:
function order_menu ($order)
{
//$order is an array of slug of menu items, reorder
//reorder it as you would want to appear in the admin menu.
 $page_slug="dolt";

 unset($order[array_search($page_slug,$order)]);
 array_unshift($order,$page_slug);
 return $order;
}

 add_filter('custom_menu_order',function(){return true;});
 add_filter('menu_order','order_menu',11);


text:
Q: Extracting a portion of an array by using pointer in C For example if I have an array and I want to extract elements of this array with a specified value as a new array. I did as the following:
int a[10] = { 1, 2, 1, 3, 2, 3, 4, 1, 2, 6 };
int i, k;

int count = 0;
for (i = 0; i < 10; i++) {
    if (a[i] == 1) {
        count = count + 1;
    }
}

int b[count];
k = 0;
for (i = 0; i < 10; i++) {
    if (a[i] == 1) {
        b[k] = a[i];
        k = k + 1;
    }
}

So, for the array "a" I extracted all the elements of value 1, and make them as a new array "b". How can I achieve the same thing by using pointers? Will it be conciser than this way? If it is possible, is there any other advantages?

A: I think you already noticed that you just had to write 1 several times; yet I suppose you want that it works for arbitrary conditions.
"Using a pointer" can mean dynamic memory allocation instead of a variable length array. Just for the sake of having use a pointer, you could then write:
int *b = malloc(count * sizeof(int));
k = 0;
for (i = 0; i < 10; i++) {
    if (a[i] == 1) {
        b[k] = a[i];
        k = k + 1;
    }
}

If, just for sake of using a pointer for the writing process, too, you could adapt the program as follows:
int *b = malloc(count * sizeof(int));
int *bPtr = b;
for (i = 0; i < 10; i++) {
    if (a[i] == 1) {
        *bPtr++ = a[i];
    }
}

Hope it helps a bit.

A: If you don't know which portion of the array your target values will be in, as in your case, where you're searching the entire unsorted array for a specific value, then there is no advantage to using pointers rather than a linear search to find the elements in the array you are after.
If, however, you are trying to access or copy a contiguous set of elements starting at a known index in the array, then you could use a pointer to simplify things.  For example, if I'm after the last few elements in an array of chars, this works:
#include <stdio.h>
int main()
{
    char str[100] = "I don\'t want anyone to think I hate the Calgary Flames";
    char *c = (str + 29);
    printf("%s\n", c);
    return 0;
}

Output:
I hate the Calgary Flames

A: In this case, no, there is no benefit. a[i] is already basically a + (sizeof(int) * i). Even if you used pointers, you'd still have to do all the counting anyway to make sure you don't walk off the end of the array.
Where its often handy is with a null terminated array of pointers, such as a string, where you don't know the length. But it's not really about performance. As you can see below, they have to do roughly the same things.
char string[] = "foo bar";

// Allocate and initialize i.
// `string + i` twice, compare, increment.
for( int i = 0; string[i] != '\0'; i++ ) {
    printf("%c", string[i]);
}
puts("");

// Allocate and initialize s.
// Dereference s twice, compare, increment.
for( char *s = string; *s != '\0'; s++ ) {
    printf("%c", *s);
}
puts("");

Where iterating by pointer is handy is when you need to iterate through an array in several steps. Instead of passing around the original array pointer plus your last index, and changing all your function signatures to accommodate, just pass around the incremented pointer and return the incremented pointer. This allows you to use standard string functions on the middle of a string.
#include <stdio.h>

char *findVal( char *string, char delim ) {
    char *val = string;
    for( ; *val != '\0' && *val != delim; val++ ) {
    }

    if( val == '\0' ) {
        return NULL;
    }
    else {
        // val is sitting on the ':'
        return val+1;
    }
}

int main() {
    char string[] = "this:that";

    char *val = findVal(string, ':');
    if( val != NULL ) {
        // Just use val, not string[valIdx].
        printf("%s\n", val);
    }
}

This is also safer. With an offset there's two things which must remain in sync, the pointer and the offset; that opens the possibility that the wrong offset will be used with the wrong pointer. An incremented pointer carries its offset with it.

As has been pointed out in the comments, you can tighten up the second loop like so:
int b[count];
for (i = 0; i < count; i++) {
    b[i] = 1;
}


text:
Q: Paste Vectors without `rbind` function I have 10 Vectors in my R environment. I want to paste this vectors for create a data frame. I used the rbind function, but i think that is very inefficient, because i have to type all variables in the function. The question is, can i use the paste0 or paste function or other function like that, for paste this vectors?, thank you.
#Por ejemplo

x1 <- c(1, 2)
x2 <- c(3, 4)
x3 <- c(5, 6)
x4 <- c(7, 8)
x5 <- c(9, 10)
x6 <- c(11, 12)
x7 <- c(13, 14)
x8 <- c(15, 16)
x9 <- c(17, 18)
x10 <- c(19, 30)

rbind(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)

I want to paste this vectors, without rbind, with some function like paste0 or paste.

A: The do.call function is useful when the argument is a list and the function is expecting items that are just vectors. Since mget, which returns a list, is the natural tool when attempting to go from character to object names, you might try:
do.call(rbind, mget(paste0("x", 1:10)))
#---
    [,1] [,2]
x1     1    2
x2     3    4
x3     5    6
x4     7    8
x5     9   10
x6    11   12
x7    13   14
x8    15   16
x9    17   18
x10   19   30

Or using matrix
matrix(unlist(mget(paste0("x", 1:10))), ncol=2, byrow = TRUE)

A: ls() returns a vector of all the variable names in your environment. If you do a regex for every variable name that begins with x then you can iterate over the new vector and get() them to call the variable with that name. If you call get in a lapply function, then you'll get a list of all the called variables. do.call() performs a function on every item in a list.
to_get <- ls()[grepl('^x', ls())]
to_bind <- lapply(to_get, get)
final_matrix <- do.call(rbind, to_bind)


text:
Q: Are variadic constructors supposed to hide the implicitly generated ones? Are variadic constructors supposed to hide the implicitly generated ones, i.e. the default constructor and the copy constructor?
struct Foo
{
    template<typename... Args> Foo(Args&&... x)
    {
        std::cout << "inside the variadic constructor\n";
    }
};

int main()
{
    Foo a;
    Foo b(a);
}

Somehow I was expecting this to print nothing after reading this answer, but it prints inside the variadic constructor twice on g++ 4.5.0 :( Is this behavior correct?

It also happens without variadic templates:
struct Foo
{
    Foo()
    {
        std::cout << "inside the nullary constructor\n";
    }

    template<typename A> Foo(A&& x)
    {
        std::cout << "inside the unary constructor\n";
    }
};

int main()
{
    Foo a;
    Foo b(a);
}

Again, both lines are printed.

A: Declaration of the implicitly declared copy constructor is not, in fact, being suppressed.  It's just not being called due to the rules of overload resolution.
The implicitly declared copy constructor has the form Foo(const Foo&).  The important part of this is that it takes a const reference.  Your constructor template takes a non-const reference.
a is not const, so the non-const user-declared constructor template is preferred over the implicitly-declared copy constructor.  To call the implicitly-declared copy constructor, you can make a const:
const Foo a;
Foo b(a);

or you can use static_cast to obtain a const reference to a:
Foo a;
Foo b(static_cast<const Foo&>(a));

The overload resolution rules that describe this are found mostly in §13.3.3.2/3 of the C++0x FCD.  This particular scenario, with a combination of lvalue and rvalue references, is sort of described by the various examples on page 303.

A variadic constructor template will suppress the implicitly declared default constructor because a variadic constructor template is user-declared and the implicitly declared default constructor is only provided if there are no user-declared constructors (C++0x FCD §12.1/5):

If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted.

A variadic constructor template will not suppress the implicitly declared copy constructor because only a non-template constructor can be a copy constructor (C++0x FCD §12.8/2, 3, and 8):

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.
A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments.
If the class definition does not explicitly declare a copy constructor and there is no user-declared move constructor, a copy constructor is implicitly declared as defaulted.


text:
Q: Tag quick-follow broken?
Possible Duplicate:
Favorite / Ignored tags interface not working?

When I hover over a tag on SO and click the star (to mark a tag as a favorite), the star does not illuminate and in my Favorite Tags list I see a tag appear that looks like tagtagnamesubscriber-info -- where TAGNAME is the name of the tag I selected.  This happens even with a cold cache.

*

*Browser: Chrome 15.0.849.0 dev-m

*OS: Windows 7 (x64)


text:
Q: Why func2() prints out 10 instead of 12? How to call function and let it run? def func1():
    Num = 3
    print(Num)

def func2():
    global Num
    Double_num = Num*2
    Num = 6
    print(Double_num)

How can I actually run it? Not sure how to call a function. And the answer says func2 prints out 10, why is it not 12?

A: Tip 1: Don't use globals unless you absolutely need to and know exactly what you're doing, because you probably don't need them.
def func1():
    Num = 3
    print(Num)
    return Num

def func2():
    Num = func1()
    Double_num = Num*4
    print(Double_num)

func1()
func2()

Here's a full example which should print 3 and then 12. When you use def that defines a function, but the code in that function doesn't execute unless you call the function, like func1().

A: The variable num has been predefined as 5 that's why when you call func2 it results in 10.
And func2() , is how you call the function


text:
Q: java.lang.NullPointerException when loading drawable which exists in each res/drawable-"density" folder I have a drawable resource called obstacle.png which exists in each of my drawable-"density" folders.  Yet, whenever I run the app, I get a null pointer exception when I am assigning the bitmap's width to my _width variable.  This code will only run on mdpi and on the Galaxy TAB addon AVDs.  It fails on ldpi or hdpi AVDs.  Why?
19 public Weapon(Context context) {
20      super(context);
21      _weapon = BitmapFactory.decodeResource(getResources(), R.drawable.obstacle);
22      _width = _weapon.getWidth();
23      _height = _weapon.getHeight();
24  } //constructor

LogCat:
Caused by: java.lang.NullPointerException
at com.shootball.Weapon.<init>(Weapon.java:22)

A: _weapon is null since BitmapFactory.decodeResource(getResources(), R.drawable.obstacle); returns null.

A: Check whether you have obstacle.png image in all drawable folder.if there is no image it will return null value.


text:
Q: if H is a subgroup and N is a normal subgroup is H normal in HN? The title speaks for itself, I saw something that requires it but I can't seem to prove it, any help is appreciated!
I'm asking because of this comment which specify that from the second isomorphism theorem we know that $[HK:H]=[K:H\cap K]$ suggesting that $H\triangleleft HK$ when in the question we have that $K\triangleleft G$ and $H\le G$

A: It appears to me that your core mistake is that you seem to think the 'index of' relation (denoted by the '[:]') is only applicable between a group and a normal subgroup.  Actually it is applicable between a group and any subgroup.