text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Redux store isn't getting updated
I have built this app using create-react-native-app, the action is dispatched but the state isn't being updated and I'm not sure why.
I see the action being logged (using middleware logger) but the store isn't getting updated, I am working on Add_Deck only for now
Here is my reducer:
// import
import { ADD_CARD, ADD_DECK } from './actions'
// reducer
export default function decks(state ={}, action){
switch(action.type){
case ADD_DECK:
return {
...state,
[action.newDeck.id]: action.newDeck
}
case ADD_CARD:
return {
...state,
[action.deckID]: {
...state[action.deckID],
cards: state[action.deckID].cards.concat([action.newCard])
}
}
default: return state
}
}
Actions file:
// action types
const ADD_DECK = "ADD_DECK";
const ADD_CARD = "ADD_CARD";
// generate ID function
function generateID() {
return (
"_" +
Math.random()
.toString(36)
.substr(2, 9)
);
}
// action creators
function addDeck(newDeck) {
return {
type: ADD_DECK,
newDeck
};
}
// export
export function handleAddDeck(title) {
return dispatch => {
const deckID = generateID();
// const newDeck = { id: deckID, title, cards: [] };
dispatch(addDeck({ id: deckID, title, cards: [] }));
};
}
function addCard(deckID, newCard) {
// { question, answer }, deckID
return {
type: ADD_CARD,
deckID,
newCard
};
}
// export
export function handleAddCard(deckID, content) {
// { question, answer }, deckID
return dispatch => {
const newCard = { [generateID()]: content };
dispatch(addCard(deckID, newCard));
};
}
And react-native component:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import {red, white} from '../utils/colors'
import { connect } from 'react-redux'
import { handleAddDeck } from '../redux/actions'
class AddDeck extends Component {
state = {
text:""
}
handleSubmit = () => {
this.props.dispatch(handleAddDeck(this.state.text))
this.setState(()=>{
return { text: ""}
})
}
render() {
return (
<View style={styles.adddeck}>
<Text> This is add deck</Text>
<TextInput
label="Title"
style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Deck Title"
value={this.state.text}
/>
<TouchableOpacity style={styles.submitButton} onPress={this.handleSubmit}>
<Text style={styles.submitButtonText}>Create Deck</Text>
</TouchableOpacity>
</View>
);
}
}
function mapStateToProps(decks){
console.log("state . decks", decks)
return {
decks
}
}
export default connect(mapStateToProps)(AddDeck);
const styles = StyleSheet.create({
adddeck: {
marginTop: 50,
flex: 1
},
submitButton: {
backgroundColor: red,
padding: 10,
margin: 15,
height: 40,
},
submitButtonText: {
color: white
}
});
A:
I guess you forgot to export your types from the actions file thus the switch(action.type) does not trigger the needed case statement.
Maybe try to add as the following:
export const ADD_DECK = "ADD_DECK";
export const ADD_CARD = "ADD_CARD";
Or further debugging just to see if the values are the ones what you are looking for:
export default function decks(state = {}, action) {
console.log({type:action.type, ADD_DECK}); // see what values the app has
// further code ...
}
I hope that helps! If not, let me know so we can troubleshoot further.
| {
"pile_set_name": "StackExchange"
} |
Q:
Application of Poisson Process
Am currently working on a Stochastic Poisson process on my project. I have thought and settled on the below scenario which I think is appropriate. However, solving it, I'm not getting what I expect.
I want to cross a road at a spot where cars pass according to a Poisson process with a rate of ฮป.
I will begin to cross as soon as I see there will be no cars passing for the next C time units.
I have taken N=the number of cars that pass before I cross and T= the time I begin to cross the road.
I want to determine the E(N) and Also E(T). What I know is that to find the E(T), I will have to condition on N
A:
Let $T$ be the time the first car passes.
$
\begin{align*}
E(N)&=\int_0^{\infty}E(N\mid T=t)\lambda e^{-\lambda t}\,dt \\
&=\int_0^C(1+E(N))\lambda e^{-\lambda t}\,dt \\
\end{align*}
$
We solve for $E(N)$ and find that $E(N)=(1-e^{-\lambda C})e^{\lambda C}.$ Also,
$
\begin{align*}
E(T)&=\int_0^{\infty}E(T\mid T=t)\lambda e^{-\lambda t}\,dt \\
&=\int_0^C(t+E(T))\lambda e^{-\lambda t}\,dt.
\end{align*}
$
Solving for $E(T)$ yields $\frac{e^{\lambda C}-\lambda C-1}{\lambda}$ when $\lambda,C>0$. Of course if $\lambda=0$ or $C=0$ then $E(T)=0$.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Endgame, why didn't the Hulk's arm regenerate?
According to the comics, the Hulk has very fast regeneration abilities similar to Deadpool.
At the end of Avengers: Endgame, the Hulk has his charred right arm in a cast because of the burns from using the Infinity Gauntlet to "unsnap" everyone who died at the end of Avengers: Infinity War.
Why hasn't it regenerated back yet, or even partially regenerated?
A:
Because that's not an ability that they've covered in the MCU. In the movies so far they've had The Hulk be basically invulnerable, in fact getting stronger as he soaks up hits in his standalone films, we haven't seen him do any healing at all on screen let alone at an accelerated rate. I understand that Endgame is already a long movie, ten more minutes run time to explain that The Hulk can regenerate, and oh that's always been a thing we just hadn't noticed was probably not a good idea.
Alternately the fact that the damage was done by the Infinity Stones may mean that he simply can't regenerate.
A:
Because the damage was caused by the Infinity Gauntlet
Joe Russo has confirmed that the damage is "permanent" and compares it to the damage Thanos receives from using the Infinity Gauntlet. As such it is safe to assume the reason is because the damage came from the Infinity Gauntlet and so the Infinity Stones. The amount of power needed to unsnap, and in Thanos' case snap, is what caused such irreversible damage.
โHeโs lost an arm,โ Russo says. โHe lost Natasha. Thatโs not coming back. Heโs damaged himself. I donโt know. Itโs interesting. Thatโs permanent damage, the same way that it was permanent damage with Thanos. Itโs irreversible damage. His arm, if you noticed, is a lot skinnier. Itโs blackened. So, he loses a lot of strength there.โ
Russo does acknowledge that โpermanentโ means something different a world of magic and super science, but thatโs not his concern any longer.
โBut who knows? Thereโs a lot of smart people left,โ he says. โMaybe someone helps him repair that. Maybe someone gives him a new arm. I have no idea where that character goes from here. The nice thing is we didnโt have to pay attention to where it goes after this, we just try to tell a satisfying ending.โ
Comicbook, Avengers: Endgame Director Reveals Hulk's Injury Is Permanent
A:
In the comics Professor Hulk has the benefit of Banner's brain but is no where near as strong as primitive Hulk. In fact when Professor Hulk gets to angry he reverts to โpuny Bannerโ with Hulk's primitive mind.
Therefore this delay in healing does follow the comic book lore.
In addition this is an Infinity Gauntlet. Banner already states that it gives off tremendous radiation that will hurt him.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use JSON Web Token (JWT) Grant for docusign
How to use JSON Web Token (JWT) Grant for docusign access token. Please provide full example of code (laravel)
Thanks
A:
You can find detailed PHP code examples that show both authentication flows, including JWT.
The JWT authentication code is using the DocuSign eSign PHP SDK. Here is a snippet:
/**
* Get JWT auth by RSA key
*/
private function configureJwtAuthorizationFlowByKey() {
self::$apiClient->getOAuth()->setOAuthBasePath($GLOBALS['JWT_CONFIG']['authorization_server']);
$privateKey = file_get_contents($_SERVER['DOCUMENT_ROOT'] .'/'. $GLOBALS['JWT_CONFIG']['private_key_file'], true);
$response = self::$apiClient->requestJWTUserToken(
$aud = $GLOBALS['JWT_CONFIG']['ds_client_id'],
$aud = $GLOBALS['JWT_CONFIG']['ds_impersonated_user_id'],
$aud = $privateKey,
$aud = $GLOBALS['JWT_CONFIG']['jwt_scope']
);
To use this code you would need to obtain an integration key, and RSA Keypair (use private key) as well as the GUID of the user you're trying to impersonate.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I download information from a website if it returns XML/JSON in its response?
Does Python3 have a built in method to do this? Any guidance at all would be great! :)
The website in question exposes all of its information and even gives you an API key to use.
A:
Python includes a json module that can do the conversion for you. For downloading the actual data from the web site, use urllib.request.
| {
"pile_set_name": "StackExchange"
} |
Q:
I want to prove some properties about list, but am stuck at induction
I tried following proof,
Require Import List Omega.
Import ListNotations.
Variable X : Type.
Lemma length_n_nth_app_error_same : forall (n:nat) (x:X) (l:list X),
n <= length l -> 0 < n -> nth_error l n = nth_error (l ++ [x]) n .
Proof.
intros.
induction l eqn:eqHl.
- unfold length in H. omega.
-
but I'm stuck, as what I have is only
1 subgoal
n : nat
x : X
l : list X
a : X
l0 : list X
eqHl : l = a :: l0
H : n <= length (a :: l0)
H0 : 0 < n
IHl0 : l = l0 ->
n <= length l0 ->
nth_error l0 n = nth_error (l0 ++ [x]) n
______________________________________(1/1)
nth_error (a :: l0) n = nth_error ((a :: l0) ++ [x]) n
I've met some similar cases also for other proofs on lists.
I don't know if the usual induction would be useful here.
How should I prove this?
Should I use generalize?
A:
Your theorem is wrong. Maybe your understanding of nth_error is incorrect.
Specifically, when n = length l, nth_error l n returns None while nth_error (l ++ [x]) n returns Some x.
Require Import List Omega.
Import ListNotations.
Lemma length_n_nth_app_error_not_always_same :
(forall (n:nat) (X:Type) (x:X) (l:list X),
n <= length l -> 0 < n -> nth_error l n = nth_error (l ++ [x]) n)
-> False.
Proof.
intros.
assert (1 <= 1) by omega. assert (0 < 1) by omega.
specialize (H 1 nat 2 [1] H0 H1). simpl in H. inversion H. Qed.
On the other hand, proving a similar theorem with fixed inequality is easy:
Lemma length_n_nth_app_error_same : forall (n:nat) (X:Type) (x:X) (l:list X),
n < length l -> nth_error l n = nth_error (l ++ [x]) n .
Proof.
induction n; intros.
- simpl. destruct l; simpl in *.
+ omega.
+ reflexivity.
- simpl. destruct l; simpl in *.
+ omega.
+ apply IHn. omega. Qed.
Note that I used induction n instead of induction l. It is mainly because nth_error does recursive calls on decreasing n.
Also, if you felt like an induction hypothesis is not general enough, it is probably because your order of intros and induction was wrong. The rule of thumb is to start the proof by induction, and then intros the variables. If it is still not enough, you can revert dependent all the variables other than the one to do induction, and then induction x; intros.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I clear text in JTable when type?
Can I make my textField in JTable acts like a cell in Excel?
Clear the text when typing in but can editing when get into the cell.
I think these 2 operations will goes to the same event. Am I wrong?
I try to use the keyPressed but nothing work. TT-TT
Here is my code
private JTable getTblMaster() {
if (tblMasterData == null) {
tblMasterData = new JTable() {
private static final long serialVersionUID = 1L;
public TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = getColumnModel()
.getColumn(column);
TableCellEditor editor = tableColumn.getCellEditor();
try {
if (editor == null) {
final JTextField text = new JTextField();
/*
text.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e){
}
});
SwingUtilities.invokeLater(new Runnable(){
public void run(){
}
});
*/
editor = new DefaultCellEditor(text);
;
return editor;
}
} catch (Exception e) {
LogWriter.error(e);
}
return editor;
}
};
}
return tblMasterData;
}
Any suggestion?
A:
better could be select all text in the JTable cell
text.setText(text.getText())
text.selectAll
by wrapping into invokeLater()
great workaround Table Select All Editor by @camickr
A:
Ohh! trashgod. Your example saved my life :D
All I needed was the code below and it worked. How easy! Thank you very very much.
private JTable getTblMaster() {
if (tblMasterData == null) {
tblMasterData = new JTable() {
public boolean editCellAt(int row, int column, EventObject e){
boolean result = super.editCellAt(row, column, e);
final Component editor = getEditorComponent();
if (editor == null || !(editor instanceof JTextComponent)) {
return result;
}
if (e instanceof KeyEvent) {
((JTextComponent) editor).selectAll();
}
return result;
} ....
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with loop in C
i'm trying to compute "2^0 + 2^1 + 2^2 + ... + 2^14", using the following program(i'm a newbie and can only compute a exponent by multiply itself a certain times). The result should be 32767, but i ran it and got 270566475, i thought for long but can't figure out why...
#include <stdio.h>
int main(void)
{
int i, e, exponent, sum;
e = 1;
exponent = 1;
sum = 1;
for (i = 1; i <=14; i++)
{
for (e = 1; e <= i; e++)
{
exponent *= 2;
}
sum += exponent;
}
printf("%d\n", sum);
return 0;
}
So what's wrong with this??? Thanks!!!
A:
You don't need the inner loop. Just execute exponent *= 2 once, directly inside the outer loop. BTW, I think you have to do it after the sum += ....
Also, you could start with sum = 0 and i = 0, which is closer to the math you described.
A:
Look at your inner loop by itself. It's trying to calculate, for one specific value of i, 2^i.
But exponent does not start at 1 every time. So you go into that loop with exponent already some very large value.
for (i = 1; i <=14; i++)
{
exponent = 1;
for (e = 1; e <= i; e++)
{
exponent *= 2;
}
sum += exponent;
}
Now you've reset exponent (which, to be clear, isn't the exponent at all but the calculated result) for each new power of 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Relationship between Riemannian Exponential Map and Lie Exponential Map
It is well known that for a matrix Lie group the Lie exponential map is $e ^z$. This maps a tangent vector $z$ at the identity to a group element.
On the other hand the general Riemannian exponential map centered at point $x$ is given by $\exp _x \triangle$ which maps a tangent vector $\triangle$ at point $x$ (not necessarily identity element) to a group element.
Is there a relationship between these two exponential maps?
For example is below formula correct? If so, are there any conditions involved?
$\exp _x \triangle = xe ^{x^{-1}\triangle}$
A:
Notice that you need to pick a metric on a Lie group for the "general Riemannian exponential map" to be defined.
If you happen to pick an invariant metric on a Lie group, then every geodesic is (locally) a translate of a 1-parameter subgroup (so essentially both exponentials are the same thing)
I don't know what happens if there are no invariant metrics.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I load dynamic HTML data in a WebBrowser from Windows Phone 8?
I'm developing a new App but I have some issues because I need to do something like an hybrid App but I have an issue:
I need to use a SQLite DB where I'm updating some new tips for our users. This data comes from a Web Service however our App is designed with XAML and C# and I'd like to know if there's any way to access to that DB from JS, this is my code:
$(function () {
var db = openDatabase('db.sqlite', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM info', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
alert(results.rows.item[i].log);
}
}, null);
});
});
It didn't do anything just said me: [object Error] with the SQLite code no error or anything or anyone has any idea if I can set HTML information directly in the control (everything has been tested on the emulator). Thanks for your time and help.
A:
After some tests and research I create this codes:
XAML:
You need to set a WebBrowser Control and set a source and enable Script and Geolocation (if you need them).
<phone:WebBrowser x:Name="wv" IsScriptEnabled="True" IsGeolocationEnabled="True" Source="/test.html" LoadCompleted="wv_LoadCompleted" />
Create a class or something where you are going to manipulate SQLite:
class data
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int idData { get; set; }
public string info { get; set; }
}
public class sqliteDB
{
private string dbPath;
public SQLiteConnection db;
public sqliteDB()
{
this.dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
}
public string getPath() {
return this.dbPath;
}
public void close()
{
db.Close();
}
public void createDB()
{
if (!FileExists("db.sqlite").Result)
{
open();
using (this.db)
{
this.db.CreateTable<data>();
}
}
}
public void open()
{
this.db = new SQLiteConnection(dbPath);
}
private async Task<bool> FileExists(string fileName)
{
var result = false;
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
result = true;
}
catch { }
return result;
}
}
To set information in your example to have data in the DB
string infoData;
public MainPage()
{
InitializeComponent();
infoData = @"<table class='infobox vcard' style='width: 22em'><tbody><tr><th colspan='2' class='n' style='text-align: center; font-size: 132%;'><span class='fn'><span style='position: relative; bottom: 0.2em;'>Xi Jinping</span></span><br><span class='nickname'><span style='position: relative; top: 0.1em;'><span style='font-weight:normal;'><span lang='zh-hans' xml:lang='zh-hans'>???</span></span></span></span></th></tr><tr><td colspan='2' style='text-align: center'><a href='/wiki/File:Xi_jinping_Brazil_2013.png' class='image'><img alt='Xi jinping Brazil 2013.png' src='//upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Xi_jinping_Brazil_2013.png/220px-Xi_jinping_Brazil_2013.png' width='220' height='298' srcset='//upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Xi_jinping_Brazil_2013.png/330px-Xi_jinping_Brazil_2013.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Xi_jinping_Brazil_2013.png/440px-Xi_jinping_Brazil_2013.png 2x' data-file-width='519' data-file-height='704'></a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'><a href='/wiki/General_Secretary_of_the_Communist_Party_of_China' title='General Secretary of the Communist Party of China'>General Secretary</a> of the <a href='/wiki/Central_Committee_of_the_Communist_Party_of_China' title='Central Committee of the Communist Party of China'>Central Committee</a> of the <a href='/wiki/Communist_Party_of_China' title='Communist Party of China'>Communist Party of China</a></th></tr><tr><td colspan='2' style='text-align:center; background-color: lavender'><b><a href='/wiki/Incumbent' title='Incumbent'>Incumbent</a></b></td></tr><tr><td colspan='2' style='text-align:center'><span class='nowrap'><b>Assumed office</b></span><br>15 November 2012</td></tr><tr><th style='text-align:left;'>Deputy</th><td><a href='/wiki/Li_Keqiang' title='Li Keqiang'>Li Keqiang</a> <small>(<a href='/wiki/Politburo_Standing_Committee' title='Politburo Standing Committee' class='mw-redirect'>? 2nd in PSC</a>)</small></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Hu_Jintao' title='Hu Jintao'>Hu Jintao</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'><a href='/wiki/President_of_the_People%27s_Republic_of_China' title='President of the People's Republic of China'>President of the People's Republic of China</a></th></tr><tr><td colspan='2' style='text-align:center; background-color: lavender'><b><a href='/wiki/Incumbent' title='Incumbent'>Incumbent</a></b></td></tr><tr><td colspan='2' style='text-align:center'><span class='nowrap'><b>Assumed office</b></span><br>14 March 2013</td></tr><tr><th style='text-align:left;'>Premier</th><td><a href='/wiki/Li_Keqiang' title='Li Keqiang'>Li Keqiang</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Vice President</span></th><td><a href='/wiki/Li_Yuanchao' title='Li Yuanchao'>Li Yuanchao</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Hu_Jintao' title='Hu Jintao'>Hu Jintao</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'><a href='/wiki/Chairman_of_the_Central_Military_Commission' title='Chairman of the Central Military Commission'>Chairman of the CPC Central Military Commission</a></th></tr><tr><td colspan='2' style='text-align:center; background-color: lavender'><b><a href='/wiki/Incumbent' title='Incumbent'>Incumbent</a></b></td></tr><tr><td colspan='2' style='text-align:center'><span class='nowrap'><b>Assumed office</b></span><br>15 November 2012</td></tr><tr><th style='text-align:left;'>Deputy</th><td><a href='/wiki/Fan_Changlong' title='Fan Changlong'>Fan Changlong</a><br><a href='/wiki/Xu_Qiliang' title='Xu Qiliang'>Xu Qiliang</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Hu_Jintao' title='Hu Jintao'>Hu Jintao</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'><a href='/wiki/Supreme_Military_Command_of_the_People%27s_Republic_of_China' title='Supreme Military Command of the People's Republic of China'>Chairman of the PRC Central Military Commission</a></th></tr><tr><td colspan='2' style='text-align:center; background-color: lavender'><b><a href='/wiki/Incumbent' title='Incumbent'>Incumbent</a></b></td></tr><tr><td colspan='2' style='text-align:center'><span class='nowrap'><b>Assumed office</b></span><br>14 March 2013</td></tr><tr><th style='text-align:left;'>Deputy</th><td><a href='/wiki/Fan_Changlong' title='Fan Changlong'>Fan Changlong</a><br><a href='/wiki/Xu_Qiliang' title='Xu Qiliang'>Xu Qiliang</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Hu_Jintao' title='Hu Jintao'>Hu Jintao</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'>Chairman of the <a href='/wiki/National_Security_Commission_of_the_Communist_Party_of_China' title='National Security Commission of the Communist Party of China'>National Security Commission</a></th></tr><tr><td colspan='2' style='text-align:center; background-color: lavender'><b><a href='/wiki/Incumbent' title='Incumbent'>Incumbent</a></b></td></tr><tr><td colspan='2' style='text-align:center'><span class='nowrap'><b>Assumed office</b></span><br>25 January 2014</td></tr><tr><th style='text-align:left;'>Deputy</th><td><a href='/wiki/Li_Keqiang' title='Li Keqiang'>Li Keqiang</a><br><a href='/wiki/Zhang_Dejiang' title='Zhang Dejiang'>Zhang Dejiang</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td>New position</td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'>First Secretary of the <a href='/wiki/Secretariat_of_the_Communist_Party_of_China_Central_Committee' title='Secretariat of the Communist Party of China Central Committee'>Central Secretariat of the Communist Party of China</a></th></tr><tr><td colspan='2' style='border-bottom:none; text-align:center'><span class='nowrap'><b>In office</b></span><br>22 October 2007 โ 15 November 2012</td></tr><tr><th style='text-align:left;'><span class='nowrap'>General Secretary</span></th><td><a href='/wiki/Hu_Jintao' title='Hu Jintao'>Hu Jintao</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Zeng_Qinghong' title='Zeng Qinghong'>Zeng Qinghong</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Succeeded by</span></th><td><a href='/wiki/Liu_Yunshan' title='Liu Yunshan'>Liu Yunshan</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'><a href='/wiki/Vice_President_of_the_People%27s_Republic_of_China' title='Vice President of the People's Republic of China'>Vice President of the People's Republic of China</a></th></tr><tr><td colspan='2' style='border-bottom:none; text-align:center'><span class='nowrap'><b>In office</b></span><br>15 March 2008 โ 14 March 2013</td></tr><tr><th style='text-align:left;'>President</th><td><a href='/wiki/Hu_Jintao' title='Hu Jintao'>Hu Jintao</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Zeng_Qinghong' title='Zeng Qinghong'>Zeng Qinghong</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Succeeded by</span></th><td><a href='/wiki/Li_Yuanchao' title='Li Yuanchao'>Li Yuanchao</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'>President of the <a href='/wiki/Central_Party_School_of_the_Communist_Party_of_China' title='Central Party School of the Communist Party of China'>CPC Central Party School</a></th></tr><tr><td colspan='2' style='border-bottom:none; text-align:center'><span class='nowrap'><b>In office</b></span><br>22 December 2007 โ 15 January 2013</td></tr><tr><th style='text-align:left;'>Deputy</th><td><a href='/wiki/Li_Jingtian' title='Li Jingtian'>Li Jingtian</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Preceded by</span></th><td><a href='/wiki/Zeng_Qinghong' title='Zeng Qinghong'>Zeng Qinghong</a></td></tr><tr><th style='text-align:left;'><span class='nowrap'>Succeeded by</span></th><td><a href='/wiki/Liu_Yunshan' title='Liu Yunshan'>Liu Yunshan</a></td></tr><tr><th colspan='2' style='background-color: lavender; text-align: center'>Personal details</th></tr><tr><th style='text-align:left;'>Born</th><td><span style='display:none'>(<span class='bday'>1953-06-15</span>)</span> 15 June 1953 <span class='noprint ForceAgeToShow'>(age 61)</span><br><a href='/wiki/Beijing' title='Beijing'>Beijing</a>, China</td></tr><tr><th style='text-align:left;'>Political party</th><td><a href='/wiki/Communist_Party_of_China' title='Communist Party of China'>Chinese Communist</a></td></tr><tr><th style='text-align:left;'>Spouse(s)</th><td><a href='/wiki/Peng_Liyuan' title='Peng Liyuan'>Peng Liyuan</a></td></tr><tr><th style='text-align:left;'>Children</th><td><a href='/wiki/Xi_Mingze' title='Xi Mingze'>Mingze</a></td></tr><tr><th style='text-align:left;'>Residence</th><td class='label'><a href='/wiki/Zhongnanhai' title='Zhongnanhai'>Zhongnanhai</a></td></tr><tr><th style='text-align:left;'><a href='/wiki/Alma_mater' title='Alma mater'>Alma mater</a></th><td><a href='/wiki/Beijing_101_Middle_School' title='Beijing 101 Middle School'>Beijing 101 Middle School</a><br><a href='/wiki/Tsinghua_University' title='Tsinghua University'>Tsinghua University</a></td></tr><tr><th style='text-align:left;'>Profession</th><td><a href='/wiki/Chemical_engineering' title='Chemical engineering'>chemical engineer</a></td></tr><tr><th style='text-align:left;'>Signature</th><td><a href='/wiki/File:Xi_Jinping_sign.svg' class='image' title='Xi Jinping's signature'><img alt='' src='//upload.wikimedia.org/wikipedia/commons/thumb/0/07/Xi_Jinping_sign.svg/128px-Xi_Jinping_sign.svg.png' width='128' height='59' srcset='//upload.wikimedia.org/wikipedia/commons/thumb/0/07/Xi_Jinping_sign.svg/192px-Xi_Jinping_sign.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/0/07/Xi_Jinping_sign.svg/256px-Xi_Jinping_sign.svg.png 2x' data-file-width='109' data-file-height='50'></a></td></tr></tbody></table>";
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
sqliteDB cn = new sqliteDB();
cn.createDB();
try
{
cn.open();
using (cn.db)
{
cn.db.RunInTransaction(() =>
{
cn.db.Insert(new data()
{
info = infoData
});
});
}
cn.close();
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
}
And then loads the information in your HTML page:
class dataInfo
{
public int idData { get; set; }
public string info { get; set; }
}
private void wv_LoadCompleted(object sender, NavigationEventArgs e)
{
sqliteDB cn = new sqliteDB();
cn.open();
string query = "SELECT * FROM data";
List<dataInfo> placeInfo = cn.db.Query<dataInfo>(query);
string[] args = { placeInfo[0].idData.ToString(), placeInfo[0].info };
wv.InvokeScript("callMe", args);
cn.close();
}
In your HTML code you need to have something like this:
<html>
<head>
<script src="jquery.js"></script>
<script>
function callMe(arg1, arg2) {
$("#status").html("arg1 is " + arg1 + " and arg2 is " + arg2 + "!");
}
</script>
</head>
<body>
<div id="status"></div>
</body>
The function from the script (CallMe) should have the same name from your InvokeScript in C# in the JS function you should have the same number of Variables that you're sending if you don't it won't work.
| {
"pile_set_name": "StackExchange"
} |
Q:
Kotlin suppress 'condition is always true'
Wasting more time scouring through the COUNTLESS number of inspections (which I know how to enable and disable), I cannot find ANY way to disable the particular inspection of 'Condition is always true' for my Kotlin (not Java) file in Android Studio. I know what I'm doing and don't need this inspection AT ALL, but more appropriately, I'd like to suppress it for the file or class or function or ANYTHING.
Incredibly frustrating, as always.
//I'm well aware the condition below is ALWAYS true
if(ANDROID_SUCKS) {
fml()
}
A:
In Kotlin, use ConstantConditionIfto ignore this warning :
@Suppress("ConstantConditionIf")
if(ANDROID_IS_AWESOME) {
fml()
}
A:
In Android Studio,
put text cursor in the condition you'd like to suppress,
press Alt+Enter on your keyboard and this pops up:
Simplify expression โฏ
Press right arrow on your keyboard,
select any of the options you like, for example:
Disable inspection
Suppress 'ConstantConditionIf' for statement/fun/class/file
A:
This is how you would do it in Java :
@SuppressWarnings("ConstantConditions") // Add this line
public int foo() {
boolean ok = true;
if (ok) // No more warning here
...
}
In Kotlin I think you have to use @Suppress("SENSELESS_COMPARISON") instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Drupal 7 - delete own account
I just installed drupal-7.16. I would like to have following functionality:
As a non-admin user I would like to delete/block my own account.
Is it possible?
I found User Delete module, but there is no version for drupal 7.x.
A:
OK, I found that it's possible from drupal properties.
Just log in as admin, go to People -> Permission
and enable permission "Cancel own user account" for authenticated users.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regarding edit summary input validation
I am writing this to inform you about a little bug (input validation) in your site.
As I am active on your site, I found that whenever I edit an answer given by any user, I have to pass text in the "Edit Summary" field at the end of the edited answer.
Now, it should be a proper and real edit summary, but I have checked it by writing 12345679801234567890. That is, any non-text value or number value, and it accepts it which it should not do.
This is a request to fix it.
A:
We're not going to implement language recognition for the edit summary field. :) If nothing else, we support sites in various languages, and... just no. That way lies madness.
If someone makes a bunch of bad edits along with bad summaries, they're just going to get suspended and we'll call the problem handled. If the edits are good... the content of the summary doesn't matter that much, although it's polite and/or a good idea to explain what was changed for future readers.
| {
"pile_set_name": "StackExchange"
} |
Q:
Looking for the name of a sci-fi kids show from the late 90's / early 00's
I remember watching it in the early 00's but I live in Argentina so it may be from the 90's.
The animation was early cg (I think it was a bit more polished than ReBoot but not by much).
It had a pulp look and feel with the basic concept being the dashing space captain fighting the evil green martians in his skin tight spacesuit.
The main character was a young white guy with black hair and at some point a Martian defector joined the team.
What triggered my memory was replaying Fallout: New Vegas, where the bright red "space suit" looks just like the one I remember the main character wearing.
A:
Sounds like "Dan Dare: Pilot of the Future". There's a picture of the main character and the alien defector here:
https://www.imdb.com/title/tt0397775/
"The main character was a young white guy with black hair" - Well... young ISH, otherwise that's an accurate description of Dan.
"and at some point a Martian defector joined the team." - This character, Sondar, was actually Venusian. I believe he defected during the first story arc.
"The animation was early cg (I think it was a bit more polished than ReBoot but not by much)." - It was CG, and as it was a few years later than Reboot there would have been improvements in the technology since then.
"It had a pulp look and feel with the basic concept being the dashing space captain fighting the evil green martians in his skin tight spacesuit." - It was partly based on a comic series from the "pulp" era, and yep, that was pretty much the theme of the show. Except that they were Venusians.
I certainly do remember the spacesuits looking like your screenshot, but haven't found a picture to link to. There's a partial pic of a suited character here: https://joshuagamedesign.files.wordpress.com/2015/02/p2.png?w=300&h=209
| {
"pile_set_name": "StackExchange"
} |
Q:
Error Installing Atomic
I'm trying to install gems to my new Ruby project using bundle install. I've set the version of Ruby using rbenv on my OS X 10.8.4 box. I get the following error:
An error occurred while installing atomic (1.1.13), and Bundler cannot continue.
Make sure that `gem install atomic -v '1.1.13'` succeeds before bundling.
Kikime:jazzcatalog curt$ gem install atomic
Building native extensions. This could take a while...
Successfully installed atomic-1.1.13
1 gem installed
Kikime:jazzcatalog curt$ rbenv rehash
Kikime:jazzcatalog curt$ bundle install
Fetching gem metadata from https://rubygems.org/.........
Fetching gem metadata from https://rubygems.org/..
Using rake (10.1.0)
Using i18n (0.6.5)
Using minitest (4.7.5)
Using multi_json (1.7.9)
Installing atomic (1.1.13)
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/curt/.rbenv/versions/2.0.0-p247/bin/ruby extconf.rb
/Users/curt/.rbenv/versions/2.0.0-p247/bin/ruby: invalid option -R (-h will show valid options) (RuntimeError)
Gem files will remain installed in /Volumes/Data RAID/htdocs/jazzcatalog/vendor/bundle/gems/atomic-1.1.13 for inspection.
Results logged to /Volumes/Data RAID/htdocs/jazzcatalog/vendor/bundle/gems/atomic- 1.1.13/ext/gem_make.out
An error occurred while installing atomic (1.1.13), and Bundler cannot continue.
Make sure that `gem install atomic -v '1.1.13'` succeeds before bundling.
The first two lines are the end of the output from first attempt. As you can see, I then successfully installed atomic as requested. I then tried again and got the same error. I've seen a few errors with installing atomic, but none like this one. It seems to have a problem with the option -R. Since I didn't enter it in the first place, I don't know where to change it.
Update
I started all over rbenv set to version 2.0.0-p0 and and ran rails new jazz catalog -d mysql. It died at the same place with this error:
Installing atomic (1.1.13)
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/Users/curt/.rbenv/versions/2.0.0-p0/bin/ruby extconf.rb
creating Makefile
make
compiling atomic_reference.c
atomic_reference.c:50:9: warning: implicit declaration of function 'OSAtomicCompareAndSwap64' is invalid in C99 [-Wimplicit-function-declaration]
if (OSAtomicCompareAndSwap64(expect_value, new_value, &DATA_PTR(self))) {
^
1 warning generated.
linking shared-object atomic_reference.bundle
make install
/usr/bin/install -c -m 0755 atomic_reference.bundle /Volumes/Data RAID/htdocs/jazzcatalog/vendor/bundle/gems/atomic-1.1.13/lib
usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
[-o owner] file1 file2
install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
[-o owner] file1 ... fileN directory
install -d [-v] [-g group] [-m mode] [-o owner] directory ...
make: *** [install-so] Error 64
Gem files will remain installed in /Volumes/Data RAID/htdocs/jazzcatalog/vendor/bundle/gems/atomic-1.1.13 for inspection.
Results logged to /Volumes/Data RAID/htdocs/jazzcatalog/vendor/bundle/gems/atomic- 1.1.13/ext/gem_make.out
An error occurred while installing atomic (1.1.13), and Bundler cannot continue.
Make sure that `gem install atomic -v '1.1.13'` succeeds before bundling.
SOLVED
Sigh - does not handle spaces in path
A:
I had this problem. It turned out to be caused by installing Mac OS 10.9 (Mavericks), since Mavericks has a new stand alone command line tools separate from Xcode. To solve this, I deleted /Applications/Xcode and then installed the stand alone command line tools via:
Note: First line may not be needed, see comments below
sudo rm -rf /Applications/Xcode
xcode-select --install
then click 'install' from the OSX pop up window
source:
http://www.computersnyou.com/2025/2013/06/install-command-line-tools-in-osx-10-9-mavericks-how-to/
A:
For those who reach this page by googling, I solved a similar issue while Installing atomic (1.1.13) on mac this way:
sudo ln -s /usr/bin/llvm-gcc-4.2 /usr/bin/gcc-4.2
It seems to be because of conflicting Xcode updates.
A:
The error messages don't give the slightest clue as to what the real problem is. Bundler or a component it calls does not properly handle directory names with spaces in them. In my case it was .../Data RAID/... that caused the problem. Once I moved the project to a different drive where there would be no spaces in the path, everything worked fine. It appears it may be only the location of the gems that are the issue. In an earlier attempt, I created a project where the gems weren't located in a path containing spaces, but the project was. It didn't have any problems as far as I went with it. Notice also that the gem install atomic was successful.
| {
"pile_set_name": "StackExchange"
} |
Q:
Roku video playback fails in published app, works fine on dev
I'm facing a strange problem, my app which is essentially simple video player. Works perfectly fine when its a dev app side loaded via eclipse plugin. However when I package and publish it on Roku and then use it , it behaves strangely. First screen gets loaded fine the one which actually plays video shows up plays a frame or two and closes abruptly.
Does anyone know if roku package and publish thingys might be doing some rewrites that is making my app misbehave ?
A:
No - it does not touch the package once it had been zip-ed and sign-ed.
Try doing the upload directly with browser at port 80 of the player, as described in the documentation. The eclipse plugin is just a crutch, it cannot do anything that can't be done with a browser/telnet/curl at the box.
Also make sure you are testing in the very same conditions - on the same player, both the (private) channel from Roku servers and the "side-loaded" version.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not able to understand the plotting of 2-Dimensional graph in python matplotlib
The data corresponds to 3 rows where the first row is the marks of Exam number one of a particular student and row number two is the marks in Exam number 2 of the student. The third row corresponds to 0 or 1 indicating his probability to enter a particular University.
Here is the code given for plotting the graph which I am not able to understand.
# Find Indices of Positive and Negative Examples
pos = y == 1
neg = y == 0
# Plot Examples
pyplot.plot(X[pos, 0], X[pos, 1], 'k*', lw=2, ms=10)
pyplot.plot(X[neg, 0], X[neg, 1], 'ko', mfc='y', ms=8, mec='k', mew=1)
The output is the image given below:
Any help in explaining the code is appreciated.
A:
This code consists two different data, put together into one plot. They are all done with 'matplotlib' as you can read documentation here.
First plot is plotting only positive examples, marked as a star.
X[pos,0] is x-axis (first row, only positive examples) and X[pos,1] is y-axis (second row, only positive examples).
Rest of the arguments: k* means the style will be "stars", lw stands for "linewidth" and ms for "markersize", how big each start is.
Second plot is the same, only now for the circle which are negative. First two arguments are the same, only with negative examples. ko means to represent each dot a circle (hence o). mfc, mec, mew are for choosing the color of the marker.
| {
"pile_set_name": "StackExchange"
} |
Q:
Communicate between React's child-component
I already asked similar question but i got new a problem). I want while click on child-component perform function of parent-component.
var Fructs = ['banana', 'mango', 'potato'];
var Kaka = React.createClass({
render() {
return <div onClick={this.props.onClick}> Hell o forld </div>
}
});
var Application = React.createClass({
handle() {
console.log("took took");
},
render() {
console.log(this.props);
var mass = Fructs.map(function(data, index) {
return <Kaka key={index} onClick={handle.bind(this)}/>
});
return (
<div>
{ mass }
</div>
);
}
});
var App = React.createClass({
render() {
return (
<div>
<Application />
</div>
);
}
});
React.render(<App/>, document.getElementById('app'));
Example on CodePen
All work perfect if child-component is one. But if i try generate list of child-component it doesn't work. Error's log write that "this" isn't find.
I find similar a problem doc React, but i do it wronะฟ (. Please, tell what i do wrong?
A:
You should set this for .map callback., also you handle is method, in order to get it you need use this.handle after changes .map should looks like this
var mass = Fructs.map(function(data, index){
return <Kaka key={index} onClick={ this.handle.bind(this) } />
^^^^^^^^^^^ - get Component method
}, this);
^^^^ - callback context
var Fructs = ['banana', 'mango', 'potato'];
var Kaka = React.createClass({
render() {
return <div onClick={this.props.onClick}>
Hell o forld
</div>
}
})
var Application = React.createClass({
handle() {
console.log("took took");
},
render() {
var mass = Fructs.map(function(data, index){
return <Kaka key={index} onClick={ this.handle.bind(this) } />
}, this);
return <div>
{ mass }
</div>
}
})
var App = React.createClass({
render() {
return <div>
<Application />
</div>
}
})
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make user input follow list in specific order
I have a code block which makes the user input Fibonacci numbers. The code block:
numb_list = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55]
numb = int(input('Enter the next Fibonacci number >'))
while numb in numb_list and numb <= 50:
numb = int(input('Enter the next Fibonacci number >'))
if numb in numb_list:
print('Well done')
else:
print('Try again')
I am asking the user to input these numbers. When the user input goes over 50 or enters all the correct numbers the program gives output 'Well done'. If user input makes a mistake the program outputs 'Try again'. This is working perfectly but how will i make the user input follow this list in this specific order and if its not in this order the program outputs 'Try again'.
This is the current output:
Enter the next Fibonacci number >1
Enter the next Fibonacci number >1
Enter the next Fibonacci number >2
Enter the next Fibonacci number >3
Enter the next Fibonacci number >8
Enter the next Fibonacci number >3
Enter the next Fibonacci number >
This is the output i would like to achieve:
Enter the next Fibonacci number >1
Enter the next Fibonacci number >1
Enter the next Fibonacci number >2
Enter the next Fibonacci number >3
Enter the next Fibonacci number >8
Enter the next Fibonacci number >3
Try again
Unfortunately I am having trouble achieving this output. Will someone be able to help me?
Thank you!
A:
You can iterate the target number through numb_list instead and use a while loop to keep asking the user for input until the input number matches the target number:
numb_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
for target in numb_list:
while int(input('Enter the next Fibonacci number >')) != target:
print('Try again')
print('Well done')
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot open Eclipse Marketplace Photon
I can not get into the Eclipse Marketplace.
I live in Korea and have access to wifi environment.
Wi-Fi status is best.
I searched Google for the same situation, but I could only see one massage like myself.
However, the article was written in the Eclipse Forum and I was not able to access the Eclipse Forum.
I also could not get into the Marketplace page on the Eclipse homepage.
Most of the errors I see are Connection Errors, but they are different from my error messages.
Below is my error message and my version is as follows.
[Version: Photon Release (4.8.0)]
[macOS Mojave ver. 10.14 (18A391)]
Cannot open Eclipse Marketplace
Cannot install remote marketplace locations: Resource not found: http://marketplace.eclipse.org/catalogs/api/p
Cannot complete request to http://marketplace.eclipse.org/catalogs/api/p: http://marketplace.eclipse.org/catalogs/api/p
http://marketplace.eclipse.org/catalogs/api/p
Resource not found: http://marketplace.eclipse.org/catalogs/api/p
http://marketplace.eclipse.org/catalogs/api/p
A:
It looks like the marketplace is unavailable.
Error | Drupal: "The website encountered an unexpected error."
https://marketplace.eclipse.org/
| {
"pile_set_name": "StackExchange"
} |
Q:
How are "special" return values that signal a condition called?
Suppose I have a function which calculates a length and returns it as a positive integer, but could also return -1 for timeout, -2 for "cannot compute", and -3 for invalid arguments.
Notwithstanding any discussion on best practices, proper exceptions, and whatnot, this occurs regularly in legacy codebases. What is the name for this practice or for return values which are outside of the normal output value range, -1 being the most common?
A:
Exceptions vs. status returns article refers to them as return status codes:
Broadly speaking, there are two ways to handle errors as they pass
from layer to layer in software: throwing exceptions and returning
status codes...
With status returns, a valuable channel of communication (the return
value of the function) has been taken over for error handling.
Personally I would also call them status codes, similarly to HTTP status codes (if we pretend HTTP response is like a function return).
As a side note, beside exceptions and return status codes, there also exists a monadic approach to error handling, which in some sense combines the former two approaches. For example, in Scala, Either monad may be used to specify a return value that can express both an error status code and a regular happy value without having to block out part of the domain for status codes:
def divide(a: Double, b: Double): Either[String, Double] =
if (b == 0.0) Left("Division by zero") else Right(a / b)
divide(4,0)
divide(4,2)
which outputs
res0: Either[String,Double] = Left(Division by zero)
res1: Either[String,Double] = Right(2.0)
| {
"pile_set_name": "StackExchange"
} |
Q:
Question regarding nowhere dense and everywhere dense sets
I was just refreshing my topology basics and started wondering about this.I do hope my question is mathematically sound. Anyway my question is whether every topological space has non-trivial dense sets or nowhere dense sets or for that matter even separable sets?? Does the presence of such sets affect the geometry of a space in any manner?? Does this question make sense in the first place??I wasn't able to get a clear picture.
Also as an exercise, I was trying to prove that if $A$ is nowhere dense in a metric space $(X,d)$ then this is equivalent to saying that every non-empty open set in $X$ has a non-empty open subset disjoint from $A$.
I was thinking along these lines if suppose $\exists \ U$ open in $X$ such that $\forall \ V$ open in $U$, $V \cap U \neq \phi$ . Then this means for every $x$ and some $\epsilon$ such that $B(\epsilon ,x) \subset U $ we have $B(\epsilon ,x) \cap A \neq \phi$ . Now if $x_1$ belongs to this intersection, then I can find $B(\epsilon_1, x_1) \subset B(\epsilon ,x)$ and further $B(\epsilon_1, x_1) \cap A \neq \phi$ and this can go on. Ultimately I feel that this shows that there has to be an open ball $B(\epsilon_n , x_n)$ contained in $A$. Is this line of thinking going to work??Or is there any other way??
A:
The answer to your first two questions is no:
In a discrete space (every subset is open) there are neither any proper dense subsets nor any nowhere-dense subsets. (If the space has at least two points.)
As for the second question, I don't think you need that X is a metric space.
Let $A$ be nowhere-dense and let $U$ be a non-empty open subset of $X$. If $A\bigcap U$ is empty, we're done. If not, $\bar{A}\bigcap U$ is non-empty. By hypothesis, $U$ is not contained in $\bar{A}$, so $U-\bar{A}$ is non-empty, and is therefore the desired open subset.
For the other direction, suppose every non-empty open subset has an open subset disjoint from $A$. If $\bar{A}$ has non-empty interior, that would be an open set with no open subset disjoint from $A$, a contradiction. Thus $\bar{A}$ has empty interior, and $A$ is nowhere-dense.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql fetch assoc VS mysql fetch array
Below are two methods commonly used in most php codes for fetch mysql data .
mysql_fetch_array()
mysql_fetch_assoc()
Now, I have a big database. For fetching data in loops (while) what's faster and better ?
I found this benchmark.
Which is your choice?
A:
It depends on how your tables are setup:
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
So using mysql_fetch_array() without specifying MYSQL_ASSOC or MYSQL_NUM, or by specifying MYSQL_BOTH will return two arrays (basically what mysql_fetch_assoc() and mysql_fetch_row() would return) so mysql_fetch_assoc() is faster.
If you have your table setup right and query written properly mysql_fetch_assoc() is the way to go, code readability wise $result['username'] is easier to understand than $result[0].
| {
"pile_set_name": "StackExchange"
} |
Q:
Storing prices in SQLite, what data-type to use?
I am using SQLite and need to store prices. SQLite's REAL data-type says it uses floating-point which is unacceptable storage for prices. Is there a data-type besides TEXT that I can use to store prices numerically so they sort correctly?
A:
Use an integer & store the prices as the lowest common unit. So, for dollars and cents you'd store it in cents. EG: $1.00 would be stored as 100.
In my experience it's standard practice.
A:
Certainly, use integer
You will have to decide how many decimal places you are assuming and be consistent at the application level.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use SLDS Icon in Visualforce Component
I have tried to used below code in Visualforce Component
<img class="slds-checklrt" src="{!URLFOR($Asset.SLDS,'assets/icons/utility/check_60.png')}" style="width:20px"/>
but not getting much output as per requirement.
Any solution for this?
A:
We can't use lightning icon direct from "Asset.SLDS".
Please use Lightning Assets path:
<img src="/apexpages/slds/latest/assets/icons/utility/check_60.png"/>
or you can use SVG:
<span class="slds-icon_container slds-icon-standard-account" title="description of icon when needed">
<svg aria-hidden="true" class="slds-icon">
<use xlink:href="{!URLFOR($Asset.SLDS, 'assets/icons/standard-sprite/svg/symbols.svg#account')}"></use>
</svg>
<span class="slds-assistive-text">Icon Assistive Text</span>
</span>
Plese follow below link if needed:
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/vf_dev_best_practices_slds_icons.htm
| {
"pile_set_name": "StackExchange"
} |
Q:
Can i able to run both the inline script and stored script in one query in ES?
ES 2.4.0
I tried to do aggregations with both the inline script and stored script. But when i executed the code it is showing error..
{
"size": 0,
"aggregations": {
"dayOfWeek": {
"terms": {
"script": "doc['created_at'].date.dayOfWeek().getAsText()"
},
"aggs": {
"byHours": {
"terms": {
"order": {
"_term": "asc"
},
"script": "test",
"params": {
"date_field": "created_at",
"format": "HH"
}
}
}
}
}
}
}
When i executed the above code, i am getting error like these
{
"took": 106,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 1,
"failed": 4,
"failures": [
{
"shard": 1,
"index": "test",
"node": "PHgQhqS8T6KORwsJ5ChzHg",
"reason": {
"type": "script_exception",
"reason": "failed to run inline script [test] using lang [groovy]",
"caused_by": {
"type": "missing_property_exception",
"reason": "No such property: test for class: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"
}
}
}
]
A:
You need to reference your script file like this:
{
"size": 0,
"aggregations": {
"dayOfWeek": {
"terms": {
"script": "doc['created_at'].date.dayOfWeek().getAsText()"
},
"aggs": {
"byHours": {
"terms": {
"order": {
"_term": "asc"
},
"script": { <--- modify this section
"file": "test",
"params": {
"date_field": "created_at",
"format": "HH"
}
}
}
}
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
two or more components as one "big" component
I want to show some information of some objects, let's put an example: cinemas
so, i need 2 or 3 TextView in one "big" component. In this case, first TextView could be cinema name, and secon TextView for the number of films.
I would like to put them like if there was only one, so, onclick events, or while pressing any of them, it would respond like 1 textview (not 2 or 3, with the same sensation of background when you press some button)
is there any way to do this? or just to handle all events i need and fire them for all views?
Thanks in advance!
A:
Sure. Extend a LinearLayout to create a Cinema class, and inflate an xml containing 2 textviews, or whatever you want. Handle all the events inside the Cinema class.
An example.
http://code.google.com/p/myandroidwidgets/source/browse/trunk/Custom_Progress_Bar/src/com/beanie/example/views/MyProgressBar.java
| {
"pile_set_name": "StackExchange"
} |
Q:
xpath dates comparison
I'm trying to filter elements based on an attribute that is a date in the format yyyy-MM-dd.
My XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
<article title="wired" pub-date="2010-11-22" />
<article title="Plus 24" pub-date="2010-11-22" />
<article title="Finance" pub-date="2010-10-25" />
</root>
My xpath attempt:
'//article[xs:date(./@pub-date) > xs:date("2010-11-15")]'
Using xpath 2.0 - would avoid adding a schema unless absolutely necessary.
From comments:
I believe I must be missing something
then. Is it possible that I need to
specify something else for xs:date to
work? Maybe a xs: namespace
definition?
A:
In both XPath 1.0 and 2.0 you can use:
//article[number(translate(@pub-date,'-','')) > 20101115]
Your XPath 2.0 expression is correct, using Saxon 9.0.3 this transformation:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:template match="/">
<xsl:sequence select="//article[xs:date(./@pub-date) > xs:date('2010-11-15')]"/>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<root>
<article title="wired" pub-date="2010-11-22" />
<article title="Plus 24" pub-date="2010-11-22" />
<article title="Finance" pub-date="2010-10-25" />
</root>
produces the wanted, correct result:
<article title="wired" pub-date="2010-11-22"/>
<article title="Plus 24" pub-date="2010-11-22"/>
| {
"pile_set_name": "StackExchange"
} |
Q:
WPF C# Deserialize an observable collection with XmlSerializer adds extra items
I wish to save and load a class (MeasConSettings) that contains a ObservableCollection<string> The problem is the list is initialized in my constructor so when I do the following:
XmlSerializer serializer = new XmlSerializer(typeof(MeasConSettings));
A list is created with items 1 2 3 4. It saves all fine, but on the loading side it goes wrong:
MeasConSettings loadedSettings = (MeasConSettings)serializer.Deserialize(stream);
It starts from the initialized list and adds the loaded list items instead of overwriting them so the result is a list with items 1 2 3 4 1 2 3 4.
Obviously the solution would be to remove the initialization from the constructor as shown in this topic:Deserializing List with XmlSerializer Causing Extra Items but then what if the file does not contain the list (e.g. a previous version of a saved file), If I remove the initialization and there is no list present in the saved file, there will be no items in the list. This is not acceptable so:
Is there a proper way to load an observable collection with initialization in the constructor without ending up with duplicate items?
or
Is there a proper way to check if a saved file contains certain parameters?
A:
If I remove the initialization and there is no list present in the saved file, there will be no items in the list. This is not acceptable
Then just handle this special case in the initialization.
public void Init()
{
if (this.List == null)
{
// Initialize the list
}
}
From there, you just have to call the Init method everytime you create a MeasConSettings object (either by calling the constructor or by using the deserializer).
That said, I'm not overly fond of the initialization methods, as they lack visibility and a fellow developer can forget to call them. As an alternative, you can use a getter:
private List<int> list;
public List<int> List
{
get
{
if (this.list == null)
{
this.list = new List<int> { 1, 2, 3, 4 };
}
return this.list;
}
set
{
this.list = value;
}
}
Note: This code isn't thread-safe.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't add custom Devise field through view
I've been at this for days, and cannot figure out the problem. When I attempt to Sign Up, it appears to work, but when I check the rails console, it shows no username. I'm able to add one from there and it works fine, but using my Sign Up view it never works. Only the fields that were created when I installed Devise work. I've also added First and Last Name, but I only attempted to get Username working, so the code for names is incomplete. If I've left anything important out, let me know. I'd REALLY appreciate the help.
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
protected
def configure_devise_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:email, :username, :password, :password_confirmation)
end
end
.
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :username, :uniqueness => {:case_sensitive => false}
has_many :posts
has_many :offers
has_many :requests
has_one :profile
def name
"#{first_name} #{last_name}"
end
protected
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value", { :value => login.downcase }]).first
end
end
.
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %>
<%= f.email_field :email, autofocus: true %></div>
<div><%= f.label :username %>
<%= f.text_field :username%><div>
<div><%= f.label :first_name %>
<%= f.text_field :first_name %><div>
...
.
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def show_user
@user = current_user
render 'show'
end
def index
@user = User.all
end
def new
@user = User.new
render profiles_path
end
def create
@user = User.new(user_params)
if @user.save
redirect_to posts_path, notice: 'User successfully added.'
else
render profiles_path
end
end
def edit
end
def update
if @user.update(user_params)
redirect_to posts_path, notice: 'Updated user information successfully.'
else
render action: 'edit'
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :first_name, :last_name, :email, :username)
end
end
.
class RegistrationsController < Devise::RegistrationsController
def update
new_params = params.require(:user).permit(:email,
:username, :current_password, :password,
:password_confirmation)
change_password = true
if params[:user][:password].blank?
params[:user].delete("password")
params[:user].delete("password_confirmation")
new_params = params.require(:user).permit(:email,
:username)
change_password = false
end
@user = User.find(current_user.id)
is_valid = false
if change_password
is_valid = @user.update_with_password(new_params)
else
@user.update_without_password(new_params)
end
if is_valid
set_flash_message :notice, :updated
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end end
end
Schema:
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "first_name"
t.string "last_name"
t.string "username"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
A:
Add this to your ApplicationController
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
end
end
Source: https://github.com/plataformatec/devise#strong-parameters
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I view the HTML source of an email sent to my Gmail address?
I'd like to see how a certain email was put together.
Is there a "View Source" for emails sent to Gmail?
A:
As Jasper pointed out, click the dropdown menu next to the reply button, and select Show original.
A:
Once you get your Show original window up, your address bar will contain something like this: https://mail.google.com/mail/u/0/?ui=2&ik=1234567890&view=om&th=1234abcd1234abcd
Just change the bit that says view=om to view=lg.
Push Enter, and bingo: itโs no longer plain text. Now save it as .html or as .pdf.
Source: http://blog.brush.co.nz/2012/09/save-a-gmail-message-to-hard-disk/
| {
"pile_set_name": "StackExchange"
} |
Q:
sending keypress signal
I m developing a program and i have to send a keypress signal to the serial port bu console application does not allow me to use System.Windows.Forms name space. In this namespace there is a SendKeys method but i cannot use it. Can anyone suggest something to me or how can i use System.Windows namespace in my console application?
Thanks
A:
Maybe SendInput is what you are after.
| {
"pile_set_name": "StackExchange"
} |
Q:
The Principle of Explosion v. Reductio ad Absurdum
The proof for the Principle of Explosion starts by assuming a contradiction.
When we use reductio ad absurdum, we establish a proof by reaching a contradictory conclusion in sub-argument and then refusing to accept a contradiction.
In classical logic, we refuse to accept a contradiction while at the same time accepting a statement derived from a contradiction. But how is this justified?
A:
In classical and intuitionistic logic, the Principle of Explosion is often a basic law of inference.
Wiki's entry deduces it from Disjunctive syllogism:
Assume P as true; then (by Disjunction introduction) we have: P โจ Q, with Q whatever.
But we have also ยฌP. Thus, we may conclude with Q.
This is what happens in classical and intuitionsitic logic when we assume as true a contradiction.
Conclusion: contradictions are never true.
We have to be clear about the difference regarding: assuming something as true, and proving something.
But it is allowed to assume something (not known to be true or false) as true and see "what happens".
If a contradiction follows by way of the correct "inference procedure" (i.e. having applied correctly the inference rules) then, because contradictions can never be true, this mean that our starting assumption is wrong e we have to reject it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Web.py "Hello world" not working - ERR_ADDRESS_INVALID
I'm trying to get the "Hello World" example for Web.py working and it's giving me an error:
This person seemed to be having the same issue in 2011 and the sole response suggested it might be a firewall issue. I have tried setting a new port as described here and it made no difference. I know that the new port I tried (5000) is not blocked by any firewall on my computer, so this isn't a firewall issue.
A:
0.0.0.0 is the IP address is bound to. Your server will be reachable on every interface of your machine on any of the IP addresses that your computer has been assigned.
To contact the server, you need to specify its actual IP address. 0.0.0.0 is not a valid IP address. For instance, if the server runs on your local machine, try http://127.0.0.1:8080/ .
| {
"pile_set_name": "StackExchange"
} |
Q:
How to make user signup once, if I've built a business with two services that both requires signup?
Am teacher and I make and sell Question bank (qbnak) for many standardize test.
I've built a business using two different service, in which both requires sign-up, So If i had a customer he should create two account one for the first service and another for the second in order to get to qbank each time
The first service is Teachable and the second is Speedexam .
So my Questions is:
How to automate user signup rather than doing it manually?
What is the permanent solution for this, What do you call it SSO/oAuth or API ?
And what are my options if SSO and API are not support in both services?
Thank you
A:
Like you mentioned, what you're trying to achieve is generally referred to as SSO.
Single Sign On works by having a central server, which all the applications trust. When you login for the first time a cookie gets created on this central server. Then, whenever you try to access a second application, you get redirected to the central server, if you already have a cookie there, you will get redirected directly to the app with a token, without login prompts, which means youโre already logged in.
(source: How to Implement Single Sign On)
You have a few options on how to implement this:
Create your own authentication server and define your own processes around how the other application interact and perform authentication
ย ย ย โคท (not recommend, time consuming and easy to get something wrong)
Create your own authentication server compliant with available authentication standards like OpenID Connect and OAuth 2.0
ย ย ย โคท (time consuming and complex, but at least you're following standards so less likely to really mess up)
Delegate the authentication to a third-party authentication provider like Auth0
ย ย ย โคท (easy to get started, depending on amount of usage it will cost you money instead of time)
Disclosure: Answer provider by an Auth0 employee.
| {
"pile_set_name": "StackExchange"
} |
Q:
Javascript issues?
So here is what I have so far. I am trying to create a button that calculates percentages of test scores then displays onto the page when you press a button. Bear in mind i'm a VERY new programmer with less than 3 weeks experience and I could really use the help.
var sam = 9;
var sally = 8;
var donald = 4;
function go(){
function percentage();
alert("Sam's score on the test is " + samp + "%\nSally's score on the test is "
+ sallyp + "%\nDonald's score on the test is " + donaldp + "%")
}
function percentage(){
var samp = sam / 10 * 100;
var sallyp = sally / 10 * 100;
var donaldp = donald / 10 * 100;
}
A:
To invoke the percentage function, remove the function keyword. The next issue is that samp, sallyp, and donaldp are scoped to the function percentage, so they're not accessible in the go function. You should make percentage take an argument
function percentage (score) {
return score / 10 * 100;
};
Then, in go:
function go () {
console.log("Sam: " + percentage(sam) + ", Sally: " + percentage(sally) +
", Donald: " + percentage(donald));
};
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP how to put the following in a loop
I've been trying for 2 hours now and I cannot seem to get it right.
How do I put the following in a loop and create unique variables for each output:
$valueEmail = mysqli_real_escape_string($sql, $_POST['Email']);
$valuePassword = mysqli_real_escape_string($sql, $_POST['Password']);
$valueConfirmPassword = mysqli_real_escape_string($sql, $_POST['ConfirmPassword']);
A:
I don't understand, what you really need, but if I understood correctly you can use something like this:
$array = //array with all your inputs
[
'Email',
'Password'
];
for($i=0; $i<count($array);$i++) {
${'value'.$array[$i]}=mysqli_real_escape_string($sql, $_POST[$array[$i]]);
}
echo $valueEmail." ".$valuePassword; // Works!
You can read more here Appending a value of a variable to a variable name?
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does keyboard-slide crash my app?
If I physically slide out the keyboard on my Moto Droid A855, it crashes my test app with the stack trace pasted below. I don't understand why?
Also, if I start my app with the keyboard out, my app crashes immediately on startup.
The app consists of an activity, which contains a viewflipper as the main view layout. The viewflipper contains two linearlayouts...
Stack trace:
06-10 21:10:17.652 E/AndroidRuntime( 3785): Uncaught handler: thread main exiting due to uncaught exception
06-10 21:10:17.668 E/AndroidRuntime( 3785): java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$1@447af0b8
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ActivityThread$PackageInfo.forgetReceiverDispatcher(ActivityThread.java:667)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ApplicationContext.unregisterReceiver(ApplicationContext.java:747)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:321)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.widget.ViewFlipper.onDetachedFromWindow(ViewFlipper.java:104)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.View.dispatchDetachedFromWindow(View.java:5835)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1076)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1074)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1074)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1074)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewRoot.dispatchDetachedFromWindow(ViewRoot.java:1570)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewRoot.doDie(ViewRoot.java:2556)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.ViewRoot.die(ViewRoot.java:2526)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:218)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.view.Window$LocalWindowManager.removeViewImmediate(Window.java:436)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3498)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3599)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ActivityThread.access$2300(ActivityThread.java:119)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1867)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.os.Looper.loop(Looper.java:123)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at android.app.ActivityThread.main(ActivityThread.java:4363)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at java.lang.reflect.Method.invokeNative(Native Method)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at java.lang.reflect.Method.invoke(Method.java:521)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-10 21:10:17.668 E/AndroidRuntime( 3785): at dalvik.system.NativeStart.main(Native Method)
06-10 21:10:17.684 I/Process ( 1017): Sending signal. PID: 3785 SIG: 3
EDIT: added XML layout and relevant snippets from main activity.
Entire XML layout file
<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/vFlipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- Linear Layout 1: messages and overview. -->
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow android:id="@+id/TableRow01" android:layout_width="fill_parent" android:layout_height="wrap_content">
<TextView
android:text="Connection info"
android:id="@+id/tvCon1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#F0F0F0"
android:textColor="#FF0000"
/>
</TableRow>
<ScrollView
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/tvMessages"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text=""
/>
</ScrollView>
</LinearLayout>
<!-- Linear Layout 2: settings -->
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow
android:id="@+id/TableRow03"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="hello world"
android:id="@+id/asdfasdf2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</TableRow>
</LinearLayout>
</ViewFlipper>
Code snippets from Main Activity:
/**
* Attempt (not currently working) to work around this bug: http://code.google.com/p/android/issues/detail?id=6191
* TODO: make it work.
*/
@Override
public void onDetachedFromWindow() {
Log.d("Dash","OnDetachedFromWindow()");
try {
super.onDetachedFromWindow();
}
catch (Exception e) {
ViewFlipper v = (ViewFlipper)findViewById(R.id.vFlipper);
if (v != null) {
Log.d("Dash","De-Bug hit. e=" + e.getMessage());
v.stopFlipping();
}
}
}
A:
To resolve this issue you must
Define a new class called MyViewFlipper which overrides ViewFlipper (see below)
Reference that new class anywhere you would have previously referenced ViewFlipper
Define your class and layout as shown below:
New class called MyViewFlipper. Contains the following:
package com.gtosoft.dash; // change this to match your own app.
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ViewFlipper;
public class MyViewFlipper extends ViewFlipper {
public MyViewFlipper(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDetachedFromWindow() {
try{
super.onDetachedFromWindow();
}catch(Exception e) {
Log.d("MyViewFlipper","Stopped a viewflipper crash");
stopFlipping();
}
}
}
Now to use this "fixed" version of ViewFlipper you have to reference it in the xml layout. Since it is basically a "custom view", you have to fully qualify the package path to MyViewFlipper, as seen here:
<com.gtosoft.dash.MyViewFlipper
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/vFlipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
(insert all the other old layout code here)
</com.gtosoft.dash.MyViewFlipper>
Now the app no longer crashes on the keyboard slide event or if the app is started with slide already out. Look for this in the log:
06-11 20:08:15.811 D/MyViewFlipper( 6106): Stopped a viewflipper crash
Credit: http://code.google.com/p/android/issues/detail?id=6191
A:
It's really difficult to help you if you don't provide some part of your code... anyway, this error is not new and there are some workarounds in order to solve it (I guess is some bug)... try to do this:
@Override
protected void onDetachedFromWindow() {
try {
super.onDetachedFromWindow();
}
catch (IllegalArgumentException e) {
stopFlipping();
}
}
This is for overriding the onDetachedFromWindow and I hope it works for you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which layout to use for git-svn in a project with standard layout currently and non standard layout in past
Should I use standard layout param (-s) for git svn when our subversion repository adheres to standard layout currently although it was not the case for most of the history?
I'm trying to import the subversion repository into git with while history.
More details
First few years the main project folders were in the root instead of trunk folder
/ - project folders in root
'- e.g. apps
'- components
/branches
/tags
/trunk - empty
After many years a migration branch was introduced and used for few additional years
/ - project folders in root
'- e.g. apps
'- components
/branches
'- migration - a long living branch used as main project work for some time
'- e.g. apps
'- components
'- few other branches (<3)
/tags
'- many tags for releases
For the past one year the current state conforms to standard layout
/ - no files, no folders in root (except trunk, branches, tags)
/branches
'- oldMigration - migration branch renamed (moved)
'- e.g. apps
'- components
'- few other branches (<5)
'- oldRoot - folders from the root moved here
/tags
'- around 150 tags for releases
/trunk
'- e.g. apps
'- components
UPDATE Just to clarify, going forward we do not plan to work (commit/checkout) with the oldMigration and oldRoot anymore. It is just that we want the history to reflect the situation how it was for the purposes of reading history log and see who changed which files and why.
A:
In this situation, you can feed git-svn multiple directories which represent trunk, branches and tags to cover all the possibilities throughout history.
I would recommend doing it in two steps, git svn init and git svn fetch, rather than a single git svn clone to give yourself a bit more control.
In your case it would be...
git svn init --trunk=trunk/ --trunk=. --branches=branches/ --tags=tags/ ...
You may wish to try --trunk=branches/migration, but honestly I would leave that as its own historical branch (presumably later merged into the new trunk) than trying to get Git to pretend it was trunk all along.
| {
"pile_set_name": "StackExchange"
} |
Q:
Keras - inverse of K.eval()
I am trying to write a lambda layer which converts an input tensor into a numpy array and performs a set of affine transforms on slices of said array. To get the underlying numpy array of the tensor I am calling K.eval(). Once I have done all of the processing on the numpy array, I need to convert it back into a keras tensor so it can be returned. Is there an operation in the keras backend which I can use to do this? Or should I be updating the original input tensor using a different backend function?
def apply_affine(x, y):
# Get dimensions of main tensor
dimens = K.int_shape(x)
# Get numpy array behind main tensor
filter_arr = K.eval(x)
if dimens[0] is not None:
# Go through batch...
for i in range(0, dimens[0]):
# Get the correpsonding affine transformation in the form of a numpy array
affine = K.eval(y)[i, :, :]
# Create an skimage affine transform from the numpy array
transform = AffineTransform(matrix=affine)
# Loop through each filter output from the previous layer of the CNN
for j in range(0, dims[1]):
# Warp each filter output according to the corresponding affine transform
warp(filter_arr[i, j, :, :], transform)
# Need to convert filter array back to a keras tensor HERE before return
return None
transformed_twin = Lambda(function=lambda x: apply_affine(x[0], x[1]))([twin1, transformInput])
EDIT: Added some context...
AffineTransform: https://github.com/scikit-image/scikit-image/blob/master/skimage/transform/_geometric.py#L715
warp: https://github.com/scikit-image/scikit-image/blob/master/skimage/transform/_warps.py#L601
I am trying to re-implement the CNN in "Unsupervised learning of object landmarks by factorized spatial embeddings". filter_arr is the output from a convolutional layer containing 10 filters. I want to apply the same affine transform to all of the filter outputs. There is an affine transform associated with each data input. The affine transforms for each data input are passed to the neural net as a tensor and are passed to the lambda layer as the second input transformInput. I have left the structure of my current network below.
twin = Sequential()
twin.add(Conv2D(20, (3, 3), activation=None, input_shape=(28, 28, 1)))
# print(twin.output_shape)
# twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
twin.add(Activation('relu'))
twin.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))
# print(twin.output_shape)
twin.add(Conv2D(48, (3, 3), activation=None))
# print(twin.output_shape)
twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
twin.add(Activation('relu'))
twin.add(Conv2D(64, (3, 3), activation=None))
twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
twin.add(Activation('relu'))
# print(twin.output_shape)
twin.add(Conv2D(80, (3, 3), activation=None))
twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
twin.add(Activation('relu'))
# print(twin.output_shape)
twin.add(Conv2D(256, (3, 3), activation=None))
twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
twin.add(Activation('relu'))
# print(twin.output_shape)
twin.add(Conv2D(no_filters, (3, 3), activation=None))
twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
twin.add(Activation('relu'))
# print(twin.output_shape)
# Reshape the image outputs to a 1D list so softmax can be used on them
finalDims = twin.layers[-1].output_shape
twin.add(Reshape((finalDims[1], finalDims[2]*finalDims[3])))
twin.add(Activation('softmax'))
twin.add(Reshape(finalDims[1:]))
originalInput = Input(shape=(28, 28, 1))
warpedInput = Input(shape=(28, 28, 1))
transformInput = Input(shape=(3, 3))
twin1 = twin(originalInput)
def apply_affine(x, y):
# Get dimensions of main tensor
dimens = K.int_shape(x)
# Get numpy array behind main tensor
filter_arr = K.eval(x)
if dimens[0] is not None:
# Go through batch...
for i in range(0, dimens[0]):
# Get the correpsonding affine transformation in the form of a numpy array
affine = K.eval(y)[i, :, :]
# Create an skimage affine transform from the numpy array
transform = AffineTransform(matrix=affine)
# Loop through each filter output from the previous layer of the CNN
for j in range(0, dims[1]):
# Warp each filter output according to the corresponding affine transform
warp(filter_arr[i, j, :, :], transform)
# Need to convert filter array back to a keras tensor
return None
transformed_twin = Lambda(function=lambda x: apply_affine(x[0], x[1]))([twin1, transformInput])
twin2 = twin(warpedInput)
siamese = Model([originalInput, warpedInput, transformInput], [transformed_twin, twin2])
EDIT: Traceback when using K.variable()
Traceback (most recent call last):
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 1039, in _do_call
return fn(*args)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _run_fn
status, run_metadata)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\contextlib.py", line 66, in __exit__
next(self.gen)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'batch_normalization_1/keras_learning_phase' with dtype bool
[[Node: batch_normalization_1/keras_learning_phase = Placeholder[dtype=DT_BOOL, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
Traceback (most recent call last):
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 1039, in _do_call
return fn(*args)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _run_fn
status, run_metadata)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\contextlib.py", line 66, in __exit__
next(self.gen)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 466, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'batch_normalization_1/keras_learning_phase' with dtype bool
[[Node: batch_normalization_1/keras_learning_phase = Placeholder[dtype=DT_BOOL, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/nickb/PycharmProjects/testing/MNIST_implementation.py", line 96, in <module>
transformed_twin = Lambda(function=lambda x: apply_affine(x[0], x[1]))([twin1, transformInput])
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\engine\topology.py", line 585, in __call__
output = self.call(inputs, **kwargs)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\layers\core.py", line 659, in call
return self.function(inputs, **arguments)
File "C:/Users/nickb/PycharmProjects/testing/MNIST_implementation.py", line 96, in <lambda>
transformed_twin = Lambda(function=lambda x: apply_affine(x[0], x[1]))([twin1, transformInput])
File "C:/Users/nickb/PycharmProjects/testing/MNIST_implementation.py", line 81, in apply_affine
filter_arr = K.eval(x)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\backend\tensorflow_backend.py", line 533, in eval
return to_dense(x).eval(session=get_session())
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\ops.py", line 569, in eval
return _eval_using_default_session(self, feed_dict, self.graph, session)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\ops.py", line 3741, in _eval_using_default_session
return session.run(tensors, feed_dict)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
run_metadata_ptr)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
feed_dict_string, options, run_metadata)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
target_list, options, run_metadata)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'batch_normalization_1/keras_learning_phase' with dtype bool
[[Node: batch_normalization_1/keras_learning_phase = Placeholder[dtype=DT_BOOL, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op 'batch_normalization_1/keras_learning_phase', defined at:
File "C:/Users/nickb/PycharmProjects/testing/MNIST_implementation.py", line 36, in <module>
twin.add(BatchNormalization(axis=1, momentum=0.99, epsilon=0.001, center=True))
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\models.py", line 466, in add
output_tensor = layer(self.outputs[0])
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\engine\topology.py", line 585, in __call__
output = self.call(inputs, **kwargs)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\layers\normalization.py", line 190, in call
training=training)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\backend\tensorflow_backend.py", line 2559, in in_train_phase
training = learning_phase()
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\keras\backend\tensorflow_backend.py", line 112, in learning_phase
name='keras_learning_phase')
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\ops\array_ops.py", line 1507, in placeholder
name=name)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1997, in _placeholder
name=name)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
op_def=op_def)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
original_op=self._default_original_op, op_def=op_def)
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'batch_normalization_1/keras_learning_phase' with dtype bool
[[Node: batch_normalization_1/keras_learning_phase = Placeholder[dtype=DT_BOOL, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Exception ignored in: <bound method BaseSession.__del__ of <tensorflow.python.client.session.Session object at 0x0000023AB66D9C88>>
Traceback (most recent call last):
File "C:\Users\nickb\Anaconda3\envs\py35\lib\site-packages\tensorflow\python\client\session.py", line 587, in __del__
AttributeError: 'NoneType' object has no attribute 'TF_NewStatus'
Process finished with exit code 1
A:
As stated in the comments above it is best to implement lambda layer functions using the Keras backend. Since there are currently no functions in the Keras backend that perform affine transformations, I decided to use a tensorflow function in my Lambda layer instead of implementing an affine transform function from scratch using existing Keras backend functions:
def apply_affine(x):
import tensorflow as tf
return tf.contrib.image.transform(x[0], x[1])
def apply_affine_output_shape(input_shapes):
return input_shapes[0]
The downside to this approach is that my lambda layer will only work when using Tensorflow as the backend (as opposed to Theano or CNTK). If you wanted an implementation that is compatible with any backend you could check the current backend being used by Keras and then perform the transformation function from the backend currently in use.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get rid of console log
I wrote a web app using React, and I build it using Webpack. But in the production build, I want to get rid of all the console log statement because I don't want people to see some information such as their UID. Is there anything I can config in Webpack so that it will automatically get rid of all the console log? I tried p flag but it didn't do that.
A:
Try using the UglifyJsPlugin with this configuration:
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
drop_console: true,
drop_debugger: true,
global_defs: {
__REACT_HOT_LOADER__: undefined // eslint-disable-line no-undefined
}
},
minimize: true,
debug: false,
sourceMap: true,
output: {
comments: false
},
}),
You can see the whole config file here: https://github.com/jquintozamora/react-typescript-webpack2-cssModules-postCSS/blob/master/webpack/webpack.config.prod.js
| {
"pile_set_name": "StackExchange"
} |
Q:
Ordering SQL Results based on Input Params
In conjunction with the fn_split function, I'm returning a list of results from a table based on comma separated values.
The Stored Procedure T-SQL is as follows:
SELECT ProductCode, ProductDesc, ImageAsset, PriceEuros, PriceGBP, PriceDollars,
replace([FileName],' ','\_') as [filename],
ID as FileID, weight
from Products
LEFT OUTER JOIN Assets on Assets.ID = Products.ImageAsset
where ProductCode COLLATE DATABASE_DEFAULT IN
(select [value] from fn\_split(@txt,','))
and showOnWeb = 1
I pass in to the @txt param the following (as an example):
ABC001,ABC009,ABC098,ABC877,ABC723
This all works fine, however the results are not returned in any particular order - I need the products returning in the 'SAME ORDER' as the input param.
Unfortunately this is a live site with a built schema, so I can't change anything on it (but I wish I could) - otherwise I would make it more sensible.
A:
If all of the references that are passed in on the @txt param are unique you could use CharIndex to find their position within the param e.g.
order by charindex(ProductCode, @txt)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create JSON Object using String?
I want to create a JSON Object using String.
Example :
JSON {"test1":"value1","test2":{"id":0,"name":"testName"}}
In order to create the above JSON I am using this.
String message;
JSONObject json = new JSONObject();
json.put("test1", "value1");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 0);
jsonObj.put("name", "testName");
json.put("test2", jsonObj);
message = json.toString();
System.out.println(message);
I want to know how can I create a JSON which has JSON Array in it.
Below is the sample JSON.
{
"name": "student",
"stu": {
"id": 0,
"batch": "batch@"
},
"course": [
{
"information": "test",
"id": "3",
"name": "course1"
}
],
"studentAddress": [
{
"additionalinfo": "test info",
"Address": [
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":33
},
{
"H.No": "1243",
"Name": "Temp Address",
"locality": "Temp locality",
"id":36
}
],
"verified": true,
}
]
}
Thanks.
A:
JSONArray may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.add(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
A:
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
| {
"pile_set_name": "StackExchange"
} |
Q:
Line backgrounds stick togerther
I'm trying to color the background of some of my headers, but when I have a couple of them right after each other their backgrounds appear to "stick together". It appears this always happens when two consecutive lines have a background. A screenshot of the problem:
What I would actually expect:
(I made this image using an empty line with font size 1 and no line distance between the headers, but this is a very ugly workaround)
And a gif that shows the problem on normal text: http://i.imgur.com/E4w0xmG.gifv
Is there a way to get the backgrounds to separate?
A:
You can add a white border to the paragraphs to get the correct amount of white space that you want after each heading.
As a preliminary step, enter a paragraph in each of the 3 heading styles and then another one in, for example, the style that you use for regular text.
Select all four paragraphs. (This step is important.)
Right-click Heading 1 in the Styles gallery, and click Modify. Click Format > Border. If I want 6 points of space below the heading paragraph, I select 6 pt as the width of the border, and set the color to white. I then select to apply both a bottom and middle border.
The border replaces any space after setting on the paragraph style, so I clicked Format > Paragraph and set After to 0.
Repeat step 3 for the Heading 2 and Heading 3 paragraph styles.
| {
"pile_set_name": "StackExchange"
} |
Q:
c# programming code optimization
I have about 20 classes which are derived from ConvertApi classes. Every class share Convert method from parent class and has unique property SupportedFiles. I use these classes for file manipulation and my code looks like
if (fileEx=="txt")
new Text2Pdf().Convert(file)
else
if (fileEx=="doc")
new Word2Pdf().Convert(file)
else
//and so on..
I know that these code can be optimized because 20 times if operator is repeated and that looks bad, but can't find a way to do that. Could anyone help me?
class Text2Pdf : ConvertApi
{
enum SupportedFiles { txt, log };
}
class Word2Pdf : ConvertApi
{
enum SupportedFiles { doc, docx };
}
class Excel2Pdf : ConvertApi
{
enum SupportedFiles { xls, xlsx };
}
class ConvertApi
{
public void Convert(....);
}
A:
In your base class, have something like this:
public abstract class ConvertApi
{
protected abstract string[] SupportedFilesImpl();
public bool Supports(string ext)
{
return SupportedFilesImpl.Contains(ext);
}
}
Now, your derived classes can implement this method:
public class Text2PDF : ConvertApi
{
protected override string[] SupportedFilesImpl { return new string[] { "txt", "log"}; }
}
public class Doc2PDF : ConvertApi
{
protected override string[] SupportedFilesImpl { return new string[] { "doc", "docx"}; }
}
... and so on for the rest of the converters. Then put these in a list...
List<ConvertApi> converters = new List<ConvertApi>();
converters.Add(new Text2PDF());
converters.Add(new Doc2PDF());
(Note, I'd probably have a class containing these rather than just a list, but anyway). Now, to find a converter:
foreach(ConvertApi api in converters)
{
if(api.Supports(fileExt))
{
// woo!
break;
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use https for authentication from EGit to GitHub
I am trying to setup EGit to work with GitHub with https authentication, instead of the default ssh. (My reason is that I am a teacher, and some of my students do their work from different machines, so it's not convenient to rely on ssh keys stored on disk.) Has anyone gotten this to work? When I try doing a "Push to Upstream" using https, I get the unhelpful error message "An internal Exception occured during push: https://[email protected]/MillsCollegeMobileAppDev2011/test.git: not authorized".
I am using Eclipse 3.6.2 (Helios) with versions 0.11.3 of Eclipse EGit (Incubation), Eclipse EGit - Source (Incubation), and EGit Mylyn (Incubation). My Destination Git Repository settings are:
Location
URI: https://[email protected]/MillsCollegeMobileAppDev2011/test.git
Host: github.com
Repository path: /MillsCollegeMobileAppDev2011/test.git
Connection
Protocol: https
Port: [unset]
Authentication
User: espertus
Password: ........
Store in Secure Store: [checked]
A:
you need input your github account password in:
Authentication
User: espertus
Password: HERE
Store in Secure Store: [checked]
enjoy it! :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How is document.createEvent supposed to work with key events?
I am trying to simulate keypresses in a web application, it is for an embedded system but it uses a Webkit derived browser. I have tested the code in Chrome and get the same error.
I tried to use code snippets from this example from Yahoo, but I keep getting the same error when firing the event using dispatchEvent. "target" is an HTML element in the DOM tree.
function fireEvent(target) {
var evt = document.createEvent("UIEvent");
evt.initEvent("keypress", true, true);
target.dispatchEvent(evt);
}
It always throws:
"Error: UNSPECIFIED_EVENT_TYPE_ERR: DOM Events Exception 0"
I have tried createEvent("Events") as well and it always boils down to the same exception, both on the embedded system and in Chrome.
A:
Ok, when doing further testing, it seemed that when all key event parameters was properly initialised, then dispatchEvent worked without fireing an exception.
The following code works.
function fireEvent(target) {
var evt = document.createEvent("Events");
evt.initEvent("keypress", true, true);
evt.view = window;
evt.altKey = false;
evt.ctrlKey = false;
evt.shiftKey = false;
evt.metaKey = false;
evt.keyCode = 0;
evt.charCode = 'a';
target.dispatchEvent(evt);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Restoring database failed in SQL Server 2005 enterprise edition
I have tried to restore a database in SQLย Server 2005 enterprise edition on Windows Server 2003. It shows the following error.
Restored failed for Server 'MYS'. (Microsoft.SqlServer.Express.Smo)
Additional information:
System.Data.SqlClient.SqlError: The database was backed up on a server running version
9.00.4053. That version is incompatible with this server, which is running version
9.00.1187. Either restore the database on a server that supports the backup, or use a
backup that is compatible with this server. (Microsoft.SqlServer.Express.Smo)
What should I do?
A:
The backup was made using SQL Server 2005 SP3, but your server appears to be running an older SQL Server 2005 CTP edition.
You will need to upgrade your server to SQL 2005 SP3.
A:
Install SQL Server 2005 Service Pack 3 on your copy of SQL server, and it will be able to restore the file without a problem. The database server which backed up the database originally was running SP3, and you must have at least that version if you want to restore the DB.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: bisection method
I am trying to write a program to determine the zeros of the given function (f(x) := ln((sin(x**(1/2))**3) + 2) - 1, using the bisection method. The values a and b, which are the initial values used in the bisection method, are inserted on the program already. All it neeeds to do is show the plot and determine the zeros, but I can't get it to run (it stops on line 22). Can anyone spot the error?
import matplotlib.pyplot as plt
import numpy as np
import math
t = np.arange(0.5, 6.0, 0.01)
s = np.log((np.sin(np.sqrt(t)))**3+2)-1
z = len(t)*(0.0,)
plt.plot(t, s, t, z)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('A procura do zero')
plt.grid(True)
plt.savefig("test.pdf")
plt.show()
def bisseรงao(a,b):
z=(a+b)/2
while b-a>10**(-5):
if (math.log((math.sin(math.sqrt(a)))**3+2)-1)*(math.log((math.sin(math.sqrt(z)))**3+2)-1)<0:
b=(a+z)/2
if (math.log((math.sin(math.sqrt(b)))**3+2)-1)*(math.log((math.sin(math.sqrt(z)))**3+2)-1)<0:
a=(z+b)/2
return a
a1=1
b1=2
a2=4
b2=5
print("Os zeros sรฃo:",bisseรงao(a1,b1),bisseรงao(a2,b2))
A:
Here is the first problem:
z=(a+b)/2
while b-a>10**(-5):
You need to cumpute a new z in every iteration not only at the beginning of the function.
Second problem part 1:
b=(a+z)/2
Second problem part 2:
a=(z+b)/2
Setting the upper/lower bound between lower/upper bound and center point is not correct. They should be set exactly at the center point.
Correct implementation (with a small simplification for clarity - no need to type the whole function five times over):
func = lambda x: np.log((np.sin(np.sqrt(x)))**3+2)-1
def bisseรงao(a, b):
while b-a>10**(-5):
z = (a + b)/2
if func(a)*func(z)<0:
b = z
if func(b)*func(z)<0:
a = z
return a
P.S. The code will run into a problem if z happens to fall exactly at the root. You may want to check for this condition explicitly.
P.P.S. The code will also fail if the starting interval does not contain a root. You may want to check for this condition too.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sbyte[] vs byte[][] using methods
It is written
byte[][] getImagesForFields(java.lang.String[] fieldnames)
Gets an array of images for the given fields.
On the other hand, as long as I use the method in the web application project built on asp.net 2.o using c#;
the provided web method declared above, returns sbyte;
Have a look my code below;
formClearanceService.openSession(imageServiceUser);
formClearanceService.prepareInstance(formId);
byte[][] fieldImagesList = formClearanceService.getImagesForFields(fieldNames);
formClearanceService.closeSession();
thus I get the following error: Cannot implicitly convert type 'sbyte[]' to 'byte[][]'
So now,
1- should I ask the web service provider what is going on?
or
2- any other way that can use the sbyte as I was suppose to use byte[][] like following using:
byte[] ssss = fieldImagesList [0]..
A:
Java has signed bytes, so that part is correct in some ways (although unsigned bytes are more natural) - but it is vexing that it is returning a single array rather than a jagged array. I expect you're going to have to compare some data to see what you have received vs what you expected.
But changing between signed and unsigned can be as simple as:
sbyte[] orig = ...
byte[] arr = Array.ConvertAll(orig, b => (byte)b);
or (faster) simply:
sbyte[] orig = ...
byte[] arr = new byte[orig.Length];
Buffer.BlockCopy(orig, 0, arr, 0, orig.Length);
| {
"pile_set_name": "StackExchange"
} |
Q:
Disable or hide save button in Odoo
I'm trying to hide the save button from the top of a form in Odoo v8. Or instead I need to overwrite the save button.
I tried with write = "false". My code on the form view:
<record id="plan_settlement_contract_view_form"
model="ir.ui.view">
<field name="name">plan.settlement.contract.view.form</field>
<field name="model">plan.settlement</field>
<field name="arch" type="xml">
<form string="Settlement Contract" write='false'>
</form>
This is what I have now:
And this is what I need:
A:
You don't need to override anything, but have to configure the access rights for the business object. In this case you have to change the "write" access right or even more (create, unlink) for a specific access group.
First thing to read should be the official documentation. The linked one is for Odoo V12, but access control hasn't changed that much since Version 7, so it should be okay for you.
You should start with model access rights, because records rules are a bit more complex:
Managed by the ir.model.access records, defines access to a whole
model.
Each access control has a model to which it grants permissions, the
permissions it grants and optionally a group.
Access controls are additive, for a given model a user has access all
permissions granted to any of its groups: if the user belongs to one
group which allows writing and another which allows deleting, they can
both write and delete.
If no group is specified, the access control applies to all users,
otherwise it only applies to the members of the given group.
Available permissions are creation (perm_create), searching and
reading (perm_read), updating existing records (perm_write) and
deleting existing records (perm_unlink)
You'll find the most access rights in every module/app in a .csv file called ir.model.access.csv or in Odoo itself under Settings/Security/Access Controls List. Since Version 9 you have to activate the developer mode to see that menu.
Edit/Save button won't show for users without write rights. Create button won't show without create rights. Delete action should'nt be there without unlink rights. And so on.
The topic is too complex to explain everything on this answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
qInstallMsgHandler error while registering log function in Qt
I am designing Qt log window, So I am using qInstallMsgHandler() function to log all the debug, critical & warning messages on to QTableWidget (in below code I have not implemented yet). I did as below
int main(int argc, char *argv[])
{
qInstallMsgHandler(MainWindow::logMessage);
//qInstallMsgHandler(&MainWindow::logMessage); //I tried this also
QApplication a(argc, argv);
MainWindow w;
qDebug() << "info message";
qWarning() << "warning message";
qCritical() << "critical message";
w.show();
return a.exec();
}
MainWindow:
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::logMessage(QtMsgType type, const char *msg)
{
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s\n", msg);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s\n", msg);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s\n", msg);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s\n", msg);
abort();
}
}
When I compile this code, I am getting below error
main.cpp:27: error: cannot convert 'void (MainWindow::*)(QtMsgType, const char*)' to 'QtMsgHandler {aka void (*)(QtMsgType, const char*)}' for argument '1' to 'void (* qInstallMsgHandler(QtMsgHandler))(QtMsgType, const char*)'
qInstallMsgHandler(MainWindow::logMessage);
Please let me know if any one had faced this issue.
Note : If I changed void MainWindow::logMessage(QtMsgType type, const char *msg); this function to static function this is working fine.
(But if this function is static, I can not create QTableWidgetItem and add them to tableWidget so I want this function to be non static).
I am using Qt4.8.6 on Windows7
Thanks In Advance.
A:
Define a static variable MainWindow in MainWindow which will allow you to access the instance of the MainWindow from a static function e.g.
static MainWindow *_this;
set this Variable in the constructor:
MainWindow::MainWindow()
{
_this = this;
}
create a static function with the same signature to be registered in qInstallMsgHandler. This function will do only the redirection to the not-static function using the static _this:
static void logMessageHandle(QtMsgType type, const char *msg)
{
if(_this)
_this->logMessage(type,msg);
}
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I import KML/KMZ files to Google Maps Engine Lite?
MapsEngine seems to import only CSV, XLS files for creating a map.
How can I import my KML/KMZ files with Maps Engine Lite
A:
It is not currently supported to import KML or KMZ to Google Maps Engine Lite or Pro.
https://support.google.com/mapsenginelite/answer/3024937
The only current way is to use MyMaps (with the Classic Version of Google Maps)
Open the classic Google Maps and click My places in the top left corner. (Make sure youโre signed-in).
Click Or create with classic My Maps link under the CREATE MAP button, add a title, then click Import.
Select the KML from from your computer that youโd like to import then click Upload from File. (Note: the maximum file size for import is 3MB).
Click Save then click Done.
More info on importing in Google Maps Engines
https://support.google.com/mapsenginelite/answer/3024836
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC controller id with further actions
So currently been trying to make a website (relatively new with MVC). Say I have the current link:
www.website.com/Project/3
Which works fine. However Inside that project, I am wanting the 3 to pretty much always be there to specify the project in a better manner (as people can have multiple projects). So if they go to a page inside the project I want it to look like so:
www.website.com/Project/3/CreateOption
I have been trying to think about a way to do it, but can't think of any nice way to do it. Done research but either can't figure out what to write into google, or it is impossible.
If anyone could help that would be awesome! If you need more information please let me know.
A:
Not sure your version of MVC.
But Attribute Routing in ASP.NET MVC 5 is what you are looking for
| {
"pile_set_name": "StackExchange"
} |
Q:
How to enable/disable an input field with a checkbox in ruby on rails
I have a simple form for a model called Searching. I am intending to perform a search with the values specified in this form, so I want to enable input when checkbox is checked. My code is:
app/views/searchings/index.html.erb
<%= form_for @search do |s|%>
<div class="form-group">
<%= check_box "enable", id:"enable", type:"checkbox" %>
<%= s.label :type %>
<%= s.select :type, options_for_select(type_array_search), {}, class:"form-control", id:"type_select", disabled: true %>
</div>
<script type="text/javascript">
$(function () {
var $checkbox = $('#enable'),
$select = $('#type_select');
$checkbox.change(function (e) {
$select.prop('disabled', !$checkbox.is(':checked'))
});
});
</script>
<%= s.submit "Search", class:"btn btn-primary" %>
<% end %>
But this is not working, probably the object is not recognised by its id in the script, or the function is not right.
A:
You are missing a document ready and since the question was tagged jQuery, here is a jQuery solution!
$(function () {
var $checkbox = $('[id^="enable"]'),
$select = $('#type_select');
$checkbox.change(function (e) {
$select.prop('disabled', !$checkbox.is(':checked'))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="enable" type="checkbox" /> Enable
<br/>
<select id="type_select" disabled="true">
<option value="">Please select...</option>
<option value="1">Something 1</option>
</select>
| {
"pile_set_name": "StackExchange"
} |
Q:
ะะฐะบ ะฟะตัะตะพะฟัะตะดะตะปะธัั ะฟัะธัะฒะฐะธะฒะฐะฝะธะต ะฒ ะดะฐะฝะฝะพะผ ัะปััะฐะต?
ะััั ะบะปะฐัั:
class Aircraft
{
public:
/* ะกะะะะะขะฌ ะะะะกะขะ ะฃะะขะะ */
// Name of an aircraft
std::string aircraftName;
// Number of a flow
int flowNumber;
// Enter time in a flow
double arrivingTime;
// Whether an aircraft was delayed or not?
bool delayFlag;
// Arriving time after delay
double arrivingTime_Delayed;
// Constructor for the class
Aircraft (std::string _aircraftName, int _flowNumber, double _enterTime, bool _delayFlag, double _arrivingTime_Delayed);
// Generates a new aircraft in a random flow
static Aircraft genNextAircraft(double _arrivingTimeLA, int _flowQuantity);
// Getting info abount an aircraft
void getInfo() const;
};
ะะฑัะตะบัั ะดะฐะฝะฝะพะณะพ ะบะปะฐััะฐ ะฟะพัะปะต ัะพะทะดะฐะฝะธั ะบะปะฐะดั ะฒ vector:
vector<Aircraft> aircrafts;
// Generating requirement amount of aircrafts
for (int counter = 0; counter < aircraftQuantity; counter++) {
if (counter == 0) {
// The firts aircraft gets arrival time from [0, 600] sec
Aircraft newAircraft = Aircraft::genNextAircraft(0, flowQuantity);
aircrafts.push_back(newAircraft);
} else {
Aircraft lastAircraft = *(aircrafts.end()--);
Aircraft newAircraft = Aircraft::genNextAircraft(lastAircraft.arrivingTime, flowQuantity);
aircrafts.push_back(newAircraft);
}
}
ะะพะปะต arrivingTime ั ะฝะพะฒะพะณะพ ะพะฑัะตะบัะฐ ะณะตะฝะตัะธััะตััั ะฝะฐ ะพัะฝะพะฒะต ะทะฝะฐัะตะฝะธั ััะพะณะพ ะถะต ะฟะพะปั ั ะฟัะตะดัะดััะตะณะพ ัะณะตะฝะตัะธัะพะฒะฐะฝะฝะพะณะพ ะพะฑัะตะบัะฐ. ะงัะพะฑั ะตะณะพ ะฟะพะปััะธัั, ัะพะทะดะฐั ัััะปะบั ะฝะฐ ะฟะพัะปะตะดะฝะธะน ะฒ ะฒะตะบัะพัะต ะพะฑัะตะบั. ะะฐัะตะผ ะฒ ะบะพะฝััััะบัะพัะต ะดะปั ะฝะพะฒะพะณะพ ะพะฑัะตะบัะฐ ัะถะต ะฑะตัั ะทะฝะฐัะตะฝะธะต ะฒ ะฟะพะปะต ะฟัะตะดัะดััะตะณะพ ะพะฑัะตะบัะฐ.
ะะตะฑะฐะณ ะฟะพะบะฐะทะฐะป, ััะพ ะฒ ััะพ ัััะพะบะต
Aircraft lastAircraft = *(aircrafts.end()--);
ะฟัะธะปะตัะฐะตั ะผััะพั. ะกะบะพัะตะต ะฒัะตะณะพ, ะฟัะพะธัั
ะพะดัั ะฝะตะฟะพะฝััะบะธ ั ะพะฟะตัะฐัะพัะพะผ = ะดะปั ัะปะพะถะฝัั
ะพะฑัะตะบัะพะฒ. ะะฐะบ ะตะณะพ ะฟะตัะตะพะฟัะตะดะตะปะธัั? ะะฐัะตะป ะฒะฐัะธะฐะฝัั ั ั
ะฐะฑัะฐ ะธ ะดััะณะธั
ัะตััััะพะฒ, ะพะดะฝะฐะบะพ ะฝะต ัะฐะฑะพัะฐะตั.
A:
*(aircrafts.end()--);
ะัะฐะบ, ััะพ ะดะตะปะฐะตััั...
ะะพะปััะฐะตะผ ะธัะตัะฐัะพั, ะบะพัะพััะน ัะบะฐะทัะฒะฐะตั ะทะฐ ะบะพะฝะตั ะฒะตะบัะพัะฐ. ะัะฟะพะปะฝัะตะผ ะฟะพัััะธะบัะฝัะน --, ะบะพัะพััะน ะฒะพะทะฒัะฐัะฐะตั ะทะฝะฐัะตะฝะธะต ะดะพ ะดะตะบัะตะผะตะฝัะฐ, ะธ ัะฐะทัะผะตะฝะพะฒัะฒะฐะตะผ ะตะณะพ. ะข.ะต. ะฟััะฐะตะผัั ะฟะพะปััะธัั ะทะฝะฐัะตะฝะธะต ะทะฐ ะบะพะฝัะพะผ ะฒะตะบัะพัะฐ.
ะััะด ะปะธ ัะฐะผ ะปะตะถะธั ััะพ-ัะพ ัะผะฝะพะต...
ะะพะฟัะพะฑัะนัะต ัะฝะฐัะฐะปะฐ ะฒัะฟะพะปะฝะธัั ะดะตะบัะตะผะตะฝั:
*(--aircrafts.end());
ะฅะพัั ะปะพะณะธัะฝะตะต ะฟะพะปััะธัั ะธะท ะฒะตะบัะพัะฐ ะฟะพัะปะตะดะฝะตะต ะทะฝะฐัะตะฝะธะต ั ะฟะพะผะพััั ัะฟะตัะธะฐะปัะฝะพ ะดะปั ััะพะณะพ ัะพะทะดะฐะฝะฝะพะน ััะฝะบัะธะธ back(). ะขะพะปัะบะพ ะฝัะถะฝะพ ัะฝะฐัะฐะปะฐ ัะฑะตะดะธัััั, ััะพ ะฒะตะบัะพั ะฝะต ะฟััั.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does the JavaScript scroll() function behave in reverse?
From this thread:
Vertical Scroll down and scroll up in Selenium WebDriver with java
I understand that scroll(xpos, ypos) needs:
positive value - scroll down
negative value - scroll up
However, isn't it that in the Cartesian Plane, down is negative for y-axis?
If anyone can clarify, that would be great. Thanks!
A:
I think, I have found a highly relevant reading and also proof:
Why is the origin in computer graphics coordinates at the top left?
And since browsers display through a monitor, the same applies.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL ะทะฐะฟัะพั ะฝะฐ ะผะฐะบัะธะผะฐะปัะฝะพะต ะบะพะปะธัะตััะฒะพ
ะะผะตะตััั ัะฐะฑะปะธัะบะฐ:
id|org_id|name|opinion|date|
1|1|ะบะฐะบะพะตัะพะฝะฐะทะฒะฐะฝะธะต|1|2013-08-02
2|1|ะบะฐะบะพะตัะพะฝะฐะทะฒะฐะฝะธะต|1|2013-08-01
3|2|ะบะฐะบะพะตัะพะฝะฐะทะฒะฐะฝะธะต|0|2013-08-03
4|3|ะบะฐะบะพะตัะพะฝะฐะทะฒะฐะฝะธะต|1|2013-08-04
5|3|ะบะฐะบะพะตัะพะฝะฐะทะฒะฐะฝะธะต|0|2013-08-01
ะะพะพะฑัะต ัะตะปั, ะฒััะฐัะธัั org_id ั ะผะฐะบัะธะผะฐะปัะฝัะผ ะบะพะป-ะฒะพะผ(COUNT) opinion = 1
ะฅะพัะตะปะพัั ะฑะตะท ัะธะบะปะพะฒ ะพะดะฝะธะผ sql ะทะฐะฟัะพัะพะผ, ะฝะพ ะฒ ะณะพะปะพะฒั ะฝะธ ัะตะณะพ ะฝะต ะปะตะทะตั
A:
SELECT `org_id`, SUM(`opinion`) as `opinion`
FROM `test`
GROUP BY `org_id`
ORDER BY `opinion` DESC
LIMIT 1
ะ ะฐะฑะพัะธะน ะฟัะธะผะตั ะฝะฐ SQL Fiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
nested conditional to check for feature image and custom field?
I have this working for the most part, but some of the syntax is wrong someplace because when the post DOESNT have a thumbnail, it still prints that last echo and closes a div outside of the conditional. Can someone help me get this syntax on this code right? Basically I want:
Check for venue image, if it's there, display it. If there IS a thumbnail image, then check for a custom field, if it's there, display it. If not, do nothing, if no venue image, do nothing.
Here is my code:
<?php
if ( has_post_thumbnail() )
echo '<div id="venue-single-img">';
{ // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail();
if ( get_post_meta($post->ID, 'Venue Image Notation', true) ) {
echo '<span>' . get_post_meta($post->ID, 'Venue Image Notation', true) . '</span>'; }
else {}
echo '</div>';
}
?>
A:
I believe this should do what you want:
<?php
if ( has_post_thumbnail() ) {
echo '<div id="venue-single-img">';
the_post_thumbnail();
if ( get_post_meta($post->ID, 'Venue Image Notation', true) ) {
echo '<span>' . get_post_meta($post->ID, 'Venue Image Notation', true) . '</span>';
}
echo '</div>';
}
?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Return string with dynamic SQL
I am using SQL Server 2008 and I have a variable @sqlFinal which is of type Varchar(500).
I fill the variable as the stored procedure runs. I want to dynamically return what is in the string to show the results
SELECT @sqlFinal = 'SELECT @Error_Return AS Final_Report'
--PRINT @sqlFinal
EXEC (@sqlFinal)
But I get the following error
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@Error_Return".
A:
I am assuming that @Error_Return is in the same scope as @SqlFinal?
If you just need to return the contents of @Error_Return, you can just execute this line:
SELECT @Error_Return as Final_Report
... making it a static SQL line rather than a dynamic one.
But if that's not acceptable, you may have to use sp_executeSQL instead. This allows you to pass variables to the line you're executing.
Declare @Error_Return VARCHAR(10)
Set @Error_return= 'Whatever'
exec sp_executesql N'SELECT @Error_Return as Final_Report', N'@Error_Return varchar(10)', @Error_Return
| {
"pile_set_name": "StackExchange"
} |
Q:
In a ControlTemplate, I want to apply the same style to all TextBlocks
I have a class library, in which I've created default styles for TextBlock, which is applied to every TextBlock in any application that uses this class library.
The problem is that I sometimes need to exclude TextBlocks inside some other controls (say, ribbon, or my own Custom Control). The textblocks are not accessible, for instance the ones inside a tab item heade.
Is there any ways to force wpf to use another style for all TextBlocks inside one control?
Thanks
A:
Ok. As it turns out, this is not possible, see Mike Strobel's answer for an explanation of the reason and the rational behind it.
The workaround is to not create an implicit style for TextBlock, because it will affect TextBlocks inside other ControlTemplates.
What works for me is to derive a class from TextBlock, say Label and apply my style to it, and then use it wherever I want a TextBlock with that specific style.
A more "Wpf Natural" way to deal with that is to create a style with a key.
| {
"pile_set_name": "StackExchange"
} |
Q:
What should the action attribute in menu.xml be?
In the file menu.xml located in MyNamespace\Mymodule\etc\adminhtml\menu.xml, I understand that this file allows me to add new items to the navigation menu in admin panel.
In the <add> tags, there is an action attribute that contains values that look like something/somethingelse. For eg:
<add id="MyNamespace_MyModule::mymodule_testing" title="Some title" module="MyNamespace_MyModule" sortOrder="10" action="Part_A/Part_B" />
What should be entered in the Part_A and Part_B of the action attribute? I doubt they are arbitrary. What do they refer to and what do they stand for? What effects would it have if I put in a wrong thing into this attribute?
A:
the action part of the menu is the actual url of the menu item.
It should be module/controller/action or module/controller if the action is index.
take a look at this example from the core for the cms page menu link
<add id="Magento_Cms::cms_page" title="Pages" translate="title" module="Magento_Cms" sortOrder="0" parent="Magento_Backend::content_elements" action="cms/page" resource="Magento_Cms::page"/>
action looks like this: action="cms/page".
This means that the menu item is going to link to the cms module and the Page controller and index action.
the first part cms in this case, is the front name you declared in the adminhtml/routes.xml for your menu.
The second part is the name of the controller folder (lowercase) found int the Controller folder and the last part is the actual controller action file (lowercase and without the php extension) or it can be missing if the action name is index.
A:
Let's say you have the following:
In your etc/adminhtml/routes.xml you declare the following route name:
<route id="hello" frontName="hello">
<module name="Vendor_Module" />
</route>
Then under Controller/Adminhtml you have a folder called World
And finally in this World folder you have an action class called Grid.php
Then the action attribute to access this controller action class should be hello/world/grid
A:
The action attribute is the action which you want to do after clicking on that menu.you need to pass url over there front name/yourcontroller/action.
Lets take example of magento-catalog module.
<add id="Magento_Catalog::catalog_products" title="Catalog" translate="title" module="Magento_Catalog" sortOrder="10" parent="Magento_Catalog::inventory" action="catalog/product/" resource="Magento_Catalog::products"/>
Here action is catalog/product so catalog is the controller and product is the action and it will go tho that particular url and perform the action.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get a index value from foreach loop in jstl
I have a value set in the request object like the following,
String[] categoriesList=null;
categoriesList = engine.getCategoryNamesArray();
request.setAttribute("categoriesList", categoriesList );
and this is how I iterate in jsp page
<% if(request.getAttribute("categoriesList") != null) { %>
<c:forEach var="categoryName" items="${categoriesList}">
<li><a onclick="getCategoryIndex()" href="#">${categoryName}</a></li>
</c:forEach>
<% }%>
How do I get index of each element and pass it to JavaScript function onclick="getCategoryIndex()".
A:
use varStatus to get the index c:forEach varStatus properties
<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
<li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>
A:
I face Similar problem now I understand we have some more option :
varStatus="loop", Here will be loop will variable which will hold the index of lop.
It can use for use to read for Zeor base index or 1 one base index.
${loop.count}` it will give 1 starting base index.
${loop.index} it will give 0 base index as normal Index of array start from 0.
For Example :
<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
<source srcset="${currentImage}" media="(min-width: 1000px)"></source>
<source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
<img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>
For more Info please refer this link
A:
You can use the varStatus attribute like this:-
<c:forEach var="categoryName" items="${categoriesList}" varStatus="myIndex">
myIndex.index will give you the index. Here myIndex is a LoopTagStatus object.
Hence, you can send that to your javascript method like this:-
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
| {
"pile_set_name": "StackExchange"
} |
Q:
Sencha touch + phonegap in android
I need to develop an app in Sencha touch and phonegap in android.I got decent performance in iphone.Does it produce good performance in Android?
A:
Use sencha touch 2 for android. They have improved the performance significantly and also resolved most of the issues on android. To use phonegap you need android 2.2 so most of the devices that have this OS have good performance so you should be ok.
| {
"pile_set_name": "StackExchange"
} |
Q:
monad bind operation on a list not intuitive to follow
I find the Option Monad to be intuitive to understand, while List is not.
Some(1) >>= { x=>Some(x+1)}
Ma -> a -> Mb -> Mb
if I extract value from Some(1) I know it is 1
but in the list case
List(3,4,5) flatMap { x=> List(x,-x) }
if I extract value from List, what do I get ? how to make the understanding process intuitive
A:
Intuition behind an Option or Maybe is actually very similar to List monad. The main difference is that List is non-deterministic - we don't know how many values we can get, when with Option it's always one on success and zero on failure. Empty list is considered a failure.
I think this piece describes it quite well:
For lists, monadic binding involves joining together a set of
calculations for each value in the list. When used with lists, the
signature of >>= becomes:
(>>=) :: [a] -> (a -> [b]) -> [b]
That is, given a list of a's and a function that maps an a onto a list
of b's, binding applies this function to each of the a's in the input
and returns all of the generated b's concatenated into a list.
And an example of list implementation:
instance Monad [] where
return x = [x]
xs >>= f = concat (map f xs)
fail _ = []
Sorry for putting Haskell into Scala answer, but that was the resource I used to understand this stuff.
Scala's flatMap is not exactly Haskell's bind >>=, but quite close to it. So what does it all mean?:
Imagine a practical situation where you have a list of clients List[Client], you can bind them to a single list of orders List[Order] that will be automatically flattened for you with flatMap or >>=. If you would use a map instead, you would get a List[List[Order]]. In practice you will provide the function for >>= to use, similarly how you provide a function to fold - you decide how data has to be generated/aggregated/etc. What bind does for you is to provide a general pattern for combining two monadic values and for each type of monads implementation will be unique.
You might prefer to look at it at as multiple levels of abstraction (from more general to less):
Monad has bind operation that will combine two monadic values into one: (>>=) :: m a -> (a -> m b) -> m b.
List as a monad instance implements bind with something like this: xs >>= f = concat (map f xs) - map the function over all elements and concatenate results into a single list.
You provide an implementation of the function f for the bind function depending on your needs (the clients -> orders example).
Once you know how bind behaves for your monad instances (List, Option) you can think in terms of just using it and "forget" about actual implementation.
| {
"pile_set_name": "StackExchange"
} |
Q:
(UNITY3D) ะะฐะบ ะฟัะตะฒัะฐัะธัั ัััะธะฝะณะพะฒะพะต ะทะฝะฐัะตะฝะธะต ะฒ ะฝะฐะทะฒะฐะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน?
ะ ะพะฑัะตะผ, ะดะพะฟัััะธะผ, ััะพ ั ั
ะพัั ัะดะฐะปะธัั ะฝะตะบะธะน ะพะฑัะตะบั, ะบะพัะพััะน ะฝะฐะทัะฒะฐะตััั Player1. ะะฐะบ ะผะฝะต ะฟัะตะฒัะฐัะธัั ััั ัััะพะบั ะฒ ะฝะฐะทะฒะฐะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน?
Rigidbody Player1;
Destroy("Player" + "1");
A:
Destroy("Player" + "1");
Destroy ััะพ ะฝะต ะฟัะพ ะบะฐะบัั-ัะพ ะฐะฑัััะฐะบัะฝัั ะฟะตัะตะผะตะฝะฝัั. ะฐ ะบะพะฝะบัะตัะฝะพ GameObject.
ะฒ ะฝะฐะทะฒะฐะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน?
ะะพั ะฝะฐะทะฒะฐะฝะธะต: GameObject.name ะพะฝะพ ะธ ัะฐะบ string, ะฝะธัะตะณะพ "ะฟัะตะฒัะฐัะฐัั" ะฝะต ััะตะฑัะตััั.
if (someGameObject.name == "Player"+"1")
Destroy(someGameObject);
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebase Authentication session does not expired
I use Firebase Authentication for login and sign up in my app.
It works fine but problem is when I delete a user manually from the Firebase Authentication page then open the app the user i deleted still logged in.
Aren't there any way to fix this problem ?
A:
Its probably due to you using Access Token and Access Token is still valid even though you deleted user. To avoid that problem easy fix would be when you start app try to Refresh Access Token.
You should also look into how long token is valid.. Maybe try to shorten expiration time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the ASP.NET MVC 3 WebGrid control support hierarchical data?
I am adapting an existing ASP.NET MVC 3 WebGrid to display more data. It currently displays one level of data, but I need to show parent-child relationships in the grid. Is this possible, or will I have to look into a third-party control, or roll my own?
A:
If you want webgrid to do it by itself, then answer is no its not possible directly. Simple nested grids you can achieve like this... Razor Nested WebGrid
To have entire grid inside another grid, you can use jQuery, AJAX multiple views to achieve this. On expand of any row call another action with ajax which will render child grid and not any other html. Use the resulted html to insert in a new row in the parent grid table. Something on these lines...
$.ajax({
url: childGridUrlString,
type: 'post',
async: true,
timeout: 10 * 1000,
success: function (data, textStatus, jqXHR) {
if (!data.Status) {
var $tr = $obj.closest("tr", $("#parentgrid"));
var $newTr = "<tr><td colspan=\"4\">" + data + "</td></tr>";
$("<tr><td> </td><td colspan=\"3\">" + data + "</td></tr>").insertAfter($tr);
}
},
});
Take care of colspans as per number of columns you have in parent and child grid. Important thing, in built sorting feature of WebGrid doesn't work properly with this type of parent child grid display.
Off course, third party controls are always an option, but you will have to consider cost as well and even they will have some coding to do.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP 7 cannot find MySQLi
For some reason, Windows 7 is unable to find the MySQL install. I've tried quite a few things to little or no avail.
I want to connect to my MySQL database with php using this code:
$con = new mysqli($server_name,$mysql_user,$mysql_pass,$db_name);
if($con->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
else{
echo "<h3> Database Connected <h3>";
}
When I do connect, I receive this error message:
Fatal error: Uncaught Error: Class 'mysqli' not found in C:\Apache\htdocs\test_connection.php:8 Stack trace: #0 {main} thrown in C:\Apache\htdocs\test_connection.php on line 8
I ran this code and it returns that I don't have mysqli loaded:
if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
echo 'We don\'t have mysqli!!! ';
} else {
echo 'Phew we have it!';
}
I have added
extension_dir = "C:\php\ext"
and
extension=php_mysqli.dll
to both php.ini-development and php.ini-production
I have my extensions in
C:\php\ext
and I also have the php_mysqli.dll file in that folder.
I have added the following code to the end of my httpd.exe file in Apache
LoadModule php7_module "c:/php/php7apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "c:/php"
A:
Change
LoadModule php7_module "c:/php/php7apache2_4.dll"
to
LoadModule php7_module /php/php7apache2_4.dll
and
PHPIniDir "c:/php"
to
PHPIniDir /php
I fought this problem for days and the answer was that simple.
A:
For me (on linux debian version) when I migrated from php5 + ubuntu 14 over to php7 + ubuntu 16, it was:
sudo apt-get install php-mysql
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Naruto allowed to teach Rasengan to Konohamaru?
Kakashi tells Jiraiya that Rasengan is a dangerous technique after he stopped Naruto and Sasuke who fought for the first time. If it is that dangerous, then why was Naruto allowed to teach Rasengan to Konohamaru?
A:
Although Rasengan may be a very dangerous technique, it's not a forbidden technique, so anybody can teach it to everybody.
The Naruto wiki has the categories for forbidden Jutsus:
Techniques that cause harm to the user themselves, such as opening the Eight Gates, which the mere use of is both highly useful as well as detrimental to the user.
Techniques that violate the laws of nature (e.g. the Summoning: Impure World Reincarnation, which reincarnates the dead with a human sacrifice).
Certain techniques that are known to cause massive collateral damage, such as the total destruction of a village and end with the death of everyone in it, thus the great moral ramifications of its potential lead many to labelling it as a forbidden technique.
Rasengan does not fit in any of these categories, so it's most likely not a forbidden Jutsu ;).
| {
"pile_set_name": "StackExchange"
} |
Q:
Issues pausing / playing an AVPlayer
I have an AVPlayer that I want to pause and resume when it's tapped.
The way I decided to go about this is by utilizing a tapGestureRecognizer on the view that the AVPlayer is attached to.
when there is a tap a boolean, variable didSelect becomes true. When there is second tap, didSelect becomes false.
Interestingly enough, when I use
if didSelect == false {
player.play()
}
if didSelect == true {
player.pause()
}
in the AVPlayerItemDidPlayToEndTime notification, it works fine but only after the video complete. Which makes me wonder if there is some notification along the lines of AVPlayerItemIsPlaying but I haven't found anything.
Here's what the code looks like.
playerView.layer.cornerRadius = playerView.bounds.width * 0.025
guard let path = Bundle.main.path(forResource: "video", ofType:"mp4") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = playerView.frame
playerLayer.frame = self.frame
playerLayer.frame = playerView.bounds
playerLayer.masksToBounds = true
playerLayer.cornerRadius = playerView.bounds.width * 0.025
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.playerView.layer.addSublayer(playerLayer)
player.isMuted = true
player.play()
if didSelect == false {
player.play()
}
if didSelect == true {
player.pause()
}
//looper
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: nil)
{ notification in
let t1 = CMTimeMake(5, 100)
player.seek(to: t1)
player.play()
}
A:
I created a global reference to player
var player: AVPlayer?
and referenced that in a UITapGestureRecognizer function and now control the pausing / playing from there.
| {
"pile_set_name": "StackExchange"
} |
Q:
If I have a maxed-out stat, can I take a half-ASI feat?
My character has 20 charisma in one of my DND games, but I want to take the Actor feat. This question kind of has two parts:
RAW, can I take it and change the stat increase to another stat?
If I take it and change the stat increase to another stat is it balanced still?
A:
Yes, you can take the feat
The feat's first bullet point is:
Increase your Charisma score by 1, to a maximum of 20.
If your character's Charisma is already 20, then the feat will not increase it further.
Feats have minimum ability score prerequisites, but not maximum ones.
No, you can't use the increase on another ability score
If you could then the feat would have said so.
A:
(1) RAW, no, you cannot take it and change the stat increase to another stat.
(2) Yes, this is balanced -- with slightly better planning, you could have put one of your previous ASIs into that other stat, so that your CHA would be 19 and could be boosted to 20 with the Actor feat. It's reasonable to let you make this change so as to not penalize you for previous bad planning.
| {
"pile_set_name": "StackExchange"
} |
Q:
trying to download a file from an azure file share via react app
i am trying to download a file from an azure file share via react app
i connect fine make a file client and download it using this method
there isn't much in the way of documentation, so i'm trying to navigate the promise to get the file contents to download them using this
the objects im getting returned are below from the console logging.
{
"lastModified": "2020-04-09T21:01:45.000Z",
"metadata": {},
"contentType": "application/x-zip-compressed",
"requestId": "xxx-401a-004e-193c-xxx",
"version": "2019-07-07",
"isServerEncrypted": true,
"fileAttributes": "Archive",
"fileCreatedOn": "2020-04-09T21:01:45.148Z",
"fileLastWriteOn": "2020-04-09T21:01:45.148Z",
"fileChangeOn": "2020-04-09T21:01:45.148Z",
"filePermissionKey": "xxx*xxx",
"fileId": "xxxxx",
"fileParentId": "xxxxx",
"leaseState": "available",
"leaseStatus": "unlocked",
"blobBody": {}
}
...
blobBody: Promise { "fulfilled" }
โโ
<state>: "fulfilled"
โโ
<value>: Blob
โโโ
size: 1960118
โโโ
type: "application/x-zip-compressed"
โโโ
<prototype>: BlobPrototype
โโโโ
arrayBuffer: function arrayBuffer()
โโโโ
constructor: function ()
โโโโ
size:
โโโโ
slice: function slice()
โโโโ
stream: function stream()
โโโโ
text: function text()
โโโโ
i tried calling the stream or arrayBuffer functions, but i can't seem to access anything inside of the promise
console.log(`downloading file: ${fileName}`)
const fileClient = this.state.doneDirClient.getFileClient(fileName)
const file = await fileClient.download()
console.log(file)
console.log(file.blobBody.Blob)
last line returns undefined
edit with altered code that worked:
async download(fileName: string) {
const fileClient = this.state.doneDirClient.getFileClient(fileName)
const file = await fileClient.download()
Promise.resolve(file.blobBody).then(function (value) {
fileDownload(value, fileName)
});
}
How can i get the file contents?
A:
If you look at the definition of FileDownloadResponse, you will notice that blobBody parameter is essentially a Promise.
type FileDownloadResponse = FileDownloadHeaders & { _response: Object, blobBody: Promise<Blob>, readableStreamBody: NodeJS.ReadableStream }
Once you resolve that promise, you should get Blob.
| {
"pile_set_name": "StackExchange"
} |
Q:
My object is not moving smoothly, but in increments of one unit
What is preventing my objects from moving smoothly? Instead of moving slowly and precisely, the object moves by one unit
.
A:
Hit shift+tab while in object mode to Exit Transform Snapping
For 2.79
(source: blender.org)
For 2.8
| {
"pile_set_name": "StackExchange"
} |
Q:
I need to convert a string date to an actual date
I have a Date field in a table that is an int. The value looks like this: 20130618 I want to be able to convert that to an actual date like 06/18/2013 so I can do date calculations on it. How do I convert that field?
A:
select convert(date, left(20130618, 8), 101)
or
select convert(date, cast(20130618 as char(8)), 101)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to apply discount on woocommerce subtotal and total on checkout?
We are trying this type of code it changes subtotal but we want to change total according to subtotal without adding any discount field in order table.
// define the woocommerce_cart_subtotal callback
function filter_woocommerce_cart_subtotal( $array, $int, $int ) {
// make filter magic happen here...
};
// add the filter
add_filter( 'woocommerce_cart_subtotal', 'filter_woocommerce_cart_subtotal', 10, 3 );
A:
Well, you're using the wrong hook. That filter is to change the display sub total.
What you need is this:
add_action( 'woocommerce_calculate_totals', 'woocommerce_calculate_totals', 30 );
function woocommerce_calculate_totals( $cart ) {
// make magic happen here...
// use $cart object to set or calculate anything.
if ( 'excl' === $cart->tax_display_cart ) {
$cart->subtotal_ex_tax = 400;
} else {
$cart->subtotal = 350;
}
}
above will result to subtotal displayed as 350 or 400, depending on your tax settings but regardless of what products are in cart. Because we are setting subtotal without logic. Add your own logic.
you can also use woocommerce_after_calculate_totals using the same concept as above.
add_action( 'woocommerce_after_calculate_totals', 'woocommerce_after_calculate_totals', 30 );
function woocommerce_after_calculate_totals( $cart ) {
// make magic happen here...
// use $cart object to set or calculate anything.
if ( 'excl' === $cart->tax_display_cart ) {
$cart->subtotal_ex_tax = 400;
} else {
$cart->subtotal = 350;
}
$cart->total = 50;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the distribution of X, EX, and VarX.
Suppose that the random variable $X$ is uniformly distributed symmetrically around zero, but in such a way that the parameter is uniform on $(0,1)$; that is, suppose that $$X\mid A=a\in U(-a,a) \text{ with } A\in U(0,1).$$ Find the distribution of $X$, $EX$, and $\operatorname{Var}X$.
The answers in the book are $f_X(x)=-\frac{1}{2} \log|x|, \; -1<x<1; \; EX=0, \text{ and } \operatorname{Var}X=\frac{1}{9}$.
Any help on how to work this type of problem would be greatly appreciated.
A:
Let $Y\sim U([0,1])$ and $X|Y=y\sim U([-y,y])$
We know that by definition: $f(x,y)=f_{Y}(y)\cdot f_{X|Y}(x|y)$.
Since $Y\sim U([0,1])$ we have it that $f_{Y}(y)=1$ when $y\in[0,1]$
and is zero otherwise. thus $f(x,y)=0$ when $y\not\in[0,1]$ and
is $f_{X|Y}(x|y)$ otherwise.
We are also given that $X|Y=y\sim U([-y,y])$ hence $f_{X|Y}(x|y)=\frac{1}{y-(-y)}=\frac{1}{2y}$
when $x\in[-y,y]$ and is zero otherwise.
We conclude
$$
f(x,y)=\begin{cases}
\frac{1}{2y} & y\in[0,1],x\in[-y,y]\\
0 & \text{otherwise}
\end{cases}
$$
Note that $x\in[-y,y]$ means $-y\leq x\leq y$, and thus $y\geq x$,
it is also clear that $y\leq1$
Also, $x\geq-y$ means $y\geq-x$ and since also $y\geq x$ we get
$y\geq|x|$
Now that we have the joint density we can get $f_{X}(x)$ by integrating:
$$
f_{X}(x)=\int_{-\infty}^{\infty}f(x,y)\, dy=\int_{|x|}^{1}\frac{1}{2y}\, dy=\frac{1}{2}(\log(y)|_{|x|}^{1})=\frac{1}{2}(\log(1)-\log(|x|))=-\frac{1}{2}\log|x|
$$
Now, $EX=EE[X|Y]$. $X|Y\sim U([-y,y])$ hence $E[X|Y|]=\frac{y+(-y)}{2}=0$.
Thus $EX=E[0]=0$.
Now we can calculate $Var(X)$:
$$
Var(X)=EX^{2}-(EX)^{2}=EX^{2}
$$
Since $x\in[-y,y]$ and $y\in[0,1]$ we have it that $x\in[-1,1]$.
$$
EX^{2}=\int_{-\infty}^{\infty}x^{2}f_{X}(x)\, dx
$$
$$
=\int_{-1}^{1}x^{2}\cdot-\frac{1}{2}\log(|x|)\, dx
$$
$$
=-\frac{1}{2}\int_{-1}^{1}x^{2}\log(|x|)\, dx
$$
Using integration by parts with $u=\log(|x|),v'=x^{2}$we get
$$
\int x^{2}\log(|x|)\, dx=\log(|x|)\cdot\frac{x^{3}}{3}-\int\frac{1}{x}\cdot\frac{x^{3}}{3}=\log(|x|)\cdot\frac{x^{3}}{3}-\frac{1}{3}\cdot\frac{x^{3}}{3}=\frac{x^{3}}{3}(\log(|x|)-\frac{1}{3})
$$
Hence
$$
-\frac{1}{2}\int_{-1}^{1}x^{2}\log(|x|)\, dx
$$
$$
=-\frac{1}{2}(\frac{x^{3}}{3}(\log(|x|)-\frac{1}{3})|_{-1}^{1})
$$
$$
=-\frac{1}{2}(\frac{1^{3}}{3}(\log(|1|)-\frac{1}{3})-\frac{(-1)^{3}}{3}(\log(|-1|)-\frac{1}{3}))
$$
$$
=-\frac{1}{2}(-\frac{1}{3\cdot3}-\frac{1}{3\cdot3})=\frac{1}{9}
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
After renewing letsencrypt SSL certifications, server only returns response code 400
I recently tried to renew my letsencrypt ssl certificate, but once I did that, Iโve been coming down with 400 server responses whenever I try to connect to my website. Iโve tried absolutely everything I can think of. I have attached a copy of my Nginx error log file with the level set to debug, and my server configuration file. Any help is super appreciated.
I'm using Django, Nginx, and Gunicorn on my server.
I ran the command
certbot renew
to renew the cert.
Once that was done, I got nothing but 400 responses.
In addition, when I try to connect to the site, I get a Django error output:
Report at /
Invalid HTTP_HOST header: 'testing.com,testing.com'. The domain name provided is not valid according to RFC 1034/1035.
It might have something to do with the repeated url, but I'm not sure if that's it either.
Below is my nginx configuration file in sites-available.
server { # redirection logic
listen 80; # port to listen on
return 301 https://$host$request_uri*;
}
server {
listen 443 ssl; # listen for HTTPS
server_name testing.com www.testing.com; # server name to use
ssl_certificate /etc/letsencrypt/live/testing.com/fullchain.pem; # ssl certs
ssl_certificate_key /etc/letsencrypt/live/dt-testing.com/privkey.pem;
location = /favicon.ico { access_log off; log_not_found off; } # site icon to use
location /static/ { # location of static files
root /websites/DT/path/;
}
location / {
proxy_set_header Host $host;
include proxy_params;
proxy_pass http://unix:/websites/DT/run/gunicorn.sock; # connector to gunicorn
#error_page 405 =200 $uri;
}
rewrite_log on;
error_log /var/log/nginx/error_log debug;
}
Here is my nginx debug log output.
"GET / HTTP/1.0
Host: testing.com
Host: testing.com
X-Real-IP: 185.252.151.5
X-Forwarded-For: 185.252.151.5
X-Forwarded-Proto: https
Connection: close
User-Agent: Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6P Build/NOF27C) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.81 Mobile Safari/537.36
Accept-Language: en-us,en-gb,en;q=0.7,*;q=0.3
Accept-Charset: utf-8,ISO-8859-1;q=0.7,*;q=0.7
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: x-gzip, gzip, deflate
"
2019/04/06 00:02:56 [debug] 11579#11579: *12 http cleanup add: 000055DF21463240
2019/04/06 00:02:56 [debug] 11579#11579: *12 get rr peer, try: 1
2019/04/06 00:02:56 [debug] 11579#11579: *12 stream socket 15
2019/04/06 00:02:56 [debug] 11579#11579: *12 epoll add connection: fd:15 ev:80002005
2019/04/06 00:02:56 [debug] 11579#11579: *12 connect to unix:/websites/DT/run/gunicorn.sock, fd:15 #13
2019/04/06 00:02:56 [debug] 11579#11579: *12 connected
2019/04/06 00:02:56 [debug] 11579#11579: *12 http upstream connect: 0
2019/04/06 00:02:56 [debug] 11579#11579: *12 posix_memalign: 000055DF2142F410:128 @16
2019/04/06 00:02:56 [debug] 11579#11579: *12 http upstream send request
2019/04/06 00:02:56 [debug] 11579#11579: *12 http upstream send request body
2019/04/06 00:02:56 [debug] 11579#11579: *12 chain writer buf fl:1 s:524
2019/04/06 00:02:56 [debug] 11579#11579: *12 chain writer in: 000055DF214F97D0
2019/04/06 00:02:56 [debug] 11579#11579: *12 writev: 524 of 524
2019/04/06 00:02:56 [debug] 11579#11579: *12 chain writer out: 0000000000000000
2019/04/06 00:02:56 [debug] 11579#11579: *12 event timer add: 15: 60000:4664042409
2019/04/06 00:02:56 [debug] 11579#11579: *12 http finalize request: -4, "/?" a:1, c:2
2019/04/06 00:02:56 [debug] 11579#11579: *12 http request count:2 blk:0
2019/04/06 00:02:56 [debug] 11579#11579: *12 http run request: "/?"
2019/04/06 00:02:56 [debug] 11579#11579: *12 http upstream check client, write event:1, "/"
2019/04/06 00:02:56 [debug] 11579#11579: *12 http upstream request: "/?"
2019/04/06 00:02:56 [debug] 11579#11579: *12 http upstream dummy handler
2019/04/06 00:02:57 [debug] 11579#11579: *12 http upstream request: "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http upstream process header
2019/04/06 00:02:57 [debug] 11579#11579: *12 malloc: 000055DF21502980:4096
2019/04/06 00:02:57 [debug] 11579#11579: *12 recv: eof:1, avail:1
2019/04/06 00:02:57 [debug] 11579#11579: *12 recv: fd:15 160 of 4096
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy status 400 "400 Bad Request"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy header: "Server: gunicorn/19.9.0"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy header: "Date: Sat, 06 Apr 2019 00:02:57 GMT"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy header: "Connection: close"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy header: "Content-Type: text/html"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy header done
2019/04/06 00:02:57 [debug] 11579#11579: *12 xslt filter header
2019/04/06 00:02:57 [debug] 11579#11579: *12 HTTP/1.1 400 Bad Request
Server: nginx/1.15.5 (Ubuntu)
Date: Sat, 06 Apr 2019 00:02:57 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
2019/04/06 00:02:57 [debug] 11579#11579: *12 write new buf t:1 f:0 000055DF214F9AC8, pos 000055DF214F9AC8, size: 173 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 http write filter: l:0 f:0 s:173
2019/04/06 00:02:57 [debug] 11579#11579: *12 http cacheable: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 posix_memalign: 000055DF21503990:4096 @16
2019/04/06 00:02:57 [debug] 11579#11579: *12 http proxy filter init s:400 h:0 c:0 l:-1
2019/04/06 00:02:57 [debug] 11579#11579: *12 http upstream process upstream
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe read upstream: 1
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe preread: 26
2019/04/06 00:02:57 [debug] 11579#11579: *12 readv: eof:1, avail:0
2019/04/06 00:02:57 [debug] 11579#11579: *12 readv: 1, last:3936
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe recv chain: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe buf free s:0 t:1 f:0 000055DF21502980, pos 000055DF21502A06, size: 26 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe length: -1
2019/04/06 00:02:57 [debug] 11579#11579: *12 input buf #0
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe write downstream: 1
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe write downstream flush in
2019/04/06 00:02:57 [debug] 11579#11579: *12 http output filter "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http copy filter: "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 image filter
2019/04/06 00:02:57 [debug] 11579#11579: *12 xslt filter body
2019/04/06 00:02:57 [debug] 11579#11579: *12 http postpone filter "/?" 000055DF214F9B88
2019/04/06 00:02:57 [debug] 11579#11579: *12 http chunk: 26
2019/04/06 00:02:57 [debug] 11579#11579: *12 write old buf t:1 f:0 000055DF214F9AC8, pos 000055DF214F9AC8, size: 173 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write new buf t:1 f:0 000055DF21503B30, pos 000055DF21503B30, size: 4 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write new buf t:1 f:0 000055DF21502980, pos 000055DF21502A06, size: 26 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write new buf t:0 f:0 0000000000000000, pos 000055DF20B058DA, size: 2 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 http write filter: l:0 f:0 s:205
2019/04/06 00:02:57 [debug] 11579#11579: *12 http copy filter: 0 "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 pipe write downstream done
2019/04/06 00:02:57 [debug] 11579#11579: *12 event timer del: 15: 4664042409
2019/04/06 00:02:57 [debug] 11579#11579: *12 event timer add: 15: 60000:4664043593
2019/04/06 00:02:57 [debug] 11579#11579: *12 http upstream exit: 0000000000000000
2019/04/06 00:02:57 [debug] 11579#11579: *12 finalize http upstream request: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 finalize http proxy request
2019/04/06 00:02:57 [debug] 11579#11579: *12 free rr peer 1 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 close http upstream connection: 15
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF2142F410, unused: 48
2019/04/06 00:02:57 [debug] 11579#11579: *12 event timer del: 15: 4664043593
2019/04/06 00:02:57 [debug] 11579#11579: *12 reusable connection: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 http upstream temp fd: -1
2019/04/06 00:02:57 [debug] 11579#11579: *12 http output filter "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http copy filter: "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 image filter
2019/04/06 00:02:57 [debug] 11579#11579: *12 xslt filter body
2019/04/06 00:02:57 [debug] 11579#11579: *12 http postpone filter "/?" 00007FFD2D728F60
2019/04/06 00:02:57 [debug] 11579#11579: *12 http chunk: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write old buf t:1 f:0 000055DF214F9AC8, pos 000055DF214F9AC8, size: 173 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write old buf t:1 f:0 000055DF21503B30, pos 000055DF21503B30, size: 4 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write old buf t:1 f:0 000055DF21502980, pos 000055DF21502A06, size: 26 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write old buf t:0 f:0 0000000000000000, pos 000055DF20B058DA, size: 2 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 write new buf t:0 f:0 0000000000000000, pos 000055DF20B058D7, size: 5 file: 0, size: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 http write filter: l:1 f:0 s:210
2019/04/06 00:02:57 [debug] 11579#11579: *12 http write filter limit 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 posix_memalign: 000055DF21506530:512 @16
2019/04/06 00:02:57 [debug] 11579#11579: *12 malloc: 000055DF214ED330:16384
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL buf copy: 173
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL buf copy: 4
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL buf copy: 26
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL buf copy: 2
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL buf copy: 5
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL to write: 210
2019/04/06 00:02:57 [debug] 11579#11579: *12 SSL_write: 210
2019/04/06 00:02:57 [debug] 11579#11579: *12 http write filter 0000000000000000
2019/04/06 00:02:57 [debug] 11579#11579: *12 http copy filter: 0 "/?"
2019/04/06 00:02:57 [debug] 11579#11579: *12 http finalize request: 0, "/?" a:1, c:1
2019/04/06 00:02:57 [debug] 11579#11579: *12 set http keepalive handler
2019/04/06 00:02:57 [debug] 11579#11579: *12 http close request
2019/04/06 00:02:57 [debug] 11579#11579: *12 http log handler
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF21502980
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF21462260, unused: 8
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF214F8C60, unused: 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF21503990, unused: 3070
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF214181D0
2019/04/06 00:02:57 [debug] 11579#11579: *12 hc free: 0000000000000000
2019/04/06 00:02:57 [debug] 11579#11579: *12 hc busy: 0000000000000000 0
2019/04/06 00:02:57 [debug] 11579#11579: *12 free: 000055DF214ED330
2019/04/06 00:02:57 [debug] 11579#11579: *12 reusable connection: 1
2019/04/06 00:02:57 [debug] 11579#11579: *12 event timer add: 8: 65000:4664048593
2019/04/06 00:02:58 [debug] 11579#11579: *12 http keepalive handler
2019/04/06 00:02:58 [debug] 11579#11579: *12 malloc: 000055DF214181D0:1024
2019/04/06 00:02:58 [debug] 11579#11579: *12 SSL_read: 0
2019/04/06 00:02:58 [debug] 11579#11579: *12 SSL_get_error: 6
2019/04/06 00:02:58 [debug] 11579#11579: *12 peer shutdown SSL cleanly
2019/04/06 00:02:58 [info] 11579#11579: *12 client 185.252.151.5 closed keepalive connection
2019/04/06 00:02:58 [debug] 11579#11579: *12 close http connection: 8
2019/04/06 00:02:58 [debug] 11579#11579: *12 SSL_shutdown: 1
2019/04/06 00:02:58 [debug] 11579#11579: *12 event timer del: 8: 4664048593
2019/04/06 00:02:58 [debug] 11579#11579: *12 reusable connection: 0
2019/04/06 00:02:58 [debug] 11579#11579: *12 free: 000055DF214181D0
2019/04/06 00:02:58 [debug] 11579#11579: *12 free: 0000000000000000
2019/04/06 00:02:58 [debug] 11579#11579: *12 free: 000055DF21431E10, unused: 16
2019/04/06 00:02:58 [debug] 11579#11579: *12 free: 000055DF21506530, unused: 400
A:
I figured out what the problem was. I suspect that cerbot renew updated the nginx software somehow, which made it render the configuration file above differently. The line proxy set header was the one doubling the incoming header, but because I had a bug in my Python code on the Django side, it wasn't working.
| {
"pile_set_name": "StackExchange"
} |
Q:
Which APIs trigger "app would like to control this computer using accessibility features"?
I've noticed that on newer macOS versions my app suddenly shows this security warning:
(screenshot taken from here because my system is in German)
Now I'm wondering why macOS is showing this. I don't remember using any accessibility features but of course I must be using some because otherwise this security warning would not appear. I've checked my code and I'm not using any features from NSAccessibility. But since I get this warning, there must be other calls that trigger it as well. But how to find them?
That's why I'd like to ask how I can find out what Cocoa APIs are actually causing this security warning to appear? What should I look for? Is there a list of functions/classes that trigger this warning?
Note that I'm not using Xcode but I'm building my app in a very old-fashioned way using a set of makefiles.
A:
This is not really a complete answer to the question but at least I've found out the culprit now. I had some code in there that allowed the user to programmatically move the mouse cursor. Disabling this code made the warning go away. The code looks like this:
CGPoint p;
CGEventRef me;
p.x = x;
p.y = y;
if(!(me = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, p, 0))) return;
CGEventPost(kCGHIDEventTap, me);
CFRelease(me);
| {
"pile_set_name": "StackExchange"
} |
Q:
Thumbnail from UiImagepicker video
I picked a video from album using UIImagePickerController and trying to generate thumbnail from it using below function:
func getThumbnailFrom(path: URL) -> UIImage? {
do {
let asset = AVURLAsset.init(url: path)
print(asset.url)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
return thumbnail
} catch let error {
print("*** Error generating thumbnail: \(error.localizedDescription)")
return nil
}
}
But on logs I van see *** Error generating thumbnail: Cannot Open
[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
Any idea why ? Its the bug in iOS 11 devices, any idea how to fix this issue and generate thumbnail ?
Thanks!
A:
Okay, this is about asking permissions which I already asked at the beginning of my app. Still I need to ask again, I dont know why, but it worked.
PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in
()
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
print("creating 2")
if let thumbnailImage = self.getThumbnailFrom(path: self.facebookVideoURL){
self.thumbnailImageForVideo.image = thumbnailImage
}
}
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Calculating number of trips without using a loop
I am currently working on postgres and below is the question that I have.
We have a customer ID and the date when the person visited a property. Based on this I need to calculate the number of trips. Consecutive dates are considered as one trip. Eg: If a person visits on first date the trip no is first, post that he visits consecutively for three days that will counted as trip two.
Below is the input
ID Date
1 1-Jan
1 2-Jan
1 5-Jan
1 1-Jul
2 1-Jan
2 2-Feb
2 5-Feb
2 6-Feb
2 7-Feb
2 12-Feb
Expected output
ID Date Trip no
1 1-Jan 1
1 2-Jan 1
1 5-Jan 2
1 1-Jul 3
2 1-Jan 1
2 2-Feb 2
2 5-Feb 3
2 6-Feb 3
2 7-Feb 3
2 12-Feb 4
I am able to implement successfully using loop but its running very slow given the volume of the data.
Can you please suggest a workaround where we can not use loop.
A:
Subtract a sequence from the dates -- these will be constant for a particular trip. Then you can use dense_rank() for the numbering:
select t.*,
dense_rank() over (partition by id order by grp) as trip_num
from (select t.*,
(date - row_number() over (partition by id order by date) * interval '1 day'
) as grp
from t
) t;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get "items" column in orders panel in WooCommerce
Since WooCommerce major update 3.0+ the "Purchased" column in backend orders list panel has been removed. This column previously showed a toggle list of items in the order for quick viewing.
How to Get back this "items" column in orders panel?
If there is any hook for that? Any ideas?
Thanks
A:
That appears to have been removed for performance reasons, but you could look at the code that was removed and add it back via the manage_shop_order_posts_columns filter and manage_shop_order_posts_custom_column action.
/**
* Modify the custom columns for orders.
* @param array $columns
* @return array
*/
function so_43719068_shop_order_columns( $columns ) {
// the new column as an array for subsequent array manip
$new_column = array( 'order_items' => __( 'Purchased', 'your-plugin' ) );
$insert_after = 'order_title';
// insert after specified column
if( isset( $columns[ $insert_after ] ) ){
// find the "title" column
$index = array_search( $insert_after, array_keys( $columns) );
// reform the array
$columns = array_merge( array_slice( $columns, 0, $index + 1, true ), $new_column, array_slice( $columns, $index, count( $columns ) - $index, true ) );
// or add to end
} else {
$columns = array_merge( $columns, $new_column );
}
return $columns;
}
add_filter( 'manage_shop_order_posts_columns', 'so_43719068_shop_order_columns', 20 );
/**
* Output custom columns for orders.
* @param string $column
* @param int $post_id
*/
function so_43719068_render_shop_order_columns( $column, $post_id ) {
global $the_order;
if ( empty( $the_order ) || $the_order->get_id() !== $post_id ) {
$the_order = wc_get_order( $post_id );
}
switch ( $column ) :
case 'order_items' :
/* translators: %d: order items count */
echo '<a href="#" class="show_order_items">' . apply_filters( 'woocommerce_admin_order_item_count', sprintf( _n( '%d item', '%d items', $the_order->get_item_count(), 'woocommerce' ), $the_order->get_item_count() ), $the_order ) . '</a>';
if ( sizeof( $the_order->get_items() ) > 0 ) {
echo '<table class="show_order_items" cellspacing="0">';
foreach ( $the_order->get_items() as $item ) {
$product = apply_filters( 'woocommerce_order_item_product', $item->get_product(), $item );
$item_meta_html = wc_display_item_meta( $item, array( 'echo' => false ) );
?>
<tr class="<?php echo apply_filters( 'woocommerce_admin_order_item_class', '', $item, $the_order ); ?>">
<td class="qty"><?php echo esc_html( $item->get_quantity() ); ?></td>
<td class="name">
<?php if ( $product ) : ?>
<?php echo ( wc_product_sku_enabled() && $product->get_sku() ) ? $product->get_sku() . ' - ' : ''; ?><a href="<?php echo get_edit_post_link( $product->get_id() ); ?>"><?php echo apply_filters( 'woocommerce_order_item_name', $item->get_name(), $item, false ); ?></a>
<?php else : ?>
<?php echo apply_filters( 'woocommerce_order_item_name', $item->get_name(), $item, false ); ?>
<?php endif; ?>
<?php if ( ! empty( $item_meta_html ) ) : ?>
<?php echo wc_help_tip( $item_meta_html ); ?>
<?php endif; ?>
</td>
</tr>
<?php
}
echo '</table>';
} else echo '–';
break;
endswitch;
}
add_action( 'manage_shop_order_posts_custom_column', 'so_43719068_render_shop_order_columns', 10, 2 );
| {
"pile_set_name": "StackExchange"
} |
Q:
H1B (or similar) while marriage based greencard pending from outside the US?
I lived in the US for the past 8 years on F1 visa. A few month ago I gave up my F1 status and moved to Canada. Afterwards I got married to my wife (US citizen) and applied for the marriage based greencard (submitted I130 two months ago).
Now we/I would like to move back to the US since things in Canada do not work out as nicely as expected. Unfortunately this greencard process can take 1-2 years.
Is it possible to obtain some work visa (e.g. H1B) while this greencard process is pending if a company (like Google or Apple) sponsors it?
A:
Most types of nonimmigrant visas are subject to the presumption of immigrant intent under INA 214(b), where they must presume that you are an intending immigrant (i.e. you intend to immigrate on this visa), and thus ineligible for the nonimmigrant visa, unless you convince the officer otherwise. And having a petition from a US citizen spouse would certainly make it harder to convince the officer you don't intend to immigrate with it, since you can easily change your mind after you enter the US and do Adjustment of Status to get permanent residency from within the US at any time.
However, H1b (as well as their dependents on H4) and L1 (as well as their dependents on L2) are exempt from INA 214(b). So immigrant intent should not affect your ability to get H1b visa or enter the US on H1b status.
| {
"pile_set_name": "StackExchange"
} |
Q:
If $f(x)=o(\log^{(k)}(x))$ for all $k$, can $f$ diverges?
Is there a divergent monotone non-decreasing continuous positive real-function $f$ such that
$$\lim\limits_{x\to +\infty} \frac{f(x)}{\log^{(k)}(x)} = 0$$
for all $k\geqslant 1$? (By $\log^{(k)}(x)$ I mean $\underbrace{\log\log\cdots\log}_{k \text{ times}}(x)$.)
I have a strange feeling that this is false, and, although, very unlikely to be false at the same time. A cool implication of a "no" would be that if you consider the poset $\langle \mathbb{P},\prec\rangle$ consisting of divergent monotone non-decreasing continuous positive real-functions defined in $[a,+\infty)$ for some $a\geqslant 0$ (note that $a$ is not fixed) with the order
$$f\prec g \iff f = o(g),$$
the set $\{\log^{(k)} : k\in\mathbb{N}\}$ would be a countable dense subset of $\mathbb{P}$ (in the sense of dense in a partial order). This is exactly what "feels" to be unlikely to me.
Any tips in prove, disprove or even in to find a dense subset of $\mathbb{P}$ are welcome.
A:
In fact if $g_k:[a_k,\infty) \to (0,\infty)$ is any sequence of functions such that $\lim_{x\to \infty}g_k(x) = \infty$ for all $k,$ then there exists an increasing continuous $f: [0,\infty) \to (0,\infty)$ with $\lim_{x\to \infty}f(x) = \infty$ such that
$$\lim_{x\to \infty}\frac{f(x)}{g_k(x)} = 0$$
for all $k.$
Proof idea: Choose $0<b_1<b_2 < \cdots \to \infty $ such that
$$\min(g_1,\dots ,g_k)> 3^k \text {on} \,[b_k,\infty).$$
Define $f$ so that $2^k\le f \le 2^{k+1}$ on $[b_k, b_{k+1}].$
| {
"pile_set_name": "StackExchange"
} |
Q:
possibility to use S3 as CDN for internal Application load balancer ( ALB) applications
For public websites, we have an option cloudfront as CDN for static content when we use internet-facing application load balancers.
Is there any similar option for internal websites using private ALB ?
Web application is implemented in ExpressJs with all static files served from server, but no clues on how to proceed on separating these static assets to move to any CDN as its a not public and cant use cloudfront for private ELB. Any ideas ?
A:
Unfortunately No, You can't use Internal ALB/ELB with CloudFront, it needs to be a public endpoint, however, now that you can have lambda as target for Application load balancers, you can write a lambda function to fetch files from S3 for you.
https://aws.amazon.com/blogs/networking-and-content-delivery/lambda-functions-as-targets-for-application-load-balancers/
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble recalling hashes from file in Perl
This phone book script works well in memory but I am having a difficult time recalling the saved data on re execution. The hashes go to the text file but I have no idea how to recall them when the script is starting. I have used "Storage" to save the data, and I have tried to use the "retrieve"function to bring the data back, with no luck. I think either I did not follow a good path from the start or I just don't know where in the code or which %hash should "retrieve" the stored data.
I am very new to Perl and programming so I hope I explained my situation clearly
#!/usr/bin/perl
use 5.18.2;
use strict;
use warnings;
use autodie;
use Scalar::Util qw(looks_like_number); # This is used to determine if the phone number entered is valid.
use Storable;
use Data::Dumper;
####################################
# Enables sub selections
my %contact; while (){
my $selection = list();
if ($selection == 1){
addContact();
}
elsif ($selection == 2){
removeContact();
}
elsif ($selection == 3){
findContact();
}
elsif ($selection == 4){
listAllContacts();
}
elsif ($selection == 5) {
clearScreen();
}
elsif ($selection == 888) {
quit();
}
else {
print "Invalid entry, Please try again.\n\n"; # displays error message
}
}
####################################
# Shows instructions for use
sub list{
print "\n------------------------------------------------------------------------\n";
print "- ----- Select an option ----- -\n";
print "- 1 = add, 2 = remove, 3 = find, 4 = list, 5 = tidy screen, 888 = quit -\n";
print "------------------------------------------------------------------------\n";
print "What would you like to do? ";
my $listChoice = <STDIN>; # enter sub choice here
return $listChoice;
}
####################################
# Add contact info sub
sub addContact{
print"Name?: ";
chomp (my $addContactName = <STDIN>); # contact name
$addContactName = lc($addContactName); # changes all letters to lower-case
if (exists $contact{$addContactName}){ # checks for duplicate contact
print"Duplicate Record!!! Please enter a different name\n\n"; # displays error message
}
else {
print"Phone Number?(omit dashes, ex. 1235551212): ";
chomp (my $phoneNumber = <STDIN>); # phone number
if (looks_like_number($phoneNumber)){ # checks that its only numbers
$contact{$addContactName} = $phoneNumber; # adds hash to contact
# open (FILE, ">>pb.txt"); # file to save contact info
# print FILE $addContactName .= ":", $phoneNumber .= "\n"; # add a colon and new line to contact info in text file
}
else{
print "Phone Numbers do not have letters!, Let's start again.\n\n"; # displays error message
}
}
}
####################################
# sub to remove contact
sub removeContact {
print"Enter name to remove: \n";
chomp (my $removeContact = <STDIN>); # enter contact name to remove
$removeContact = lc($removeContact); # changes all letters to lower-case
if (exists $contact{$removeContact}){ # looks for contact name
delete($contact{$removeContact}); # delete contact name and all info
print"The contact \' $removeContact \' has been removed\n"; # gives confirmation of contact removal
}
else {
print"This name does not exist in the record!! Try Again.\n\n"; # displays error message
}
}
####################################
# sub to find a contact
sub findContact {
print"Whom are you looking for?: \n";
chomp(my $findContact = <STDIN>); # enter contact name to find
$findContact = lc($findContact); # changes all letters to lower-case
if (exists $contact{$findContact}) { # looks for contact name
print($contact{$findContact},"\n\n"); # prints info for found contact name
}
else {
print"This name does not exist in the record!!! Try Again.\n\n"; # displays error message
}
}
###############################################
# Lists all contacts entered alphabetically
sub listAllContacts {
for my $key (sort keys %contact) { # sorts contacts alphabetically
print "$key, $contact{$key}\n"; # shows all contacts on screen
}
}
#################################################
# Tidy sub - just clears the screen of clutter
sub clearScreen {
system("clear");
}
####################################
# sub to leave the program
sub quit{
store (\%contact, "pb.txt"); # save data to text file
system("clear"); # clears screen
exit(); # exits program
}
A:
The store function comes from the module Storable (you can see full documentation for the module by typing perldoc Storable).
It's counterpart is called retrieve.
So in order to read back the contacts on the script start you can replace the line
my %contact; while (){
with
my %contact;
eval {
%contact = %{ retrieve "pb.txt" };
};
while (1) {
The eval makes the retrieval not die on error (whether because pb.txt is not there or does not contain the data in a format compatible with Storable). You might want to have somewhat more elaborate error handling instead of just ignoring any errors, but this should do as an example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it correct to read the pasuk of Deuteronomy 15:11 with the "never" term?
In one of the Torah Readings for the eighth day of Pesach, falling in a week day, there's the following passukim (Deuteronomy 15:10-11) ืย ย ื ึธืชืึนื ืชึผึดืชึผึตื ืืึน, ืึฐืึนื-ืึตืจึทืข ืึฐืึธืึฐืึธ ืึผึฐืชึดืชึผึฐืึธ ืืึน:ย ืึผึดื ืึผึดืึฐืึทื ืึทืึผึธืึธืจ ืึทืึผึถื, ืึฐืึธืจึถืึฐืึธ ืึฐืืึธื ืึฑืึนืึถืืึธ, ืึผึฐืึธื-ืึทืขึฒืฉืึถืึธ, ืึผืึฐืึนื ืึดืฉืึฐืึทื ืึธืึถืึธ. ืืย ย ืึผึดื ืึนื-ืึถืึฐืึผึทื ืึถืึฐืืึนื, ืึดืงึผึถืจึถื ืึธืึธืจึถืฅ; ืขึทื-ืึผึตื ืึธื ึนืึดื ืึฐืฆึทืึผึฐืึธ, ืึตืืึนืจ, ืคึผึธืชึนืึท ืชึผึดืคึฐืชึผึทื ืึถืช-ืึธืึฐืึธ ืึฐืึธืึดืืึธ ืึทืขึฒื ึดืึผึถืึธ ืึผืึฐืึถืึฐืึนื ึฐืึธ, ืึผึฐืึทืจึฐืฆึถืึธ.ย {ืก} โ
Thou shalt surely give him, and thy heart shall not be grieved when thou givest unto him; because that for this thing the LORD thy God will bless thee in all thy work, and in all that thou puttest thy hand unto. For the poor shall NEVER [?] cease out of the land; therefore I command thee, saying: 'Thou shalt surely open thy hand unto thy poor and needy brother, in thy land.'
Is it supposed to be read with the never term in the hebrew version? And if so, is there a predestination factor in play here and in all its implications?
Do judaism really believe in Predestination Theology?
... Or the translation of this passuk is simply incorrect, after all?
A:
See Ramban on this verse: ืื ืื ืืืื ืืืืื ืืงืจื ืืืจืฅ. ืืคืจืฉืื [1]โ ืืืจื ืฉืื ืืืื ืืืืืื ืืงืจื ืืืจืฅ ืืืื ืืื ืืืื ืื ืื ืืขืืื ืืืื ืืืืื ืืืจืฅ ืฉืืืื ืืื ืืคื ืื ืฉืื ืืขืฉื ืื ืฉืืืจ ืืื ืื ืื ืืืื ืื ืืืืื ืื ืฉืืืข ืชืฉืืข ืืงืื ื' ืืืืื ืืฉืืืจ ืืขืฉืืช ืืช ืื ืืืฆืื
โ[2]โ ืืืื ื ื ืืื ืืืขืชื ืื ืืชืืจื ืชืจืืื ืืื ืฉืขืชืื ืืืืืช ืืื ืื ืืชื ืื ืขืืืื ืืคืืจืืฉ ืฉืื ืืงืืืื ืืชืืจื ืืืฆืื ืืืฆืื ืืขืืื ืืืืืื [3]โืจืง ืืืจื ืืืืจื ืืืืืจ ืืืืจ ืืื ืืื ืฉืืืืจ ืฉืื ืืืื ืืืืื ืฉืืืื ื ืื ืข ืืื ืืืฆื ืขืื ืืขืืื ืืืืืืจ ืื ืืขืืืจ ืฉืืืืื ืฉืื ืืืื ืืื ืืืืื ืืฉืืจื ืื ืืืฆืื ืืืจ ืืื ืืืขืชื ืื ืื ืืืื ืื ืืืืจืืช ืื ืืื ืขืืื ืืื ืฉืืืจืื ืื ืืืฆืื ืขื ืฉืื ื ืฆืืจื ืืื ืืฆืืืช ืขื ืืืืืื ืื ืืืื ืืงืฆืช ืืืืื ืืืฆื ืืืืื ืืื ื ืืฆืื ืขืืื ืื ืืืฆื ืืืืจ "ืืงืจื ืืืจืฅ" ืืจืืื ืขื ืื ืืืฉืื ืื ืืืืืื ืฉืื ืืืื ืื ื ืืืืื ืืืจืฅ ืืฉืจ ื' ืืืืื ื ื ืืชื ืื ื ื ืืื ืื ื ืงืืื ืฉื ืื ืืืฆืืช [4]โ ืืขืชื ืืืจ ืื ืืชืื ืฉืืืฆื ืืืืื ืืืื ืื ืืืื ืื ืืืืื ืื ืืืงืืืืช ืืฉืจ ืชืฉื ืื ืื ืืขื "ืืืจืฆื" ืืืขื ืืื ืืืฉืืืชืืื (ืืืืืจ ืื ืื) ืืืจืฅ ืืืืืฆื ืืืจืฅ ืืืขื ืืืืืืื ื ืืืจืฆื ืืืืืจ ืืืืื ืืขื ื ืืืื ืืืืื ื ืืจืฆื ืื ืืขืืืจ ืฉืืืฆืื ืืืฉืจืื ืืืืืจ ืืืื ืืืฆืืจื ืืคืจืฉ ืืืื ืืื ืืืืื ื ืืจืฆื ืืฆืืืช ืขื ืืื ืืฉืจืื ืืืืจืฉื (ืกืคืจื ืงืื) ืืืงืืื ืืงืืื (ืืจืื"ื)โ
[1] Some commentators says that it clear for G_d that Israel do not achieve the Mitsvot
[2] Ramban rejects this opinion.
[3] The verse is a warning.
[4] He comment this as a possibility. "It is never excluded that... "
TRANSLATION: So there will be no poor man on land. Some commentators said that poor not disappear all time. The reason there will always be poor: It is clear for him (G_d) that they do not do what he tells them to do. Indeed, the lack of poverty is a consequence of obedience to G_d, to respect and accomplish. But for me it is not correct. Because Torah provides scraps of information about what going to append. It is not a comprehensive prophecy that they do not accomplish Torah and he would order again infinitely. The scope is to provide warning. The truth is "the poor shall never cease": resurgence of poverty is never impossible as if poverty can not come back. He did mention that after the promise he made that it will not be poor (when they comply with laws). He said, but I know that not every generation at every time, all, comply to such an extent that there is no need to warning to care for the poor. It may be that in far distant future will be a poor....
| {
"pile_set_name": "StackExchange"
} |
Q:
is it possible to check how many DIMM slots are filled in a pc motherboard, remotely?
I am basically away from my office, but would like to check whether a pc (which has 4GB of RAM) has 4x 1GB DIMMs or 2x 2GB DIMMs.
I am referring to a windows XP system. Is it possible to gather this info from System information or otherwise, remotely?
A:
Windows itself doesn't show this anywher as far as I know.
You will have to run a utility like CPU-Z on the system itself to determine this.
If you have an Intel AMT infrastructure you can probably query this through that, but those are pretty rare in the wild. (I have never seen one.)
It is possible to query this via WMIC, but I don't know this is available on XP. A quick attempt shows it appears to work on Win7.
wmic memorychip get Capacity /format:list
Will give a line for each chip with the capcity in bytes.
A:
If you have remote desktop, just install and run CPU-Z.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to coerce functors applied to coercible arguments
Consider the following Haskell code:
import Data.Coerce
newtype Decorated s a = Decorated a
fancyFunction :: Ctx s => f (Decorated s a) -> r
fancyFunction = ...
instance Ctx s => SomeClass (Decorated s a)
myFunction :: Functor f => f a -> r
myFunction = fancyFunction . fmap coerce
I'd like to make myFunction faster by replacing fmap coerce with coerce. The rationale is that coerce behaves like id and one of the functor laws is fmap id = id.
The only way I can see of doing this is to add Coercible (f a) (f (Decorated s a)) to the context but it refers to s which is not referred to anywhere else. Even worse, if a is bound in a universal type, I cannot express the constraint. Is there a constraint I could express in terms of f only to let me use coerce to convert between f a and f (Decorated s a)?
Is this something that the compiler figures out on its own from the fact that f is a functor? If so, does it also work with bifunctors, traversables and bitraverables?
A:
Unfortunately, Coercible (f a) (f (Decorated s a)) really what you want in your constraint given the current state of GHC. Now, the fact that s and a don't show up elsewhere is not something good - it means GHC won't know what to do with them (they are ambiguous)! I won't get into that...
Depending on the role of the type parameter fed to the type constructor f, Coercible a b may or may not imply Coercible (f a) (f b). In this case, we'd want that role to be nominal - but there isn't (yet at least) a way to express this in a constraint. To explain what I mean, consider the following two data definitions:
{-# LANGUAGE TypeFamilies #-}
import Data.Coerce
-- type role of `a` is "representational"
data Data1 a = Data1 a
-- type role of `a` is "nominal"
data Data2 a = Data2 (TypeFunction a)
type family TypeFunction x where
TypeFunction Bool = Char
TypeFunction _ = ()
Then, while it is true that Coercible a b entails Coercible (Data1 a) (Data1 b), it does not entail Coercible (Data2 a) (Data2 b). To make this concrete, load up the above in GHCi, then try:
ghci> newtype MyInt = My Int
ghci> let c1 = coerce :: (Data1 MyInt) -> (Data1 Int)
ghci> let c2 = coerce :: (Data2 MyInt) -> (Data2 Int) -- This doesn't work!
Unfortunately, there is no built-in constraint based way of enforcing that the role of a type variable is representational. You can make your own classes for this, as Edward Kmett has done, but GHC doesn't automatically create instances of some of these classes the way class instances for Coercible are.
This led to this trac ticket where they discuss the possibility of having a class Representational f with instances generated like for Coercible which could have things like
instance (Representational f, Coercible a b) => Coercible (f a) (f b)
If this was actually a thing today, all you would need in your constraint would be Representational f. Furthermore, as Richard Eisenberg observes on the ticket, we really ought to be able to figure out that a in f a has a representational role for any reasonable functor f. Then, we might not even need any constraint on top of Functor f as Representational could be a superclass of Functor.
Here is a good discussion of the current limitations of roles.
| {
"pile_set_name": "StackExchange"
} |
Q:
how do you return a string from an Erlang C node?
I want to be able to pass in a string - list - into a C node for Erlang and return back a string to the Erlang process after some computation.
result = function(input_string),
where input_string is of type ETERM *
My computation on the string uses char * variables for strings.
Please let me know if this is sufficient information to go on.
[The C node example in the erl_interface tutorial uses integer input to and output from the C node]
TIA,
BR,
Shailen
A:
Use erl_iolist_to_string for input (every Erlang "string" is also an iolist).
Use erl_mk_string instead of erl_mk_int for output.
http://erlang.org/doc/man/erl_eterm.html#erl_iolist_to_string
http://erlang.org/doc/man/erl_eterm.html#erl_mk_string
| {
"pile_set_name": "StackExchange"
} |
Q:
double replacement
$$\ce{KNO3(aq) + BaCl2(aq) -> KCl(aq) + Ba(NO3)2(aq)}$$
I found products but I noticed in product that both of them are in the aqueous phase. So actually no reaction occurs?
Does a reaction need at least a precipitate to occur to be double replacement?
A:
The reason the reaction you drew isn't a double replacement reaction is that the aqueous compounds listed don't have their ions actually bound together in solution, but instead the individual ions are solvated by shells of water molecules. If you write the net ionic equation for your reaction, you get $$\ce{K+(aq) +NO3-(aq) + Ba^{2+}(aq) +2Cl-(aq) -> K+(aq) +NO3-(aq) + Ba^{2+}(aq) +2Cl-(aq)}$$
where you can see that we haven't actually created any new compounds in going from reactants to products.
If one of the products were a precipitate, it then becomes a true reaction, as you start with four kinds of ions in solution, and end with a solid formed from two of the ions and a solution containing the other two.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sales report in SQL Server 2008 merging same year into one?
I have the following query to display sales report in each year and month
SELECT
YEAR(orderDate) as SalesYear,
MONTH(orderDate) as SalesMonth,
SUM(Price) AS TotalSales
FROM Sales
GROUP BY YEAR(orderDate),MONTH(orderDate)
ORDER BY YEAR(orderDate), MONTH(orderDate)
output
2013 2 350.00
2013 5 350.00
2014 8 30.00
2014 11 30.00
2015 1 350.00
2015 8 120.00
But I need?
output like:
2013 2 700.00
2014 2 60.00
2015 2 470.00
Note: The month part should be the total number of months in each year.
Any help?
Thanks in Advance.
A:
create table sales (orderdate date, price money);
insert into sales values
(N'2013-02-01', 350.00),
(N'2013-05-01', 350.00),
(N'2014-08-01', 30.00),
(N'2014-11-01', 30.00),
(N'2015-01-01', 350.00),
(N'2015-08-01', 120.00);
Alternatively, you could also use window functions SUM() OVER and COUNT() OVER to do this:
SELECT distinct
YEAR(orderDate) as SalesYear,
count(MONTH(orderDate)) OVER (PARTITION BY YEAR(OrderDate)) as SalesMonth,
SUM(Price) OVER (PARTITION BY YEAR(OrderDate)) AS TotalSales
FROM Sales
ORDER BY YEAR(orderDate);
Result:
+-----------+------------+------------+
| SalesYear | SalesMonth | TotalSales |
+-----------+------------+------------+
| 2013 | 2 | 700 |
| 2014 | 2 | 60 |
| 2015 | 2 | 470 |
+-----------+------------+------------+
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the nuclear envelope present in G1 of interphase?
Is the nuclear envelope present in G1 of interphase of eukaryotic cell? If so how does a method like Calcium mediated transfection get DNA past the nuclear envelope?
A:
To answer the question about nuclear envelope in G1 phase, yes it exists. The nuclear envelope is reformed at the end of Telophase after the 2 copies of the DNA are pulled apart, but before the two daughter cells are separated by cytokinesis. We can see the new nuclear envelope in these images:
Image from here
Nuclei visible near end of cytokinesis, centrosome still visible. Image from here.
As for how DNA gets into the nucleus without cellular division I don't have a good answer and I'm not sure anyone does right now. The nuclear envelope is a major barrier for non-viral gene delivery.
| {
"pile_set_name": "StackExchange"
} |
Q:
SPLIT COLUMNS INTO BINARY MATRIX
Basically I have a column like this:
+----------------+
| Marks |
+----------------+
|Maths,Phy,Che |
|Maths,Phy |
|Phy,Che |
|Che |
|Maths,Phy,Che |
|Maths,Phy,Che |
+----------------+
And I would like to be like this
+-------------------------+-------+------+------+
| marks | Maths | Phy | Che |
+-------------------------+-------+------+------+
| Maths,Phy,Che | 1 | 1 | 1 |
| Maths,Phy | 1 | 1 | 0 |
| Phy,Che | 0 | 1 | 1 |
| Che | 0 | 0 | 1 |
| Maths,Phy,Che | 1 | 1 | 1 |
| Maths,Phy,Che | 1 | 1 | 1 |
+-------------------------+-------+------+------+
I was trying to use substring as posted in this answer (how to split a column into multiple columns in mysql)
but I could not make it work the way I want
A:
could using column like value result
select marks
, (marks like '%Maths%') as Maths
, (marks like '%Phy%') as Phy
, (marks like '%Che%') as Che
from my table
| {
"pile_set_name": "StackExchange"
} |
Q:
Sphinx-quickstart doesn't work
I am trying to install sphinx on a remote machine.
Since I don't have an access to the root, I did this:
$bash
$mkdir -p ~/local/lib/python2.7/site-packages
$export PYTHONPATH=$PYTHONPATH:~/local/lib/python2.7/site-packages
$export PATH=$PATH::~/local/lib/python2.7/site-packages
$easy_install -U --prefix=$HOME/local Sphinx
But apparently, $easy_install doesn't build sphinx-quickstart; when I type
$sphinx-quickstart
I get the following message:
bash: sphinx-quickstart: command not found
I tried
find $HOME -name sphinx-quickstart
and no result was found. However, I can import sphinx inside python:
$python
And then
>>import sphinx
works. Any idea why sphinx-quickstart doesn't work?
A:
An alternative way to invoke sphinx-quickstart is to explicitly load Sphinx's quickstart module. For Sphinx v1.7+:
python -m sphinx.cmd.quickstart
For older versions of Sphinx:
python -m sphinx.quickstart
For example:
$ /c/Python35/python -m sphinx.quickstart
Welcome to the Sphinx 1.6.2 quickstart utility.
...
A:
I found the solution in this webpage:
User (root/sudo free) installation of Python modules.
In section 3. Python 2.6+ he mentioned that the command line commands are in
~/local/bin
Although I had put ~/local/lib/python2.7/siste-packages in the path, the ~/local/bin directory was not in the path. So all I did
$export PYTHONPATH=$PYTHONPATH:~/local/bin
and now it works.
I don't know why find $HOME -name sphinx-quickstart did not find sphinx-quickstart
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use less memory generating Array permutation?
So I need to get all possible permutations of a string.
What I have now is this:
def uniq_permutations string
string.split(//).permutation.map(&:join).uniq
end
Ok, now what is my problem: This method works fine for small strings but I want to be able to use it with strings with something like size of 15 or maybe even 20. And with this method it uses a lot of memory (>1gb) and my question is what could I change not to use that much memory?
Is there a better way to generate permutation? Should I persist them at the filesystem and retrieve when I need them (I hope not because this might make my method slow)?
What can I do?
Update:
I actually don't need to save the result anywhere I just need to lookup for each in a table to see if it exists.
A:
Just to reiterate what Sawa said. You do understand the scope? The number of permutations for any n elements is n!. It's about the most aggressive mathematical progression operation you can get. The results for n between 1-20 are:
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000,
6402373705728000, 121645100408832000, 2432902008176640000]
Where the last number is approximately 2 quintillion, which is 2 billion billion.
That is 2265820000 gigabytes.
You can save the results to disk all day long - unless you own all the Google datacenters in the world you're going to be pretty much out of luck here :)
A:
Your call to map(&:join) is what is creating the array in memory, as map in effect turns an Enumerator into an array. Depending on what you want to do, you could avoid creating the array with something like this:
def each_permutation(string)
string.split(//).permutation do |permutaion|
yield permutation.join
end
end
Then use this method like this:
each_permutation(my_string) do |s|
lookup_string(s) #or whatever you need to do for each string here
end
This doesnโt check for duplicates (no call to uniq), but avoids creating the array. This will still likely take quite a long time for large strings.
However I suspect in your case there is a better way of solving your problem.
I actually don't need to save the result anywhere I just need to lookup for each in a table to see if it exists.
It looks like youโre looking for possible anagrams of a string in an existing word list. If you take any two anagrams and sort the characters in them, the resulting two strings will be the same. Could you perhaps change your data structures so that you have a hash, with keys being the sorted string and the values being a list of words that are anagrams of that string. Then instead of checking all permutations of a new string against a list, you just need to sort the characters in the string, and use that as the key to look up the list of all strings that are permutations of that string.
A:
Perhaps you don't need to generate all elements of the set, but rather only a random or constrained subset. I have written an algorithm to generate the m-th permutation in O(n) time.
First convert the key to a list representation of itself in the factorial number system. Then iteratively pull out the item at each index specified by the new list and of the old.
module Factorial
def factorial num; (2..num).inject(:*) || 1; end
def factorial_floor num
tmp_1 = 0
1.upto(1.0/0.0) do |counter|
break [tmp_1, counter - 1] if (tmp_2 = factorial counter) > num
tmp_1 = tmp_2 #####
end # #
end # #
end # returns [factorial, integer that generates it]
# for the factorial closest to without going over num
class Array; include Factorial
def generate_swap_list key
swap_list = []
key -= (swap_list << (factorial_floor key)).last[0] while key > 0
swap_list
end
def reduce_swap_list swap_list
swap_list = swap_list.map { |x| x[1] }
((length - 1).downto 0).map { |element| swap_list.count element }
end
def keyed_permute key
apply_swaps reduce_swap_list generate_swap_list key
end
def apply_swaps swap_list
swap_list.map { |index| delete_at index }
end
end
Now, if you want to randomly sample some permutations, ruby comes with Array.shuffle!, but this will let you copy and save permutations or to iterate through the permutohedral space. Or maybe there's a way to constrain the permutation space for your purposes.
constrained_generator_thing do |val|
Array.new(sample_size) {array_to_permute.keyed_permute val}
end
| {
"pile_set_name": "StackExchange"
} |
Q:
laravel migration error after define defaultStringLength
i get this error after define 'defaultStringLength'
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to undefined method
Illuminate\Database\Schema\MySqlBuilder::defaultSt ringLength()
A:
You're using an older version of Laravel. You can use this method only since 5.4
You can limit string length manually:
$table->string('name', 100);
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to receive HumanTask response to the BPEL process
I'm quite new to WSO2 BPS 3.2.0 and for BPEL as well. I created a BPEL process for firing a HumanTask using bpel4people extension. For that I took the sample humantask shipped with the BPS. I could successfully fire the task. But once I complete the task, My bpel process does not receive the response from the task. Is there any special procedure to get the respose ? Here are my bpel process and the HumanTask's WSDL file.
bpel file..
<!-- JavaTraining BPEL Process [Generated by the Eclipse BPEL Designer] -->
<!-- Date: Mon Mar 05 12:13:11 IST 2012 -->
<bpel:process name="JavaTraining" targetNamespace="http://loits.com/bps/training" suppressJoinFailure="yes" xmlns:tns="http://loits.com/bps/training" xmlns:bpel="http://docs.oasis-open.org/wsbpel/2.0/process/executable" xmlns:ns1="http://www.w3.org/2001/XMLSchema"
xmlns:ns2="http://www.example.com/claims/" xmlns:xsd="http://www.example.com/claims/schema" xmlns:b4p="http://docs.oasis-open.org/ns/bpel4people/bpel4people/200803">
<!-- Import the client WSDL -->
<bpel:extensions>
<bpel:extension namespace="http://docs.oasis-open.org/ns/bpel4people/bpel4people/200803" mustUnderstand="yes"></bpel:extension>
</bpel:extensions>
<bpel:import namespace="http://www.example.com/claims/" location="ClaimsApprovalTask.wsdl" importType="http://schemas.xmlsoap.org/wsdl/"></bpel:import>
<bpel:import location="JavaTrainingArtifacts.wsdl" namespace="http://loits.com/bps/training" importType="http://schemas.xmlsoap.org/wsdl/" />
<!-- ================================================================= -->
<!-- PARTNERLINKS -->
<!-- List of services participating in this BPEL process -->
<!-- ================================================================= -->
<bpel:partnerLinks>
<!-- The 'client' role represents the requester of this service. -->
<bpel:partnerLink name="client" partnerLinkType="tns:JavaTraining" myRole="JavaTrainingProvider" />
<bpel:partnerLink name="b4pPtlnk" partnerLinkType="tns:b4pPtlnkType" myRole="requester" partnerRole="receiever"></bpel:partnerLink>
</bpel:partnerLinks>
<!-- ================================================================= -->
<!-- VARIABLES -->
<!-- List of messages and XML documents used within this BPEL process -->
<!-- ================================================================= -->
<bpel:variables>
<!-- Reference to the message passed as input during initiation -->
<bpel:variable name="input" messageType="tns:JavaTrainingRequestMessage" />
<!--
Reference to the message that will be returned to the requester
-->
<bpel:variable name="output" messageType="tns:JavaTrainingResponseMessage" />
<bpel:variable name="dummyVar" type="ns1:boolean"></bpel:variable>
<bpel:variable name="b4pIn" messageType="ns2:ClaimApprovalRequest"></bpel:variable>
<bpel:variable name="b4pOut" messageType="ns2:ClaimApprovalResponse"></bpel:variable>
</bpel:variables>
<!-- ================================================================= -->
<!-- ORCHESTRATION LOGIC -->
<!-- Set of activities coordinating the flow of messages across the -->
<!-- services integrated within this business process -->
<!-- ================================================================= -->
<bpel:sequence name="main">
<!-- Receive input from requester.
Note: This maps to operation defined in JavaTraining.wsdl
-->
<bpel:receive name="receiveInput" partnerLink="client" portType="tns:JavaTraining" operation="process" variable="input" createInstance="yes" />
<!-- Generate reply to synchronous request -->
<bpel:if name="If_amount_1000">
<bpel:condition expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[number($input.payload/tns:amount) > number(1000)]]>
</bpel:condition>
<bpel:sequence>
<bpel:assign validate="no" name="Assign1">
<bpel:copy>
<bpel:from>
<bpel:literal>
<tschema:ClaimApprovalData xmlns:tschema="http://www.example.com/claims/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tschema:cust>
<tschema:id>tschema:id</tschema:id>
<tschema:firstname>tschema:firstname</tschema:firstname>
<tschema:lastname>tschema:lastname</tschema:lastname>
</tschema:cust>
<tschema:amount>0.0</tschema:amount>
<tschema:region>tschema:region</tschema:region>
<tschema:priority>0</tschema:priority>
</tschema:ClaimApprovalData>
</bpel:literal>
</bpel:from>
<bpel:to variable="b4pIn" part="ClaimApprovalRequest"></bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from part="payload" variable="input">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:customer/tns:custId]]>
</bpel:query>
</bpel:from>
<bpel:to part="ClaimApprovalRequest" variable="b4pIn">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:cust/xsd:id]]>
</bpel:query>
</bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from part="payload" variable="input">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:customer/tns:firstName]]>
</bpel:query>
</bpel:from>
<bpel:to part="ClaimApprovalRequest" variable="b4pIn">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:cust/xsd:firstname]]>
</bpel:query>
</bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from part="payload" variable="input">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:customer/tns:lastName]]>
</bpel:query>
</bpel:from>
<bpel:to part="ClaimApprovalRequest" variable="b4pIn">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:cust/xsd:lastname]]>
</bpel:query>
</bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from part="payload" variable="input">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:amount]]>
</bpel:query>
</bpel:from>
<bpel:to part="ClaimApprovalRequest" variable="b4pIn">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:amount]]>
</bpel:query>
</bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from part="payload" variable="input">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:priority]]>
</bpel:query>
</bpel:from>
<bpel:to part="ClaimApprovalRequest" variable="b4pIn">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:priority]]>
</bpel:query>
</bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from part="payload" variable="input">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:region]]>
</bpel:query>
</bpel:from>
<bpel:to part="ClaimApprovalRequest" variable="b4pIn">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:region]]>
</bpel:query>
</bpel:to>
</bpel:copy>
</bpel:assign>
<bpel:extensionActivity>
<b4p:peopleActivity name="HumanTask" inputVariable="b4pIn" outputVariable="b4pOut">
<b4p:remoteTask partnerLink="b4pPtlnk" operation="approve" responseOperation="approvalResponse"></b4p:remoteTask>
</b4p:peopleActivity>
</bpel:extensionActivity>
<bpel:assign validate="no" name="Assign3">
<bpel:copy>
<bpel:from part="ClaimApprovalResponse" variable="b4pOut">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[xsd:approved]]>
</bpel:query>
</bpel:from>
<bpel:to variable="dummyVar"></bpel:to>
</bpel:copy>
</bpel:assign>
<bpel:if name="If_approved">
<bpel:condition expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[$dummyVar = true()]]>
</bpel:condition>
<bpel:assign validate="no" name="Assign">
<bpel:copy>
<bpel:from>
<bpel:literal>
<tns:JavaTrainingResponse xmlns:tns="http://loits.com/bps/training" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tns:result>tns:result</tns:result>
</tns:JavaTrainingResponse>
</bpel:literal>
</bpel:from>
<bpel:to variable="output" part="payload"></bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA["Approved"]]>
</bpel:from>
<bpel:to part="payload" variable="output">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:result]]>
</bpel:query>
</bpel:to>
</bpel:copy>
</bpel:assign>
<bpel:else>
<bpel:assign validate="no" name="Assign4">
<bpel:copy>
<bpel:from>
<bpel:literal>
<tns:JavaTrainingResponse xmlns:tns="http://loits.com/bps/training" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tns:result>tns:result</tns:result>
</tns:JavaTrainingResponse>
</bpel:literal>
</bpel:from>
<bpel:to variable="output" part="payload"></bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA["Rejected"]]>
</bpel:from>
<bpel:to part="payload" variable="output">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:result]]>
</bpel:query>
</bpel:to>
</bpel:copy>
</bpel:assign>
</bpel:else>
</bpel:if>
</bpel:sequence>
<bpel:else>
<bpel:assign validate="no" name="Assign2">
<bpel:copy>
<bpel:from>
<bpel:literal>
<tns:JavaTrainingResponse xmlns:tns="http://loits.com/bps/training" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tns:result>tns:result</tns:result>
</tns:JavaTrainingResponse>
</bpel:literal>
</bpel:from>
<bpel:to variable="output" part="payload"></bpel:to>
</bpel:copy>
<bpel:copy>
<bpel:from expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA["Approved Automatically"]]>
</bpel:from>
<bpel:to part="payload" variable="output">
<bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0">
<![CDATA[tns:result]]>
</bpel:query>
</bpel:to>
</bpel:copy>
</bpel:assign>
</bpel:else>
</bpel:if>
<bpel:reply name="replyOutput" partnerLink="client" portType="tns:JavaTraining" operation="process" variable="output" />
</bpel:sequence>
</bpel:process>
and the wsdl..
<?xml version="1.0" encoding="UTF-8" ?>
<wsdl:definitions name="ClaimApproval" targetNamespace="http://www.example.com/claims/" xmlns:tns="http://www.example.com/claims/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tschema="http://www.example.com/claims/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype">
<wsdl:documentation>
Example for WS-HumanTask 1.1 - WS-HumanTask Task Interface Definition
</wsdl:documentation>
<wsdl:types>
<xsd:schema targetNamespace="http://www.example.com/claims/schema" xmlns:tns="http://www.example.com/claims/schema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xsd:element name="ClaimApprovalData" type="tns:ClaimApprovalDataType" />
<xsd:complexType name="ClaimApprovalDataType">
<xsd:sequence>
<xsd:element name="cust">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:string">
</xsd:element>
<xsd:element name="firstname" type="xsd:string">
</xsd:element>
<xsd:element name="lastname" type="xsd:string">
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="amount" type="xsd:double" />
<xsd:element name="region" type="xsd:string" />
<xsd:element name="priority" type="xsd:int" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="ClaimApprovalNotificationData" type="tns:ClaimApprovalNotificationDataType" />
<xsd:complexType name="ClaimApprovalNotificationDataType">
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string" />
<xsd:element name="lastname" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="ClaimApprovalResponse" type="tns:ClaimApprovalResponseType"></xsd:element>
<xsd:complexType name="ClaimApprovalResponseType">
<xsd:sequence>
<xsd:element name="approved" type="xsd:boolean"></xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<wsdl:message name="ClaimApprovalRequest">
<wsdl:part name="ClaimApprovalRequest" element="tschema:ClaimApprovalData" />
</wsdl:message>
<wsdl:message name="ClaimApprovalResponse">
<wsdl:part name="ClaimApprovalResponse" element="tschema:ClaimApprovalResponse" />
</wsdl:message>
<wsdl:message name="ClaimApprovalNotificationRequest">
<wsdl:part name="ClaimApprovalNotificationRequest" element="tschema:ClaimApprovalNotificationData" />
</wsdl:message>
<wsdl:portType name="ClaimsHandlingPT">
<wsdl:operation name="approve">
<wsdl:input message="tns:ClaimApprovalRequest" />
</wsdl:operation>
<wsdl:operation name="escalate">
<wsdl:input message="tns:ClaimApprovalRequest" />
</wsdl:operation>
</wsdl:portType>
<wsdl:portType name="ClaimsHandlingCallbackPT">
<wsdl:operation name="approvalResponse">
<wsdl:input message="tns:ClaimApprovalResponse" />
</wsdl:operation>
</wsdl:portType>
<wsdl:portType name="ClaimApprovalReminderPT">
<wsdl:operation name="notify">
<wsdl:input message="tns:ClaimApprovalNotificationRequest" />
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="ClaimSoapBinding" type="tns:ClaimsHandlingPT">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="approve">
<soap:operation soapAction="urn:approve" style="document" />
<wsdl:input>
<soap:body use="literal" namespace="http://www.example.com/claims/" />
</wsdl:input>
</wsdl:operation>
<wsdl:operation name="escalate">
<soap:operation soapAction="urn:escalate" style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="ClaimSoapBindingReminder" type="tns:ClaimApprovalReminderPT">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="notify">
<soap:operation soapAction="urn:notify" style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="ClaimSoapBindingCB" type="tns:ClaimsHandlingCallbackPT">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="approvalResponse">
<soap:operation soapAction="urn:approvalResponse" style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ClaimService">
<wsdl:port name="ClaimPort" binding="tns:ClaimSoapBinding">
<soap:address location="http://localhost:9763/services/ClaimService" />
</wsdl:port>
</wsdl:service>
<wsdl:service name="ClaimReminderService">
<wsdl:port name="ClaimReminderPort" binding="tns:ClaimSoapBindingReminder">
<soap:address location="http://localhost:9763/services/ClaimReminderService" />
</wsdl:port>
</wsdl:service>
<wsdl:service name="ClaimServiceCB">
<wsdl:port name="ClaimPortCB" binding="tns:ClaimSoapBindingCB">
<soap:address location="http://localhost:9763/services/ClaimServiceCB" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
A:
Finally I could make it.
What we need to do is to add correlationFilter attribute to the corresponding provide activity in the deploy.xml file.
By adding this namespace will provide b4pFilter
xmlns:b4p="http://docs.oasis-open.org/ns/bpel4people/bpel4people/200803"
<provide partnerLink="b4p" correlationFilter="b4p:b4pFilter">
<service name="biApprove:ClaimServiceCB" port="ClaimPortCB"/>
</provide>
Full code of the deploy.xml
<?xml version="1.0" encoding="UTF-8"?>
<deploy xmlns="http://www.apache.org/ode/schemas/dd/2007/03"
xmlns:biApprove="http://www.example.com/claims/"
xmlns:sample="http://loits.com/bps/training"
xmlns:b4p="http://docs.oasis-open.org/ns/bpel4people/bpel4people/200803">
<process name="sample:JavaTraining">
<active>true</active>
<retired>false</retired>
<process-events generate="all"/>
<provide partnerLink="client">
<service name="sample:BpelTest" port="BpelTestPort"/>
</provide>
<provide partnerLink="b4p" correlationFilter="b4p:b4pFilter">
<service name="biApprove:ClaimServiceCB" port="ClaimPortCB"/>
</provide>
<invoke partnerLink="b4p">
<service name="biApprove:ClaimService" port="ClaimPort"/>
</invoke>
</process>
</deploy>
| {
"pile_set_name": "StackExchange"
} |
Q:
DDD Implementation detail using a Service
I have two distinct repositories that I will be using simultaneously throughout my app.
There will be instances when I need to read from one (REST WS) and then turn around write to another (SQLite DB).
Should this be done in a "domain-service", or is ok to do within the presentation/application layer?
NOTE: To give some context, I have a separate service-process that fetches new records from a remote WS, and then makes them available to another process by writing to a local DB, which it then in turn loads from.
One process is a service that deals with fetching and updating data between the local and remote DB's. The other process is the actual app that operates solely off the local DB, and issues requests to the service-process via a request-queue table).
A:
I would probably have one service for the REST reads, one for the SQLite writes, and one (a Facade) that binds them together. The pattern here is the Facade Pattern.
| {
"pile_set_name": "StackExchange"
} |
Q:
New Signature Field Rotated 90 Degrees
Iโm able to add a new signature block on the PDF using an annotation, but itโs always rotated 90* to the page. Iโve tried using the .Rotate method on the annotation before adding it, but that does nothing. I also rotated the PDF template and the added signature field maintains the same relative 90* orientation. I've also changed the rectangle points and that does not appear to have any effect on the rotation. I do NOT want to sign the PDF...I only wish to add a blank sig field for signing by other parties later.
//Get location to the field where we will place the signature field
AcroFields.FieldPosition NewPosition = fields.GetFieldPositions("DESC_0_" + (itemno + 1).ToString())[0];
float l1 = NewPosition.position.Left;
float r1 = NewPosition.position.Right;
float t1 = NewPosition.position.Top;
float b1 = NewPosition.position.Bottom;
PdfFormField field = PdfFormField.CreateSignature(pdfStamper.Writer);
field.FieldName = "G4_Signature";
// Set the widget properties
field.SetWidget(new iTextSharp.text.Rectangle(r1, t1, l1, b1), PdfAnnotation.HIGHLIGHT_NONE);
field.Flags = PdfAnnotation.FLAGS_PRINT;
// Add the annotation
pdfStamper.AddAnnotation(field, 1);
Link: Template PDF
Link: Populated PDF
A:
The page in your document is rotated using the Rotate page dictionary entry. When creating a field to be filled-in by others later, you have to add a hint to the field indicating a counter-rotation if you want the field content to effectively appear upright.
You do this by setting the MKRotation attribute of the field:
field.Flags = PdfAnnotation.FLAGS_PRINT;
// Add a hint for upright signature creation
field.MKRotation = 90;
// Add the annotation
pdfStamper.AddAnnotation(field, 1);
This creates a rotation entry R with value 90 in the appearance characteristics dictionary MK of the field.
For backgrounds:
MK dictionary (Optional) An appearance characteristics dictionary (see Table 189) that shall be used in constructing a dynamic appearance stream specifying the annotationโs visual presentation on the page.
The name MK for this entry is of historical significance only and has no
direct meaning.
(Table 188 โ Additional entries specific to a widget annotation - in ISO 32000-1)
and
R integer (Optional) The number of degrees by which the widget annotation shall be rotated counterclockwise relative to the page. The value shall be a multiple of 90. Default value: 0.
(Table 189 โ Entries in an appearance characteristics dictionary - in ISO 32000-1)
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.