text:
Q: How to add to mongodb, MERN app validation failed error I'm trying to learn the MERN stack, I'm trying to create a simple shopping list app.
I have a simple api to get, post and delete items, this all works using Postman when testing the api.
Locally the get works and I can get items from the db.
When I try to add to the db I get this error.
(node:28550) UnhandledPromiseRejectionWarning: ValidationError: item validation failed: name: Path `name` is required.
[0]     at new ValidationError (/Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/error/validation.js:30:11)
[0]     at model.Document.invalidate (/Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/document.js:2080:32)
[0]     at p.doValidate.skipSchemaValidators (/Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/document.js:1943:17)
[0]     at /Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/schematype.js:933:9
[0]     at _combinedTickCallback (internal/process/next_tick.js:131:7)
[0]     at process._tickCallback (internal/process/next_tick.js:180:9)
[0] (node:28550) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
[0] (node:28550) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

As the api works in postman I think it must be something to do the redux I'm using.
ShoppingList js
import React, {Component} from 'react';
import uuid from 'uuid';
import {connect} from 'react-redux';
import {getItems, deleteItem, addItem} from '../actions/itemActions';

class ShoppingList extends Component{

  componentDidMount(){
    this.props.getItems()
  }

  onDeleteClick = (id) => {
    this.props.deleteItem(id);
  }

  render(){

    const {items} = this.props.item

    return(

        <button
          onClick={() => {
            const name = prompt('New Item')

            if(name){
              this.props.addItem(name)
            }
          }}
        >
          Add Item
        </button>

          {items.map(({id,name}) =>{
            return(

                <button
                  onClick={this.onDeleteClick.bind(this, id)}
                >
                  ×
                </button>
                {name}

            )
          })}

    )
  }

}

const mapStateToProps = state => ({
  item: state.item
})

export default connect (mapStateToProps, {getItems, deleteItem, addItem})(ShoppingList)

itemActions
import axios from 'axios';
import {GET_ITEMS, ADD_ITEM, DELETE_ITEM, ITEMS_LOADING} from '../actions/types';

export const getItems = () => dispatch =>{
  dispatch(setItemsLaoding());
  axios
    .get('/api/items')
    .then(res =>
      dispatch({
        type: GET_ITEMS,
        payload: res.data
      })
    )
}

export const addItem = (name) => dispatch =>{
  axios
    .post('/api/items', name)
    .then(res =>
      dispatch({
        type: ADD_ITEM,
        payload: res.data
      })
    )
}

export const deleteItem = (id) =>{
  return{
    type: DELETE_ITEM,
    payload: id
  }
}

export const setItemsLaoding = () => {
  return{
    type: ITEMS_LOADING
  }
}

itemReducer.js
import {GET_ITEMS, ADD_ITEM, DELETE_ITEM, ITEMS_LOADING} from '../actions/types';

const initialState = {
  items: [],
  loading: false
}

export default function(state = initialState, action){
  switch(action.type){
    case GET_ITEMS:
      return{
        ...state,
        items: action.payload,
        loading:false
      }
    case DELETE_ITEM:
      return{
        ...state,
        items: state.items.filter(item => item.id !== action.payload)
      }
    case ADD_ITEM:
      return{
        ...state,
        items: [...state.items, { name: action.payload}]
      }
    case ITEMS_LOADING:
      return{
        ...state,
        loading:true
      }
    default:
      return state
  }
}

models/Item.js (mongoose model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ItemSchema = new Schema({
  name:{
    type: 'String',
    required: true
  },
  Date:{
    type: Date,
    default: Date.now
  }
})

module.exports = Item = mongoose.model('item', ItemSchema);

routes/api/items.js
const express = require('express');
const router = express.Router();

const Item = require('../../models/Item');

router.get('/', (req, res) => {
    Item.find()
        .then(items => res.json(items))
        .catch(err => console.log(err))
});

router.post('/', (req, res) => {
    const newItem = new Item({
        name: req.body.name
    })
    newItem
        .save()
        .then(item => res.json(item))
        .catch(err => console.log(err))
})

router.delete('/:id', (req, res) =>{
    Item.findById(req.params.id)
        .then(item => item.remove().then(() => res.json({success:true})))
        .catch(err => err.status(404).json({success:false}))
})

module.exports = router;

A: Okay, I did some debugging and here is the problem, you are sending the item name as the key with no value so the API cannot understand it.
Change this code:
export const addItem = (name) => dispatch =>{
  axios
    .post('/api/items', name)
    .then(res =>
      dispatch({
        type: ADD_ITEM,
        payload: res.data
      })
    )
}

to this code:
export const addItem = name => dispatch => {
  const req = {
    name,
  };

  axios.post('/api/items', req).then(res =>
    dispatch({
      type: ADD_ITEM,
      payload: res.data,
    })
  );
};

A: I solved this problem by adding this code to routes/api/items.js:
var bodyParser = require("body-parser");

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));


text:
Q: How to Password Char a Column in DataGridView I am trying to password char a column when loading in a table.
Code below loads the table.
//Fills out Student table
private void loadStudentTable()
{
    SqlConnection conn2 = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
    conn2.Open();

    try
    {
        SqlCommand cmdDatabase2 = new SqlCommand("Select * from Student", conn2);
        SqlDataAdapter sda2 = new SqlDataAdapter();
        sda2.SelectCommand = cmdDatabase2;
        DataTable dbdataset2 = new DataTable();
        sda2.Fill(dbdataset2);
        BindingSource bSource2 = new BindingSource();
        bSource2.DataSource = dbdataset2;
        studentGridView.DataSource = bSource2;
        sda2.Update(dbdataset2);
        studentGridView.Columns[0].Width = 92;
        studentGridView.Columns[1].Width = 200;
        studentGridView.Columns[2].Width = 180;
        studentGridView.Columns[3].Width = 180;
        studentGridView.Columns[4].Width = 170;
        studentGridView.Columns[5].Width = 170;
        studentGridView.Columns[6].Width = 130;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    conn2.Close();
}

I am trying to password char the studentGridView.Columns[5].Width = 170; column.
Any help or ideas?

A: You need the CellFormatting event of your DataGridView like this
private void studentGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (gv_Input.Columns[e.ColumnIndex].Index == 5 && e.Value != null)
    {
        studentGridView.Rows[e.RowIndex].Tag = e.Value;
        e.Value = new String('*', e.Value.ToString().Length);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure VNet and address space Just started learning Azure Virtual Network. Following excerpt is about Address Space as defined here: VNet Address Space. Question: When you say a VNet has an address space 10.0.0.0/16, what does it mean? I have read an address space is a range of IP addresses for a Virtual Network and its subnets. What is 16 in 10.0.0.0/16 and when you assign IP address to a resource from this address space what role does 10.0.0.0/16 play? I assume you cannot just pick any four numbers and create an IP address xx.x.x.x (x's are numbers here) for a resource in the VNet with the above address space. I just read some online docs on the subject but, for a newbie in this subject, I found those to be bit overwhelming to understand. Can there be a simple explanation to start with?
Address space: When creating a VNet, you must specify a custom private IP address space using public and private (RFC 1918) addresses. Azure assigns resources in a virtual network a private IP address from the address space that you assign. For example, if you deploy a VM in a VNet with address space, 10.0.0.0/16, the VM will be assigned a private IP like 10.0.0.4.

A: Think about the internet with 255.255.255.255 addresses.
Now think about your internal/private at home Router/Switch network and how it typically starts with 192.168.0.0.
In organisations you typically assign the private network with 10.0.0.0 addresses. NIC cards in PCs can communicate using the internal network as well as the public internet.

Question: When you say a VNet has an address space 10.0.0.0/16, what does it mean?

In order to define the size of the network (how many IP addresses) we use a CIDR range.
So a Network with 10.0.0.0/28, the calculation is 32 minus the CIDR, eg:
32 - 28 = 4

Then 2 to the power of the result:
2^4 = 2 * 2 * 2 * 2

16 addresses!
In real life you'd create VNet with more than 16 addresses. Because inside VNets you define Subnets which are smaller address ranges that fit inside the VNets address range.
Your example of 10.0.0.0/16 is more realistic VNet size for an organisation and equals 65536 addresses.
Ref: https://devblogs.microsoft.com/premier-developer/understanding-cidr-notation-when-designing-azure-virtual-networks-and-subnets/#:~:text=The%20second%2C%20and%20most%20important,which%20provides%20eight%20IP%20addresses.
Best to learn this particular topic VNets & Subnets with CIDR from online video's because it involves electronics with masking and binary it can confuse people when they look deeper beyond what I've just explained.


text:
Q: What is the role of app key and secret key in every SDK I am building SDK in which I require to take app id and app secret key from app which will integrate my android SDK.
I see every SDK is using this concept app id and secret key. I don't know what is the use of this ? How this make system secure ?
Can anyone help me on this topic.

A: App ID and secret key are two different things. Let me try to address both separately and then tie them together.
App ID
App ID is simply a unique identification label for an app. This is to avoid overlaps in the App Store and on your device. If two apps have the same App ID, one can be installed on top of the other, effectively erasing the old one, and maybe hijacking your data. App ID is only the first step to SECURITY. To ensure there is absolutely no way of the above scenario happening, we use the secret key.
Secret Key
The secret key is a security implementation, usually for asymmetric encryption. Let's take a look at Wikipedia's definition of asymmetric encryption:

Public-key cryptography, also known as asymmetric cryptography, is a class of cryptographic protocols based on algorithms that require two separate keys, one of which is secret (or private) and one of which is public. Although different, the two parts of this key pair are mathematically linked.

The secret key is part of a pair of keys, the other being the public key. The public key, as the name suggests, is openly available to the public. The secret key should ideally be available only to one person.
The pair of keys are used to open a lock, in your case to 'unlock' apps. Each app has a unique asymmetric lock. An asymmetric lock is either locked with a secret key, and opened with the public key, or vice versa. The purpose is IDENTIFICATION. Only one person can have the secret key. So any app by this person, we know is definitely from that person and not some hacker/doubious source. That is why the secret key is important.
Hence, these two concepts work hand-in-hand to bring you better security. When you use APIs, you sometimes do not need the secret key, but only the app ID so the main service you are using APIs for knows which exact product you are using.

A: Basically it's used for authorization. That in return enables the SDK creators more control over their users. I can think of a few reasons why an SDK would require an authorization:

*

*Prevent/Block spam attacks on the servers that the SDK possibly connects to

*Limit the use of the SDK

*Track the use for statistics (e.g. usage frequency)


text:
Q: Add client name in custom routing I want to add the client name in each and every route in my .net core application. I do not want to add in each controller using Route OR RoutePrefix. It should be available for all controllers. So,how can I do this ?
Lets say I have following routes

*

*mysite.com/virtualdir1/clientname/Login

*mysite.com/virtualdir1/clientname/Dashboard

*mysite.com/virtualdir1/clientname/Home

*mysite.com/virtualdir1/clientname/AboutUs
I have tried to setup in startup.cs file as follows but it gives 404 error
 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Backend",
                    template: "{clientname}/{controller=Home}/{action=Login}");

            });

Thanks for the help !


text:
Q: Getting Clock/Time information from PC to an STM32F4 Assume I connect a microcontroller board (like an STM32F4) to a PC via USB. Is there anything in the USB communication protocol that contains host clock data? In other words, can I sync the microcontroller to the PC clock just by hooking up to USB?
If that's not possible, could you suggest some clever minimal-effort way to get the clock info from PC to the STM32F4?
I guess I could always write some software to run on the PC in the background and provide that info to the STM32F4, and I'll do that if I must, but I'd like to avoid that.
I could also use a network shield and have the STM32F4 query the PC over the network, but I'd like to keep cost and complexity down by not using any extra shields.
I could also have the STM32F4 run its own clock base, but that's not an option - it must be synced to this particular PC down to the second, even if the PC itself is out of sync with NTP.


text:
Q: captiva Theme Error I have Install Captiva in my system local.its showing error like this
Warning: POST Content-Length of 36013235 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
Are you sure you want to do this?

A: 8388608 bytes is 8M, which is the default post size limit in PHP. Update your post_max_size in php.ini to a larger value, may be 50M.
post_max_size sets the maximum amount of data that can be sent via a POST in a form.


text:
Q: ERROR: operator does not exist: jsonb[] -> integer select id,rules from links where id=2;
 id |                                                                                rules
----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  2 | {"{\"id\": \"61979e81-823b-419b-a577-e2acb34a2f40\", \"url\": \"https://www.wikijob.co.uk/about-us\", \"what\": \"country\", \"matches\": \"GB\", \"percentage\": null}"}

I'm trying to get the elements of the jsonb using the operators here https://www.postgresql.org/docs/9.6/functions-json.html
Whether I use 'url', or an integer as below, I get a similar result.
select id,rules->1 from links where id=2;
ERROR:  operator does not exist: jsonb[] -> integer
LINE 1: select id,rules->1 from links where id=2;
                       ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

What am I doing wrong?
PS Postgres version 9.6.12.

A: The column is an array, you can access the first element using index:
select id, rules[1]
from links
where id = 2

Be sure to check also this answer.
Use jsonb_each() in a lateral join to see all rules in separate rows:
select id, key, value
from links
cross join jsonb_each(rules[1]) as rule(key, value)
where id = 2

You can get a single rule in this way:
select id, value as url
from links
cross join jsonb_each(rules[1]) as rule(key, value)
where id = 2 and key = 'url'

Use unnest() to find an url in all elements of the array, e.g.:
select id, unnest(rules)->'url' as url
from links
where id = 2;


text:
Q: About combinatorics $$x = -\sum_{k=1}^p \binom{p}{k} p^{k-2}\bigl(-xA(x)\bigr)^k$$
For degree $n>1$, the left hand side of the equation is equal to $0$.
Setting $0$ equal to the degree $n$ term of the right hand side of the equation gives this equation
$$0=-\sum_{k=1}^p \binom{p}{k} p^{k-2}
\sum_{i_1+\ldots+i_k=n} \prod_{j=1}^k a(i_j-1) (-1)^kx^n.$$
This was taken from the article entitled "Super Patalan numbers" by Thomas M. Richardson...
I want to see the full details of the transformation and shifting

A: The power series $A(x)$ is the generating function of the Patalan numbers $a(n)$. Thus the coefficient of $x^{i_j}$ in the product $xA(x)$ is $a(i_j - 1)$; the factor $x$ results in the index shift. Then we are pulling out the factor $(-1)^k$ from the product, and writing the expression for the degree $n$ term of the $k^{\rm th}$ power of a series.


text:
Q: how can I detect all the text that inside a block with Google Vision Api I'm trying to extract text from an image with google vision api, it works. But I just want to detect part of the image to get certain text.
this is the image I used

I just want to extract all the text from maybank2u.com until From Account:
I know there are some tutorials to do this trick by using block but those tutorials are different programming languages.
My code:

            <?php foreach ($text as $key => $texts): ?>

 <?php echo ucfirst($texts->info()['description']) ?>
<

            <?php endforeach ?>

This code will getting all the text from image
Output:

A: The code below works for me. I have one php file, test.php and one image file /images/UUIPXl.png.
To get each line of text, I iterate the text annotations from Google Vision, and create an array of row items. Each of these has an x position and a text value.
I then sort each row by x position and concatenate to create a line of text.
Finally we stop once we get the final desired line of text.
I get a result like so:

*

*  maybank2u.com

*  Open BillPayment

*  Status: Successful

*  Reference number: 2950211545

*  Transaction date: 01 Feb 2016 13:09:17

*  Amount: RM100.00

*  From Account 564155051577 WCA

The php code:
<?php

    require 'vendor/autoload.php';
    use Google\Cloud\Vision\VisionClient;

    $config = ["keyFile" => json_decode(file_get_contents("./APIKey.json"), true) ];
    $vision = new VisionClient($config);

    $image = $vision->image(
        fopen('./images/UUIPXl.png', 'r'),
        ['TEXT_DETECTION']
    );

    $textAnnotations = $vision->annotate($image)->text();
    $rows = [];

    // Function used to sort our lines.
    function sortProc($a, $b)
    {
        if ($a["x"] === $b["x"]) {
            return 0;
        }
        return ($a["x"] < $b["x"]) ? -1 : 1;
    }

    // Remove first row (complete text).
    array_shift($textAnnotations);

    // We should calculate this, use a reasonable value to begin with.
    $lineHeight = 8;

    foreach ($textAnnotations as $text) {
        $key = round(((double)($text->info()["boundingPoly"]["vertices"][0]["y"]))/$lineHeight);
        $x = (int)$text->info()["boundingPoly"]["vertices"][0]["x"];
        $value = ["x" => $x, "text" => $text->description()];
        if (!isset($rows[$key])) {
            $rows[$key] = [];
        }
        $rows[$key][] = $value;
    }

    $text = [];
    foreach ($rows as $key => $value) {
        // Sort by x value.
        usort($value, "sortProc");

        // Concatenate each line
        $result = array_reduce($value, function($acc, $elem) {
            $acc .= " " . $elem["text"];
            return $acc;
        }, "");

        $text[] = $result;

        // Stop when we get here!
        if (preg_match("/from account/i", $result)) {
            break;
        }
    }

?>

            <?php foreach ($text as $row): ?>

 <?php echo ucfirst($row) ?>

            <?php endforeach ?>

A: If you only want to limit the output and its every time the same string that should stop the execution, then do the following:

            <?php foreach ($text as $key => $texts): ?>
                <?php if (strpos($texts->info()['description'], 'From Account') !== false) break; ?>

 <?php echo ucfirst($texts->info()['description']) ?>
<

            <?php endforeach ?>

Explanation:
If $texts->info()['description'] contains the text From Account it ends the execution of the foreach loop through break. If you need to check for multiple keywords read this.
An alternative solution would be to crop the image with imagecrop() before sending it to the API. But for this you need to be sure that it never changes the size / position of the texts.
P.S. are you sure everyone should see those private data in your screenshot?
Update1
As you asked. This would be the same code but using the alternative syntax for control structures:

            <?php foreach ($text as $key => $texts): ?>
                <?php if (strpos($texts->info()['description'], 'From Account') !== false): ?>
                <?php break; ?>
                <?php endif; ?>

 <?php echo ucfirst($texts->info()['description']) ?>
<

            <?php endforeach ?>

Maybe this solves your problem as the same page includes this note:

Mixing syntaxes in the same control block is not supported.

Update2
After you updated your question its more clear now. The output does not contain one element per text line. Instead it contains multiple lines of texts. Because of that my first code did not echo anything as it finds From Account in the very first array element.
Because of that we need to search for the string From Account and cut the text line:

            <?php foreach ($text as $key => $texts): ?>
                <?php
                $text = $texts->info()['description'];
                // search for string
                $pos = strpos($texts->info()['description'], 'From Account');
                if ($pos !== false) {
                    // if the string was found cut the text
                    $text = substr($text, 0, $pos);
                }
                ?>

 <?php echo $text ?>
<

            <?php endforeach ?>

Optionally you could add this before <?php endforeach ?> to skip all following array elements:
                <?php
                if ($pos !== false) {
                    break;
                }
                ?>

Note: @TerryLennox uses preg_match to find From Account. There is no difference between this and using strpos (most prefer avoiding regex). But his answer contains another good tip. He uses the text position information to add the text line by line to a new array. This could be really useful depending on your targets how to display/store the text.


text:
Q: Cannot convert type 'int' to 'bool' I'm working on a custom login Textbox that has an Auto Complete function. However, When i try to:
public static void SetSelectOnMouseOver(DependencyObject obj, bool value)
    {
        obj.SetValue(ListBoxItemBehavior.SelectOnMouseOverProperty,
            (object)(bool)(value ? 1 : 0));
    }

I get an error (object)(bool)(value ? 1 : 0)); > cannot convert type 'int' to 'bool', what's wrong?

A: value is already a bool.  Why not just use (object) value, or even just value?


text:
Q: Could we have independent browser CSS in Next JS If I write the CSS as style jsx in Next JS, do I need to write all browser supports manually in my styles or Next JS add them automatically during build time for the production?
for example:
transofm:translate(50%,50%)
-webkit-transofm:translate(50%,50%)  // such line will be added automatically during build time?

......

A: It does not add them automatically for CSS in JS by default, but Next.js uses PostCSS by default with Autoprefixer plugin (you should have a postcss.config.js file in your root dir), so you can use postcss-js (also mentioned in autoprefixer docs)
Default behavior of PostCSS in Next: https://nextjs.org/docs/advanced-features/customizing-postcss-config


text:
Q: How to repeat a pattern and modify with a "tab" with sed My input looks like this separated by tabs):
Yadda yaddabla            blubb_1234          extremlylongtext, with commata
awesomo sappa             dwarf_775           extremlylongbutdifferenttext, with commata

The output should be:
Yadda yaddabla S23            blubb_1234      1234      extremlylongtext, with commata
awesomo sappa y5            dwarf_775       775       extremlylongbutdifferenttext, with commata

So I want to repeat only the Numbers after a "_" character seperated with a tab. Any suggestions? : )

A: sed 's/_\([[:digit:]]\{1,\}\)/_\1\t\1/g'

I have shown this with a \t indicating a tab in the output. If you're not using GNU sed, you may need to replace it with a literal tab.

A: awk solution for tab separated file
awk -F"\t" 'BEGIN{OFS="\t";}{$2 = gensub(/_([0-9]+)/,"_\\1\t\\1","g",$2);}1' temp.txt


text:
Q: Java 11 : Create class instance out of generic type I'd like to implement a custom deserialization object in Java 11. For this I have
public class ObjectDeserializer<T extends ObjectDeserializable> {
    public T deserialize(ByteBuffer buf)
    {
        T ret = instantiateNew();
        return (T) ret.deserialize(buf);
    }
}

How can I implement instantiateNew() method?
Is it possible to create an instance of class using it's type ? What is the right way to do it?


text:
Q: Injecting cache to a module I am trying to inject cache to a module using module.config.php with no luck. My module.config.php looks like this
return array(
    'di' => array(
        'instance' => array(
            'AssetLoader\Module' => array(
                'parameters' => array(
                    'cache'       => 'Zend\Cache\Storage\Adapter\Filesystem',
                ),
            ),
        ),
    ),
);

and in my Module.php
public function setCache(\Zend\Cache\Storage\Adapter\Filesystem $cache)
{
    die(__FUNCTION__);
    $this->cache = $cache;
}

But nothing happens. I expect script to die but for some reason this function is never executed. I am sure I am doing something wrong but can someone explain how to inject a cache (or any other object in that matter) to the module?

A: This question is answered on Zend mailing list now.
See here
Matthew pointed out that Module classes weren't pulled out from locator, so you can't use DI to inject resources to the modules. See the link to see how it's done.


text:
Q: Changing max_length on a CharField for a ModelForm I have defined the max_length on a field to be 50 in the model definition. When a form is created it takes those attributes to make the fields, but I would like to overwrite that max_length for that specific form without changing the model itself.
This is what I have in my model
text_field01 = models.CharField(max_length=50, default="")
text_field02 = models.CharField(max_length=50, default="")

I tried overwriting the widget with a new widget in my forms.py but that threw an error. I also tried it in the init but that seemed to have no effect. I am a bit stuck, any help would be greatly appreciated.
EDIT
At first I tried setting the widgets in class meta as shown below.
widgets = {
'text_field01': forms.CharField(max_length=10)

This produced an error "CharField" object has no attribute 'is_hidden'
Then I tried doing it in init as shown below.
        def __init__(self, *args, **kwargs):
            super(AutomationForm, self).__init__(data=data, files=files, *args, **kwargs)
            if self.instance:
                if self.fields['text_field01']:
                    self.fields['text_field01'].max_length = 2

Which simply had no effect.

A: You can create a ModelForm, and override the value for the max_length=… parameter [Django-doc]:
class MyModelForm(forms.ModelForm):
    text_field01 = forms.CharField(max_length=25)

    class Meta:
        model = MyModel
        fields = '__all__'
The max_length you define in the ModelForm can only be less than or equal to the one in the Model itself, since validation in the model has to succeed as well.


text:
Q: PHP accessing String vars as Array and changing value Is it ok to do this please?
for($i=0;$i<strlen($str);$i++)
{
    if(!in_array($str[$i],$arAllowedCharset)){$str[$i]='';}
}
return $str;

It works, but I am unsure if I am "allowed" to do that, i.e. $str[$i]='';.
Note: $str is a string variable, $arAllowedCharset is an array containing only alphanumerical characters and a dash.
I use that to format user-submitted URLs in a custom CMS.
Thank you.

A: It would be easier to check and correct the url with a regular expression. For example
$str = preg_replace('#[^a-z0-9-]#i', '', $str);


text:
Q: Proof that the sum of the reciprocals of primes diverges Reading the proof-sketch (as set out here) that the sum of the reciprocals of the prime numbers is divergent, I get stuck. The proof starts with Euler's product formula $\sum _{n=1}^{\infty } \frac{1}{n}=\prod_p \frac{1}{1-p^{-1}}$. Then it proceeds as follows:
"Euler considered the above product formula and proceeded to make a sequence of audacious leaps of logic. First, he took the natural logarithm of each side, then he used the Taylor series expansion for $\ln x$ as well as the sum of a converging series:
$$\ln \left(\sum _{n=1}^{\infty } \frac{1}{n}\right)=\ln \left(\prod_p \frac{1}{1-p^{-1}} \right)$$
$$=\sum_p \frac{1}{p} +\frac{1}{2p^2}+\frac{1}{3p^3}+...$$
$$=\sum_p \frac{1}{p}+\frac{1}{2}\sum_p \frac{1}{p^2}+\frac{1}{3}\sum_p \frac{1}{p^3}+...$$
$$=A+\frac{1}{2}B+\frac{1}{3}C+...$$
$$=A+K$$
for a fixed constant $K<1$."
I don't follow the last step. Clearly, $B=\sum_p \frac{1}{p^2}$, $C=\sum_p \frac{1}{p^3}$, $D=\sum_p \frac{1}{p^4}$ and so on, and each of these sums is convergent. But why is $\frac{1}{2}B+\frac{1}{3}C+\frac{1}{4}D+...<1$ given that $\frac{1}{2}+\frac{1}{3}+\frac{1}{4}+...$ is divergent?
I get that the value of $\sum_p \frac{1}{p^k}$ becomes rapidly smaller with increasing $k$, but how does one prove the convergence of $\frac{1}{2}B+\frac{1}{3}C+\frac{1}{4}D+...$ to a value less than $1$?

A: Could be following from this (for $k\ge 2$): $$\sum_p\frac{1}{p^k}\lt\sum_{n=2}^{\infty}\frac{1}{n^k}\lt\int_1^{\infty}\frac{dx}{x^k}=\frac{1}{k-1}$$ so $\frac{1}{2}B+\frac{1}{3}C+\frac{1}{4}D\cdots$ becomes bounded by a simple telescopic series $\sum_{k=2}^\infty\frac{1}{(k-1)k}$ with the sum $1$?


text:
Q: Modify the scroll button of a JTabbedPan I'm working on a UI on Java with Swing, I want to change the scroll button of a JTabbedPane, so I use a new UI (MyTabbedPaneUI) that I create from the extends MetalTabbedPaneUI.
But when I create my JTabbedPanel there are 2 tabs which appear and I don't want them. If I remove them my scroll bar disappear.
The code :
  public class MyTabbedPaneUI extends MetalTabbedPaneUI{

        private Icon southIcon = new ImageIcon(MyTabbedPaneUI.class.getResource("south.png"));
        private Icon northIcon = new ImageIcon(MyTabbedPaneUI.class.getResource("north.png"));
        private Icon eastIcon  = new ImageIcon(MyTabbedPaneUI.class.getResource("flecheVerte-gauche-20px.png"));
        private Icon westIcon  = new ImageIcon(MyTabbedPaneUI.class.getResource("flecheVerte-droite-20px.png"));

        public static ComponentUI createUI( JComponent x ) {
            return new MyTabbedPaneUI();
        }

        @Override
        protected JButton createScrollButton(int direction) {

            if ((direction != SOUTH) && (direction != NORTH) && (direction != EAST) && (direction != WEST)) {
                throw new IllegalArgumentException("Direction must be one of: " + "SOUTH, NORTH, EAST or WEST");
            }

            JButton b = new JButton();

            //b.setText("");
            b.setPreferredSize(new Dimension(eastIcon.getIconWidth(), eastIcon.getIconHeight()));

            if (direction == SOUTH) {
                b.setIcon(southIcon);
            } else if (direction == NORTH) {
                b.setIcon(northIcon);
            } else if (direction == WEST) {
                b.setIcon(westIcon);
            } else {
                b.setIcon(eastIcon);
            }

            return b;
        }

    }

A: please see my post for clarifying

based on code, notice required add tb.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

A: @Override
protected JButton createScrollButton(int direction) {
    if (direction != SOUTH && direction != NORTH && direction != EAST
            && direction != WEST) {
        throw new IllegalArgumentException("Direction must be one of: "
                + "SOUTH, NORTH, EAST or WEST");
    }
    return new ArrowButton(direction);
}

//
public final class ArrowButton extends JButton implements UIResource, SwingConstants {

protected int direction;
private final Image left, disabledleft, pressedleft;
private final Image right, disabledright, pressedright;

public ArrowButton(int direction) {
    super();
    setDirection(direction);
    left = new ImageIcon(getClass().getResource("/resources/arrowicons/left.png")).getImage();
    disabledleft = new ImageIcon(getClass().getResource("/resources/arrowicons/disabledleft.png")).getImage();
    pressedleft = new ImageIcon(getClass().getResource("/resources/arrowicons/leftpressed.png")).getImage();

    right = new ImageIcon(getClass().getResource("/resources/arrowicons/right.png")).getImage();
    disabledright = new ImageIcon(getClass().getResource("/resources/arrowicons/disabledright.png")).getImage();
    pressedright = new ImageIcon(getClass().getResource("/resources/arrowicons/rightpressed.png")).getImage();
}

public int getDirection() {
    return direction;
}

public void setDirection(int direction) {
    this.direction = direction;
}

@Override
public void paint(Graphics g) {
    boolean isPressed, isEnabled;
    int w, h, size;
    w = getSize().width;
    h = getSize().height;
    isPressed = getModel().isPressed();
    isEnabled = isEnabled();

    Image image = null;
    if(direction == EAST){
        if(isEnabled && isPressed){
            image = pressedright;
        }else if(!isEnabled){
            image = disabledright;
        }else{
            image = right;
        }
    }else{
        if(isEnabled && isPressed){
            image = pressedleft;
        }else if(!isEnabled){
            image = disabledleft;
        }else{
            image = left;
        }
    }
    g.drawImage(image, 0, 0, null);
}

@Override
public Dimension getPreferredSize() {
    return new Dimension(32, 32);
}

@Override
public Dimension getMinimumSize() {
    return new Dimension(5, 5);
}

@Override
public Dimension getMaximumSize() {
    return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}

}
//This is my solution pretty easy and usefull. You can use easily. Actually the post is 8 years old, probably it is not an issue for you anymore but somebody else can use.


text:
Q: Fuzzy matching to find the index of a word in a sentence Python I have the following sentence which is Catalan language:

en aquest sentit, la llei preveu que quan l'administració s'hagi abstingut d'actuar per sancionar una determinada conducta, com a conseqüència d'un procés penal, i aquest procediment acabi en sentència absolutòria, podrà iniciar o continuar el corresponent procediment administratiu.

After tokenizing the sentence and it becomes a list of words, I need to find the index of the word "actuar", but indexof() is not going to work. Moreover, I don't know Catalan language at all, but I have seen cases like "l'" could also be preceding the word I need.
Is there any easy way to fix this?

A: You can try this:
>>> sen = "en aquest sentit, la llei preveu que quan l'administració s'hagi abstingut d'actuar per sancionar una determinada conducta, com a conseqüència d'un procés penal, i aquest procediment acabi en sentència absolutòria, podrà iniciar o continuar el corresponent procediment administratiu."
>>> tokens = sen.split()
>>> tokens
['en', 'aquest', 'sentit,', 'la', 'llei', 'preveu', 'que', 'quan', "l'administraci\xc3\xb3", "s'hagi", 'abstingut', "d'actuar", 'per', 'sancionar', 'una', 'determinada', 'conducta,', 'com', 'a', 'conseq\xc3\xbc\xc3\xa8ncia', "d'un", 'proc\xc3\xa9s', 'penal,', 'i', 'aquest', 'procediment', 'acabi', 'en', 'sent\xc3\xa8ncia', 'absolut\xc3\xb2ria,', 'podr\xc3\xa0', 'iniciar', 'o', 'continuar', 'el', 'corresponent', 'procediment', 'administratiu.']
>>> def get_index(tokens, substr):
...    for i, tk in enumerate(tokens):
...       if substr in tk: return i
...
>>> get_index(tokens, "actuar")
11


text:
Q: Xcode 5 doesn't let me adding Icons and Launch Images I am using Xocde 5 , in my Phone Project I am working on I am having some problem on adding Icons and Launch Images to my project. I don't use storyboard and asset catalog , so I always delete them after creating a new project.

Usually, when "Don't use asset catalog" is selected in the Launch Images and Icons section in general tab of project settings , I see there's option for adding images for different screen sizes. But currently, I don't get that options. "Don't use asset catalog" is selected here , but there's no other things on that menu and right arrow icon beside that does nothing when I click that. So, It seems there's no way I can add launch images and app icons to my project.
Can anyone give me some hint , how can I resolve that. I have to add Launch Images and App Icons. Thanks in advance for your help.

A: I have managed to solve it. I have copied Images.xcassets file from another project and added to my project. Then I got the options to add images in the place I mentioned in the attached image in the question. So, I have deleted the images that came from other projects in the asset catalog and add the necessary files there from my project. Now everything is fine.

A: Another solution might be by adding a 'New App Icon' and/or 'New Launchimage' in the Assets Catalog and then select the created image sets in project settings.


text:
Q: Prevent ruby on rails 3 from parsing JSON post I have a controller method in Ruby on Rails 3 that accepts application/JSON as the content type.  This all works as expected, but I actually do not want rails to automatically parse the JSON in the body of the POST request.  This method is acting as a gateway and just shuttles the information in to a queue and could be quite large.  I do not want to waste the time processing the data in to the @_params since it's unnecessary.
I believe I could get around this by setting the content-type in the header of the request to something else, but I would like to be semantically correct for the HTTP requests.
How can I disable this functionality?
EDIT:
more specifically how can I edit this functionality for just this one route?

A: Parameter parsing is baked pretty deeply inside actionpack's lib/action_dispatch/middleware/params_parser.rb.
I'd say the best you're going to get away with is intercepting the request with Rack, something like this.
In lib/raw_json.rb
module Rack
  class RawJSON
    def initialize(app)
      @app = app
    end

    def call(env)
      request = Request.new(env)
      if request.content_type =~ /application\/json/i
        # test request.path here to limit your processing to particular actions
        raw_json = env['rack.input'].read
        env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        env['rack.input'] = StringIO.new("raw_json=#{raw_json}")
      end
      return @app.call(env)
    end
  end
end

In config.ru, insert this before the call to run <your app name>::Application
require 'raw_json'
use Rack::RawJSON

A: The overhead for parsing the JSON from a single request is relatively low. Do you have a specific reason to believe that processing the JSON is contributing to any kind of slowness in overall processing?
If not, then I'd recommend that you leave this as it is until such time is it can be identified as a problem.
Configuring rails to not parse that JSON (either via some sort of rack configuration or in some other method) will create at lest one route in your application that is not handled in a standard Rails Way.
Eventually, you may find yourself having to do some sort of processing of this data. Or maybe you'll need to put some sort of security in front of it. Or maybe you'll want to log it and related it to the user that sent it. And when that day comes you (or someone else on your team) will need to go in and make changes to this non-standard implementation.
Doing things in a non-standard way in a Rails implementation can add to the complexity and time to maintain the software. It is also a common source of defects since people are less familiar with non-standard processing.
So unless it is a real issue, I'd recommend just letting rails process the JSON and then simply pass it through the normal Rails Way.

A: It may be baked in, but looking at the code:
 module ActionDispatch
  class ParamsParser
    DEFAULT_PARSERS = {
      Mime::XML => :xml_simple,
      Mime::JSON => :json
    }

    def initialize(app, parsers = {})
      @app, @parsers = app, DEFAULT_PARSERS.merge(parsers)
    end

     [ ... ]

        strategy = @parsers[mime_type]

So, if you can arrange to send a hash to this initializer, you can add or override the default.  Not sure the allow for removing, but an empty parser method could work.
Parsers answer here: How do I initialize ActionDispatch::ParamsParser in Rails 3.1?
Code is from actionpack-3.2.8/lib/action_dispatch/middleware/params_parser.rb


text:
Q: Why all result showing failed ![I have created Test plans & users for my project, I took 10 number of threads & 2 loops, when i ran the test Result is showing like this .
I have attached two screenshots : 1. Sample result 2. Response data.
I am not able to understand why result is coming like this
Load time : 0 & latency: 0, then why error count:1 it should be OK.]

I am doing a web based project. I am doing performance testing using JMeter.
 I have created 10 users for sample test of my project & have taken 2 loops . I tested for all pages of my project but error or warning is showing in all results.
I have checked for Facebook & Gmail pages also for getting clarity but for Facebook & Gmail it shows error in results.
What to do?
Why error is showing?
somebody help
Thanks in advance

A: @sonam thats the url exception,check the url path that have you specified correct URL
because it rises the "java.netURI Syntax Exception"

A: You have most probably misconfigured the HTTP Request by putting the URL in "Server Name of IP" field like this:

While you should set it like this:


text:
Q: When checking box how to redirect_to? When checking a box how can the page automatically redirect_to @habit? This behavior would be similar to hitting a submit button.
habits/show
  <% if @habit.current_level_strike %>

 <label id="<%= @habit.id %>" class="habit-id">Strikes:
  <% else %>

 <label id="<%= @habit.id %>" class="habit-id-two">Strikes:
  <% end %>
    <% @habit.levels.each_with_index do |level, index| %>
      <% if @habit.current_level >= (index + 1) %>

          <% if @habit.current_level_strike %>
            <label id="<%= level.id %>" class="level-id">Level <%= index + 1 %>:
          <% else %>
            <label id="<%= level.id %>" class="level-id-two">Level <%= index + 1 %>:
          <% end %>
          <%= check_box_tag nil, true, level.missed_days > 0, {class: "habit-check"} %>
          <%= check_box_tag nil, true, level.missed_days > 1, {class: "habit-check"} %>
          <%= check_box_tag nil, true, level.missed_days > 2, {class: "habit-check"} %>

      <% end %>
    <% end %>

habit.js
$(document).on("page:change", function()
{
  $(".habit-check").change(function()
  {
    habit = $(this).parent().siblings(".habit-id").first().attr("id");
    level = $(this).siblings(".level-id").first().attr("id");
    if($(this).is(":checked"))
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed",
         method: "POST"
       });
    }
    else
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
         method: "DELETE"
       });
    }
  });
});

days_missed_controller
class DaysMissedController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]
  before_action :correct_user, only: [:create, :destroy]

  def create
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days + 1
    @habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days + 1
    if level.missed_days == 3
      level.missed_days = 0
      level.days_lost += habit.calculate_days_lost + 1
    end
    level.save!
    redirect_to @habit, notice: 'Added Strike Against You!' # This message pops up once the user manually goes to a new page, but I'd want the page to automatically redirect_to @habit so that the show page can refresh with the new number of strikes
    head :ok
  end

The larger issue is this, but I think implementing this feature might help me further clarify what the larger problem is.

A: You can just change the location of the page without needing to go to the server.
In JavaScript:
var habitURL = '<%= raw(habit_url(@habit)) %>';

$('input[type=checkbox]').on('change', function() {
  if($(this).prop('checked')) { // Only when it is changed to checked
    window.location = habitURL;
  }
});

A: I guess, you would like to "refresh" the page the user is currently on. You can do something like this in you habit.js (done is executed when any of your AJAX calls is finished):
$(document).on("page:change", function()
{
  $(".habit-check").change(function()
  {
    // ...

    if($(this).is(":checked"))
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed",
         method: "POST"
       })
       .done(function () {
         location.reload();
       });
    }
    else
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
         method: "DELETE"
       })
       .done(function () {
         location.reload();
       });
    }
  });
});

Good luck!


text:
Q: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 14633: invalid continuation byte I am following this code bellow and have this issue, does anybody know what is wrong or how to fix it?
Issue:

utf-8' codec can't decode byte 0xed in position 14633: invalid
  continuation byte

code:
    # Import DataReader
from pandas_datareader.data import DataReader

    # Import date
from datetime import date

    # Set start and end dates
start = date(2016, 1, 1)
end = date(2016, 12, 31)

    # Set the ticker
ticker = 'APPL'

    # Set the data source
data_source = 'google'

    # Import the stock prices
stock_prices = DataReader(ticker, data_source, start, end)

    # Display and inspect the result
print(stock_prices.head())
stock_prices.info()


text:
Q: correct way to use mod_rewrite I have followed lots of stackoverflow questions and Googling But i cant do my url rewrite correctly.
Here is an simple exapmle of my website
root-|
     |__mydomain-|
                 |
                -|
                 |__cat1-|__.htaccess
                 |       |__index.php
                 |       |__single.php
                 |
                 |__.htaccess
                 |__index.php  // home-page

my home page contains A menu link: mysite.com/cat1
->  which is showing "root/cat1/index.php" correctly.
Question1:
For any other links which contains cat1/post-id/title i need to rewrite url to single.php?id=post-id
mysite.com/cat1/123/title
   ->  should show single php with content of post with id:123

What i wrote in root/cat1/.htaccess
Options +FollowSymLinks
RewriteEngine on
<IfModule mod_rewrite.c>

RewriteBase /cat1/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ single.php?id=$1 [L,QSA]

</IfModule>

i get errors like
[Mon Nov 24 13:49:08.549284 2014] [:error] [pid 7144:tid 784] [client 127.0.0.1:21397]
script 'C:/wamp/www/single.php' not found or unable to stat

A: You can change your rule a bit inside /cat1/.htaccess:
Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /cat1/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\d+)/(.+?)/?$ single.php?id=$1&title=$2 [L,QSA]

</IfModule>

Make sure this is in /cat1/.htaccess
PS: I added title parameter so that you can verify title is correct (if needed) inside single.php file.


text:
Q: parse POST request from HTTP Request body What is the best and easiest way to get the HTTP Body from the POST request and parse it with variables? Say I have two attributes called latitude and longitude in the body in which the values I want to extract.
Another thing is how can I test it so I can see these values?

A: In your PHP which handles the POST request you can do something like:
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];

Some browsers have developer tools that allow you to see the POST data that the browser sent.  I use the FireBug plug-in for Firefox.  I think the built-in developer tools in IE 8 and above (F12 I think) can do the same thing.  Not sure about Chrome, but I'm sure there's something around.

A: You're a little unclear in your question, if what you're asking is how to get the values of post variables, then PHP has the $_POST super global that you can reference as $_POST['key'].
If what you're asking is how to get some xml or something from the post body and parse it for values you might try the $HTTP_RAW_POST_DATA super global. It would depend how the data is formatted when it gets there.

A: read to $_POST like this:
echo '<pre>';
  print_r ( $_POST );
echo '</pre>'

and to access: $_POST [variablename] read more at: http://us2.php.net/manual/en/reserved.variables.post.php


text:
Q: Pause Parallel.For Loop I have a nested Parallel.For and Parallel.ForEach loop which will be sending out emails to chunks.  The list could be over 10000 emails long - so I decided to chunk the list into parts and send.  But I would also like to be able to pause after each Parallel.For iteration.  I have looked for a way - but got nowhere.
if (Page.IsValid)
            {
                List<string> emailList;
                List<string> invalidList = new List<string> { };
                string[] attachments = { };
                if (rbListType.Items.FindByValue("CSV").Selected)
                {
                    emailList = tbEmailTo.Text.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    int count = 0;
                    int total = emailList.Count;
                    RadRadialGauge1.Scale.Max = total;
                    RadRadialGauge1.Scale.Min = 0;
                    var errorList = new ConcurrentBag<string>();
    var chunk = emailList
        .Select((value, index) => new { Index = index, Value = value })
        .GroupBy(x => x.Index / 2)
        .Select(g => g.Select(x => x.Value).ToList())
        .ToList();

    Parallel.For(0, chunk.Count, i =>
    {
        Parallel.ForEach(chunk[i], email =>
        {
            try
            {
                MailMessage em = new MailMessage();
                em.From = new MailAddress(tbEmailFrom.Text);
                em.To.Add(email.ToString());

                if (!String.IsNullOrEmpty(tbEmailCC.Text))
                {
                    em.CC.Add(tbEmailCC.Text);
                }

                if (!String.IsNullOrEmpty(tbEmailBC.Text))
                {
                    em.Bcc.Add(tbEmailBC.Text);
                }

                em.ReplyToList.Add(tbReplyTo.Text);
                em.Body = tbEmailBody.Text;
                em.IsBodyHtml = true;
                em.Subject = tbSubject.Text;
                em.Priority = System.Net.Mail.MailPriority.Normal;
                em.BodyEncoding = System.Text.Encoding.UTF8;
                SmtpClient sm = new SmtpClient();

                if (String.IsNullOrEmpty(smtpServer))
                {
                    sm.Host = Host.SMTPServer;
                }
                else
                {
                    sm.UseDefaultCredentials = false;
                    sm.Host = smtpServer;
                    sm.Credentials = new System.Net.NetworkCredential(smtpUsername, smtpPassword);
                }

                sm.Send(em);
                Interlocked.Increment(ref count);
            }
            catch (SmtpException smtp)
            {
                errorList.Add(email.ToString() + "<br />");
            }
        });
     });


text:
Q: DecimalType Issue - scala.MatchError of class java.lang.String I am using Spark 1.6.1 with Scala 2.10.5 built in. I am examining some weather data for which sometimes I have decimal values. Here is the code:
 val sqlContext = new org.apache.spark.sql.SQLContext(sc)
 import sqlContext.implicits._

 import org.apache.spark.sql.Row
 import org.apache.spark.rdd.RDD
 import org.apache.spark.sql._
 import org.apache.spark.sql.types._
 import org.apache.spark.sql.SQLContext

val rawData=sc.textFile("Example_Weather.csv").map(_.split(","))

val header=rawData.first

val rawDataNoHeader=rawData.filter(_(0)!= header(0))

rawDataNoHeader.first

object schema {
val weatherdata= StructType(Seq(
StructField("date", StringType, true),
StructField("Region", StringType, true),
StructField("Temperature", DecimalType(32,16), true),
StructField("Solar", IntegerType, true),
StructField("Rainfall", DecimalType(32,16), true),
StructField("WindSpeed", DecimalType(32,16), true))
)
}

val dataDF=sqlContext.createDataFrame(rawDataNoHeader.map(p=>Row(p(0),p(1),p(2),p(3),p(4),p(5))), schema.weatherdata)

dataDF.registerTempTable("weatherdataSQL")

val datasql = sqlContext.sql("SELECT * FROM weatherdataSQL")

datasql.collect().foreach(println)

When running code, I get what is expected for the schema and sqlContext:
scala> object schema {
 | val weatherdata= StructType(Seq(
 | StructField("date", StringType, true),
 | StructField("Region", StringType, true),
 | StructField("Temperature", DecimalType(32,16), true),
 | StructField("Solar", IntegerType, true),
 | StructField("Rainfall", DecimalType(32,16), true),
 | StructField("WindSpeed", DecimalType(32,16), true))
 | )
 | }
16/09/24 09:40:58 INFO BlockManagerInfo: Removed broadcast_2_piece0 on localhost:56288 in memory (size: 4.6 KB, free: 511.1 MB)
16/09/24 09:40:58 INFO BlockManagerInfo: Removed broadcast_2_piece0 on localhost:39349 in memory (size: 4.6 KB, free: 2.7 GB)
16/09/24 09:40:58 INFO ContextCleaner: Cleaned accumulator 2
16/09/24 09:40:58 INFO BlockManagerInfo: Removed broadcast_1_piece0 on localhost in memory (size: 1964.0 B, free: 511.1 MB)
16/09/24 09:40:58 INFO BlockManagerInfo: Removed broadcast_1_piece0 on localhost:41412 in memory (size: 1964.0 B, free: 2.7 GB)
16/09/24 09:40:58 INFO ContextCleaner: Cleaned accumulator 1
defined module schema

scala> val dataDF=sqlContext.createDataFrame(rawDataNoHeader.map(p=>Row(p(0),p(1),p(2),p(3),p(4),p(5))), schema.weatherdata)
dataDF: org.apache.spark.sql.DataFrame = [date: string, Region: string, Temperature: decimal(32,16), Solar: int, Rainfall: decimal(32,16), WindSpeed: decimal(32,16)]

However, the last line of code gives me the following:
16/09/24 09:41:03 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 2, localhost): scala.MatchError: 20.21666667 (of class java.lang.String)

The number 20.21666667 is indeed the first temperature observed for a specific geographical region. I thought I had successfully specified for Temperature to be a Decimaltype(32,16). Is there a problem with my code or with even the sqlContext I am calling on?
As recommended I changed the dataDF to as follows:
val dataDF= sqlContext.createDataFrame(rawDataNoHeader.map(p=>Row(p(0),p(1),BigDecimal(p(2)),p(3),BigDecimal(p(4)),BigDecimal(p(5)))), schema.weatherdata)

Unfortunately, I now get a casting problem
16/09/24 10:31:35 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 2, localhost): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

A: The code in your first edit was almost correct - p(3) had to be converted toInt
I created a sample csv file without headers:
2016,a,201.222,12,12.1,5.0
2016,b,200.222,13,12.3,6.0
2014,b,200.111,14,12.3,7.0

The results:
val dataDF= sqlContext.createDataFrame(rawData.map(p=>Row(p(0),p(1),BigDecimal(p(2)),p(3).toInt,BigDecimal(p(4)),BigDecimal(p(5)))), schema.weatherdata)

dataDF.show
+----+------+--------------------+-----+-------------------+------------------+
|date|Region|         Temperature|Solar|           Rainfall|         WindSpeed|
+----+------+--------------------+-----+-------------------+------------------+
|2016|     a|201.2220000000000000|   12|12.1000000000000000|5.0000000000000000|
|2016|     b|200.2220000000000000|   13|12.3000000000000000|6.0000000000000000|
|2014|     b|200.1110000000000000|   14|12.3000000000000000|7.0000000000000000|
+----+------+--------------------+-----+-------------------+------------------+

A: It may be because you are reading this data from a .csv file.And by default it takes the data as "Text/String" format.You can solve this problem by 2 ways
1.Change the datatype in .csv file for the attribute temperature.
2.val temperatureInDecimal = BigDecimal("20.21666667")
I would recommened to use 2nd approach if you want to make your application from future perspective where .csv file can change.

A: Since you know expected schema it is better to skip manual parsing and use proper input format. For Spark 1.6 / Scala 2.10 include spark-csv package (--packages com.databricks:spark-csv_2.10:1.4.0) and:
val sqlContext: SQLContext = ???
val path: String = ???

sqlContext.read
  .format("csv")
  .schema(schema.weatherdata).option("header", "true")
  .load(path)

For 2.0+:
val spark: SparkSession = ???
val path: String = ???

spark.read
  .format("csv")
  .schema(schema.weatherdata).option("header", "true")
  .load(path)


text:
Q: Why $\mathbb{D}^2 / \mathbb{S}^1 = \mathbb{S}^2$? Let $\mathbb{D}^2$ be the closed planar unit disk, $\mathbb{D}^2 = \{(x, y) \in \mathbb{R}^2 \mid x^2 + y^2 \leq 1\}$, and let $\mathbb{S}^1$ be the  boundary circle, $\mathbb{S}^1 = \{(x, y) \in \mathbb{R}^2 \mid x^2 +y^2 = 1\}$.
Why $\sim$ such that $\mathbb{D}^2 / \mathbb{S}^1 = \mathbb{S}^2$?
$\mathbb{S}^2$ denotes the sphere in $\mathbb{R}^3$.
My attempt:
Define an equivalence relation $\thicksim$ whose equivalence class of a point $(x, y)$ is $\{(x,y)\}$ when $(x, y) \not\in \mathbb{S}^1$ and $(x,y) \thicksim (1,0)$  whenever $(x,y) \in \mathbb{S}^1$. Is $\mathbb{D}^2/ \sim = \mathbb{S}^2$?
Please help me.


text:
Q: calling a function from a new, child, window in react instead of parent window I am using react-new-window to load a small component in a new window. There it is staged to export as a png using html2canvas. I wish to call the export function from the newly opened window, so that  its element can be exported, not an element from the parent window.
Problem: the export function takeScreenShot() is always called from the parent window and html2canvas cannot find the element in the new child window as it is querying the parent window instead.
/*Export is the parent, functional component, which creates a pop up menu so user can copy item to clipboard, or export to a file as a screenshot*/

const Export = (props) => {
/*redacted*/
const [showWindowPortal, toggleWindowPortal] = useState(false); /*toggles new window with specific item */
const takeScreenShot = () => {
    let id = `#${card.tag}`;
    html2canvas(document.querySelector(id), {}).then((canvas) => {
     /*redacted*/
      });
    });
  };
return(
/*redacted*/
      {showWindowPortal && (
        <NewWindow
          onUnload={() => {
            toggleWindowPortal(false); //turns off toggle on close
          }}

          onOpen={() => console.log('opened')} //this property's function is called in the parent
          features={features}
        >
          <div id={card.tag}>
            <Card/>
          </div>
        </NewWindow>
      )}

I have tried calling takeScreenShot() from:

*

*a button's onClick prop in the child window

*the onOpen prop in <NewWindow/>

*from a [useEffect] hook with NewWindow or showWindowPortal as a parameter (this shouldn't have worked, i know)

and so far nothing has worked and the document.querySelector inside the function always inside of the parent function.
Any thoughts? Thanks!

A: I found a solution. I needed to reference the new child window, and access that reference's document in html2canvas.
I added name="exportPopup" as a prop to <NewWindow/>.
var newWindow = window.open('', 'exportPopup'); //Reference the popup
  const takeScreenShot = () => {
    let id = `#${card.tag}`;
    console.log(id);
    //use the reference for html2canvas
    html2canvas(newWindow.document.querySelector(id), {}).then((canvas) => {
      canvas.toBlob((blob) => {
        var file = new File([blob], 'test.png', {
          type: 'application/octet-stream',
        });
        document.location.href = URL.createObjectURL(file);
      });
    });
  };


text:
Q: UICollectionView cells stay highlighted after reloaddata I have a UICollectionView with labels inside the cells that change automatically periodically. When this update triggers I call reloadData on the UICollectionView and I have set the cells to change the background colour on [UICollectionViewCell setHighlighted:].
The problem is if a user holds down on a cell then the update happens, when the user releases the cell stays highlighted and also cannot be selected anymore.
I have noticed that dequeueReusableCellWithReuseIdentifier:forIndexPath: calls setHighlighted on the cells after reloadData.
I have also tried reloadSections: instead of reloadData, this fixes the problem of the cells getting 'stuck', but causes a fade out and in on the cells when ever its called.
Placing the calls inside performBatchUpdates: doesn't seem to fix the problem either.

A: Inside the cell's class try calling:
- (void)prepareForReuse {
    [super prepareForReuse];
    [self setHighlighted:NO];
    ... Any other custom stuff that should be cleaned up ...
}

The issue is that you are probably doing background coloring differently then the cell would normally do on its self when highlighted. Normally the cell's superclass would undo those changes in prepareForReuse, but it doesn't know about your changes.

A: I used the following as a workaround:
// Both highlightedData and lastHighlightedData are only needed if you want to prevent user from selecting a cell which data changed during the reload. If not needed, a boolean may be used instead
@property (nonatomic) id highlightedData;
@property (nonatomic) id lastHighlightedData;
@property (nonatomic) BOOL pendingCollectionViewReload;

// Wrap the reloadData call. Enqueue it if there's a highlighted cell:
- (void)reloadCollectionView
{
    if (self.highlightedData) {
        self.pendingCollectionViewReload = YES;
        return;
    }

    [self.collectionView reloadData];
    self.pendingCollectionViewReload = NO;
}

// When a cell is highlighted, save its index, or better the related data:
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    // Save data at indexPath to self.highlightedData
}

// Then reload the data when the cell is unhighlighted:
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.lastHighlightedData = self.highlightedData;
    self.highlightedData = nil;

    if (self.pendingCollectionViewReload) {
        [self reloadCollectionView];
    }
}

// The following can be used from shouldPerformSegueWithIdentifier or didSelectItemAtIndexPath to prevent actions if the data associated with the indexPath changed:
- (BOOL)selectedDataEquals:(id)data
{
    // I used lastHighlightedData in addition to highlightedData because this function may be used after the didUnhighlightItemAtIndexPath was called:
    return (self.highlightedData && self.highlightedData == data) || (!self.highlightedData && self.lastHighlightedData == data);
}

A: I encountered the same problem in a collection view that didn't need highlighting and I noticed that the didHighlight/didUnhighlight methods behaved correctly, so I ended up blocking reloads while a touch was in progress, using something like this:
BOOL blockColviewUpdate,colviewUpdateQueued;

and then
-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    blockColviewUpdate=YES;
}

-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    blockColviewUpdate=NO;
    if(colviewUpdateQueued==YES) [self CollectionViewRefresh];
}

while using an own function instead of calling reloadData directly:
-(void)CollectionViewRefresh
{
    if(blockColviewUpdate==YES) colviewUpdateQueued=YES;
    else
    {
        colviewUpdateQueued=NO;
        [self.colview reloadData];
    }
}

It helped in my case and no reloads were lost.

A: I am using collection views in one of my recent projects and the following code works fine for me.
    - (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:    (NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    return YES;
}

In the collectionviewcell subclass
@interface SalesLegendCell : UICollectionViewCell
below is the code
    - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"SalesLegendCell" owner:self options:nil];

        if ([arrayOfViews count] < 1) {
            return nil;
        }

        if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[SalesLegendCell class]]) {
            return nil;
        }

        self = [arrayOfViews objectAtIndex:0];

        UIView* backgroundView = [[UIView alloc] initWithFrame:self.bounds];
        backgroundView.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];

        UIView* selectedBGView = [[UIView alloc] initWithFrame:self.bounds];
        selectedBGView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1];

        self.selectedBackgroundView = backgroundView;
        self.backgroundView = selectedBGView;
    }
    return self;
}

A: Possibly unrelated, but this bit me: UIImage instances rendered on a UIViewCollectionCell in .alwaysTemplate mode get by default highlighted.


text:
Q: Easy way to parse ASCII plist files in PHP I'm trying to deal with data from a legacy system, which seems to be in ASCII plist format. Is there an easy method to parse these or convert them to an easier to deal with format? Ideally, the output should be nested arrays. (These files are also used by GNUstep and for XCode project files)
A library exists, but their sample fails even with Apple's sample of a NSDictionary: (My yacc / lex knowledge is not sufficient to quickly try and fix that...) (It fails for any unquoted values or key names)
Apple's sample file:
{
    AnimalSmells = { pig = piggish; lamb = lambish; worm = wormy; };
    AnimalSounds = { pig = oink; lamb = baa; worm = baa;
                    Lisa = "Why is the worm talking like a lamb?"; };
    AnimalColors = { pig = pink; lamb = black; worm = pink; };
}

The available libraries for plist files seems to only support XML and binary plist files, not ASCII ones.
Implementing a full library for parsing some output from a legacy system in one place seems like overkill...
An ugly approach seen in some other (non-PHP) code that I've seen, is to use regular expressions to modify the data until other methods can parse it.

For the linked library:
In the Lexer, this is likely part of the problem:
stringliteral = /\"(\\.|[^\\\"])*\"/

(Strings are required to be quoted) (The library seems to be written for a specific use case, and my use case seems quite far from that...)
Compiling the lexer with plex also results in different source file, which makes randomly modifying to see what happens tricky...

A: It almost looks like JSON! You could try doing a string replace?
replace = with :
replace ; with ,
replace ; } with } // semicolon space closed_curly
Then you can json_decode($string); it into an array!
If that feels hacky to you, try a library such as https://github.com/rodneyrehm/CFPropertyList
Good luck!


text:
Q: Make jsp fields readonly based on document creation I have a Struts 2 , spring security app. I have a requirement for which I need to make the fields in JSP read only. If the user logged in is not the creator of document then he/she should not be able to edit the document just view the information. Is there any way I can achieve this using struts and JSP ? Or I need to have a different form for read and edit?

A: This is assuming that you're saving some kind of an identification for the current user on your session.
On your form, use a ternary operator to know if it should be readonly or not.
Something like this:
<input type="text" ... ${sessionScope.userId.equals(userIdOfTheCreator)?"":"readonly"}>

If the current user is the same as the one who created the document, then don't add readonly attribute, else do otherwise.

A: There are really several ways to do this.
Assuming a List<Document> documents;, and the Document object having fields like documentId, ownerId, description, and a User object stored somewhere, and accessible through getCurrentUser() (eg. from a BaseAction extended by the other ones), you can check it inline with
<s:iterator value="allDocuments" var="currentDocument" status="stat">
    <s:hidden name="allDocuments[%{#stat.index}"].documentId />

    <s:if test="%{currentUser.id.equals(#currentDocument.ownerId)}">
        <s:textfield name="allDocuments[%{#stat.index}"].description" />
    </s:if>
    <s:else>
        <s:textfield name="allDocuments[%{#stat.index}"].description"
                 readonly="true" />
    </s:else>

</s:iterator>

In case you have to perform more complicated checks, you can call an Action function while iterating the documents:
<s:iterator value="allDocuments" var="currentDocument" status="stat">
    <s:hidden name="allDocuments[%{#stat.index}"].documentId />

    <s:if test="%{amIOwnerOfThisDocument(#currentDocument.ownerId)}">
        <s:textfield name="allDocuments[%{#stat.index}"].description" />
    </s:if>
    <s:else>
        <s:textfield name="allDocuments[%{#stat.index}"].description"
                 readonly="true" />
    </s:else>

</s:iterator>

and in the Action:
public boolean amIOwnerOfThisDocument(String ownerId){
    return getService().checkSomethingComplex(getCurrentUser().getId(),ownerId);
}

And so on.
Important : don't forget to replicate this kind of control server side while accepting the data received from the JSP... it's easy for a malicious user to forge a request with data that should not be modifiable by him, eg. with Firebug / Firefox console, simply removing the readonly attribute.


text:
Q: How to resolve TableView with css in Titanium Android Emulator xsml file as below its display good in web browser but not showing in Android Emulator.
 <Alloy >

        <Window id="readWin" class="bg">
            <TableView id="tableView">

            <TableViewRow class="titlebar"></TableViewRow>

            <TableViewRow></TableViewRow>

            <TableViewRow>

                <TextField class="serachbar"></TextField>

            </TableViewRow>

            <TableViewRow></TableViewRow>

            <TableViewRow center="center" width="190" height="63">

                <Button class="sbtn" id="subbtn"></Button>

            </TableViewRow>

            </TableView>
        </Window>

</Alloy>

my index.tss code is like
'#tableView':{
separatorColor:'none'
 }

"View":{
layout:'vertical',
},

".bg":{
    backgroundImage:'images/bg.png',

},

".titlebar":{
    backgroundImage:'images/logo.png',
    width:'339dp',
    height:'71dp',
    top:'140dp'

},

'.serachbar':{
backgroundImage:'images/searchbar.png',
    width:'400dp',
    height:'50dp',
    borderStyle:'none',

},
'.sbtn':{
backgroundImage:'images/btn.png',
    width:'187dp',
    height:'60dp',
    borderStyle:'none',

}

my index.js file code is
$.readWin.open();

bg css is applying at window successfully but tableview data is not showing in Andriod Emulator event its good display in Web Browser. what can be the problem please help

A: Kind of an old post, but I thought I'd add my 2 cents. First, there's no way we can test this code because we don't have the referenced images. Second, remove all the dp references in your code by adding this line to your tiapp.xml <property name="ti.ui.defaultunit" type="string">dp</property>. Finally, explain what you've tried, and what you're trying to accomplish. Your post lacks a great deal of information that would allow others to help you.


text:
Q: Gwt Controller With Annotation Approach I already integrated GWT with Spring MVC by implementing the Controller which is called
by DispatcherServlet using SimpleUrlHandlerMapping.

public class GwtRpcController extends RemoteServiceServlet implements Controller,
        ServletContextAware {
        @Override
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        super.doPost(request, response);
        return null;
    }
}

I want to use the new approach with the annotation @Controller, like below:

@Controller
public class GwtRpcController extends RemoteServiceServlet implements
        ServletContextAware {

}

In this case there will be no handleRequest method, where should I do super.doPost(request, response); ?

A: See annotated web mvc controllers in spring 2.5
You should not to do doPost/doGet manually, just define controller method with corresponding parameters, return value and annonations for url mapping.


text:
Q: Same config for node.js and for browser javascript Is it possible to have the same config file for server node.js and client js code?
Now I use .json config for node.js, but can convert it to any format

A: Without more information, all I can offer is a simple suggestion: Require.js. You can reference a config module in the Node.js code and reference it in the client script. Just make sure that the config file can be served to the client.
// Example reference
var config = require('./data/config.js');


text:
Q: Wordpress Costum Post Type and pagination would not cooperate I have made my own costum post type in wordpress. I have already use WordPress's post type on my website. So i actually have two post type who running  the loop on my website.  But now i have kinda trouble with the pagination. It won't paginate from my own post type. Its like my post type and pagination wont work together. Because the pagination display that there are 2 pages, but when i click on page 2 it only display the same posts as on page 1.
<?php
$holdene = get_field('kampreferaterne');
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

$the_query = query_posts(array(
    'post_type'=>'kampreferater',
    'paged'=>$paged
));

$kampf_args = array(
    'post_type' => 'kampreferater',
    'tax_query' => array( array(
            'taxonomy' => 'hold_kategori',
            'terms' => $holdene
    ))
);

$kampf = new WP_Query($kampf_args);
?>

<?php if ( $kampf->have_posts() ) : while ( $kampf->have_posts() ) : $kampf->the_post(); ?>

some content..

<?php wp_reset_postdata(); ?>

<?php endwhile; else: ?>

Sorry, no posts matched your criteria.

<?php endif; ?>

<?php wp_pagenavi(); ?>

A: $holdene = get_field('kampreferaterne');
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

$kampf_args = array(
        'post_type' => 'kampreferater',
        'paged' => $paged,
        'tax_query' => array( array(
        'taxonomy' => 'hold_kategori',
        'terms' => $holdene
     ))
 );

$kampf  = new WP_Query($kampf_args);

Instead of wp_pagenavi(), use wp_pagenavi('query'=>$kampf);
Hope this helps.


text:
Q: d3.js foreignObject text transition I am using d3.js to build a little project that involves data, shapes and text. According to the data, the text appears inside of a shape. If you mouse-over the shape, the shape should become larger and show more text.
The text is added in the following manner and it works fine:
Shapes
.append("foreignObject")
[...]
.append("xhtml:body")
.style("font", "14px 'Helvetica Neue'")
.html(function(d) {return d.text;   });

I use foreignObject rather than text because I need the text to line-wrap and this is the only way that I've so far been able to achieve this effect.
What's giving me grief is the mouse-over. I can re-size the shape just fine but I am having trouble calling a transition on the text. In fact, I don't really know how to access it successfully.
Here is some of the code from the mouse-over event:
d3.select(this)
.transition()
.duration(250)
.attr("height", function(d,i) {
    d.showAll()
    //d.textObject.width = 4;
    return d.height;
} );

d3.select(this).select("foreignObject").transition()
.duration(250)
.select("xhtml:body")
.html(function(d) {return d.text;   });

The idea is that the showAll() function has already changed the text to a new value, however the code does not get that far. The message that Chrome gives me is "Uncaught TypeError: Object [object Array] has no method 'html' ".
So, how do I access the text and update it so that my transition will lead to the new text being visible and the old text disappearing?
I've been banging my head against this for a while so any help is deeply appreciated.

A: Replace d3.select(this).select("foreignObject") with d3.selectAll(this.getElementsByTagName("foreignObject"))
I just solved this myself and thought I would help.


text:
Q: Templates doesnot name a type error in c++ for function templates I want to sort array of any data type for that I use sort function inside  swap() function is used. I've tested this with integer array and
I'm getting a error like  : 'T' does not name a type
 T sort(T t[],int n)
  and some other errors(Check the image) . I'm a beginner in c++ so explain me what's wrong with this code and how to resolve it.
#include <iostream>
using namespace std;
template <class T>
void swap(T,T);
T sort(T t[],int n)
{
for(int i=0;i<n;i++)
    for(int j=i+1;i<n;i++)
        if(t[i]>t[j])
          swap(t[i],t[j]);

    return t;
}
void swap(T &x ,T &y)
{
     T temp;
     temp=*x;
     *x=*y;
     *y=temp;
 }
int main() {
int n;
cout<<"enter n value";
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int result[n];
result=sort(arr,n);
for(int i=0;i<n;i++)
 cout<<result[i];
return 0;
}

A: After the some edits now its working.Thank you guys.
#include <iostream>
using namespace std;
template <class TT> void swape(TT &x ,TT &y)
{
    x=x+y;
    y=x-y;
    x=x-y;
}

template <class TT> void  sort(TT t[],int n)
{
    for(int i=0;i<n;i++)
       for(int j=i+1;j<n;j++)
           if(t[i]>t[j])
               swape(t[i],t[j]);

 }
  int main() {
      int n;
       cout<<"enter n value";
      cin>>n;
      int arr[n];
      for(int i=0;i<n;i++)
      cin>>arr[i];
      sort(arr,n);
      for(int i=0;i<n;i++)
      cout<<arr[i];
      return 0;
    }


text:
Q: Termux says "'Bad Interpreter: No such file or directory" I have a problem and hope someone can help me. I am currently trying to write a script for Termux or Termux:Task. My script currently looks like this:
#!/data/data/com.termux/files/usr/bin/bash
cd /./sdcard/www/public/
wp post list sleep 5

Every time I load the script I get the following error message:
/data/data/com.termux/files/usr/bin/wp: /usr/bin/env: bad interpreter: No such file or directory.
I've been looking for a solution to my problem for hours, unfortunately without success.
I am using an extension for Termux called "WordPress CLI". When I start termux and enter the commands individually, everything works. But as soon as I write the commands into a sh script and start it doesn't work anymore. :(
Can anyone help me?
Thanks a lot

A: This is simple error you can fix it by replacing !/data/data/com.termux/files/usr/bin/bash. With #!/data/data/com.termux/files/usr/bin/bash
Please tell if you get error again

A: Try with #!/usr/bin/env bash in the shebang line.

Termux-exec allows you to execute scripts with shebangs for traditional Unix file structures. So shebangs like #!/bin/sh and #!/usr/bin/env python should be able to run without termux-fix-shebang.

From https://wiki.termux.com/wiki/Termux-exec

A: According to doc:

Why do I keep getting a '/bin/sh bad interpreter' error?
This error is thrown due to access script interpreter at nonexistent
location.
Termux does not have common directories like /bin, /sbin, /usr/bin at
their standard place. There is an exception for certain devices where
/bin is a symbolic link to /system/bin, but that does not make a
difference.
Interpreters should be accessed at this directory only:
/data/data/com.termux/files/usr/bin
There are three ways to fix this:

*

*Install termux-exec by using pkg install termux-exec. It won't affect the current session, but after a restart should work without
any setup. Not needed if your Termux is up to date. If still not
working, try the next workaround.

*Use command termux-fix-shebang to fix the shebang line of specified file.

*Use termux-chroot from package proot to setup a chroot environment mimicking a normal Linux file system in Termux.

termux-fix-shebang my_script.py of second method work for me, which it modify the shebang(first line of my_script.py) from #!/usr/bin/env python to #!/data/data/com.termux/files/usr/bin/env python. Since /usr/bin/ is not exist in Android, that's why it throws the error /usr/bin/env: bad interpreter: No such file or directory. The other solution is run with python my_script.py, neither of my_script.py nor ./my_script.py.
In my test, termux-exec of the first method only work if I added correct shebang in main script(child OR child of child script no need) and ran command export LD_PRELOAD=/data/data/com.termux/files/usr/lib/libtermux-exec.so.
And for the issue of this question, error shows /usr/bin/env in the middle with /data/data/com.termux/files/usr/bin/wp even though the shebang of script #!/data/data/com.termux/files/usr/bin/bash looks ok, it means that wp command (located at /data/data/com.termux/files/usr/bin/wp) used inside the script contains shebang #!/usr/bin/env wp and should modify it to #!/data/data/com.termux/files/usr/bin/env wp too. termux-exec of first method should fix this specific case too(already has correct shebang in main script).


text:
Q: How to compare two columns with a twist We have two reports, which we want to compare by ID (fields: Reference & Transaction ID):

Column A to F are out freighting company's invoice starting how much they have charged out company
Column H-I are pulled from Google Analytics stating the amount we have charged to our clients .
Column D and H carry the same records ( just unsorted ) .
What I want to find out is for each record ( order H/D) the amount we have paid and the amount we were charged to work out profitability
Column D paired with column F is to be compared with column I , I hope I am making sense here .
The result should look like below
Reference   Transaction ID  Total Amount    Shipping
16672062468 16672062468      86.9            105

A: *

*Try using vlookup function in J2:
=vlookup(H2, D:E, 3, 0)

*To convert values in column "Shipping" into numbers, try regexextract formula in K2:
=REGEXEXTRACT(I2,"\d+\.?\d+")*1
These formulas are to be copied down.


text:
Q: Sqlalchey query date filter with string format I have sqldb where date is encoded as string.
By using of sqlalchemy I need to implement query, where date is used as a filter (date within specific range).
I tried to define hybrid method, but it seems, that datetime.strptime cannot be used here ("TypeError: strptime() argument 1 must be str, not InstrumentedAttribute")
Do you have any idea (maybe different approach than hybrid method), how to make it working?
Sample code:
class Sample(db.Model):
__tablename__ = "sample"

id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(32))

@hybrid_property
def date2(self):
    return datetime.datetime.strptime(self.date, "%Y-%m-%d")

@date2.expression
def date2(cls):
    return datetime.datetime.strptime(cls.date, "%Y-%m-%d")

...

date_min = datetime.datetime(2020, 1, 1)
date_max = datetime.datetime(2020, 3, 31)
out = Sample.query.filter_by(date2 > date_min, date2 < date_max).all()

A: You can use STR_TO_DATE function in MySQL:
from sqlalchemy import func

@date2.expression
def date2(cls):
    return func.str_to_date(cls.date, "%Y-%m-%d")


text:
Q: Completely removing old Nvidia drivers I recently installed a fresh installation of Ubuntu, and downloaded some Nvidia drivers via nvidia-driver-390. I noticed that nvidia-340 was also installed (as a "binary driver" instead of a "driver metapackage"). Interesting. Later, I installed nvidia-driver-396. I'd like to remove versions 340 and 390, so I can only use 396. I have used sudo apt remove --purge nvidia-340 nvidia-390 and also uninstalled some of the related packages (nvidia-common, nvidia-current, nvidia-settings, nvidia-prime, nvidia-kernel-common*, etc.) At this point, I'm just trying to remove every trace of Nvidia drivers from my system and start fresh. Unfortunately, in the included "Software and Updates", drivers 340, 390, and 396 are still listed. A screenshot is attached. Thanks for your help.
ls -la /etc/apt/sources.list.d:
total 44
drwxr-xr-x 2 root root 4096 Jul 10 08:43 .
drwxr-xr-x 6 root root 4096 May 20 12:58 ..
-rw-r--r-- 1 root root  142 Jul 10 08:43 alexlarsson-ubuntu-flatpak-bionic.list
-rw-r--r-- 1 root root  142 Jul 10 08:43 alexlarsson-ubuntu-flatpak-bionic.list.save
-rw-r--r-- 1 root root   57 Jul 10 08:43 etcher.list
-rw-r--r-- 1 root root   57 Jul 10 08:43 etcher.list.save
-rw-r--r-- 1 root root  132 Jul 10 08:43 gezakovacs-ubuntu-ppa-bionic.list
-rw-r--r-- 1 root root  132 Jul 10 08:43 gezakovacs-ubuntu-ppa-bionic.list.save
-rw-r--r-- 1 root root  189 Jul 10 08:43 google-chrome-beta.list
-rw-r--r-- 1 root root  189 Jul 10 08:43 google-chrome-beta.list.save
-rw-r--r-- 1 root root  144 Jul 10 08:43 graphics-drivers-ubuntu-ppa-bionic.list

Notes: So you have to remove the ppa to completely remove it?
cat /etc/apt/sources.list:
# deb cdrom:[Ubuntu 18.04 LTS _Bionic Beaver_ - Release amd64 (20180426)]/ bionic main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://us.archive.ubuntu.com/ubuntu/ bionic main restricted
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates main restricted
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ bionic universe
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic universe
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates universe
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://us.archive.ubuntu.com/ubuntu/ bionic multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic multiverse
deb http://us.archive.ubuntu.com/ubuntu/ bionic-updates multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu bionic partner
# deb-src http://archive.canonical.com/ubuntu bionic partner

deb http://security.ubuntu.com/ubuntu bionic-security main restricted
# deb-src http://security.ubuntu.com/ubuntu bionic-security main restricted
deb http://security.ubuntu.com/ubuntu bionic-security universe
# deb-src http://security.ubuntu.com/ubuntu bionic-security universe
deb http://security.ubuntu.com/ubuntu bionic-security multiverse
# deb-src http://security.ubuntu.com/ubuntu bionic-security multiverse
deb http://us.archive.ubuntu.com/ubuntu/ bionic-proposed main universe restricted multiverse

ubuntu-drivers devices:
== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
modalias : pci:v000010DEd00001382sv000010DEsd00001065bc03sc00i00
vendor   : NVIDIA Corporation
model    : GM107 [GeForce GTX 745]
driver   : nvidia-340 - third-party free
driver   : nvidia-driver-390 - third-party free
driver   : nvidia-driver-396 - third-party free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

== /sys/devices/pci0000:00/0000:00:1c.7/0000:04:00.0 ==
modalias : pci:v000014E4d00004365sv00001028sd00000016bc02sc80i00
vendor   : Broadcom Limited
model    : BCM43142 802.11b/g/n (Wireless 1704 802.11n + BT 4.0)
driver   : bcmwl-kernel-source - distro non-free

Note: The second one is my wireless card, the first one is my graphics card that this is about.
ubuntu-drivers list:
nvidia-driver-390
nvidia-340
nvidia-driver-396
bcmwl-kernel-source

Note: Again, the first three are the ones I want to remove, and the last is for my wireless card.

A: Pay your attention to ubuntu-drivers devices command output - there are following lines:
driver   : nvidia-340 - third-party free
driver   : nvidia-driver-390 - third-party free
driver   : nvidia-driver-396 - third-party free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

The lines mean you can use nvidia 340, 390, 396 drivers from third-party repository and open-source nouveau driver from distro repository. Only one driver is recommended to you. The list doesn't mean all of the mentioned drivers has been installed in your system. It indicates only potential possibility to install the drivers. The list can't be changed manually as being formed with ubuntu-drivers utility designed to automate proprietary drivers detecting, inspecting and installing from available to Ubuntu repositories.
Thus, to change the list it's necessary to remove third-party repository, which is proprietary GPU drivers repo in the particular case. But it's highly unrecommended to do, since your goal is to keep nvidia 396 driver anyway and remove from automatically created list nvidia 340 and 390 drivers. If you remove the third-party repository, only distro drivers will be detected as available, which will be in the particular case only 340 and 390 - thus, you'll obtain most undesired for you situation.
My suggestion for you is to do nothing. Your system looks healthy, everything works well.
If you like experiments, follow guide below.
The described below is for experimental purposes only - if you're not sure don't do it!
Press Ctrl+Alt+F4, log in and remove all of the nvidia staff:
sudo apt remove nvidia-*

Next remove proprietary PPA GPU drivers repository. Run in terminal:
sudo add-apt-repository --remove ppa:graphics-drivers/ppa
sudo apt update

Afterwards check available drivers in terminal:
ubuntu-drivers devices

You'll see the third-party nvidia drivers have dissapeared and only distro nvidia drivers are available. Among the drivers nvidia 396 will be absent since the driver isn't a part of Ubuntu distro repository.
Add your PPA proprietary GPU drivers repository back:
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt update

Install your desired nvidia 396 again:
sudo ubuntu-drivers autoinstall

Reboot:
sudo reboot

After reboot, type nvidia-smi which will show different information about your graphic card like below:
xyz@xyz-workstation:~$ nvidia-smi
Mon Apr 27 12:41:50 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 166...  On   | 00000000:01:00.0 Off |                  N/A |
| N/A   45C    P8     1W /  N/A |    470MiB /  5944MiB |      5%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1905      G   /usr/lib/xorg/Xorg                            28MiB |
|    0      2058      G   /usr/bin/gnome-shell                          47MiB |
|    0      2956      G   /usr/lib/xorg/Xorg                           145MiB |
|    0      3133      G   /usr/bin/gnome-shell                         120MiB |
|    0      3587      G   ...AAAAAAAAAAAACAAAAAAAAAA= --shared-files   122MiB |
+-----------------------------------------------------------------------------+

For systems having nvidia-prime, if it returns an error then type sudo prime-select intel and then reboot and then type sudo prime-select nvidia and then reboot again. Now type nvidia-smi and it should work. This method works on most of the system with kernel till 5.4
Additionally see this my post.

A: *

*nvidia-installer --uninstall

*sudo apt remove nvidia-*

A: I faced the below error nvidia-driver connectivity issue on AWS VM after a reboot.
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.

*

*Uninstall Nvidia Driver
sudo apt remove nvidia-*

*Add Nvidia drivers PPA
    sudo add-apt-repository --remove ppa:graphics-drivers/ppa

    sudo apt update

*Install the nviida-drivers (change 430 to your requirement)
 sudo apt-get install nvidia-driver-430

*(optional) Install Nvidia-drivers
  distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
  curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
  curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list

  sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit
  sudo systemctl restart docker

*(optional) Install Nvidia Container Run time

sudo apt-get install nvidia-container-runtime

A: Make sure that nvidia is completely removed before new install or update.
sudo apt-get remove --purge '^nvidia-.*'


text:
Q: Possible that new messages pop-up out of the app? There is an app that displays news from the RSS feed. What should I implement to have new news popup when the application is not active? Popup directly on the screen no matter which app is running.
I would not like Toast-like message, but rather a real popup with images and text. Is this possible?
Is AlarmManager used for this or something else?

A: Dialogs are only possible when your application context is active. So it would not help. Toast could be quite boring for users. Wouldn't you prefer to use notification just to notify new news items are available.
If you really them to be displayed when your app is "not running". I would recommend to provide a desktop widget to your users.
Regards,
 Stéphane