text:
Q: How to determine "Checked" value for Checkboxes (from GetAppearanceStates) I have a question about checkbox fields, and consistently figuring out which value to use for a checked state.
I have been searching, and shelled out $50 for the iText in Action book and scoured it as well.  The book is great, but it didn't answer this particular question.
I know to call GetAppearanceStates(fieldName) to get the domain of possible values for a particular field, and know to call SetField(fieldName, value) to check the box.
My question is: how do I definitively know WHICH of the values returned by GetAppearanceStates is the "Check" value, or the value I need to use to check the field?
To be fair, most forms I've seen use values like: True,False,On,Off,Yes,No... but if I understand things correctly, the creator of the PDF can specify any arbitrary value.
Is there a way to find out, for sure, WHICH of the values returned by GetAppearanceStates is the "check" value?
The examples I saw seemed to indicate the first element in the array would be the one to check it, but apparently that was just me reading too much into the example, because I've run into a document where the first element is "Off" (and the second is "Yes").  Before I dive in and write code that explicitly looks for string values like True,Yes,On,Oui,Yuppers,Check… or whatever, I thought I'd see if there is a better way!  I really hope I'm missing something.
Again, I'm working only with checkbox fields here.
Thanks for any help at all!

A: ISO 32000-1:2008 ("PDF 1.7 spec") says in 12.7.4.2.3 ("Check Boxes"):

The appearance for the off state is optional but, if present, shall be
  stored in the appearance dictionary under the name Off. Yes
  should be used as the name for the on state.

So if there's an appearance for the unchecked state, it has to be Off.  The Yes for the checked state is a recommendation; it can be named differently.
If 2 arbitrary names are used for checked and unchecked, you can't reliably determine which should be used for checked and which for unchecked.


text:
Q: How can I use the amount variable outside this function please can any one help me Please can anyone tell me how can I get the amount variable or its data which I am fetching from req.body outside of the this function?
app.post("/pay", (req, res) => {
  console.log(req.body);
  const { amount , description , name } = req.body;    //this is that amount variable
  const create_payment_json = {
    intent: "sale",
    payer: {
      payment_method: "paypal",
    },
    redirect_urls: {
      return_url: "http://localhost:3000/success",
      cancel_url: "http://localhost:3000/cancel",
    },
    transactions: [
      {
        item_list: {
          items: [
            {
              name: name,
              sku: "001",
              price: amount,
              currency: "USD",
              quantity: 1,
            },
          ],
        },
        amount: {
          currency: "USD",
          total: amount,
        },
        description: description,
      },
    ],
  };

  paypal.payment.create(create_payment_json, function (error, payment) {
    if (error) {
      throw error;
    } else {
      for (let i = 0; i < payment.links.length; i++) {
        if (payment.links[i].rel === "approval_url") {
          res.redirect(payment.links[i].href);
        }
      }
    }
  });
});

app.get("/success", (req, res) => {
  const payerId = req.query.PayerID;
  const paymentId = req.query.paymentId;

  const execute_payment_json = {
    payer_id: payerId,
    transactions: [
      {
        amount: {
          currency: "USD",
          total: amount,    // I want it here also
        },
      },
    ],
  };

  paypal.payment.execute(
    paymentId,
    execute_payment_json,
    function (error, payment) {
      if (error) {
        console.log(error.response);
        ;
      } else {
        console.log(JSON.stringify(payment));
        res.send("Success");
      }
    }
  );
});

A: It's very unclear from your question, but it seems like you just want to have access to amount from outside the response callback.  If it is as plain as that, you just need to have a place for it in a higher scope.  For example, I'm going to store all the payments in a payments array.  I'm also renaming "ammount" to "amount" (it's misspelled).
Whenever a POST is made to app.post("/pay"), we push a payment.  payments is available to app.get("/success") because it is in a higher scope.
If this isn't what you are trying to do, you need to add more details to your question and explain exactly what isn't working.
index.js
import express from "express";

const app = express();

const payments = [];

app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello world");
});

app.get("/success", (req, res) => {
  console.log(`There have been ${payments.length} payments`);
  if (payments.length) {
    const {person, amount, time} = payments[payments.length - 1];
    console.log(`Last payment was ${amount} by ${person} @ ${time}`);
  }
  res.sendStatus(200);
});

app.post("/pay", (req, res) => {
  const {person, amount} = req.body;
  const time = Date.now();

  payments.push({person, amount, time});
  console.log(`${person} paid ${amount} @ ${time}`);

  res.sendStatus(200);
});

app.listen(3002, () => {
  console.log("Listening");
});

This is the file that I used to test with.  It uses node-fetch as a fetch polyfill.
test.js
import fetch from "node-fetch";

const sleep = (t=1000) => new Promise(r => setTimeout(r, t));

const main = async () => {
  const payResponse = await fetch("http://localhost:3002/pay", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      person: "Bob Barker",
      amount: 500
    })
  });

  await sleep();

  const checkResponse = await fetch("http://localhost:3002/success");
};

main()
  .then(() => console.log("Done"))
  .catch(err => console.error(err));

Running it produces this:
Listening
Bob Barker paid 500 @ 1631202912836
There have been 1 payments
Last payment was 500 by Bob Barker @ 1631202912836

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conservation of Energy
Hello, I am trying to solve the following question using conservation of energy. Part (a) is fine, I have compared it with suvat questions and I have got:
$z_{max} = v_0^2sin^2a/2g$
I am struggling with (b).
I have set
$1/2mv_0^2(cos^2a(j)+sin^2a(k)=1/2mv^2+mgz(k)$ by conservation of energy.
Rearranging and integrating I got
$s = (v_0cosa)t(j)+(v_0sina-\sqrt(2gz))t(k)$
Can anyone point me in the right direction?
Thank you.

A: For the second equation, from conservation you can write $\frac 12 v_0^2=\frac 12 v(t)^2+gz$-you shouldn't have the angles on the left of the second equation.  Now use the fact that $v_y$ is constant to get $v_z(t)$ and integrate.


text:
Q: IndexError: string index out of range - finding out if a letter is in a string I am trying to code a piece such as the game mastermind, and I am having the IndexError telling me that my string index is out of range. Please ignore the notes in the hashtags - they're for me knowing what part of the assignment that I have completed. [further notes below :D]
    #makes a random thingie
import random

l = 0
k = 0
m = 0
r = 0

x = "kkkk"
available_colours = ['G','Y','B','R']

x = list(x)

while l != 4:
 random_colour = random.choice(available_colours)

 x[l] = random_colour

 l = l + 1

x = "".join(x)

#user inputs guesses
print(x)
print('there is a choice from these colours [G,Y,B,R]')
print('guess a pattern [xxxx]')
y = str(input())

while r != 5:
 while m != 4:
   for i in range (0,3):
     if x[k] == y[k]:
       m = m + 1
       k = k + 1
     else:
       k = k + 1
   #informs the user how many pins they have got correct
   if m > 0:
     print('You found', m, 'in the correct position')
   else:
     print('You have found none in the correct position.')
   n = 0
   o = 0
   if m != 4:
     if y[0] == x[1] or y[0] == x[2] or y[0] == x[3]:
       o = o + 1
     elif y[1] == x[0] or y[1] == x[2] or y[1] == x[3]:
       o = o + 1
     elif y[2] == x[0] or y[2] == x[1] or y[2] == x[3]:
       o = o + 1
     elif y[3] == x[0] or y[3] == x[1] or y[3] == x[2]:
       o = o + 1

     #informs the user how many pins they have got correct
     if o > 0:
       print('You found', o, 'correct letters, but not in the right place')
     else:
       print('You have found no correct letters in the wrong place')
   #user knows they won
   if k == 4:
     print('You have won!')
   else:
     r = r + 1
     if r == 5:
       print('You have used all of your goes.')
     else:
       q = 5 - r
       print('You have' , q ,' rounds left.')

The following error message is displayed:
Traceback (most recent call last):
File "main.py", line 32, in
if x[k] == y[k]:
IndexError: string index out of range
There is also another issue with the code where it will tell me there are 2 letters correct, but in the wrong place if i put that letter once in the pattern_guessed, and it is more than once in the pattern_random. Example:
pattern_random = GGYB
pattern_guessed = GYYB
The computer will tell me that there are 2 colours correctly guessed but not in the right space. However the main problem right now is trying to get the code to work.
Thank you for reading c:


text:
Q: How do I get my building back? I built a costume shop in Minecraft, but when I look at it next, it's disappeared!
I built it a couple of weeks ago and have had no trouble with it loading, then this morning it was no longer there. I put a lot of time into that building, and I have restarted Minecraft, but don't know what else to try. Also, in my library, the librarian I had encased in fences escaped.
I used Glowstone For The building, I used Cobble Stairs For The Register, And I used Armour Stands For About, Everything else. (except the costumes) kinda like SethBling, puts armour stands in EVERYTHING.
I really don't want to lose my costume shop. Does anyone know how to fix this?

A: 1.9 has a serious infestation of bugs. On several occasions I have seen chunks either reset to their generated state or have a completely new layout. I tried quitting and loading the world and or game a couple of times and sometimes my buildings and such would return.
I recommend copying your save file to back it up.

A: If you upgraded to version 1.9, it may have been deleted as a bug from the snapshots.  Otherwise if you made a previous save you can reload from the save. If this is a big problem and none of the above work. If you reload your game to a working version that you built it in try like 1.8.8. You could do a google search on this problem and most likely it is just a chunk glitch.
Next time, when you build something big and that you spent a lot of time in. Take the time to copy the world save.
Windows

*

*Open start

*Type run

*Press enter

*In the field type '%appdata%'

*Open folder '.minecraft'

*Open folder 'saves'

*Find the folder that says your world name

*Copy the folder to your desired location(that is your safe copy)

Mac or Linux
http://www.howtogeek.com/207484/how-to-find-your-minecraft-saved-games-folder/
I hope this will help you


text:
Q: API - use GET to add, edit, and delete? I'm building an API and want Ajax to be able to interact with it. The API needs to allow inserting, updating, and deletion of data. Is it a good idea to allow any of these operations via GET?
For example: http://api.domain.com/insert_person/?name=joe
My original plan way to use GET for my "getting" methods (basically, just a simple DB query) and POST for add, edit, and delete. Problem is JS same-origin policy which would make it hard for Ajax to interact with my API. There is a jQuery workaround for GET (via JSONP).
Suggestions?

A: In a word: NO
GET should always be used only for retrieving information and should never have side effects, ever.
This is a best practice across just about every web api out there and has to do with both  the intent of the verb as well as how existing software expects things to behave.

A: If you're trying to get around the same origin policy, GET via JSONP is the only possible front-end solution. If you've got control of the back end you can setup a proxy service that is on the same domain as the page, but relays to and from the API service.
If you're going to go down the JSONP GET path, make sure you read up on XSS and CSRF.

A: Add another layer of to handle your code and interact with your database (different domain).
You would still use POST and you can make a request to your db in the server side, using what ever language your are working with, example php will use curl.(to make request to a different domain)
If you allow to interact with your db using get, then anyone can simply type the url with the commands they want, so yes avoid it .

A: As others have pointed out, GET should not be used for actions with side effects like inserting, updating and deleting.
To allow cross-origin use of your API, look into Cross-Origin Resource Sharing, although it's currently only partially supported by browsers.


text:
Q: SqliteConstraintException Android I have a proble with a SqliteConstraintException.
My db is like that
private static final String CREATE_TABLE_1 =
   "create table table_1 (uid integer primary key autoincrement, "
+ table_1.c1 + " TEXT,"
+ table_1.c2 + " integer,"
+ table_1.c3 + " TEXT,"
+ table_1.c4 + " TEXT,"
+ table_1.c5 + " integer);";

private static final String CREATE_TABLE_2 =
        "create table table_2 (uid integer primary key autoincrement, "
+ table_2.c1 + " TEXT,"
+ table_2.c2 + " integer,"
+ table_2.c3 + " TEXT);";

private static final String CREATE_TABLE_3 =
        "create table table_3 (uid integer primary key autoincrement, "
        + "uid_table_1 integer, "
        + "uid_table_2 integer, "

+ "FOREIGN KEY(uid_table_1) REFERENCES table_1(uid) ON DELETE CASCADE, "
+ "FOREIGN KEY(uid_table_2) REFERENCES table_2(uid) ON DELETE CASCADE);";

private static final String CREATE_TABLE_4 =
        "create table table_4 (uid integer primary key autoincrement, "
+ "uid_table_2 integer,"
+ "FOREIGN KEY(uid_table_2) REFERENCES table_2(uid) ON DELETE CASCADE);";

And i use in my SQLiteOpenHelper to enable foreign key constraints
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}

But when i want to delete on row of the table_2, i get SqliteConstraintException.
Can you help me please ?
Thank you

A: I looks like most of your tables reference each other. if you want to delete a row in Table 2 that is used as the foreign key in a different table, you need to delete the records that reference it. so delete records from tables 3 and 4 that have a foreign key reference to the row you are trying to delete in 2 and THEN call delete for that row.


text:
Q: How to change text color in spinner without using textview I want to change text color for spinner without using textView, I have already searched and found some tutorials Android: Where is the Spinner widget's text color attribute hiding?
but the main thing is they have used textView.
<Spinner
     android:layout_height="wrap_content"
     android:layout_width="0dp"
     android:layout_weight="1"
     android:entries="@array/Gender_Selection_arrays"
     android:prompt="@string/Gender_Selection"
     android:id="@+id/gendersel"
     android:popupBackground="#67656c"/>

I know this code is not to change text color.
I have no idea how to do that,please guide me for doing the same.
Any help would be appreciable.

A: Your Spinner
<Spinner
    android:layout_height="wrap_content"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:entries="@array/Gender_Selection_arrays"
    android:prompt="@string/Gender_Selection"
    android:id="@+id/gendersel"
    style="@style/mySpinnerItemStyle"
    android:popupBackground="#67656c"/>

mySpinnerItemStyle (Add this to styles.xml)
<style name="mySpinnerItemStyle" parent="Base.Widget.AppCompat.Spinner">
    <item name="android:textColor">@color/my_spinner_text_color</item>
</style>

And finally in colors.xml
<color name="my_spinner_text_color">#FFFFFF</color>

mySpinnerItemStyle inherits from Base.Widget.AppCompat.Spinner and in that android:textColor attribute changes the color of the spinner text

A: I got solution for this, Create a new xml "spinner_style.xml"
<?xml version="1.0" encoding="UTF-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:textColor="@color/Black" />

And fix this layout as your spinner style in your activity:
   ArrayAdapter<String > gender_adapter = new ArrayAdapter<String> (getActivity(), R.layout.spinner_style,gender_spinner );


text:
Q: Why does this expression have a valid type? Banging around in ghci, I happened to notice that the expression (*) 1 [1..5] apparently has a valid type.
:t (*) 1 [1..5]
(*) 1 [1..5] :: (Enum t, Num [t], Num t) => [t]

Apparently it is a list with several type constraints, including Num [t] which looks impossible to me, like it should give an error.
How is this the type of the expression? Why does ghci's :t command not give an error here?

A: Let's look at how these constraints come to be to explain the type.
Numbers
In Haskell a literal number is replaced with a call to fromInteger (or fromRational if it has a decimal point or an 'e' in it). This way one can write '1' and have it be float or a double or an int or whatever. The type of fromInteger is
fromInteger :: Num a => a

So 1 gets desugared to fromInteger (1::Integer) which has type Num t => t
Ranges
In Haskell the syntax [a..b] is converted into the call enumFromTo a b and the type is enumFromTo :: Enum a => a -> a -> [a]. Putting these together we get
[1..5] == enumFromTo (fromInteger 1) (fromInteger 5) :: (Enum a, Num a) => [a]

Putting it all together
Now the type of (*) is Num b => b -> b -> b so we combine these all together to get:
(Num t,
Num a,
Enum a,
Num b,
t~b,
[a]~b) => b

Note that a~b means the types a and b are the same. Combining these gives the type
(Num a, Enum a, Num [a]) => [a]

A: Num [t] is not just possible, it's easy:
import Control.Applicative
liftA0 = pure -- hobgoblins, simple minds, etc.
liftA1 = fmap
instance Num t => Num [t] where
    (+) = liftA2 (+)
    (-) = liftA2 (-)
    (*) = liftA2 (*)
    negate = liftA1 negate
    abs    = liftA1 abs
    signum = liftA1 signum
    fromInteger n = liftA0 (fromInteger n)

So it would be awful for GHC to produce an error instead of inferring that your expression could be well typed with an appropriate instance.
Of course, it would also be awful to ever write this instance in real code, but GHC shouldn't be in the business of passing judgment on code like we humans do.

A: This pattern of idiomatic/applicative lifting exists as Data.Monoid.Ap where Ap [] a specifies lifting operations with pure, fmap and liftA2: (+) = liftA2 (+):
>> :set -XDerivingVia
>> :set -XStandaloneDeriving
>>
>> import Data.Monoid (Ap(..))
>>
>> deriving via Ap [] a instance Num a => Num [a]
>>
>> 1 * [1..5]
[1,2,3,4,5]
>> [100,200] * [1..5]
[100,200,300,400,500,200,400,600,800,1000]

The behaviour for lists is derived via Ap [] a. You get different applicative behaviour through ZipList
>> import Control.Applicative (ZipList(..))
>>
>> deriving via Ap ZipList a instance Num a => Num [a]
>>
>> 1 * [1..5]
[1,2,3,4,5]
>> [100,200] * [1..5]
[100,400]


text:
Q: How to open a pdf from my flatlist in react-native? Im trying to pick a file (pdf-file) from a module called react-native-file-picker. This works ok, and gaves me name, type, path and uri.
After this, i display the name of the document that i picked in a flatlist.
Now, what i want is to "onPress" of the item in the flatlist, open the document with some pdf viewer or something like that.
I've already tried to use other modules like react-native-view-pdf and react-native-pdf and react-native-pdf-view but i cant access the state of my uri with either of them.
The last one that i used it was react-native-file-viewer and doesn't work very well because it doesn't open the item on press.
This is my actual code.
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Button, TextInput,
Dimensions, FlatList } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage'
import FilePickerManager from 'react-native-file-picker';
import FileViewer from 'react-native-file-viewer';

global.myfunction = function myfunction() {
FilePickerManager.showFilePicker(null, (response) => {
console.log('Response = ', response);

if (response.didCancel) {
  console.log('User cancelled file picker');
}
else if (response.error) {
  console.log('FilePickerManager Error: ', response.error);
}
else {
  this.storeItem(response)
}
});
};

export default class Docs extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
  title: 'Docs',
  header: null

}
};

state = {
arr: [],
local: '',
password: '',
obj: null,
count: 1,
image: {},
b64: '',
isModalVisible: false,
pdfuri: null,

};

pdf = () => {

FilePickerManager.showFilePicker(null, (response) => {
  console.log('Response = ', response);

  if (response.didCancel) {
    console.log('User cancelled file picker');
  }
  else if (response.error) {
    console.log('FilePickerManager Error: ', response.error);
  }
  else {
    this.storeItem(response)
    this.setState({
      pdfuri: response.path
    });
  }
});

}
toggleModal = (item) => {
this.setState({ isModalVisible: !this.state.isModalVisible, obj: item });
};

 storeItem(item) {
 try {
  //we want to wait for the Promise returned by AsyncStorage.setItem()
  //to be resolved to the actual value before returning the value~
  console.log(item)
  var joined = this.state.arr.concat(item);
  console.log('files   ', joined)

  this.setState({ arr: joined })

  AsyncStorage.setItem('files', JSON.stringify(joined));
  console.log(this.state.arr)

} catch (error) {
  console.log(error.message);
}
}

componentDidMount() {
//Here is the Trick
const { navigation } = this.props;

 }

componentWillMount() {
AsyncStorage.getItem('files').then(array => {
  item = JSON.parse(array)

  item ? this.setState({ arr: item }) : null;
  console.log(this.state.arr)

  })
 }

verpdf() {
const path =
"content://com.android.providers.downloads.documents/document/4183"
FileViewer.open(path, { showOpenWithDialog: true })
    .then(() => {
      // success
    })
    .catch(error => {
      // error
    });
 }

render() {

return (
  <View style={[styles.container, { marginTop: 20 }]}>
    <FlatList
      data={this.state.arr}
      renderItem={({ item }) => <TouchableOpacity onPress=
  {this.verpdf(item)} style={{ marginBottom: 10, marginTop: 10, alignItems: 'center' }}>
        <Text>{item.fileName}</Text></TouchableOpacity>}
    />

    <Button title='ok' onPress={this.pdf}></Button>
  </View>
  );
 }
}

How should i do this?

A: Try to change the event handler from
 onPress=
  {this.verpdf(item)}

to

 onPress=
  {()=>this.verpdf(item)}

A: Like @Oleg said, to open a certain item i needed to change the event handler to a arrow function.
onPress = {this.verpdf(item)}

to
onPress= {()=>this.verpdf(item)}

After that i wanted to open a certain item from my flatlist which i did:
verpdf(item) {
const path = item.path
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
  // success
})
.catch(error => {
  // error
});
}


text:
Q: How to prevent Orientation change 180 degrees First, sorry for my bad english, and thanks for stop by,
I need to know if is possible prevent the Orientation change to make the APP with static portait all the time. No change orientation with any orientation change in portait, and if the device is rotate 90 or 180 degrees, the screen don't change.
I used a cordova-plugin-screen-orientation, and i can make a portrait or landscape but always change orientation with 180 degrees rotate of the device...
I proved with manifest android:screenOrientation and the options, but no results...
Someone could help me!?
Thanks!

A: I am able to lock the screen orientation without any plugin.
For Android, putting the following in config.xml seems to work for me:
<platform name="android">
  <preference name="orientation" value="portrait" />
</platform>

For iOS I set the permitted orientation in Xcode, in the General/Deployment Info section.
For locking/unlocking on the fly, you could try https://github.com/cogitor/PhoneGap-OrientationLock.


text:
Q: htaccess regex redirecting I have over 700 redirects in a htaccess file all using RewriteRules. I'm having trouble figuring out how to redirect multiple pages with numbers 2-20 in the URL. Here are my non-working redirects:
RewriteRule ^orlando-airport/americas-best-cocoa-beach/1-person-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/americas-best-cocoa/1-person [R=301,L]
RewriteRule ^orlando-airport/americas-best-cocoa-beach/[0-9]-people-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/americas-best-cocoa/$1-people [R=301,L]
RewriteRule ^orlando-airport/double-tree-cocoa-beach/1-person-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/doubletree-cocoa-beach/1-person [R=301,L]
RewriteRule ^orlando-airport/double-tree-cocoa-beach/[0-9]-people-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/doubletree-cocoa-beach/$1-people [R=301,L]

Lines 1 and 3 work but 2 and 4 don't. The number of people in the URLs should be 1 person and then 2-20 people. Any help would be appreciated

A: You're not capturing the expression, and you're only allowing one digit.
Use ([0-9]+) instead of [0-9]:
RewriteRule ^orlando-airport/americas-best-cocoa-beach/1-person-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/americas-best-cocoa/1-person [R=301,L]
RewriteRule ^orlando-airport/americas-best-cocoa-beach/([0-9]+)-people-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/americas-best-cocoa/$1-people [R=301,L]
RewriteRule ^orlando-airport/double-tree-cocoa-beach/1-person-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/doubletree-cocoa-beach/1-person [R=301,L]
RewriteRule ^orlando-airport/double-tree-cocoa-beach/([0-9]+)-people-fly-snooze-cruise-hotel-package.html$ /fly-snooze-cruise/orlando-airport/doubletree-cocoa-beach/$1-people [R=301,L]


text:
Q: OpenCV VideoWriter: Issues with playing video Problem: I'm having issues correctly rendering/playing a video created by OpenCV's videowriter.
Details:Python does not spit out any errors and sucessfully runs through/creates the video. When I try to play the video with VLC, it looks like VLC is trying to play an empty video (it looks like it has time length 00:00). Furthermore, the video size is a mere 5kbs. I've used this function with other NumPy image arrays, and they have worked.
My NumPy Array Preparation Code:
for i in range(len(frames)-1):
    fig = PIV.runPIV(frames[i].astype(np.int32),frames[i+1].astype(np.int32),dt = self.context.attrs.dt)
    agg = fig.canvas.switch_backends(FigureCanvasAgg)
    agg.draw()  #This produces a successful image. Simple Quiver plot.

    image = np.fromstring(agg.tostring_rgb(),dtype = np.uint8)
    image.shape = agg.get_width_height() + (3,)
    images.append(image)
self._render(images)

Images Array:
[[[191 191 191]
  [191 191 191]
  [191 191 191]
  ...,

  [191 191 191]
  [191 191 191]
  [191 191 191]]]

Note:
This array has a shape of (640,480,3) which was what other arrays previously that worked similarly had. The only difference between this and other past successes is that before I loaded images and did processing on them before rendering, but this stack is from matplotlib.pyplot with a switched backend to FigureCanvasAgg; however, when I save the image prior to its NumPy conversion, the image looks perfectly fine.
My OpenCV VideoWriter Code:
def writeMovie(self, fileName, fps=20):
    isColor = len(self[0].shape) == 3
    writer = cv2.VideoWriter(fileName,
                             fps=fps,
                             fourcc=cv2.cv.CV_FOURCC(*"PIM1"),
                             frameSize=self[0].shape[0:2],
                             isColor=isColor)
    for image in self:
        if image.dtype == np.bool:
            image = image.astype(np.uint8)*255
        writer.write(image)

I will gladly provide more information to the best of my abilities to clarify and help answer this question. Any advice/suggestions will be greatly appreciated.

A: When the video seems to be empty, that's because the images you want to put into the video don't fit the video parameters. I had an equivalent problem in C++ and my problem was the input size and the codec.
I'm a neophyte in python, but I think you might have the same problem. Maybe you should try to print frameSize and fourcc to see if theses parameters are correct ( shouldn't it be self[0].shape[0:1] ? (Again, I don't know much about python, so I might be wrong on this point))

A: Not sure what the problem is still, but the way I got around it was saving each image as a file and then concatenating all the files with ffmpeg.


text:
Q: Sturm - Liouville theorem, nonhomogeneous form and eigenfunctions generate a function space. $$\frac{d}{d x}\left\{p(x) \frac{d y}{d x}\right\} + \big(q(x) + \lambda r(x)\big)y = f(x)$$
It is standard form of nonhomogeneous Sturm - Liouville .
We first solve the homogeneous part and find eigenvalues and corresponding eigenfunctions if there are any. Further, we say that eigenfunctions are complete that is they generate the "functions space", every function can be expressed as power series with eigenfunctions (like writting vectors with bases).
My question is: What is that eigenfunction space? How general is it? For example, how we are so sure that $f(x)$ at the nonhomogeneous part is in this eigenfunction space?


text:
Q: Can't insert records into a kinesis queue from flink? I have an Apache Flink process that reads from a kinesis stream, makes some queries and I want the result to be dumped to another kinesis stream (version 1.13)
The whole process is Ok, except for the part of inserting the records in the kinesis stream, in which I get this error:
Caused by: org.apache.flink.table.api.TableException: Table sink 'default_catalog.default_database.output_events' doesn't support consuming update and delete changes which is produced by node Join(joinType=[LeftOuterJoin],....

The processing of the data that I do

*

*Table A: Filter original table, overlapping window of 10 min each min and field aggregation.

*Table B: Filter original table, overlapping window of 10 min each min and field aggregation.

*Left Join of Table A and Table B, filtering the results that interest me.

can you help me?


text:
Q: Getting Heap Space Issue while deserializing Avro packet in Kafka Consumer Getting heap space out of memory exception while deserializing avro message in Kafka consumer.
Running consumer code in Java with local kafka producer and consumer and i tried to increase heap memory till 10GB in IntelliJ but still getting this issue.
Simple Consumer Class Code
Properties props = new Properties();

            props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                    "localhost:9092");
            props.put(ConsumerConfig.GROUP_ID_CONFIG, "test1");
             props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
            props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
            props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
           props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                    StringDeserializer.class.getName());
            props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                    AvroDeserializer.class.getName());

            KafkaConsumer<String, BookingContext> consumer = new KafkaConsumer<>(props);

                consumer.subscribe(Arrays.asList("fastlog"));
       while (true) {
                    ConsumerRecords<String, MyClass> records = consumer.poll(100);
                    for (ConsumerRecord<String, MyClass> record : records)
        {
                        System.out.printf("----------------------" +
                                "+\noffset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());

       }
    }

Here is my class for deserializer where i wrote to convert packet to normal class after the process.
Avro Deserializer Code :
public T deserialize(String topic, byte[] data) {
        try {
          T result = null;

          if (data != null) {
            LOGGER.debug("data='{}'", DatatypeConverter.printHexBinary(data));

            DatumReader<GenericRecord> datumReader =
                new SpecificDatumReader<>(MyClass.getClassSchema());
            Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);

            result = (T) datumReader.read(null, decoder);
            LOGGER.debug("deserialized data='{}'", result);
          }
          return result;
        } catch (Exception ex) {
          throw new SerializationException(
              "Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex);
        }
      }

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at org.apache.avro.generic.GenericData$Array.<init>(GenericData.java:245)
        at org.apache.avro.generic.GenericDatumReader.newArray(GenericDatumReader.java:391)
        at org.apache.avro.generic.GenericDatumReader.readArray(GenericDatumReader.java:257)
        at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:177)
        at org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:116)
        at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
        at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
        at org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:116)
        at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:222)
        at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:175)
        at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
        at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:145)
        at kafka.serializer.AvroDeserializer.deserialize(AvroDeserializer.java:59)
        at kafka.serializer.AvroDeserializer.deserialize(AvroDeserializer.java:21)
        at org.apache.kafka.common.serialization.ExtendedDeserializer$Wrapper.deserialize(ExtendedDeserializer.java:65)
        at org.apache.kafka.common.serialization.ExtendedDeserializer$Wrapper.deserialize(ExtendedDeserializer.java:55)
        at org.apache.kafka.clients.consumer.internals.Fetcher.parseRecord(Fetcher.java:918)
        at org.apache.kafka.clients.consumer.internals.Fetcher.access$2600(Fetcher.java:93)
        at org.apache.kafka.clients.consumer.internals.Fetcher$PartitionRecords.fetchRecords(Fetcher.java:1095)
        at org.apache.kafka.clients.consumer.internals.Fetcher$PartitionRecords.access$1200(Fetcher.java:944)
        at org.apache.kafka.clients.consumer.internals.Fetcher.fetchRecords(Fetcher.java:567)
        at org.apache.kafka.clients.consumer.internals.Fetcher.fetchedRecords(Fetcher.java:528)
        at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1110)
        at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1043)
        at SimpleConsumer.main(SimpleConsumer.java:43)

A: The code you posted doesn't show anything that would run out of memory, but you're obviously storing these result returned values somewhere else, and not cleaning up after them.  I suggest you check whatever is calling your deserialize method, and check if you are maybe storing all those results in a list or another data structure, and not cleaning them up.
The other thing you can do is run a JVM profiler like JVisualVM, and you do a heap dump that will show you what type/quantity of objects are clogging up your JVM heap.


text:
Q: Catch blank (including all-whitespace) form submissions If have a problem on my site that users can post empty messages if they use space.
Code:
if (isset($_POST['submit'])) {

  // check for empty fields
  if (empty($_POST['headline']) || empty($_POST['text']) ||
      empty($_POST['forum_id'])) {
      header("Refresh: 2; url=/add-thread");
      die('You must fill out every field.');
  }

// No errors? Save.
else {
$headline = mysql_real_escape_string($_POST['headline']);
$text = mysql_real_escape_string($_POST['text']);

mysql_query("INSERT INTO threads (headline, text, date, forum_id, user_id)
             VALUES ('$headline', '$text', NOW(), '$_POST[forum_id]', '$user[id]')");

header("Location: /thread/".mysql_insert_id()."");
}

}

How can I fix this?

A: trim() the text inputs. You can do that easily like this:
// get input vars and trim space
$callback = array('filter' => FILTER_CALLBACK, 'options' => 'trim');
$fields = filter_input_array(INPUT_POST, array(
    'headline' => $callback,
    'text'     => $callback,
    'forum_id' => $callback,
));

// check for empty fields by counting how many are set
if ( count($fields) != count(array_filter($fields)) ) {
    // something was unset
}

A: The empty function checks for variables that meet a set criteria, from the manual

Returns FALSE if var  has a non-empty and non-zero value.
The following things are considered to be empty:

*

*"" (an empty string)

*0 (0 as an integer)

*"0" (0 as a string)

*NULL

*FALSE

*array() (an empty array)

*var $var; (a variable declared, but without a value in a class)

Your $_POST fields actually contain something like this
"   ";

This isn't and empty string, but a string that's filled with whitespace characters.
Before using empty(), trim() the white-space from your POSTed values
$trimmed_post = array();
foreach($_POST as $key=>$value){
    $trimmed_post[$key] = $value;
}
if(!empty($trimmed_post['headline'])){
    //...
}

You don't need to put the new values into a new array, but I'm not a big fan of changing what's in the auto-generated superglobals.
One final note, you can't do something like this
if(!empty(trim($_POST['headline']))){
   //...
}

because the empty function expects to be passed an actual variable.  You could do something like this instead
if('' != trim($_POST['headline'])){
//...
}

This is probably the best approach to take.  You reduce the number of functions that you need to call, users can post entries with a value of 0, and the code is more explicit about what it does.  Another form you'll see is
if(trim($_POST['headline'])){

}

This works because PHP evaluates an empty string ('') as false, and a non empty string as true.  I tend to avoid this form because I've found a lot of PHP bugs crop up around misunderstandings on how the equality operators get boolean values out of certain types.  Being explicit helps reduce occurrences of these types of bugs.

A: Just a quick note: You're injecting the value of $_POST['forum_id'] into the SQL; that's not a good idea, since a user could manipulate that value as desired, even if it is coming from a hidden field. It would be wise to escape the value, or at least pass it through intval() and ensure it's an integer (assuming integral post identifiers).

A: I agree that trimming is the way to go.  Here's a much easier way to go about it:
$_POST = array_map('trim', $_POST);

A: Try
if (!empty($_POST['headline']) && !empty($_POST['text']) &&
!empty($_POST['forum_id']))

For the logic.
You'd have to switch it around though.
UPDATE to clarify:
if (isset($_POST['submit']) && !empty($_POST['headline']) &&
!empty($_POST['text']) && !empty($_POST['forum_id'])) {

    $headline = mysql_real_escape_string($_POST['headline']);
    $text = mysql_real_escape_string($_POST['text']);

    mysql_query("INSERT INTO threads (headline, text, date, forum_id, user_id)
         VALUES ('$headline', '$text', NOW(), '$_POST[forum_id]', '$user[id]')");

    header("Location: /thread/".mysql_insert_id()."");
}
else
{
  header("Refresh: 2; url=/add-thread");
  die('You must fill out every field.');
}

}

A: Right after checking for a submission:
foreach ( $_POST as $key => &$value ) $value = trim($value);

edit in response to asker's comment:
Odd that it didn't work as above.  Here was my exercise to confirm it would.
tbramble@wayfarer:~$ php -a
Interactive shell

php > $arr = array('one',' two', ' three ');
php > print_r($arr);
Array
(
    [0] => one
    [1] =>  two
    [2] =>  three
)
php > foreach ( $arr as $key => &$value ) $value = trim($value);
php > print_r($arr);
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Must have something to do with working on a superglobal instead of a normal array.

A: I trim every $_GET & $_POST variable as soon as the app starts. try something like this:
function trimArray(&$array) {
    if (empty($array)) {
        return;
    }

    foreach ($array as $k => $v) {
        if (! is_array($v)) {
            $array[$k] = trim($v);
        } else {
            trimArray($v);
        }
    }
}

if (! empty($_GET)) {
    trimArray($_GET);
}
if (! empty($_POST)) {
    trimArray($_POST);
}


text:
Q: AngularJS - How to change the color of one of a pair of buttons on button click I am dynamically creating rows of pairs of buttons from data. I found a question on stack that looked like it would solve my problem and implemented it, but when I click a particular button in a row, it activates both buttons in that row. I only want one or the other to change color when clicked. How can I get around this? Thanks.
HTML:

                <button type="button" class="btn form-control"
                    data-ng-class="{'btn-success': pickChosen, 'btn-default': !pickChosen}"
                    data-ng-click="pick()">
                </button>

                <button type="button" class="btn form-control"
                    data-ng-class="{'btn-success': pickChosen, 'btn-default': !pickChosen}"
                    data-ng-click="pick()">
                </button>

Controller:
    .controller('dashController', function ($scope, $http) {
        $scope.pickChosen = false;
        //....
        $scope.pick = function () {
        //non-important code
        this.pickChosen = true;
        };
    })

A: I think that in this case it better to make pickChosen to be a button index, rather then boolean and then switch button class comparing the index pickChosen == 1 ? 'btn-success' : 'btn-default':

        <button type="button" class="btn form-control" data-ng-class="[pickChosen == 1 ? 'btn-success' : 'btn-default']" data-ng-click="pickChosen = 1; makePick()">{{item.name}}</button>

        <button type="button" class="btn form-control" data-ng-class="[pickChosen == 2 ? 'btn-success' : 'btn-default']" data-ng-click="pickChosen = 2; makePick()">{{item.name}}</button>

Demo: http://plnkr.co/edit/JyoBvFOcT9sQYIJVIJyn?p=info


text:
Q: How to get the unique numbers of a list in a new list? I have this list:
list = [{1,2,3,4}, {3,4,5}, {2,6}]

I want to have this as the output:
{1,6}

So I only want the unique numbers to have an output.
This is what I tried, but it does not work:
list = [{1,2,3,4}, {3,4,5}, {2,6}]
s1 = []
for number in list:
   if number not in s1:
      s1.append(number)
def unique(s1):
   return set.difference(*s1)
print (unique(s1))

My output is:
{1, 2, 3, 4}

I have no clue how to fix this? I am a python beginner so can anyone explain what the answer is and why that should be the solution? Many thanks in advance!

A: Use a Counter object.
>>> from collections import Counter
>>> from itertools import chain
>>> my_list = [{1,2,3,4}, {3,4,5}, {2,6}]
>>> set(k for k,v in Counter(chain.from_iterable(my_list)).items() if v == 1)
set([1, 5, 6])

chain.from_iterable "flattens" my_list. The Counter compiles how many times each element from the flattened list is seen, and the generator expression sends only the keys mapped to a value of 1 to set.

Some of the intermediate values involved:
>>> list(chain.from_iterable(my_list))
[1, 2, 3, 4, 3, 4, 5, 2, 6]
>>> Counter(chain.from_iterable(my_list))
Counter({2: 2, 3: 2, 4: 2, 1: 1, 5: 1, 6: 1})

A: I had an earlier answer posted that wasn't right. I don't like to give up, and I wanted to find an answer to this question that only used sets.  I'm not saying that this is a better answer than the others, but it does achieve at least my own goal of not bringing any extra packages into the solution:
def unique(data):
    result = set()
    dups = set()
    for s1 in data:
        # accumulate everything we see more than once
        dups = dups | (result & s1)
        # accumulate everything
        result = (result | s1)
    # the result is everything we only saw once, or in other words,
    # everything we saw minus everything we saw more than once
    return result - dups

print(unique([{1,2,3,4}, {3,4,5}, {2,6}]))
print(unique([{1}, {1}, {1}]))

Output:
set([1, 5, 6])
set([])

There's probably a better solution even to using just sets. I always want to try to use the simplest set of tools possible because I think it is the most understandable to do so, and will often turn out to be as efficient as anything else as well.

A: Not a fancy python solution but what you probably want is to build a dict where the key is a number in the list and the value is the number of times it occurs.
This solution is by no way optimal since we are performing to many iterations:
list = [{1,2,3,4}, {3,4,5}, {2,6}]
count_hash = {}

for dict in list:
    for number in dict:
        if number in count_hash:
            count_hash[number] += 1
        else:
            count_hash[number] = 1

for number in count_hash:
    if count_hash[number] == 1:
        print(number)

A: I agree with chepner on using a Counter.  Using functools.reduce to flatten the list came from here.
import functools
import operator
from collections import Counter

my_list = [{1,2,3,4}, {3,4,5}, {2,6}]
flat_list = functools.reduce(operator.iconcat, my_list, [])

results = [k for (k, v) in Counter(flat_list).items() if v == 1]

print(results)

# OUTPUT
# [1, 5, 6]

A: I didn't see any of the answers given that were like my solution. I hope the symmetric difference of the sets given provides that correct manner (to this question).
>>> L = [{1,2,3,4}, {3,4,5}, {2,6}]
>>> M = L[0]
>>> for s in L[1:]:
    M ^= s

>>> M
{1, 5, 6}

Note: The question was about lists but the list he gave was a list of sets.


text:
Q: Case in-insensitive lookup in an Excel table I need to search a value on the first column of a Table in Excel and delete the correspondent Table row. The search must be case insensitive.
If I use .Find method on the Table.DataBodyRange a range is returned, but I do not know where this range is located relatively to the Table.DataBodyRange.
Set oCell = oTable.ListColumns("Client name").DataBodyRange.Find(what:=szClientName, MatchCase:=False, searchformat:=False)

oTable.ListRows(oCell.Row).Delete 'THIS DOES NOT DELETE THE TABLE ROW WHERE szClientName HAS BEEN FOUND BUT IT DELETES THE WORKSHEET ROW WHERE oCell IS LOCATED

If I use the Application.match method on Table.DataBodyRange, it returns the Index of found element relatively to the Table but unfortunately the search is case sensitive.
vIndex = Application.Match(szClientName, oTable.ListColumns("Client Name").DataBodyRange, 0)

oTable.ListRows(vIndex).Delete 'THIS DELETES THE TABLE ROW BUT THE SEARCH ON szClientName IS CASE SENSITIVE

How can I do what I need to do?

A: Your first solution didn't work because oCell returns a Range object that is not relative to your table/list oTable.
Although not an elegant solution, this should work:
Set oCell = oTable.ListColumns("Client name").DataBodyRange.Find(what:=szClientName, MatchCase:=False, searchformat:=False)
oCell.EntireRow.Delete

I did not put any error checking here; if it finds nothing the code will throw an error.


text:
Q: Using Firebase SimpleLogin in a non android Java environment I have server written in Java, the server is writing to my firebase and I would like to add authentication to ensure that it is only my server that can perform these updates.
I have included the firebase-simple-login-LATEST.jar in my class path and altered by code to attempt to authenticate based on a user/password combination see below
Firebase fb = new Firebase("https://myfirebase.firebaseio.com");
SimpleLogin sl = new SimpleLogin(fb);
sl.loginWithEmail("user@email.address", "password", new SimpleLoginAuthenticatedHandler() {
  @Override
  public void authenticated(Error error, User user) {
    if (error == null) {
       // Do some work here
    }
  }
});

My problem is that even though my server is pure java and not running any aspects of android, I get run time errors complaining that
java.lang.ClassNotFoundException: android.net.Uri

I presume there is some internal dependency in the simple login java code.  I am wondering if there is a pure Java (with no android dependency) jar file that I can use as I do not really want to have to include a load of android jars in my build

A: The simple login jar depends on the Android runtime, but if you just want to authenticate a server, you can do one of two things:

*

*Use your Firebase secret as the auth credential

*Generate a specific admin token for your server
See the documentation here: https://www.firebase.com/docs/security/custom-login.html
Helper libraries are available in several languages for generating your own token.


text:
Q: Receiving EnvCommandError when run poetry install on Apple M1 MacOs Monterey I'm facing the issue when running poetry install command in my new Macbook Pro using Apple M1 chip and MacOS Monterey. I tried many suggestions so far but still cannot make it fixed.
Python version: 3.8.12
>>> poetry install
Installing dependencies from lock file

Package operations: 20 installs, 0 updates, 0 removals

  • Installing scipy (1.6.0): Failed

  EnvCommandError

  Command ['/Users/<retacted>/Library/Caches/pypoetry/virtualenvs/reporting-executor-3zOoUFwf-py3.8/bin/pip', 'install', '--no-deps', 'file:///Users/<retacted>/Library/Caches/pypoetry/artifacts/e2/fc/a9/d781fc7053c9e0aa0b94b47220fee30ba4ef114e7d11b36b3cc68b1b95/scipy-1.6.0.tar.gz'] errored with the following return code 1, and output:
  Processing /Users/<retacted>/Library/Caches/pypoetry/artifacts/e2/fc/a9/d781fc7053c9e0aa0b94b47220fee30ba4ef114e7d11b36b3cc68b1b95/scipy-1.6.0.tar.gz
    Installing build dependencies: started
    Installing build dependencies: finished with status 'done'
    Getting requirements to build wheel: started
    Getting requirements to build wheel: finished with status 'done'
    Preparing metadata (pyproject.toml): started
    Preparing metadata (pyproject.toml): finished with status 'error'
    ERROR: Command errored out with exit status 1:
     command: /Users/<retacted>/Library/Caches/pypoetry/virtualenvs/reporting-executor-3zOoUFwf-py3.8/bin/python /Users/<retacted>/Library/Caches/pypoetry/virtualenvs/reporting-executor-3zOoUFwf-py3.8/lib/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py prepare_metadata_for_build_wheel /var/folders/54/n12zwf1n74vg5knvnd37ph880000gp/T/tmpusexpj06
         cwd: /private/var/folders/54/n12zwf1n74vg5knvnd37ph880000gp/T/pip-req-build-xbw8rqq2
    Complete output (4 lines):
    setup.py:461: UserWarning: Unrecognized setuptools command ('dist_info --egg-base /private/var/folders/54/n12zwf1n74vg5knvnd37ph880000gp/T/pip-modern-metadata-1_oeqwwo'), proceeding with generating Cython sources and expanding templates
      warnings.warn("Unrecognized setuptools command ('{}'), proceeding with "
    Error: 'None' must be installed before running the build.

Here is what I tried:

*

*Running the terminal under Rosetta mode

*I can be able to install scipy via the command arch -arm64 pip install scipy without issue but the version is 1.7.3

*Tried arch -arm64 pip install scipy==1.6.0 getting the error

error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [4 lines of output]
      setup.py:461: UserWarning: Unrecognized setuptools command ('dist_info --egg-base /private/var/folders/54/n12zwf1n74vg5knvnd37ph880000gp/T/pip-modern-metadata-rsi6te2b'), proceeding with generating Cython sources and expanding templates
        warnings.warn("Unrecognized setuptools command ('{}'), proceeding with "
      Error: 'None' must be installed before running the build.

      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.

A: We had a similar issue and it seems to be a Python version issue: https://github.com/python-poetry/poetry/issues/2629
We downgraded to Python 3.7 for example. Maybe try other versions that is still fine for your project.


text:
Q: Mouse Coordinates keep getting on top of one another -Java I am trying to get the mouse coordinates display in the panel but each time I move the cursor the message and new coordinates are being displayed on the previous one.I am using MouseMotionListener with JPanel. I can't figure out the problem.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
    public static void main(String[] args) {
      new Main();
      JFrame frame = new JFrame();
      frame.setTitle("MouseCoordinates");
      frame.setSize(400, 400);
      frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
        System.exit(0);
            }
        });
        Container contentPane = frame.getContentPane();
        contentPane.add(new Main());
        frame.setVisible(true);
    }
      public Main() {
      setSize(400, 400);
      label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
      add(label);
      addMouseMotionListener(this);
    }
    public void mouseMoved(MouseEvent e) {
    label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
    }
    public void mouseDragged(MouseEvent e) {}
    }

A: You're creating Main twice.
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;

public static void main(String[] args) {
    Main m = new Main();// create an object and reference it
    JFrame frame = new JFrame();
    frame.setTitle("MouseCoordinates");
    frame.setSize(400, 400);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            System.exit(0);
        }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(m);
    frame.setVisible(true);
}
//...

your problem was creating the Main object twice (which is a jpanel) and then the writing appeared twice. if you give the Main object a reference, then your problem should be fixed.


text:
Q: multi threads modify a global list in python i want to add an item into a global list every 2 seconds in one thread,
and save the list into database before empty it  every 3 seconds in another thread.
i create two local varibles to monitor the total added items and total saveditems, they should be equal every 6 senconds,but it is not.
here is my code:
import datetime
import psutil,os,time
from threading import *
class AddToList(Thread):
    totalAdded=0
    def run(self):
        lock=RLock()
        lock.acquire()
        while True:
            entryList.append("AddToList at "+str(datetime.datetime.now()))
            self.totalAdded=self.totalAdded+len(entryList)
            print("totalAdded:"+str(self.totalAdded))
            time.sleep(2)
        lock.release()
class SaveList(Thread):
    totalSaved=0
    '''save entry to server'''
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        lock=RLock()
        lock.acquire()
        while True:
            #save list to database,then empty the list
            self.totalSaved=self.totalSaved+len(entryList)
            del entryList[:]
            print("totalSaved:"+str(self.totalSaved))
            time.sleep(3)
        lock.release()

if __name__=="__main__":
    global entryList
    entryList=[]
    addClass= AddToList()
    addClass.start()
    saveClass=SaveList()
    saveClass.start()

result:
totalAdded:2
totalSaved:2
totalAdded:3
totalSaved:3totalAdded:4

totalAdded:6
totalSaved:5
totalAdded:7
totalSaved:6
totalAdded:8
totalAdded:10
totalSaved:8
totalAdded:11
totalSaved:9
totalAdded:12
totalAdded:14
totalSaved:11
totalAdded:15
totalSaved:12
...........
...........
totalAdded:51
totalSaved:39totalAdded:52

totalAdded:54
totalSaved:41
totalAdded:55
totalSaved:42
totalAdded:56
totalAdded:58
totalSaved:44
totalAdded:59
totalSaved:45totalAdded:60
......
......

i anm new to python and searched a lot about threading ,Lock and RLock ,but with no luck.
where am wrong?

A: To make Lock and RLock work you must use the same object in every thread. The lock objects must have the same "visibility" of the object that you want to "protect".
Here is a new version of you code which should work. It also avoid using things like global variables etc.
import datetime
import time
import threading

class AddToList(threading.Thread):

    def __init__(self, lock, entryList):
        threading.Thread.__init__(self)
        self.totalAdded = 0
        self.entryList = entryList
        self.lock = lock

    def run(self):
        while True:
            self.lock.acquire()
            entryList.append("AddToList at {}".format(datetime.datetime.now()))
            self.totalAdded += 1
            self.lock.release()
            print("totalAdded: {}".format(self.totalAdded))
            time.sleep(2)

class SaveList(threading.Thread):
    def __init__(self, lock, entryList):
        threading.Thread.__init__(self)
        self.totalSaved = 0
        self.entryList = entryList
        self.lock = lock

    def run(self):
        while True:
            self.lock.acquire()
            self.totalSaved += len(self.entryList)
            del self.entryList[:]
            self.lock.release()
            print("totalSaved: {}".format(self.totalSaved))
            time.sleep(3)

if __name__=="__main__":
    lock=threading.Lock()
    entryList=[]

    addClass = AddToList(lock, entryList)
    addClass.start()

    saveClass = SaveList(lock, entryList)
    saveClass.start()

Some things to note:

*

*Use Lock instead of RLock when you don't have any particular needs. RLock is much slower.

*As already pointed out by someone it is better avoid using global variables when not needed. Also Class variables should be used only when it makes sense.

*When you use a lock you should try to limit as much as possible the code between acquire and release. In you previous code you never release the lock.


text:
Q: How to update database using Windows Form data grid? (Visual Studio 2010) When I drag the table from DataSet onto my Windows Form, a bindingNavigator and a dataGridView is created by default. Now when I run the project, add rows in the dataGridView, save it before exiting, and then re-run the project the added rows are there, but when I go to Server Explorer to view the Table Data, those rows aren't there in the Database.
On searching, I found that Visual Studio creates a copy of my database in the /bin/Debug folder, and performs all the changes in that copy of database. Is there a way to ensure that the new copy is created in the Project Directory so that older copy is modified instead of creating it in another directory? Or any other way to update the original Database?
p.s. Changing the 'Copy to Output Directory' property of Database to 'Do not copy' did not solve the problem.

A: You can update your Database using SqlAdapter.
// load data
if(ds != null)
        ds.Clear();
adap = new SqlDataAdapter("select id,title, description from testtable", con);
ds = new DataSet();
adap.Fill(ds);
dataGrid1.DataSource = ds.Tables[0];

// perform update
SqlCommandBuilder com = new SqlCommandBuilder(adap);
foreach(DataRow dr in ds.Tables[0].Rows)
        dr["title"] = txtTitle.Text;
adap.Update(ds);

hope this helps

A: When you were creating your DataSet, did you uncheck the "Enable local database caching"  checkbox on the "Data Source Configuration Wizard" screen?

A: Instead of using Binding. You could use Application Settings. Just an XML File is written!


text:
Q: Android Menu Option always become list menu not grid menu hi i wanna make grid option menu instead of list option menu
but no mather i try (xml or programmatically) i always get list option menu like this

i wanna create grid menu something like this

this is code i use
XML
<item android:id="@+id/item1" android:title="Option1"></item>
<item android:id="@+id/item2" android:title="Option2"></item>
<item android:id="@+id/item3" android:title="Option3"></item>
<item android:id="@+id/item4" android:title="Option4"></item>
<item android:id="@+id/item5" android:title="Option5"></item>
<item android:id="@+id/item6" android:title="Option6"></item>

Programatically
 public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(1, 1, 0, "Option1");
    menu.add(1, 2, 1, "Option2");
    menu.add(1, 3, 2, "Option3");
    menu.add(1, 4, 3, "Option4");
    menu.add(1, 5, 4, "Option5");

    menu.add(2, 6, 0, "Option6");
    menu.add(2, 7, 1, "Option7");
    menu.add(2, 8, 2, "Option8");
    menu.add(2, 9, 3, "Option9");
    menu.add(2, 10, 4, "Option10");

 return true;

}

Update @Krupa Patel
hm, i used android 2.3.3 and you're right i used holo theme
i don't mind to change theme, but i can't find
@android:style/Theme.Holo.Wallpaper.NoTitleBar

instead i found
android:theme="@style/AppTheme" > in AandroidmMnifest.xml (root firectory)

is it right? i try to change it to
android:theme="@style/Theme.Wallpaper.NoTitleBar" >

but it's give error message

Update
i try to create new project and change theme (wizardly)
i see there is available 4 option for theme when i create new project
"none" - "Holo Dark" - "Holo Light" - "Holo Light with Dark Action Bar"
i choice "none" and when i run my new project menu..it's still become list menu not as i expect....any idea?

A: Displaying option menu as grid-style in Android 4.0.3. is not working, because you may used @android:style/Theme.Holo for your application. Menu of Theme.Holo was set for displaying in list-style.
The solutions are:

*

*Try to use another theme such as

@android:style/Theme.Wallpaper.NoTitleBar
instead of @android:style/Theme.Holo.Wallpaper.NoTitleBar

*

*Or if you want to use Theme.Holo only, then try to create a style for menu in values/style.xml. References: see styles in Android Framework.

Hope this will help!


text:
Q: SparseBooleanArray and 2 arraylists, item not removed from arraylist I have a listview from which I remove selected items, I am doing this through a SparseBooleanArray.
However when I remove the selected items, I also want them removed from that position from 2 other arraylists (trackedItems, dateWatchList) but in the dateWatchList arraylist always 1 item it not removed.
I already checked several threads but I cannot get this right.
Would be great if someone can help.
Code piece:
...
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();

   for (int i = 0; i < adapter.getCount(); i++) {

       if (checkedItems.get(i)) {
       // This item is checked and can be removed
       trackedItems.remove(i);
       dateWatchList.remove(i); // 1 item always remains and is NOT removed?
       adapter.remove(adapter.getItem(i));
       }
   }

   checkedItems.clear();
   adapter.notifyDataSetChanged();
...

A: I solved it myself, for anyone who has the same problem, here is my working code:
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();

   for (int i = checkedItems.size()-1; i >= 0; i--) {
       String selecteditem = adapter.getItem(checkedItems.keyAt(i));
       String currentName = trackedItems.get(checkedItems.keyAt(i));
       long currentDate = dateWatchList.get(checkedItems.keyAt(i));

            if (checkedItems.get(checkedItems.keyAt(i))) {
                adapter.remove(selecteditem);
                trackedItems.remove(currentName);
                dateWatchList.remove(currentDate);
            }
    }
    checkedItems.clear();
    adapter.notifyDataSetChanged();


text:
Q: Help plot with horizontal filling I want to plot a graph that looks like the following, where the blue curve is $y=x^2$ and the red lines are $y=8x-12$ and $y=-8x+20$. The filling is applied horizontally from the lines to the edge of the graph

I tried the following code, but the filling is as desired.
Show[Plot[x^2, {x, -1, 4}], Plot[{-8 x + 20, 8 x - 12}, {x, -1, 4}, PlotStyle -> Red, Filling -> Top]]

Thank you!

A: Plot[{x^2, 8 x - 12, -8 x + 20}, {x, -1, 4},
 PlotStyle -> {Blue, Red, Red},
 Filling -> {2 -> {3}},
 AspectRatio -> 1,
 PlotRange -> {-10, 10}]

The crucial part here is the Filling option. You can of course tweak this further to get what you want.


text:
Q: Drive Mapping through GPO on few Servers I have a requirement to fulfill related to Drive mapping through GPO.
We have a domain (let's call it contoso.com).
Under contoso, we have an OU "InfraComputers" where there are 1000s of Server's Computers Objects
Under contoso, we have multiple OUs named NorthAmerica, Europe, Asia, and these OUs have multiple Sub OUs for each site. These Sub OUs have User Objects
The requirement is to Drive Maps to only these 2 Servers (let's call them ServerA & ServerB) so no matter which user logs in to these 2 Servers, they should see Network Drives mapped using GPO
Note: The Drive Maps should not happen on any other servers.
My understanding is the following:

*

*Create a GPO and link it to InfraComputers

*Remove Authenticated Users from Security Filtering and add these 2 Computer Objects

*Create the Drive Mapping with appropriate Shares Paths

*Since Drive Mapping is User Configuration and won't apply to Computers unless Loopback is enabled. So I plan to Enable Loopback with Merge Mode

I am trying to understand if this is a good way to implement Drive Mapping through GPO to few Servers? OR if there is a flaw in this approach? Also if there is a better way to map Drives

A: That's a fine plan, with one exception:
Because you're using these drive mappings for the users logging onto these servers and will be configuring these drive mappings under User Configuration in the GPO, you need to include the users in the Security Filtering of the GPO. If you intend this so apply to all/any users then simply add the Domain Users group to the Security Filtering of the GPO, along with the computer accounts for these two servers.


text:
Q: change image size with availHeight and availWidth of javascripts i am new in this forum, i actually just signed in.
I have an index file which includes only one  tag.
this is my code

<!DOCTYPE HTML>

<link rel="stylesheet" href="css/style.css" type="text/css"/>

    <map name="map">
        <area shape="rect" coords="13,250,455,450" alt="shops" href="">
        <area shape="rect" coords="675,310,1080,390" alt="eshop" href="/opencart/upload">
    </map>

what i want to do is change the size of the image according to the visitor's screen size.
i know that availHeight and availWidth return the height and width of the screen which the browser uses. i want to save the returned values in the variables h and w and then parse these variables inside the html  tag as height=h and width=w
can you help me build my function please and make this work?
any help will be highly appreciated.

A: You can assign in width and height in javascript. Put your script just before ending body tag or put in document.ready.
h=screen.availHeight;
w=screen.availWidth;
$(document).ready(function(){
  $img = $('#image');
  $img.width(w);
   $img.height(h);
});

OR
h=screen.availHeight;
w=screen.availWidth;
$(document).ready(function(){
  img = document.getElementById('image');
  img.style.width = w;
  img.style.height = h;
});


text:
Q: Ejecutar archivo PHP con Crontab Hola buenos días tengo un archivo .php llamado hola.php el cual obtiene la hora y fecha del servidor y lo imprime en un archivo .txt llamado example_crontab.txt. Programe una tarea en crontab para ejecutar el archivo .php a cada minuto, pero resulta que no se esta ejecutando el archivo hola.php porque me meti a ver el archiv example_crontab.txt y no esta la hora y fecha. Para asegurarme de que mi archivo hola.php no tenga errores de código ejecute con el comando php hola.php y si se plasmo la hora y fecha en el archivo example_crontab.txt llegando a la conclusión que no estoy programando bien mi tarea en crontab.
Podrían apoyarme a ver en que parte de mi programación en crotab esta mal. Les anexo mi código.

Tarea programada en Crontab

* * * * * /var/www/html/php hola.php

Código PHP

<?php
  $fh = fopen("example_crontab.txt", 'w') or die("Se produjo un error al crear el archivo");
  $hoy = date("Y-m-d H:i:s");
  $texto = <<<_END
  $hoy
_END;

  fwrite($fh, $texto) or die("No se pudo escribir en el archivo");

  fclose($fh);

  echo "Se ha escrito sin problemas";
?>

Ejecute el comando php hola.php para validar que esté funcionando bien el código y si plasmo la hora y fecha en el archivo example_crontab.txt, pero con la tarea en crontab no se ejecuta el archivo .php
Espero que me puedan apoyar.
Gracias.

A: Hola intenta esto.
***** /opt/alt/php73/usr/bin/php -q /home/**tuusuario**/public_html/hola.php

en servidor centos y php 7.3
claro también revisa la versión de tu php y especifica que servidor es , espero te sirva.


text:
Q: React Native run-android error in emulator "Could not get BatchedBridge, make sure your bundle is packaged correctly" I am using Android Studio Emulator and configured react-native-web support as per this doc as well. But Whenever I run npm run android it gets the below error:

"Could not get BatchedBridge, make sure your bundle is packaged correctly"
I tried many solutions out there like:

*

*Delete node_modules and re install

*Clear cache in react-native start --reset-cache

*Run react-native start before run-android

*check .npmrc
But no solution yet. There is no error in metro terminal as well.
Below is my package.json
{
  "name": "shipdemo",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start --reset-cache",
    "test": "jest",
    "lint": "eslint .",
    "web": "webpack serve -d source-map --mode development --config \"./web/webpack.config.js\" --inline --color --hot",
    "build:web": "webpack --mode production --config \"./web/webpack.config.js\" --hot"
  },
  "dependencies": {
    "react": "17.0.1",
    "react-dom": "^17.0.2",
    "react-native": "0.64.2",
    "react-native-web": "^0.16.5"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "babel-loader": "^8.2.2",
    "babel-plugin-module-resolver": "^4.1.0",
    "babel-plugin-react-native-web": "^0.16.5",
    "eslint": "7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.64.0",
    "react-test-renderer": "17.0.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.39.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2"
  },
  "jest": {
    "preset": "react-native-web"
  }
}

UPDATE:
After enabling Pause on Caught Exception, I got below in the dev tools.

At the same time, Now I got an error in metro as well

A: I have the fix but the reason behind it, posting this answer for increasing the visibility of the solution which is equivalent to this commit.
So I removed .babelrc file and moved the module resolver settings to the webpack config, updated babel.config.js so now the web related settings will not disturb the App-related babel settings.
I have updated the mentioned article as well.

.babelrc:
<Deleted>
babel.config.js:
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
};

web/webpack.config.js:
...
...
...

      // The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
      presets: ['module:metro-react-native-babel-preset'],
      // Re-write paths to import only the modules needed by the app
      plugins: [
        'react-native-web',
        [
          'module-resolver',
          {
            alias: {
              '^react-native$': 'react-native-web',
            },
          },
        ],
      ],
...
...
...

A: restart your Metro Bundler
  yarn start --reset-cache


text:
Q: Dynamics 365 Finance and Operations SSRS Dependant Parameter I'm trying to create a dependant parameter but am struggling to get it to work properly.  Once I select a project, then when I click estimate parameter to display relevant estimates.  If I change the project parm, it is then not updating the estimates parm.  Please see code etc. below. I am fairly new to X++ development, thanks not sure whether i need a build method just to filter a parameter so I have it commented out for now.
/// <summary>
/// Data Contract class for ProjListTransProj SSRS report
/// </summary>
/// <remarks>
/// This is the Data Contract class for the ProjListTransProj SSRS Report.
/// </remarks>

[
DataContractAttribute,
SysOperationContractProcessingAttribute(classStr(ProjListTransProjUIBuilder))
]
public class ProjListTransProjContract
{
    ProjId     projId;
    EstimateTemplateCode    EstimateTemplateCode;

[
        DataMemberAttribute('ProjId'),
        SysOperationLabelAttribute(literalstr("ProjId")),
        SysOperationHelpTextAttribute(literalstr("ProjId"))
]
    public ProjId parmProjId(ProjId _projId = projId)
    {
        projId = _projId;
        return projId;
    }
    [
    DataMemberAttribute('EstimateTemplateCode'),
    SysOperationLabelAttribute(literalstr("Estimate Template")),
    SysOperationHelpTextAttribute(literalstr("Select Estimate Template"))
    ]
public EstimateTemplateCode parmEstimateTemplateCode(EstimateTemplateCode _EstimateTemplateCode = EstimateTemplateCode)
{
    EstimateTemplateCode = _EstimateTemplateCode;
    return EstimateTemplateCode;
}

}
public class ProjListTransProjUIBuilder extends SrsReportDataContractUIBuilder
{
    ProjId                          parmProjId;
    EstimateTemplateCode        EstimateTemplateCode;
    ProjListTransProjContract   contract;

//public void build()
//{

//    //get the current dialog
//    Dialog      dlg = this.dialog();

//    //get the report data contract object
//    contract = this.dataContractObject();
//    projId = contract.parmProjId();

//    //associate dialog field with data contract method
//    this.addDialogField(methodStr(ProjListTransProjContract,parmProjId), contract);
//}

public void lookupEstimate(FormStringControl _formStringControl)
{
    contract = this.dataContractObject();
    parmProjId = contract.parmProjId();
    Query query = new Query();
    QueryBuildDataSource    qbdsEstimateTemplateTable, qbdsEstimateTemplateProj;
    SysTableLookup  sysTableLookup = sysTableLookup::newParameters(tableNum(EstimateTemplateTable), _formStringControl);

    qbdsEstimateTemplateTable = query.addDataSource(tableNum(EstimateTemplateTable));

    qbdsEstimateTemplateProj = qbdsEstimateTemplateTable.addDataSource(tableNum(EstimateTemplateProj));
    qbdsEstimateTemplateProj.relations(true);

    qbdsEstimateTemplateProj.addRange(fieldNum(EstimateTemplateProj, ProjId)).value(parmProjId);

    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, Code));
    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, Name));
    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, Status));
    sysTableLookup.addLookupMethod(tableMethodStr(EstimateTemplateTable, displayGrandTotalValue));
    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, CreatedDateTime));
    sysTableLookup.parmQuery(query);

    sysTableLookup.performFormLookup();
}

public void postBuild()
{
    DialogField dlgEstimate;

    super();

    //get the field to override by providing the data contract object and the associated attribute/method
    dlgEstimate = this.bindInfo().getDialogField(this.dataContractObject(),
            methodStr(ProjListTransProjContract,parmEstimateTemplateCode));

    //register the method we want to override
    dlgEstimate.registerOverrideMethod(
      methodStr(FormStringControl, lookup),
      methodStr(ProjListTransProjUIBuilder,lookupEstimate),
      this);
}

}

A: Example of UI builder where second parameter is filtered by selection of first parameter.
public class ProjListTransProjUIBuilder extends SrsReportDataContractUIBuilder
{
    ProjId                          parmProjId;
    EstimateTemplateCode            EstimateTemplateCode;
    ProjListTransProjContract       contract;
    DialogField                     dialogProjId;
    DialogField                     dialogEstimate;

public void build()
{
    //get the current dialog
    Dialog      dialogLocal  = this.dialog();

    //get the report data contract object
    contract = this.dataContractObject();
    parmProjId = contract.parmProjId();

    //associate dialog field with data contract method
    dialogProjId = this.addDialogField(methodStr(ProjListTransProjContract,parmProjId), contract);
    dialogEstimate = this.addDialogField(methodStr(ProjListTransProjContract,parmEstimateTemplateCode), contract);
}

public boolean projIdModified(FormStringControl _control)
{
    dialogProjId.value(_control.valueStr());
    dialogEstimate.value('');
    return true;
}

public void lookupEstimate(FormStringControl _control)
{
    Query query = new Query();
    QueryBuildDataSource    qbdsEstimateTemplateTable, qbdsEstimateTemplateProj;
    SysTableLookup  sysTableLookup = sysTableLookup::newParameters(tableNum(EstimateTemplateTable), _control);

    qbdsEstimateTemplateTable = query.addDataSource(tableNum(EstimateTemplateTable));

    qbdsEstimateTemplateProj = qbdsEstimateTemplateTable.addDataSource(tableNum(EstimateTemplateProj));
    qbdsEstimateTemplateProj.relations(true);

    qbdsEstimateTemplateProj.addRange(fieldNum(EstimateTemplateProj, ProjId)).value(dialogProjId.value());

    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, Code));
    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, Name));
    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, Status));
    sysTableLookup.addLookupMethod(tableMethodStr(EstimateTemplateTable, displayGrandTotalValue));
    sysTableLookup.addLookupfield(fieldNum(EstimateTemplateTable, CreatedDateTime));
    sysTableLookup.parmQuery(query);

    sysTableLookup.performFormLookup();
}

public void postBuild()
{

    super();

    //get the field to override by providing the data contract object and the associated attribute/method
    dialogProjId = this.bindInfo().getDialogField(this.dataContractObject(),
            methodStr(ProjListTransProjContract,parmProjId));

    if (dialogProjId)
    {
        dialogProjId.lookupButton(2);
    }

    // register override method for lookup cust Group
    //dialogProjId.registerOverrideMethod(methodStr(FormStringControl, lookup), methodStr(ProjListTransProjUIBuilder, lookupEstimate), this);
    // register override method for modified
    dialogProjId.registerOverrideMethod(methodStr(FormStringControl, modified), methodStr(ProjListTransProjUIBuilder, projIdModified), this);

    //binding info for estimate drop down
    dialogestimate = this.bindInfo().getDialogField(
                     this.dataContractObject(),
                     methodStr(ProjListTransProjContract,parmEstimateTemplateCode));

    // register override method for lookup estimate
    dialogestimate.registerOverrideMethod(methodStr(FormStringControl, lookup), methodStr(ProjListTransProjUIBuilder, lookupEstimate), this);

    if (dialogEstimate)
    {
        dialogEstimate.lookupButton(2);
    }

}

    public void getFromDialog()
    {
        contract = this.dataContractObject();
        super();
    }

    public void initializeFields()
    {
        contract = this.dataContractObject();
    }

    public void postRun()
    {
        super();
    }

}


text:
Q: Card IO phonegap plugin is not working   .controller('paymentsController', function ($scope, $localStorage, $log, $state, $window, $ionicModal, Payment, ItemList, SweetAlert) {

$scope.scanCard = function(){

  var cardIOResponseFields = [
    "card_type",
    "redacted_card_number",
    "card_number",
    "expiry_month",
    "expiry_year",
    "cvv",
    "zip"
  ];

  var onCardIOComplete = function(response) {
    for (var i = 0, len = cardIOResponseFields.length; i < len; i++) {
      var field = cardIOResponseFields[i];
      console.log(field + ": " + response[field]);
    }
  };

  var onCardIOCancel = function() {
    console.log("card.io scan cancelled");
  };

  var onCardIOCheck = function (canScan) {
    console.log("card.io canScan? " + canScan);
    var scanBtn = angular.element($("#scanBtn")).scope();
    //var scanBtn = document.getElementById("scanBtn");
    if (!canScan) {
      scanBtn.innerHTML = "Manual entry";
    }
  };

  CardIO.scan({
      "collect_expiry": true,
      "collect_cvv": false,
      "collect_zip": false,
      "shows_first_use_alert": true,
      "disable_manual_entry_buttons": false
    },
    onCardIOComplete,
    onCardIOCancel
  );

  CardIO.canScan(onCardIOCheck);
};

}
I installed a card reader plugin in my phonegap(i'm using ionic as a framework) the problem I'm having is that the plugin doesn't work. this is the plugin I'm using https://github.com/card-io/card.io-iOS-SDK-PhoneGap.
this is my view.
<button id="scanBtn" ng-click="scanCard()" class="button button-large button-block button-light">Scan Card</button>

when the user click on the #scanBtn it loads this script.
      var cardIOResponseFields = [
    "card_type",
    "redacted_card_number",
    "card_number",
    "expiry_month",
    "expiry_year",
    "cvv",
    "zip"
  ];

  var onCardIOComplete = function(response) {
    for (var i = 0, len = cardIOResponseFields.length; i < len; i++) {
      var field = cardIOResponseFields[i];
      console.log(field + ": " + response[field]);
    }
  };

  var onCardIOCancel = function() {
    console.log("card.io scan cancelled");
  };

  var onCardIOCheck = function (canScan) {
    console.log("card.io canScan? " + canScan);
    var scanBtn = angular.element($("#scanBtn")).scope();
    //var scanBtn = document.getElementById("scanBtn");
    if (!canScan) {
      scanBtn.innerHTML = "Manual entry";
    }
  };

  CardIO.scan({
      "collect_expiry": true,
      "collect_cvv": false,
      "collect_zip": false,
      "shows_first_use_alert": true,
      "disable_manual_entry_buttons": false
    },
    onCardIOComplete,
    onCardIOCancel
  );

  CardIO.canScan(onCardIOCheck);
};

my app doesn't work in my browser or using the phonegap app, but when i launch the ionic emulator only the entry to input the card form shows up and no camera loads to scan the card, which led me to believe the camera execution is failing.
When load the cardio on my browser i get the following console error:
ReferenceError: CardIO is not defined.

A: Try the same on device.
I got the same error on browser and it works well on the device. You could think of this as the camera / or contacts picker plugin - which will work only on device - and not on sim or browser.

A: All cordova plugins will throw an error when running on browsers or emulators. Always use them on devices and inside
$ionicPlatform.ready(function() { ... });


text:
Q: Combinations with missings so i am new to C# and I've got this task:
I have a list of unidentified number of people(ex. 5 people). The task is to get the groups of people where the person and the person after him in the list can't be in the same group.
EX:
5 people
{1},{2},{3},{4},{5},{1,3},{1,4},{1,5},{2,4},{2,5},{3,5},{1,3,5}
I used the combination method from the link
http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G
and i have this code
private void button3_Click(object sender, EventArgs e)
    {
        outputBox.Clear();
        int nr = Convert.ToInt32(nmbrBox.Value);
        double tmp = Math.Pow(2, nr);
        double combs = tmp - 1;
        List<int> list = new List<int>();
        for (int i = 1; i <= nr; i++ )
        {
            list.Add(i);
        }

        outputBox.AppendText(combs.ToString() + " combinari\n\n");

        List<string> allCombinations = new List<String>();
        for (int i = 1; i <= list.Count; i++)
        {
            var combis = new Facet.Combinatorics.Combinations<int>(list, i, Facet.Combinatorics.GenerateOption.WithoutRepetition);
            allCombinations.AddRange(combis.Select(c => string.Join("", c)));
        }

        foreach (var combi in allCombinations)
        {
            outputBox.AppendText(combi + "\n");
        }
    }

How do i make it show me only the result i want?

A: I can offer a straightforward solution. Considering you have your group string in format "1 2 3" or "1" or "1 2", foreach group in allCombinations use a validation method like:
public static bool IsGroupValid(string group)
{
    var indexes= group.Split(' ').Select(x=>Int32.Parse(x)).ToList();
    for (int i = 0; i < indexes.Count; i++)
    {
        if (indexes.Any(x=>x+1==indexes[i]))
            return false;
    }
    return true;
}

So it'd look like that:
foreach (var combi in allCombinations)
{
    if(IsGroupValid(combi))
        outputBox.AppendText(combi + "\n");
}

A: You question is a mix of Windows Forms and some combinatorial code. In my answer I will focus on the combinatorial aspect of your question. The library you are using seems to be very nice but to create a self-contained answer I have decided to create my own method for generating combinations. The implementation is using LINQ and recursion in a way that is not good for performance but as long as you do not have too many elements that should not be a problem.
To create the combinations of a source sequence of a given length the following extension method is used (you have to put this inside a static class):
public static IEnumerable<IEnumerable<T>>  Combinations<T>(this IEnumerable<T> source, Int32 count)
  where T : IComparable<T> {
  if (count == 1)
    return source.Select(t => new T[] { t });
  return Combinations(source, count - 1)
    .SelectMany(
      values => source.Where(value => value.CompareTo(values.Last()) > 0),
      (values, value) => values.Concat(new T[] { value })
    );
}

If the input is [1, 2, 3, 4, 5] and count is 4 then the output is [1, 2, 3, 4], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5].
To make it easier to determine if a combination is valid another extension method is used to create tuples from a sequence:
public static IEnumerable<Tuple<T, T>> ToTuples<T>(this IEnumerable<T> source) {
  using (var enumerator = source.GetEnumerator()) {
    if (!enumerator.MoveNext())
      yield break;
    var lastValue = enumerator.Current;
    while (enumerator.MoveNext()) {
      yield return Tuple.Create(lastValue, enumerator.Current);
      lastValue = enumerator.Current;
    }
  }
}

If the input is [1, 2, 4, 5] then the output is [[1, 2], [2, 4], [4, 5]].
A predicate is used to determine if given combination is valid. The combination is assumed to be a sequence of indices so two consequtive indices has to be at least 2 a part to be valid:
Boolean IsValidCombination(IEnumerable<Int32> combination) {
  return combination
    .ToTuples()
    .All(tuple => tuple.Item2 - tuple.Item1 > 1);
}

Now you can put it together. In this case the input is an array of names:
var people = new[] { "Arthur", "Bertha", "Cristobal", "Dolly", "Edouard" };
var indices = Enumerable.Range(0, people.Length);
var result = Enumerable
  .Range(1, people.Length - 1)
  .SelectMany(i => indices.Combinations(i))
  .Where(IsValidCombination)
  .Select(combination => combination.Select(i => people[i]));

This gives the following result:

Arthur
Bertha
Cristobal
Dolly
Edouard
Arthur, Cristobal
Arthur, Dolly
Arthur, Edouard
Bertha, Dolly
Bertha, Edouard
Cristobal, Edouard
Arthur, Cristobal, Edouard


text:
Q: Is python Queue.queue get and put thread safe? http://docs.python.org/2/library/queue.html#Queue.Queue.put
It seems a naive question, but I didn't find the answer on the docs nor with Googling, so are these methods thread safe ? I assume so otherwise there is no point in this queue.

A: See 8.10 Queue — A synchronized queue class (at the top)

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads.


text:
Q: Custom taxonomy and list of pages I'm wondering how to add a list of existing pages to a custom taxonomy as terms.
My goal is to be able to add a reference to a page for an uploaded attachment.
I'm able to create the taxonomy and it shows up, it's just not populated.
Also - if there's a better way to go about this I'm all ears as well.
eg:
I have pages "Info","Contact"
I want these items to show up as terms.

A: I solved this by getting the pages and inserting them with wp_insert_term. Note: I only need a specific page so this is more specific than above.
// create a new taxonomy
function add_product_pages_to_attachments() {
    register_taxonomy(
        'productpages',
        'attachment',
        array(
            'hierarchical'=>true,
            'label' => __( 'Assign to Product Page' ),
            'rewrite' => array( 'slug' => 'productpages' ),
            'show_in_nav_menus'=>false,

        )
    );
}
add_action( 'init', 'add_product_pages_to_attachments' );

//populate the list
function populate_product_list()
{
    //get my specific page id which will be used in the 'parent' argument
    $id = get_page_by_path("products")->ID;
    $args   = array(
        'post_type'=>'page',
        'parent'=>$id
    );
    //get all the pages matching the arguments above
    $pages = get_pages($args);
    //loop through the pages and add them to the taxonomy list
    foreach ($pages as $page) {
        wp_insert_term($page->post_title,'productpages');
    }
    delete_option("productpages");
}
add_action('init','populate_product_list');


text:
Q: PHP Xdebug installation settings Here are my php xdebug settings
When I run my php code I get the errors in this format
However xdebug is perfectly working with netbeans but xdebug not showing errors in formatted manner.
Thanks.

A: check your php.ini if you have the
html_errors = On

and confirm it from your phpinfo()


text:
Q: JSP rendering issues, before struts 2 action and after struts 2 action I am working on struts 2 project and facing a weird issue badly need your help on that issue
1 -- I have developed a web page with bootstrap css which is actually in local
      I mean css and js files are in my local
2 -- I have developed a struts action for that jsp, when you clock a button it will call a action class and do some business logic and returns to same page
My problem is when that page loads first time css is been applied properly but after button click flow will go to struts2 config and mapped to action on return success from that action I am returining to same jsp, except this time on the same jsp css are not been properly loaded
and that action I am referring now is in a struts-school.xml which is been included into struts.xml   --  I don't believe this would be the issue but just in case
Note : it is a maven project, which is actually a web project when I started but later converted to maven
Please go through the code and images of the same jsp when it renderd before struts 2 action and after struts 2 action
JSP  "schoolHome.jsp"
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="viewport" content="width = device-width, initial-scale = 1">
  <link href="CustomCssAndScript/bootstrap/css/bootstrap.min.css" rel="stylesheet">

<title>Insert title here</title>

    <%@include file="schoolHeaderMenus/schoolHeader.jsp" %>
    <%@include file="schoolLeftSideMenus/sideMenu1.jsp" %>

OTHER INCLUDED JSP "schoolHeader.jsp"
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="viewport" content="width = device-width, initial-scale = 1">
  <link href="CustomCssAndScript/bootstrap/css/bootstrap.min.css" rel="stylesheet">

<title>Insert title here</title>

 Home

Students Managment

Staff Managment

Library Managment

  Add Members

 Add Teacher's

  Add Student's

  Add Non-Teaching Staff

  Add Parent's

  Add Branche's

  Other Managment's

 Transport Managment

  Non-Teaching Staff Managment

  Furniture Managment

  Building Managment

  Complaints

 Hello, <s:property value="#session.user.articleUserName"/>

 Logout

 Update Profile

  View your profile

INCLUDED OTHER JSP "sideMenu1.jsp"
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <link href="CustomCssAndScript/bootstrap/css/bootstrap.min.css" rel="stylesheet">

<meta name="viewport" content="width = device-width, initial-scale = 1">
<title>Insert title here</title>

     Menu

  Dash Board

 Setting's

  Acadamic Detail's

  Privilege's

  Assign Cources

  Enquiry List

  Event Managment

  Academic's

  Subjects and Batched

  Lession Planning

  Time Table

  Exams

  Notes and Assignment's

struts-school.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="schoolStrutsConfig" namespace="/school" extends="struts-default">
        <action name="addTeachersAdminAction" class="baci.portal.school.schoolActions.SchoolAdminAction" method="addPeople">
            <result name="teacher">schoolHome.jsp</result>
            <result name="student">addStudent.jsp</result>
            <result name="nonteaching">addNonteaching.jsp</result>
            <result name="parent">addParent.jsp</result>
            <result name="branch">addBranch.jsp</result>
        </action>
    </package>
</struts>

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

    <package name="default" namespace="/" extends="struts-default">
        <action name="login" class="baci.portal.actions.UserActions" method="login">
            <result name="it">portal.jsp</result>
            <result name="school">school/schoolHome.jsp</result>
            <result name="input">index.jsp</result>
        </action>

        <action name="postArticle" class="baci.portal.actions.ArticleAction" method="postArticle">
            <result name="success">portal.jsp</result>
        </action>
        <action name="viewArticle" class="baci.portal.actions.ArticleAction" method="viewArticle">
            <result name="success">article.jsp</result>
        </action>
        <action name="comment" class="baci.portal.actions.ArticleAction" method="comment">
            <result name="success">article.jsp</result>
        </action>
        <action name="articleSolution" class="baci.portal.actions.ArticleAction" method="articleSolution">
            <result name="success">article.jsp</result>
        </action>
        <action name="viewProfile" class="baci.portal.actions.UserActions" method="viewProfile">
            <result name="success">profile.jsp</result>
            <result name="input">index.jsp</result>
        </action>
        <action name="logout" class="baci.portal.actions.UserActions" method="logout">
            <result name="success">index.jsp</result>
            <result name="input">index.jsp</result>
        </action>
        <action name="viewPublicProfile" class="baci.portal.actions.UserActions" method="viewPublicProfile">
            <result name="success">publicProfile.jsp</result>
            <result name="input">index.jsp</result>
        </action>
        <action name="signUp" class="baci.portal.actions.UserActions" method="signUp">
            <result name="success">registration.jsp</result>
            <result name="fail">index.jsp</result>
        </action>
        <action name="registerUser" class="baci.portal.actions.UserActions" method="registerUser">
            <result name="success">index.jsp</result>
            <result name="false">registration.jsp</result>
        </action>
        <action name="checkAval" class="baci.portal.actions.UserActions" method="checkAval">
        </action>
        <action name="homePage" class="baci.portal.actions.UserActions" method="homePage">
            <result name="success">portal.jsp</result>
            <result name="input">index.jsp</result>
        </action>
        <action name="publicProfile" class="baci.portal.actions.UserActions" method="publicProfile">
            <result name="success">portal.jsp</result>
            <result name="input">index.jsp</result>
        </action>
    </package>
    <include file="/struts-school.xml"></include>
</struts>


text:
Q: Badge Based on Total Number of Questions Shared? I'd like to propose a badge for the "volume" of shares (hopefully I'm not contributing to annoying dups) ...
Sharing Badge
Currently the badges are based of the "volume" of vists to particular questions ... based on shares, but not on the number of total shares overall.
This has two major drawbacks as I see it ...

*

*Tags that have less overall traffic
(while still being very valid) are
unfairly misrepresented. The idea
being a question/anwser might be
really good +10 or more but the
traffic (in general) is lower than a
more "popular" topic.

*By only rewarding super popular questions there is no incentive to continually share links to questions ... which I belive would be encouraged by a badge rewarding such behavoir? Maybe something like: shared 10,100,500 ... whatever ... posts?

What are you meta-people's thoughts?

A: You'd need to have a minimum number of visits for those links (otherwise how would the system know that you'd posted one?).
Given that it doesn't seem that there's much to distinguish this from the Announcer badge.