text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Pandas Using .str on a dataframe filtered with .loc
I am trying to pad the float(64) values with some zeros in a column called date_of_birth within a dataframe called drugs_tall. date_of_birth contains some NA.
This was my initial idea:
drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']] = drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']].astype('int').astype('str').str.zfill(6)
However, this generates the error
AttributeError: 'DataFrame' object has no attribute 'str'
I got around this by simply doing (this works):
drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']] = drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']].astype('int').astype('str')
drugs_tall['date_of_birth'] = drugs_tall['date_of_birth'].str.zfill(6)
Note that it is not possible to go directly to:
drugs_tall['date_of_birth'] = drugs_tall['date_of_birth'].str.zfill(6)
As this will generate the error:
AttributeError: Can only use .str accessor with string values, which use
np.object_ dtype in pandas
It is also not possible to change the data type without using .loc selection:
drugs_tall['date_of_birth'].astype('int').astype('str')
As this will give:
ValueError: Cannot convert non-finite values (NA or inf) to integer
Am I going about this in a strange way or misunderstanding how the dataframes work? I know my two line solution is reasonably brief, but I don't understand what makes the two line solution different from my initial idea.
Thank you
A:
Your column indexer should be a scalar 'dob' instead of a list ['dob']. This is why you find a dataframe as the output of your indexing operation. This makes some sense: a sequence of columns is interpreted as a dataframe, a scalar column gives a series.
For your task, you can use pd.Series.notnull together with pd.DataFrame.loc. Integer conversion is recommended in case Pandas is storing your values as float.
df = pd.DataFrame({'dob': [np.nan, None, 11585, 52590]})
mask = df['dob'].notnull()
df.loc[mask, 'dob'] = df.loc[mask, 'dob'].astype(int).astype(str).str.zfill(6)
print(df)
dob
0 NaN
1 NaN
2 011585
3 052590
| {
"pile_set_name": "StackExchange"
} |
Q:
Import statement is breaking down application
im trying to import a mongoose model from one file containing the schema (issue.js) to another file (server.js). i am running the app with nodemon and all works well until i try to import the Issue model from the issue.js file into the server.js file, nodemon then logs a message saying
SyntaxError: Unexpected identifier"
referring to the model in the import statement
Ive tried implementing different types of import statements and
here is my "issue model" and export statement in issue.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Issue = new Schema({
title: {
type: String
},
responsible: {
type: String
},
description: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
export default mongoose.model('Issue', Issue);
and here is where i try to import it into server.js
const mongoose = require('mongoose');
import Issue from './models/Issue.js';
when i save the server.js file with the import statement nodemon restarts the application and crashes with the console message
SyntaxError: Unexpected identifier
in reference to the Issue import.
Is there something that i am missing here about the syntax of these import and export statements?
A:
To use imports you need to config it in Babel. A quick fix is to use the common JS system
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Issue = new Schema({
title: {
type: String
},
responsible: {
type: String
},
description: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
module.exports ={ mongoose.model('Issue', Issue);}
and then
const Issue = require('./models/Issue.js')
for import
| {
"pile_set_name": "StackExchange"
} |
Q:
Disabling editing of a product field in Magento's "manage products" area?
In Magento Admin -> Catalog -> Manage Products, I'd like to disable a couple of product fields so that administrators can't edit them.
Essentially turning this:
into this:
Magento pulls the field HTML in via the template at adminhtml/default/default/template/catalog/form/renderer/fieldset/element.phtml, via the function getElementHtml() but I can't find the place where the actual <input> HTML is being constructed.
Besides, there's probably a more modular way of doing this, rather than just editing the template's HTML.
Any thoughts?
A:
I discovered a similar question, here, which led me to the solution:
Open up app\design\adminhtml\default\default\template\catalog\form\renderer\fieldset\element.phtml
Find the line which reads <?php $this->checkFieldDisable() ?>
Underneath this, insert this block (edit "sku" to whatever you need):
<?php
// Disable editing of SKU field
if ($_element->name == "sku") {
$_element->setDisabled(true);
}
?>
There may be an even more elegant way of doing this, such as setting the "disabled" option somewhere in the database, but since these are system attributes I doubt it. This works!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to give Shadow on image
Image with Shadow Effect,This is JPG Image,
Here Is png image where create shadow:
My Code Is :
img.image-shadow {
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.4);
}
<body>
<img class="image-shadow" src="http://i.stack.imgur.com/CtIqi.png">
</body>
A:
Try this to add shadow below your image,
img{
-webkit-filter: drop-shadow(0px 16px 10px rgba(0,0,225,0.6));
-moz-filter: drop-shadow(0px 16px 10px rgba(0,0,225,0.6));
-ms-filter: drop-shadow(0px 16px 10px rgba(0,0,225,0.6));
-o-filter: drop-shadow(0px 16px 10px rgba(0,0,225,0.6));
filter: drop-shadow(0px 16px 10px rgba(0,0,225,0.6));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting new Date with FMT and SpringMVC
I have a problem with FMT and SpringMVC:
I have an object which contains a date field, so i use fmt to show it in my jsp page like this:
<fmt:formatDate value="${form.dtBegin}" type="date" pattern="dd/MM/yyyy HH:mm" />
The problem is that when i submit my page, this field "form.dtBegin" get a new Date and in my case this field should not change!!
So have you any idea for this problem?
Thanx all!
A:
Maybe you could try binding date in your controller.
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy HH:mm"), true));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
If union and intersection of two subsets are connected, are the subsets connected?
I'm starting with the basics of topology theory and I'm trying to show:
Let $A$ and $B$ be closed subsets of a topological space. If $A\cap B$ and $A\cup B$ are both connected, $A$ and $B$ are connected.
I've tried to prove it whit subsets operations and by contradiction, but I've failed with both strategies. Can you help me, please?
A:
Suppose for a contradiction that $A$ is disconnected. Then there are closed, disjoint, non-empty subsets $S, T$ of $A$ such that $A=S\cup T$.
Since $A\cap B$ is connected, one of $B\cap S$ and $B\cap T$ must be empty, otherwise $A\cap B=(B\cap S)\cup (B\cap T)$. WLOG assume $B\cap S=\emptyset$.
Now, since $S$ and $T$ are closed in $A$ and $A$ is closed in $X$, $S$ and $T$ are closed in $X$. Therefore, $B\cup T$ and $S$ are closed non-empty subsets of $A\cup B$. Obviously, $(B\cup T)\cap S=\emptyset$ and $A\cup B=(B\cup T)\cup S$, so $A\cup B$ is disconnected, contradiction.
A:
Let's use proof by contradiction. Without loss of generality, assume $A$ is not connected. Then (by definition) $A = A_1 \cup A_2$ such that $A_1 \subseteq U_1$, $A_2 \subseteq U_2$, $U_1 \cap U_2 = \emptyset$, and the sets $U_i$ are open. Can you proceed from there? Hint, you'll have to show one of $A \cap B$ or $A \cup B$ is in fact disconnected.
| {
"pile_set_name": "StackExchange"
} |
Q:
select all rows with lowest product_id
i have this table and i want to select all rows with product id 105. i can easily do this if i know product id and put in where clause but i dont know product id and it increases once this id work is completed it will delete these rows and search for next lowest product id.
with order bt product_id i can do but how to ensure that all rows are listed. if i will give 100 limit then first 10-15 may be lowest after that it will start listing next higher product_id rows
here is table
id name product_id some_columns
1 dff 105 gfff
2 fg 109 ffgfgf
3 tt 106 gttytt
4 tt 105 trtr
5 trr 112 trrrt
6 rrr 111 rttttr
7 ttyt 108 ttrtrtr
8 rrrr 105 rrerer
SELECT id, name, product_id, some_columns
FROM table_name
WHERE product_id = (SELECT MIN(product_id) FROM table_name)
here you can see that lowest product_id is 105 but i dont have any control on how many times it will appear in table. in some case it may be 10 rows and in some case it may be 250 rows.
so order by product_id will not work. as giving limit will list all id initial few rows may be 105 but after than when all 105 rows are listed it will start listing all rows which is higher than 105
the best solution would be if i could use where product_id=105 but my bad luck i dont have any control on product id so cant use product id in where clause. next big problem is i want to use it efficiently so we have indexed product_id column
i was exploring min value option but i am highly doubtful about its efficiency and probable affect on mysql
so any help will be great
A:
You can try something like
SELECT id, name, product_id, some_columns
FROM table_name
WHERE product_id = (SELECT MIN(product_id) FROM table_name)
As far as I understood you want to select all the rows that match the minimum product_id. Be it 101, 102 or whatever, it's uncontrollable, so you get the minimum product_id in the row and then you select the rows that has the current minimum product_id.
| {
"pile_set_name": "StackExchange"
} |
Q:
Program that prints A to Z and Z to A in x86 Assembly
I am writing a program that prints A to Z and Z to A in assembly using loops, but it crashes every time after 'A' is printed out.
TITLE A to Z
;loop that prints from a to z & z to a
INCLUDE Irvine32.inc
.code
letter BYTE 65, 0
space BYTE ' ', 0
main PROC
MOV ECX, 26
myloop:
MOV EDX, offset letter
CALL writechar
INC letter
MOV EDX, offset space
CALL writechar
LOOP myloop
CALL crlf
MOV ECX, 26
myloop2:
MOV EDX, offset letter
CALL writechar
DEC letter
MOV EDX, offset space
CALL writechar
LOOP myloop2
exit
main ENDP
END main
This program uses some functions from the Irvine32.inc library, but I am sure that has nothing to do with the problem, so I disregard it for now. . . I'll provide more details if requested.
Thanks a lot!
JLL
Here's the Irvine32.inc file:
; Include file for Irvine32.lib (Irvine32.inc)
INCLUDE SmallWin.inc ; MS-Windows prototypes, structures, and constants
.NOLIST
; Last update: 1/27/02
;----------------------------------------
; Procedure Prototypes
;----------------------------------------
ClrScr PROTO ; clear the screen
Crlf PROTO ; output carriage-return / linefeed
Delay PROTO ; delay for n milliseconds
DumpMem PROTO ; display memory dump
DumpRegs PROTO ; display register dump
GetCommandTail PROTO ; get command-line string
GetDateTime PROTO, ; get system date and time
startTime:PTR QWORD
GetMseconds PROTO ; get milliseconds past midnight
Gotoxy PROTO
IsDigit PROTO ; return ZF=1 if AL is a decimal digit
Randomize PROTO ; reseed random number generator
RandomRange PROTO ; generate random integer in specified range
Random32 PROTO ; generate 32-bit random integer
ReadInt PROTO ; read signed integer from console
ReadChar PROTO ; reach single character from console
ReadHex PROTO ; read hexadecimal integer from console
ReadString PROTO ; read string from console
SetTextColor PROTO ; set console text color
WaitMsg PROTO ; display wait message, wait for Enter key
WriteBin PROTO ; write integer to output in binary format
WriteChar PROTO ; write single character to output
WriteDec PROTO ; write unsigned decimal integer to output
WriteHex PROTO ; write hexadecimal integer to output
WriteInt PROTO ; write signed integer to output
WriteString PROTO ; write null-terminated string to output
; Copy a source string to a target string.
Str_copy PROTO,
source:PTR BYTE,
target:PTR BYTE
; Return the length of a null-terminated string..
Str_length PROTO,
pString:PTR BYTE
; Compare string1 to string2. Set the Zero and
; Carry flags in the same way as the CMP instruction.
Str_compare PROTO,
string1:PTR BYTE,
string2:PTR BYTE
; Trim a given trailing character from a string.
; The second argument is the character to trim.
Str_trim PROTO,
pString:PTR BYTE,
char:BYTE
; Convert a null-terminated string to upper case.
Str_ucase PROTO,
pString:PTR BYTE
;-----------------------------------
; Standard 4-bit color definitions
;-----------------------------------
black = 0000b
blue = 0001b
green = 0010b
cyan = 0011b
red = 0100b
magenta = 0101b
brown = 0110b
lightGray = 0111b
gray = 1000b
lightBlue = 1001b
lightGreen = 1010b
lightCyan = 1011b
lightRed = 1100b
lightMagenta = 1101b
yellow = 1110b
white = 1111b
.LIST
A:
A little pet peeve I have - You call functions called writechar and crlf, yet, Mr. Kip created those functions and calls them WriteChar and Crlf.
All you need to do is open up Irvine32.asm and look at the source for WriteChar, at the beginning of the procedure, Mr. Irvine left this for all to see:
WriteChar PROC
;
; Write a character to the console window
; Recevies: AL = character
; Last update: 10/30/02
; Note: WriteConole will not work unless direction flag is clear.
;------------------------------------------------------
So before you call WriteChar, you put the ASCII value of the character to print into AL NOT the address!
MOV al, letter
CALL WriteChar
INC letter
Also, as Frank mentioned, your variables should be in the .data or .data? section not the .code section
| {
"pile_set_name": "StackExchange"
} |
Q:
How to conditionally download file using p:fileDownload
A file has to be downloaded conditionally. When the button is clicked, the data is fetched from the database. The data is validated. If the data is valid (#{reportPage.validData}) the file is created & downloaded.
However, if the data is invalid, the file is not to be downloaded. As per my understanding fileDownload has 2 attributes: value; contextDisposition. How can I download the file conditionally ?
<p:commandButton id="generaterReport" ajax="false"
value="#{msg['report.generateReport']}" actionListener="#{reportPage.onGenerateReport}">
<p:fileDownload value ="#{reportPage.csvFile}" />
</p:commandButton>
A:
If validation fails simply make sure that `#{reportPage.csvFile} resolves to nothing.
| {
"pile_set_name": "StackExchange"
} |
Q:
I am not able to load Self Reference in SQLAlchemy
I currently having an issue with a self reference relationship.
I have the table Customer which can have a parent (also a Customer) like this:
class CustomerModel(db.Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('customer.id'))
parent = relationship("CustomerModel", foreign_keys=[parent_id])
So my problem is that when I'm trying to load the parent, the following query is built by SQLAlchemy:
Lets take this customer for example: Customer(id=1, parent_id=10)
SELECT *
FROM customer
WHERE 1 = customer.parent_id
So the WHERE condition is wrong because it compares the parent_id to the id of the customer I'm trying to load the parent from.
The correct query should be:
SELECT *
FROM customer
WHERE 10 = customer.parent_id
What am I doing wrong?
A:
So i finally found the answer.
I need to add the param remote_side like this:
class CustomerModel(db.Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('customer.id'))
parent = relationship("CustomerModel", foreign_keys=[parent_id], remote_side=[id])
| {
"pile_set_name": "StackExchange"
} |
Q:
Switch function not returning correct value when referencing "nothing"
having a small issue here.
I have a Switch function in a report as shown below:
=Switch(
Fields!Duration.Value > 0, Round(Fields!Duration.Value / 60),
Fields!LastTime.Value = nothing, "Still Occupied",
Fields!LastTime.Value = Fields!FirstTime.Value, "Passing By"
)
This is for a column that is showing the total "Fields!Duration.Value" in minutes (rounded up), and it is working other than the second line:
If the Last Time value is the same as the First Time value, then it is assumed the object was just passing by and outputs "Passing By" and it does this correctly.
However, if the Last Time value is equal to nothing (it is defined in the column for "Last Time" that if it IsNothing, it is 'nothing', and it should output in this report with "Still Occupied" - which it's not doing. The cell is left blank, as if I have it written as Fields!LastTime.Value = nothing, nothing,
Why is this line of code not working?
Fields!LastTime.Value = nothing, "Still Occupied",
Thank you
A:
You cannot test for Nothing using the = operator. There are two ways for which Nothing can be tested; using the IsNothing inspection function like this IsNothing(Fields!LastTime.Value) = True, or by using the Is operator like this Fields!LastTime.Value Is Nothing.
If these tests do not produce the expected result you may be dealing with a field that is set to something other than NULL, like empty '' or an arbitrary value. You can open the Query Designer on your Dataset properties to run your query and check the results.
You could also be looking at a mismapping with your dataset. Use the Refresh Fields button on your Dataset properties to verify your Field Mappings and then double-check that the name being used in your expression matches.
A:
I found that using an IIF statement instead of a Switch statement worked for me, at least for this specific case:
=IIF(Fields!Duration.Value > 0, Round(Fields!Duration.Value / 60),
IIF(Fields!LastTime.Value = Fields!FirstTime.Value, "Passing by", "Still Occupied"))
Going to try to explain it for future people that might not understand (like me when I eventually forget it - I am very new to this sort of stuff) -
Rather than using the Switch statement I had in place to see if Fields!LastTime.Value is a number, equal to Fields!FirstTime.Value, or nothing, it now just asks if it is a number or if it is equal to Fields!FirstTime.Value, and if neither of those are true, it marks it as "Still Occupied" thus removing the need to reference nothing entirely. Like I said, this is pretty case specific, but you never know.
Thank you for the help @JamieSee and @SuperSimmer 44. Cheers!
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get a value from this localStorage array to create a new var?
Here is the localStorage entry I want to use:
Key: file
Value: [{"id":"usethis","somethingelse":"otherstuff"}]
I want to create a var from id in the Value array so I can make an if that says:
var idvalue = ??? (...this is what I need help retrieving...)
if (idvalue == "usethis") { ...do some stuff... } else { ...do something else... }
A:
Try
//read the string value from localStorage
var string = localStorage.getItem('file');
//check if the local storage value exists
if (string) {
//if exists then parse the string back to a array object and assign the first item in the array to a variable item
var file = JSON.parse(string),
item = file[0];
//check whether item exists and its id is usethis
if (item && item.id == "usethis") {} else {}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Find a group of objects in JSON
[
{"id":1,"id_parent":7,"name":"sub category of cat 7-1"},
{"id":2,"id_parent":7,"name":"sub category of cat 7-2"},
{"id":3,"id_parent":8,"name":"sub category of cat 8-1"},
{"id":4,"id_parent":8,"name":"sub category of cat 8-2"}
]
I want to find a group of objects in a bigger group. For example, just get objects that have id_parent=7. Now I use a for loop to do that, but I wonder there is any alternative solution to do that. Thank you
A:
If your browser has Array.filter, you could do this:
var children_of_7 = data.filter(function(item) {
return item.id_parent === 7;
});
If your browser doesn't have it natively, you could shim it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return object method properly
I created MyObject in javascript and I need to return its method like this
var m = new MyObject();
document.onclick = m.myMethod;
But the problem is, all the m instance variables appear to be undefined, I can't access them (even though they are defined on m) and operations on them result in NaN. How do I do this properly, so instance variables stay set when method is executed?
A:
It is because the this scope is the html element, not the instance.
Either a closure
document.onclick = function(evt) { m.myMethod(evt); }
or bind
document.onclick = m.myMethod.bind(m);
is needed to maintain the scope you are after.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como carregar uma PartialView para criar um comentário
Estou a trabalhar num projeto para aprender ASP.NET MVC e Razor. Neste momento tenho um modelo de post com uma view, e uma view associada ao model class do comentário para criar um novo comentário. Queria saber como devo fazer para colocar a view de criação de comentário no final do post, e quando submeter como associo o comentário ao post (tenho um variável PostId no modelo do comentário para fazer a associação). Inseri manualmente na base de dados alguns comentários e aparecem no sítio certo pois coloquei o PostId manualmente, o que não é funcional. Veja a view para criar um comentário:
@model shanuMVCUserRoles.CommentSet
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CommentSet</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.MemberID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.MemberID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.MemberID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PostID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PostID, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PostID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
A:
O começo está ok, mas será necessário mudar algumas coisas para que faça sentido usar como PartialView:
@model shanuMVCUserRoles.CommentSet
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Adicione um comentário</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.MemberID)
@Html.HiddenFor(model => model.PostID)
<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Criar" class="btn btn-default" />
</div>
</div>
</div>
}
Note que PostID e MemberID são hidden, e teremos que preenchê-los ao chamar a Partial:
@Html.Partial("_AdicionarComentario", new CommentSet { PostID = Model.PostID, MemberID = User.Identity.GetUserId() })
Isto pode ser carregado na View Details, ou na View que exibe o Post. O nome você escolhe.
Ao inserir o comentário, você redireciona a página para o Post, e não para o comentário.
return RedirectToAction("Details", "Posts", new { PostID = Model.PostID });
| {
"pile_set_name": "StackExchange"
} |
Q:
No update app after click on notification
I use react native and I writing a native module for notification! so I want to when I click on notification just resume app and no restart
I write below code but this work in first time that app runs and after that every click on notification restart app. what's wrong?
Class cl = null;
try {
cl = Class.forName(packageName + ".MainActivity");
} catch (ClassNotFoundException e) {
//TODO: if you want feedback
}
Intent openIntent = new Intent(reactContext, cl);
openIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent contentIntent = PendingIntent.getActivity(reactContext, 0, openIntent, 0);
Notification.Builder notificationBuilder = new Notification.Builder(reactContext)
.setSmallIcon(smallIconResId)
.setVibrate(new long[]{0,500})
.setContentTitle("test")
.setOngoing(true)
.setContentText("test is here :)")
.setContentIntent(contentIntent);
A:
OK, I find answer, I change my manifest and everything is ok now.
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTask" // <-- add this line
>
| {
"pile_set_name": "StackExchange"
} |
Q:
Returning Object Value Based On Property
I have an object that includes a variety of animals:
var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}]
I'm wanting to return the names of the animals that are cats, only. I'm struggling to do so. Here is my attempt:
var cats = []
function onlyCats(array) {
if (toonimals.animal === 'cat') {
cats.push(toonimals.name)
}
return cats
}
console.log(onlyCats(toonimals));
Currently, it is only returning the empty array so the .push() method isn't working for some reason.
Thank you in advance.
A:
You have to loop through the array to filter() the animal. Then use map() to modify the array to return the name:
var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}];
function onlyCats(array) {
return array.filter(a => a.animal === 'cat').map(a => a.name);
}
console.log(onlyCats(toonimals));
In your way with the help of forEach():
var toonimals = [ {name: 'Itchy', animal: 'mouse'}, {name: 'Stimpy', animal: 'cat'}, {name: 'Daffy', animal: 'duck'}, {name: 'Scratchy', animal: 'cat'}, {name: 'Ren', animal: 'dog'}, {name: 'Felix', animal: 'cat'}];
var cats = []
function onlyCats(array) {
array.forEach(function(animal){
if (animal.animal === 'cat') {
cats.push(animal.name)
}
});
return cats;
}
console.log(onlyCats(toonimals));
| {
"pile_set_name": "StackExchange"
} |
Q:
Mulesoft Development Environment (Anypoint Studio Version)
Mule 4 improvements makes it easier to learn, develop and manage than that of Mule 3. Mulesoft had recently released Mule 4 and for any customer to decide regarding the versions for integration looking forward for the following details:
Is Mule 4 stable ??
(Mule 4 is new in the market, since Client has to deal with financial related data and can not effort to take a risk to play with customer data)
Since older versions are stable,if customer go with older versions of Anypoint Studio <= 3.9.2, to what extend and till when Mulesoft can provide support to older versions like Mule 3.8.3 as Mule 4 is already in the market??
Thanks & Regards
A:
To answer your first question, Yes and No.
The runtimes themselves are pretty stable, and once something works you can be pretty sure it stays working.
The problem lies in the development.
If your use-cases are a bit complex, and you start needing the non-basic connectors you will probably find some bugs. For some you can find workarounds, for some you can't.
In the 6-9 months i've worked with mule 4 however, Mulesoft did show active improvement, and most bugs reported are fixed in a decent timeframe.
One advice i can make though: If you have the choice, run on linux.
Although windows is technicaly supported, we've had quite a few issues regarding windows (Server 2016).
A current one we are facing is that when redeploying an API you have to log into the server, stop the runtime(4.1.5) service, and remove the api files manualy, as the redeploy breaks an API. A patch was provided which reduces the chances of this happening but it's still around.
As for Question two:
The page provided by Alejandro Dobniewski suggests only 7 more months of support for 3.9.
And 3.8.x is already unsupported, extending it to 2021 is possible however. (for a price) (as of 8-3-2019).
For us, this was the motivation to adopt version 4, along with saving us the effort of later switching to 4.
Mule 3.9 applications and code are completely incompatible with mule 4, so every api you develop will have to be re-built from scratch.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sharepoint Web Service returns error when used in iPad App
I pretty much made an API to consume Sharepoint Web Services and everything is working OK except for Delete Item part.
I am using Lists.asmx web service, and am calling method UpdateListItems.
My Request looks like this:
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>Shared Documents</listName>
<updates><Batch OnError="Continue" ListVersion="1" ><Method ID='1' Cmd='Delete'><Field Name='ID'>99</Field></Method></Batch></updates>
</UpdateListItems>
</soap12:Body>
</soap12:Envelope>
And the response shows the following error:
<soap:Reason>
<soap:Text xml:lang="en">Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown
</soap:Text></soap:Reason>
<detail>
<errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.</errorstring>
<errorcode xmlns="http://schemas.microsoft.com/sharepoint/soap/">0x8102006d</errorcode>
Any ideas how can I solve this?
A:
After a lot of testing and googling, I found that this error is received from web services that create, update or delete. The error shows because in the header file I didn't include SOAPAction.
You can check the details on the blog where I find the solution
http://weblogs.asp.net/jan/archive/2009/05/25/quot-the-security-validation-for-this-page-is-invalid-quot-when-calling-the-sharepoint-web-services.aspx
After changing the request to include following code the security error was gone.
NSString *soapAction = [NSString stringWithFormat:@"http://schemas.microsoft.com/sharepoint/soap/%@", method];
[theRequest addValue:serverName forHTTPHeaderField:@"Host"];
[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Lenght"];
[theRequest addValue:soapAction forHTTPHeaderField:@"SOAPAction"];
[theRequest setHTTPMethod:@"POST"];
I hope that this answer will help somebody.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to create a login page in asp.net
First of all I'm new to C# and I'm trying to create a login page for my project. I made the database there are Id and Pass in my Students table.
I'm trying to login with using the credentials, but i think I made a mistake somewhere and whatever i write to Id and Pass fields, and even if I leave them blank, I can get through the login page.
Here's my code hope you can help me thanks from now.
protected void Button1_Click(object sender, EventArgs e){
try{
con.Open();
string IdText = user.Text;
string PassText = pass.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Id, '') AS Id, ISNULL(Pass,'') AS Pass FROM Students WHERE Id = @Id and Pass = @Pass", con);
cmd.Parameters.Add(new SqlParameter("Id", IdText));
cmd.Parameters.Add(new SqlParameter("Pass", PassText));
SqlDataReader dr = cmd.ExecuteReader();
Response.Redirect("Main.aspx");
try{
dr.Read();
if (dr["Id"].ToString().Trim() == IdText && dr["Pass"].ToString().Trim() == PassText) {
Label4.Text = "This message won't Display";
}
}
catch{
Label4.Text = "Invalid Username or Password";
}
dr.Close();
con.Close();
}
catch (Exception ex){
Label4.Text = (ex.Message);
}
}
}
A:
Update Your code with following
protected void Button1_Click(object sender, EventArgs e){
try{
con.Open();
string IdText = user.Text;
string PassText = pass.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Id, '') AS Id, ISNULL(Pass,'') AS Pass FROM Students WHERE Id = @Id and Pass = @Pass", con);
cmd.Parameters.Add(new SqlParameter("@Id", IdText));
cmd.Parameters.Add(new SqlParameter("@Pass", PassText));
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr["Id"].ToString().Trim() == IdText && dr["Pass"].ToString().Trim() == PassText) {
Response.Redirect("Main.aspx");
}
else
{
Label4.Text = "Invalid Username or Password";
}
dr.Close();
con.Close();
}
catch (Exception ex){
Label4.Text = (ex.Message);
}
}
}
I hope this will help.
| {
"pile_set_name": "StackExchange"
} |
Q:
Escaping html characters in a javascript array
I would like to escape some html characters that I have stored in an array.
var quiz = [{
"question": "How would we use css to select an element with <h1 class = \"intro\">",
"choices": [".intro{ property: attribute }", "intro{ property :attribute }", "#intro{property: attribute }"],
"correct": ".intro{ property: attribute }"
}, {
"question": "How would we select the element with id firstname <p id=\"firstname\">?",
"choices": ["#firstname{ property: attribute }", ".firstname{ property: attribute }", "who cares?"],
"correct": "#firstname{ property: attribute }"
}, {
"question": "How would we select all elements?",
"choices": ["#{ property: attribute }", "@all{ property: attribute }", "*{ property: attribute }"],
"correct": "*{ property: attribute }"
}, {
"question": "what does this do div > p?",
"choices": ["Selects all <p> elements inside <div> elements", "Selects <p> element that is a child of <div>", "Selects all <p> that are placed immediately after <div>"],
"correct": "Selects <p> element that is a child of <div>"
}, {
"question": "what does div + p do?",
"choices": ["Selects all <div> and <p> elements", "Selects all <p> elements inside <div> elements", "Selects all <p> elements that are placed immediately after <div> elements"],
"correct": "Selects all <p> elements that are placed immediately after <div> elements"
}];
I know that there are multiple answers to escaping html tags within javascript. For example I found this function which is very straightforward.
var htmlString = "<h1>My HTML STRING</h1><p>It has html characters & such in it.</p>";
$(document).ready(function(){
$("#replaceDiv").text(htmlString)
});
However, all the solutions I have seen require creating a function assigning variables etc. This seems overly complicated. Is there any easier way to accomplish my goals here?
A:
Thanks @GrawCube for help in the chat room.
Solution was to create an escape function and then parse the quiz array.
function escapeHtmlChars(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
for (var i = 0; i < quiz.length; i++) {
quiz[i].correct = escapeHtmlChars(quiz[i].correct);
for (var j = 0; j < quiz[i].choices.length; j++) {
quiz[i].choices[j] = escapeHtmlChars(quiz[i].choices[j]);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read the MPEG2VideoDescriptor in an MXF file?
Here follows the hex dump of the MPEG2VideoDescriptor:
06 0e 2b 34 02 53 01 01 0d 01 01 01 01 01 51 00
83 00 00 f3 3c 0a 00 10 a3 be 51 b2 00 05 e7 11
bf 82 21 97 f7 a0 14 ed 30 06 00 04 00 00 00 02
30 01 00 08 00 00 ea 60 00 00 03 e9 80 00 00 04
01 c9 c3 80 30 04 00 10 06 0e 2b 34 04 01 01 02
0d 01 03 01 02 04 61 01 32 15 00 01 05 32 0e 00
08 00 00 00 10 00 00 00 09 32 0d 00 10 00 00 00
02 00 00 00 04 00 00 00 1a 00 00 00 00 32 0c 00
01 00 32 08 00 04 00 00 02 d0 32 09 00 04 00 00
05 00 32 02 00 04 00 00 02 d0 32 03 00 04 00 00
05 00 32 01 00 10 06 0e 2b 34 04 01 01 03 04 01
02 02 01 04 03 00 33 02 00 04 00 00 00 02 33 08
00 04 00 00 00 01 33 03 00 01 04 33 01 00 04 00
00 00 08 33 0b 00 01 00 33 07 00 02 00 00 33 04
The first 16 bytes:
06 0e 2b 34 02 53 01 01 0d 01 01 01 01 01 51 00 (UID)
Next 4 bytes is the BER size:
83 00 00 f3 (0xf3 bytes long)
Next 4 bytes:
3c 0a 00 10 (0x3c0a means Instance UUID and 0x0010 is the size)
Then follows the UUID:
a3 be 51 b2 00 05 e7 11 bf 82 21 97 f7 a0 14 ed
Next 4 bytes:
30 06 00 04 (0x3006 means Linked Track ID and 0x0004 is the size)
Next 4 bytes is the Linked Track ID: 00 00 00 02
Next 4 bytes: 30 01 00 08 (0x3001 means Sample Rate and 0x0008 is the size)
The following 8 bytes are actually frame rate numerator and denominator:
0000ea60 == 60000 and 000003e9 == 1001.
Now we have the bold part: 80 00 00 04
.
Can somebody please explain what does it mean?
The next four bytes are 01 c9 c3 80 and it is definitely the bitrate (30000000), but how can I know that for sure?
Edit:
Does 80 00 00 04 mean the following:
0x8000 is a dynamic tag. According to SMPTE 337, tags 0x8000-0xFFFF are dynamically allocated. The 0x0004 is the size (4 bytes). If that's true, how can I tell that the following 4 bytes 01 c9 c3 80 are actually the bitrate? It could be anything, or?
A:
First you have to understand how local tags work.
Local tags 0x8000 and above are user defined.
You have to look at the primer pack of the header partition.
The primer pack translates the local tag to a global UL which may or may not be vendor specific.
Consider the primer pack being a translation table between the 2 byte local tag and the 16 byte UL.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof by induction: inequality $n! > n^3$ for $n > 5$
I'm given a inequality as such: $n! > n^3$
Where n > 5,
I've done this so far:
BC: n = 6, 6! > 720 (Works)
IH: let n = k, we have that: $k! > k^3$
IS: try n = k+1, (I'm told to only work from one side)
So I have (k+1)!, but I'm not sure where to go from here.
I've been told that writing out: $(k+1)! > (k+1)^3$ is a fallacy, because I can't sub in k+1 into both sides, but rather prove from one side only.
Any Help on how to continue from here, would be much appreciated.
A:
You have $(k+1)!=(k+1)k!>(k+1)k^3$ by the induction hypothesis. Now it suffices to show that if $k>5$ then $k^3 > (k+1)^2$. To do that, we write $(k+1)^2 = k^2 +2k+1 < k^2 + kk + k^2 = 3k^2 < kk^2 = k^3$, since we're assuming $k>5$.
| {
"pile_set_name": "StackExchange"
} |
Q:
responsive datatable not working with bootstrap
The header and footer are rendered twice, and sorting is working but not pagination.
What I have tried:
Added latest jQuery version
Included the JS files in the last when all CSS is included already.
Made table responsive on document ready.
I have converted page to XHTML and checked for any open tags everything is ok there
My code is shown below.
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- Morris Charts JavaScript -->
<script src="../bower_components/raphael/raphael-min.js"></script>
<script src="../bower_components/morrisjs/morris.min.js"></script>
<script src="../js/morris-data.js"></script>
<script src="../bower_components/datatables/media/js/jquery.dataTables.min.js"></script>
<script src="../bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script>
<div class="dataTable_wrapper">
<div id="dataTables-example_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="row">
<div class="col-sm-6">
<div class="dataTables_length" id="dataTables-example_length">
<label>Show
<select name="dataTables-example_length" aria-controls="dataTables-example" class="form-control input-sm">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>entries</label>
</div>
</div>
<div class="col-sm-6">
<div id="dataTables-example_filter" class="dataTables_filter">
<label>Search:
<input type="search" class="form-control input-sm" placeholder="" aria-controls="dataTables-example">
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div id="dataTables-example_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="row">
<div class="col-sm-6">
<div class="dataTables_length" id="dataTables-example_length">
<label>Show
<select name="dataTables-example_length" aria-controls="dataTables-example" class="form-control input-sm">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>entries</label>
</div>
</div>
<div class="col-sm-6">
<div id="dataTables-example_filter" class="dataTables_filter">
<label>Search:
<input type="search" class="form-control input-sm" placeholder="" aria-controls="dataTables-example">
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<table class="table table-striped table-bordered table-hover dataTable no-footer" id="dataTables-example" role="grid" aria-describedby="dataTables-example_info">
<thead>
<tr role="row">
<th class="sorting_asc" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Rendering engine: activate to sort column descending" style="width: 0px;" aria-sort="ascending">Rendering engine</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending" style="width: 0px;">Browser</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending" style="width: 0px;">Platform(s)</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Engine version: activate to sort column ascending" style="width: 0px;">Engine version</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="CSS grade: activate to sort column ascending" style="width: 0px;">CSS grade</th>
</tr>
</thead>
<tbody>
<tr class="gradeA odd" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Camino 1.0</td>
<td>OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA even" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Camino 1.5</td>
<td>OSX.3+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA odd" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Epiphany 2.20</td>
<td>Gnome</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA even" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Firefox 1.0</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.7</td>
<td class="center">A</td>
</tr>
<tr class="gradeA odd" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Firefox 1.5</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA even" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Firefox 2.0</td>
<td>Win 98+ / OSX.2+</td>
<td class="center">1.8</td>
<td class="center">A</td>
</tr>
<tr class="gradeA odd" role="row">
<td class="sorting_1">Gecko</td>
<td class="sorting_1">Firefox 3.0</td>
<td>Win 2k+ / OSX.3+</td>
<td class="center">1.9</td>
<td class="center">A</td>
</tr>
<tr class="gradeX even" role="row">
<td class="sorting_1">Misc</td>
<td class="sorting_1">Dillo 0.8</td>
<td>Embedded devices</td>
<td class="center">-</td>
<td class="center">X</td>
</tr>
<tr class="gradeU odd" role="row">
<td class="sorting_1">Other browsers</td>
<td class="sorting_1">All others</td>
<td>-</td>
<td class="center">-</td>
<td class="center">U</td>
</tr>
<tr class="gradeA even" role="row">
<td class="sorting_1">Trident</td>
<td class="sorting_1">AOL browser (AOL desktop)</td>
<td>Win XP</td>
<td class="center">6</td>
<td class="center">A</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="dataTables_info" id="dataTables-example_info" role="status" aria-live="polite">Showing 1 to 10 of 10 entries</div>
</div>
<div class="col-sm-6">
<div class="dataTables_paginate paging_simple_numbers" id="dataTables-example_paginate">
<ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_previous"><a href="#">Previous</a>
</li>
<li class="paginate_button active" aria-controls="dataTables-example" tabindex="0"><a href="#">1</a>
</li>
<li class="paginate_button next disabled" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_next"><a href="#">Next</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="dataTables_info" id="dataTables-example_info" role="status" aria-live="polite">Showing 1 to 10 of 57 entries</div>
</div>
<div class="col-sm-6">
<div class="dataTables_paginate paging_simple_numbers" id="dataTables-example_paginate">
<ul class="pagination">
<li class="paginate_button previous disabled" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_previous"><a href="#">Previous</a>
</li>
<li class="paginate_button active" aria-controls="dataTables-example" tabindex="0"><a href="#">1</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0"><a href="#">2</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0"><a href="#">3</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0"><a href="#">4</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0"><a href="#">5</a>
</li>
<li class="paginate_button " aria-controls="dataTables-example" tabindex="0"><a href="#">6</a>
</li>
<li class="paginate_button next" aria-controls="dataTables-example" tabindex="0" id="dataTables-example_next"><a href="#">Next</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
A:
I have implemented responsive DataTable many times. Just read document Responsive DataTable. I hope this will help you. You have to add
.table-responsive
class.
| {
"pile_set_name": "StackExchange"
} |
Q:
ホームボタンを押下時してポーズされた画面がアプリに戻った時に解除されてしまう
Xcode8、Swift3、SpriteKitでランアクションライクなアプリを作っています。
ポーズボタンを実装し、プレイ中に
1、ポーズボタンを押下した際と
2、ホームボタンや電源ボタンを押下した際に
isPausedを使って障害物を停止させ、タップを禁止しています。
同時にtimer.invalidateによって障害物を出現させるタイマーを一時停止させ、
再開ボタンを出現させて、ゲームを再開できるようにしています。
このうち2によってポーズされた場合、アプリアイコンをタップして再開した際、障害物の動きが止まっておらず、タップもできてしまいます。タイマーは正常に停止したままで、再開ボタンも出現しています。
また、1によってポーズされたまま、ホームに戻ってアプリを再開した場合も同様の現象が起こります。
AppDelegateからNotificationCenterによって呼び出されたprintにより、ゲームを閉じようとした時、閉じた時、開こうとした時、開いた時のいずれの時点でも self.isPaused = true であることを確認しています。
isPausedで停止された画面をアプリの再開時に動き出さないようにするにはどうしたらよいのでしょうか。
A:
API Reference - class SKView
これの、isPausedの項目から、一部引用します。
Discussion
When an application moves from an active to an inactive state, isPaused is automatically set to true. When an application returns to an active state, isPaused is automatically set to its previous value.
すなわち、UIApplicationのNotificationを利用しなくても、「automatically」に、アプリがバックグラウンドに回ったら、ポーズになって、フォアグラウンドに戻ったら、ポーズが解除されます。
「えーっ、SKSceneのisPausedは操作したけど、SKViewのisPausedは操作してないよ!」とおっしゃるかもしれませんが、じっさいのアプリの挙動を見ると、連動しているのだと推測できます。
●第1案
なので、意図したポーズをするには、「automatically」なポーズの解除がなされた直後に、isPausedをtrueにするといいでしょう。では、そのタイミングはなにかというと、.UIApplicationDidBecomeActiveというNotificationが使えそうです。
SKSceneのサブクラス
override func didMove(to view: SKView) {
NotificationCenter.default.addObserver(self, selector: #selector(becomeActive(_:)), name: .UIApplicationDidBecomeActive, object: nil)
}
func becomeActive(_ notification: Notification) {
isPaused = true
}
●第2案
SKViewのサブクラスを作成し、プロパティisPausedを上書きすることを考えます。
class SubSKView: SKView {
override var isPaused: Bool {
get {
return super.isPaused
}
set {
scene?.isPaused = true
}
}
}
プロジェクト内のすべてのソースコード、Storyboardで、SKViewと型指定している箇所を、SubSKViewに書き換えてください。アプリがフォアグラウンドに戻っても、ポーズしたままになります。
なお、このままでは、複数のSceneを採用している場合、すべてのSceneにそれが適用されますし、意図しないケースでポーズしたままということになるおそれがあります。クラスの上書きには、副作用を注意すべきです。
| {
"pile_set_name": "StackExchange"
} |
Q:
"A killed B" translation
I hope this is the correct place to ask, I have 0 experience with Latin but need this one phrase translated.
"A killed B" as in "Tom killed John".
From what I understand, for my context the best verb is "occido" but how would you use this verb?
Google offers several options:
"A occisus B"
"A occisus est B"
"A occidit B"
"A occidi B"
I assume the second option will be translated more like "A was killed by B", so for my purposes I should go with option 1?
Thank you in advance :)
A:
There are many words for killing, but occidere is a good one.
The form occidit means "he/she/it kills/killed".
For this particular verb the present and perfect tense forms for third person singular look alike, and these forms are also agnostic of gender.
The A and B in "A killed B" are more complicated than you might expect.
If you have any such sentence, you cannot replace A and B with any names and expect it to work.
Latin is far more concerned with the form of A and B than their order.
To illustrate this, let me replace A with Arrius and B with Baebius.
Here are some valid ways to say "Arrius killed Baebius":
Arrius Baebium occidit.
Baebium Arrius occidit.
Arrius occidit Baebium.
Baebium occidit Arrius.
Baebius ab Arrio occisus est.
ab Arrio Baebius occisus est.
Baebius occisus est ab Arrio.
The list is not exhaustive, and options 5–7 are only valid because Baebius is a man.
Who killed whom is not decided by the order of the words — you can shuffle the words freely in a sentence like Arrius Baebium occidit without changing meaning — but by their forms.
If you wanted to swap the roles, you can change it to Arrium Baebius occidit.
The first item on my list would be the typical way to phrase it.
But if you just say "A B occidit", I would have hard time parsing it.
Perhaps "A B" is a person?
The least ambiguous way would be "A occidit B".
This is your option 3.
The others do not mean what you want.
Google Translate is horrible with Latin.
Latin works best if the words can be declined.
Foreign names or placeholders like "A" make it a little awkward.
The best way to say "A killed B" in Latin is A[nom.] B[acc.] occidit, where A is in the nominative and B in the accusative case.
There is no easy general format the way you have in English.
The required endings are different for different words, and figuring out how all that works is a key element of learning Latin.
In the specific case "Ludwig kills/killed Maria", you should choose "Ludwig Mariam occidit".
The name Maria is used as such in Latin, so the different forms are very natural.
There is a Latin version of Ludwig (Ludovicus), but that is not needed to make it all work.
The important thing is that Maria is marked as the unambiguous object with the accusative case.
A:
The verb
Here are some choices suitable for killing by sword in a battle:
Thomas Johannem occidit.
(Tom cut John down, or Tom "felled" John—a very common way to express this.)
Thomas Johannem interfecit.
(Tom did John in—a common, generic way to say "killed" in Latin, regardless of how.)
Thomas Johannem obtruncavit.
(Tom killed John by cutting him apart.)
Thomas Johannem deiecit.
(Tom brought John down with a mortal wound.)
Thomas Johannem percussit.
(Tom killed John by thrusting a weapon through him; suggests great force, enough to get through armor. Suitable for an arrow as well as a sword.)
Thomas Johannem peregit.
(Tom ran John through—thrust through, piercing, not implying great force.)
For anyone wanting more options, this blog post by Carla Hurt lists a total of 33 Latin verbs for "kill", with details about each. A common one is neco, the root of the English word "internecine", but neco suggests killing without a weapon.
Who killed whom
Indicating who killed whom works differently in Latin than in English. Latin indicates this not by word order but by the "case" of the nouns—exactly like "who" and "whom" in English, but Latin does this on nearly all nouns. The nominative case indicates the killer, and the accusative case indicates who was killed. If John killed Tom, then you say:
Johannes Thoman occidit.
I've added links to web pages that show all the cases of each name.
Unlike English, Latin lets you rearrange the words in any order without changing the meaning. The word order creates different emphasis, which we usually indicate in English with intonation or additional words:
Thoman Johannes occidit.
(Regarding Tom, John killed him.)
Thoman occidit Johannes.
(Regarding Tom, the one who killed him was John.)
Johannes occidit Thoman.
(John killed someone—Tom.)
Occidit Thoman Johannes.
(The one who killed Tom was John.)
Occidit Johannes Thoman.
(The one whom John killed was Tom.)
If you don't want to deal with noun cases, you can stick with the prosaic word order of "Killer killee verb", as in all the examples in the first section above. Latin has to resort to this word order when dealing with foreign surnames that have no case-endings in Latin.
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS - Pool Survey form
Hey guys I am trying to make something like this:
How it should look:
How it actualy looks:
CSS
h1{
font-size: 16px;
}
.bar{
width:170px;
background-color: #ccc;
border: 1px solid #ccc;
height: 17px;
margin-left: 15px;
}
.progress{
background-image: url("images/survey_bar.png");
background-repeat: repeat-x;
padding: 5px;
text-align: right;
height: 17px;
}
.label{
margin-bottom: 15px;
margin-left: 15px;
}
HTML
<div class="bar">
<div class="progress" style="width:75%;">65%</div>
</div>
<div class="label">Dominik !</div>
<div class="bar">
<div class="progress" style="width:20%;">20%</div>
</div>
<div class="label">Jenda</div>
<div class="bar">
<div class="progress" style="width:15%;">15%</div>
</div>
<div class="label">Lojza</div>
You see the difference, its in text color but mostly on position of that number of %
Can somebody help me to fix it? I try to padding/margin that text but just cant fix it.
A:
Colour can be solved just by adding color:#fff, not really a big issue.
As for the positioning, try adding line-height:17px (ie. matching your height). This will cause it the centre the text vertically on the bar.
| {
"pile_set_name": "StackExchange"
} |
Q:
Execute Python script from AutoIt
I have a Python (.py) file and need to execute it from AutoIt. How can I do this?
A:
Python scripts can be executed from command line. For a script called myscript.py, you can run it (assuming Python is installed) by typing:
python myscript.py
If you want to run myscript.py without having to prefix it by python, then set the path to the Python binary (e.g. C:\Python27\Python.exe) as Windows environment variable. This enables AutoIt to execute the Python script as if it were an external program. Reference: ShellExecute().
ShellExecute("myscript.py")
Point to where myscript.py resides of course. Use:
RunWait("C:\Python27\Python.exe myscript.py")
to avoid setting environment variables.
| {
"pile_set_name": "StackExchange"
} |
Q:
Tool for analyzing large Java heap dumps
I have a HotSpot JVM heap dump that I would like to analyze. The VM ran with -Xmx31g, and the heap dump file is 48 GB large.
I won't even try jhat, as it requires about five times the heap memory (that would be 240 GB in my case) and is awfully slow.
Eclipse MAT crashes with an ArrayIndexOutOfBoundsException after analyzing the heap dump for several hours.
What other tools are available for that task? A suite of command line tools would be best, consisting of one program that transforms the heap dump into efficient data structures for analysis, combined with several other tools that work on the pre-structured data.
A:
Normally, what I use is ParseHeapDump.sh included within Eclipse Memory Analyzer and described here, and I do that onto one our more beefed up servers (download and copy over the linux .zip distro, unzip there). The shell script needs less resources than parsing the heap from the GUI, plus you can run it on your beefy server with more resources (you can allocate more resources by adding something like -vmargs -Xmx40g -XX:-UseGCOverheadLimit to the end of the last line of the script.
For instance, the last line of that file might look like this after modification
./MemoryAnalyzer -consolelog -application org.eclipse.mat.api.parse "$@" -vmargs -Xmx40g -XX:-UseGCOverheadLimit
Run it like ./path/to/ParseHeapDump.sh ../today_heap_dump/jvm.hprof
After that succeeds, it creates a number of "index" files next to the .hprof file.
After creating the indices, I try to generate reports from that and scp those reports to my local machines and try to see if I can find the culprit just by that (not just the reports, not the indices). Here's a tutorial on creating the reports.
Example report:
./ParseHeapDump.sh ../today_heap_dump/jvm.hprof org.eclipse.mat.api:suspects
Other report options:
org.eclipse.mat.api:overview and org.eclipse.mat.api:top_components
If those reports are not enough and if I need some more digging (i.e. let's say via oql), I scp the indices as well as hprof file to my local machine, and then open the heap dump (with the indices in the same directory as the heap dump) with my Eclipse MAT GUI. From there, it does not need too much memory to run.
EDIT:
I just liked to add two notes :
As far as I know, only the generation of the indices is the memory intensive part of Eclipse MAT. After you have the indices, most of your processing from Eclipse MAT would not need that much memory.
Doing this on a shell script means I can do it on a headless server (and I normally do it on a headless server as well, because they're normally the most powerful ones). And if you have a server that can generate a heap dump of that size, chances are, you have another server out there that can process that much of a heap dump as well.
A:
The accepted answer to this related question should provide a good start for you (uses live jmap histograms instead of heap dumps):
Method for finding memory leak in large Java heap dumps
Most other heap analysers (I use IBM http://www.alphaworks.ibm.com/tech/heapanalyzer) require at least a percentage of RAM more than the heap if you're expecting a nice GUI tool.
Other than that, many developers use alternative approaches, like live stack analysis to get an idea of what's going on.
Although I must question why your heaps are so large? The effect on allocation and garbage collection must be massive. I'd bet a large percentage of what's in your heap should actually be stored in a database / a persistent cache etc etc.
A:
I suggest trying YourKit. It usually needs a little less memory than the heap dump size (it indexes it and uses that information to retrieve what you want)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I keep my Android notification displayed until my app is closed?
I've been developing for Android for awhile but this is my first shot at notifications. I've got my notification setup as described in the Android SDK tutorial, but I can't figure out how to keep the notification displayed until my app is closed. I want to disable that little minus sign at the end of the notification. I don't want my notification to disappear when a user clicks it. I would think there would be a notification flag... but I can't seem to figure this out. I'm developing on Android SDK 2.2. I know this is a simple question, and I apologize if this answer is already on here... I wasn't able to find exactly what I was looking for.
// Create notification manager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
Notification notification = new Notification(R.drawable.ic_launcher, "Ready", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// Make a notification
notification.setLatestEventInfo(getApplicationContext(), "Ready", "Select to manage your settings", contentIntent);
mNotificationManager.notify(0, notification);
A:
You want FLAG_ONGOING_EVENT. Also try removing FLAG_NO_CLEAR and FLAG_AUTO_CANCEL if they are part of the defaults.
| {
"pile_set_name": "StackExchange"
} |
Q:
when navigating to localhost:3000, navigate to localhost:3000/workers
When navigating to localhost:3000, I want to navigate to: localhost:3000/workers.
So I changed public/index.html to public/index.html.bak and in routes.rb, I defined the next followings:
devise_for :users do get '/users/sign_out' => 'devise/sessions#destroy' end
resources :tasksadmins
resources :workers
root to: "workers#index"
However, it doesn't work. The page localhost:3000 shows me the Welcome aboard page.
How can I fix it? Any help appreciated.
A:
Seems fine. Have you restarted the server?
| {
"pile_set_name": "StackExchange"
} |
Q:
Trigger the launch of another PHP file, but return right now
Is it possible to launch a task (some long processing) but return right now the page for the user in PHP?
index.php
<?php
...
// the page rendering is finished here, so don't make the user wait, return now
launch('do_some_10_seconds_long_processing.php')
?>
A:
Yup, shell_exec('php other.php >/dev/null 2>&1 &');
But you should use a proper worker queue instead, such as Gearman.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't edit text view after putting swipe gesture on it
I have a textview that when I swipe to the right it paste text into it. The only problem is I can not edit the text view. After I put the swipe gesture onto the textview it won't allow me to edit the text anymore. Once I take the gesture off it works again.
Does anybody know why this happens or how to fix it?
A:
When I dragged the swipe gesture onto my app, I dragged it onto the text view itself. By doing this it didn't allow me to edit my textview. When I drug the swipe gesture onto my view and not the textview it allowed me to swipe to paste in that textview while still being able to edit it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Layering text and images in Canvas HTML5
Hi am making a small HTML5 canvas demo.
I initiated the canvas using modernizer from O'Reilly's HTML5 text.
This is for iPad so my canvas is 1024 by 768.
I then load in a background image in my DrawScreen function.
var backgroundImage = new Image();
backgroundImage.src = "images/background.jpg";
backgroundImage.onload = function(){
context.drawImage(backgroundImage,0,0);
}
I want to add text to this then. So I do:
function drawText(){
context.fillStyle ="gray";
context.font = "28px Helvetica";
context.fillText(message, 260, 700);
}
I then call both functions:
DrawScreen();
DrawText();
However my background image totally over writes my text. Or is on top of it. If I disable DrawScreen(); I can see the text. Changing the function order doesn't make a differnce...
How to do this? I feel so stupid that am stuck on something that seems so elementary.
Thanks
A:
The problem is that your image is being drawn after -- and therefore on top of -- your text. This is because of the time it takes the image to load. Basically, what's happening is this:
You call your DrawScreen function
You start loading your background image by assigning the src attribute
You assign the onload() handler to fire once the image has finished loading.
DrawScreen exits, having completed all its work
You call DrawText, which immediately draws the text
At some point later, the image finishes loading, fires the onload() event, and you draw the background image.
I'd suggest restructuring your code so that all the drawing is kicked off by the successful loading of the image. That way, nothing asynchronous will be going on, and the image will be drawn, followed by the text.
Here's a quick example, on jsFiddle.
| {
"pile_set_name": "StackExchange"
} |
Q:
BDE inmem000.rem access/sharing violation
I have this proprietary web CGI executable which opens a connection to a BDE Thingy each time a page is requested.
I do know nothing of the workings of that compiled exe, nor of BDE, but I observed that during each page request BDE generates a temporary INMEM000.REM file.
The problem is that during heavy load on the server, page generation can last some time, during which it's impossible for any other user to request another page, as BDE tries to create/lock that same INMEM000.REM file.
I've found some info that the file has something to do with application sessions towards BDE.
But why does BDE perseveres on that same file ? Can't it be instructed to create multiple session lockfiles ? Or is it application dependent, and should it be encoded in the CGI part ?
Thanks in advance.
A:
Problem with old technology is, less people complain about.
The solution was simple, the folder wherein the INMEM000.REM file was generated had too restrictive access rights. BDE could only generate 1 lock/temp file, only god knows why.
Once the access rights were set loose, a distant child laughed, BDE screamed and soared and INMEM###.REM files filled the folder.
Joy fell upon the earth, and it was good.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL Server query with null value
In my C# code, I have to do an SQL Query like this :
context.ExecuteStoreQuery("SELECT * FROM MyTable WHERE Field0 = {0} AND
Field1 = {1}", field0, field1)
When field1 = null in c# and NULL in database this query doesn't work. (I have to use a different syntax with IS NULL)
How can I correct this without make an if (in reality, I have 10 fields...) ?
A:
By default, SQL server does not allow you to compare a value to null. All comparisons resolve to false, even those that are logically opposite. In other words, you can do:
where field = 1 and where field <> 1. If field is null, both logically resolve to false.
In any case, you need an explicit check for null in your query:
context.ExecuteStoreQuery(@"SELECT * FROM MyTable WHERE
(Field0 = {0} or (Field0 is null and {0} is null)) AND
(Field1 = {1} or (Field1 is null and {0} is null))", field0, field1)
| {
"pile_set_name": "StackExchange"
} |
Q:
'NoneType' object is not callable when calling a function written in C# from Python
I'm a newbie to Python and C#. I'm trying to make a dll in C# with two methods implemented as interface, and call them in python file after registering in COM.
namespace Sample
{
public interface interf
{
bool printHello(string name);
void printWorld();
}
public class A : interf
{
public bool printHello(string name)
{
Console.WriteLine(name);
return true;
}
public void printWorld()
{
Console.WriteLine("World!");
}
}
}
I'm calling these functions in python as:
import win32com.client
dllCall = win32com.client.Dispatch("Sample.A")
hello = dllCall.printHello("Hello")
dllCall.printWorld()
I'm getting the following error when I try to execute the python file.
Hello
Traceback (most recent call last):
File "C:\Temp\sampleTest.py", line 23, in <module>
World!
dllCall.printWorld()
TypeError: 'NoneType' object is not callable
What is that I'm missing?
A:
Finally I got it working.
If I call printWorld without brackets ().
dllCall.printWorld
| {
"pile_set_name": "StackExchange"
} |
Q:
Sorting DIVs inside other DIVs
Possible Duplicate:
How to sort divs according to their id using jQuery?
Well I'm having a really hard time trying to solve this and I actually had no sucess until now, I'm trying to sort DIVs inside Other DIVs by ID.
So here's how my DIVs are distribuited in my page
<div id="products" >
<div class="line">
<div id="Album2">[there are images and even other divs here in each Album]</div>
<div id="Album1"></div>
<div id="Album10"></div>
<div id="Album16"></div>
</div>
<div class="line">
<div id="Album9"></div>
<div id="Album3"></div>
<div id="Album4"></div>
<div id="Album7"></div>
</div>
<div class="line">
<div id="Album5"></div>
<div id="Album11"></div>
<div id="Album6"></div>
<div id="Album13"></div>
</div>
<div class="line">
<div id="Album8"></div>
<div id="Album14"></div>
<div id="Album12"></div>
<div id="Album15"></div>
</div>
</div>
and this should be my output:
<div id="products" >
<div class="line">
<div id="Album1"></div>
<div id="Album2"></div>
<div id="Album3"></div>
<div id="Album4"></div>
</div>
<div class="line">
<div id="Album5"></div>
<div id="Album6"></div>
<div id="Album7"></div>
<div id="Album8"></div>
</div>
<div class="line">
<div id="Album9"></div>
<div id="Album10"></div>
<div id="Album11"></div>
<div id="Album12"></div>
</div>
<div class="line">
<div id="Album13"></div>
<div id="Album14"></div>
<div id="Album15"></div>
<div id="Album16"></div>
</div>
</div>
But I have one more problem, all my products are listed and there are more than one page, I was actually able to track them and made a sorted Array of Strings but I didn't had the same luck doing it with the DIVs.
This is my page:
http://biscoitofino.jumpseller.com/catalogo
Any suggestions?
Thanks in advance.
A:
Something like this should do it, at least within the context of a single page:
var lines = $("#products .line");
var elems = $("#products .line div");
for (var index = 1; index <= elems.length; index++) {
var elemId = "Album" + index;
var containerIndex = parseInt((index - 1) / 4);
var container = lines[containerIndex];
var elem = document.getElementById(elemId);
elem.parentNode.removeChild(elem);
container.appendChild(elem);
}
Here's an example: http://jsfiddle.net/dpHyn/
Although I think the real answer is, since presumably you've got a server that's providing the list of albums dynamically already, why not just have the server sort the elements properly when it loads them from the database (or whatever other datasource you are using)? That would save you all this trouble, and work properly with pagination as well.
A:
var lines = $("#products > .line"),
albums = lines.children().toArray(),
line = -1;
albums.sort(function(a, b) {
return a.id.replace("Album", "") - b.id.replace("Album", "");
});
$.each(albums, function(i, el) {
if (!(i % lines.length))
line += 1;
lines.eq(line).append(el);
});
or without jquery
var lines = document.querySelectorAll("#products > .line"),
line = -1;
[].slice.call(document.querySelectorAll("#products > .line > div"))
.sort(function(a,b) {
return a.id.replace("Album", "") - b.id.replace("Album", "");
})
.forEach(function(el, i) {
if (!(i % lines.length))
line += 1;
lines[line].appendChild(el);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do these ImageButtons changing position using relative layout?
Learning some Android development through trial and error, however I'm having a slight issue with the rendering of buttons on top of an image view depending on the resolution of the phone.
I have an imageview with two imagebuttons (at the moment) on top. They are relative to the imageview. I will post the xml markup below. The issue is when I run this on the "Nexus 4" in Android studio, everything looks correct. When I debug through my Samsung Galaxy S4, the imagebuttons are off slightly, and I'm not sure why this would be a problem if everything is truly relative to the imageview. I understand that the resolutions are different, but how would one go about making sure that this renders the same on the smallest of screens, as well as the newer 1080p screens that are becoming more popular?
I can post pictures if need be, but I feel that the xml will provide adequate information on the issue.
Any help is appreciated. Thanks in advance!
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/SRMap"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="false"
android:background="@drawable/sr_map"
android:layout_columnSpan="2"
android:layout_rowSpan="1"
android:layout_column="0"
android:layout_row="0"
android:contentDescription="Map of Summoners Rift"
android:cropToPadding="false"
android:layout_marginBottom="177dp"/>
<ImageButton
android:layout_width="15dp"
android:layout_height="15dp"
android:id="@+id/BlueSideAlert_BlueBuff"
android:background="@drawable/blue_alert_circle"
android:layout_alignTop="@+id/SRMap"
android:layout_alignLeft="@+id/SRMap"
android:layout_marginLeft="90dp"
android:layout_marginTop="128dp"/>
<ImageButton
android:layout_width="15dp"
android:layout_height="15dp"
android:id="@+id/BlueSideAlert_RedBuff"
android:background="@drawable/blue_alert_circle"
android:layout_alignTop="@+id/SRMap"
android:layout_alignLeft="@+id/SRMap"
android:layout_marginLeft="180dp"
android:layout_marginTop="215dp"/>
A:
I handled this in a fairly ugly way, but it works across all screen sizes now. Basically say the primary image was 800x800 dp (the image view). The buttons would be smaller than this (20x20 dp), however through transparency, i created 800x800 dp imageviews (note: no longer buttons) with everything transparent but the "icon" (still 20x20 dp). Although slightly larger in terms of file size, it's negligible in my case. Now no matter what the size of the screen, the imageviews all stretch the same amount, thus removing any guesswork from using the different pixel densities.
I realize that this wasn't the most graceful solution, but I cannot see any drawback aside from making some of the layout development more difficult, and the image files are slightly larger. I used Paint.NET in order to create the .png's that I used.
I am creating an app that is relevant to me, and that I figured would be easy to implement using some of the core functionality already provided in android. My idea is a simple League of Legends Jungle Timer Application. This is important to know as I link the pictures so people can understand the context.
Note that both images are the same resolution, there is just no border on the second one.
http://i.stack.imgur.com/Ad3LZ.jpg
http://i.stack.imgur.com/NfhRM.png
Additional details:
For this app I have disabled the "landscape" orientation, I plan on doing this using some of the details that were provided on this page (layouts).
All of these icon ImageViews are relative to the map, which is the first link, so they will always resize correctly. There are 12 of them also, if it matters.
Thanks all for your help!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find out the number of possible ways of adding 1 2 and 3 to given sum avoiding repetition?
This problem is related to this and this one, but I want to put some restrictions here.
Repeat the question
So, I want to find out the number of possible ways to add 1, 2 and 3 to N. The solution can be calculated using recursive formula F[n] = F[n-1] + F[n-2] + F[n-3], where F[0] = 1, F[1] = 1, F[2] = 2. Of course, using dynamic programming I can solve it in linear time.
My restriction
The restriction is: the resulting sequence must have no two elements repeated in a row.
So, for N = 4 the result could be [[1, 1, 1, 1], [2, 1, 1], [1, 2, 1], [3, 1], [1, 1, 2], [2, 2], [1, 3]], but 1 1 1 1, 2 1 1, 1 1 2 and 2 2 is forbidden, so, applying the restriction F[4] becomes 3.
Can someone say how the recursive formula for this problem will look like? Or maybe someone has better idea?
I'm posting this problem here, because it's related to dynamic programming, not to math and combinatorics.
A:
Let F1, F2, F3 be the number of ways of constructing N from 1, 2 and 3, without starting with 1, 2, 3 respectively.
Then:
F1(N) = F2(N-2) + F3(N-3)
F2(N) = F1(N-1) + F3(N-3)
F3(N) = F1(N-1) + F2(N-2)
with the edge conditions:
F1(0) = F2(0) = F3(0) = 1
F1(x) = F2(x) = F3(x) = 0 (for x < 0)
Then to solve the original problem: F(0) = 1, F(N) = F1(N-1) + F2(N-2) + F3(N-3)
A linear-time solution that uses O(1) space:
def F(N):
a, b, c, d, e, f, g, h, i = 1, 0, 0, 1, 0, 0, 1, 0, 0
for _ in range(N-1):
a, b, c, d, e, f, g, h, i = e+i, a, b, a+i, d, e, a+e, g, h
return a+e+i
for n in range(11):
print(n, F(n))
This uses these recurrence relations:
F1(i+1), F1(i), F1(i-1) = F2(i-1)+F3(i-2), F1(i), F1(i-1)
F2(i+1), F2(i), F2(i-1) = F1(i)+F3(i-2), F2(i), F2(i-1)
F3(i+1), F3(i), F3(i-1) = F1(i)+F2(i-1), F3(i), F3(i-1)
This gives you a way to construct Fn(i+1), Fn(i), Fn(i-1) from Fn(i), Fn(i-1), Fn(i-2) in the same way that the usual linear-time Fibonacci algorithm works (constructing Fib(n+1), Fib(n) from Fib(n), Fib(n-1)). These recurrence relations are encoded in the line that updates the variables a to i.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to identify a section in an Evernote's note to update it later
I am making an App that automatically creates Notes into Evernote based on a Government API and I need to update these notes if this Government API change something.
But the thing is, Evernote uses a superset of XHTML called ENML and it doesn't allows me to use "id" or "data" attributes in any tag.
My question is how can I identify one tag or section in a Note that I've created to change/update it later.
A:
We had the same issue, so we wrapped the inner HTML with a traceable span like this:
<span style="x-your-business-name:section;">Here put the inner HTML content</span>
At this point it's just XHTML traversing and updating.
The span doesn't influence in any way the display of the Evernote note.
| {
"pile_set_name": "StackExchange"
} |
Q:
NewID() - Is there a high chance of exposing the previous/next GUIDs
I know GUIDs are theoritically unique with a very low chance of collision. However, if I understand properly some of that uniqueness is available because it's seeding from information on the computer used to generate it depending on the algorithm in use.
How likely is it that given a GUID a user could guess other GUIDs in the table?
As an example, if you have newsletter subscribers with a unsubscribe feature you could just have it post to example.com/subscriber/unsubscribe/{id}
With an integer identity this is obviously a bad idea. The user with ID 1000 can unsubscribe your entire database in seconds by guessing IDs.
If the ID column is a GUID initialized to a newid() how likely is it that your user could guess correct IDs if they know theirs?
A:
I'd say that it's probably possible in theory, but very, very unlikely to actually happen.
I've read Eric Lippert's blog posts that SLaks linked in his comment, and some other answers on Stack Overflow:
How to predict the next GUID from a given GUID?
How easily can you guess a GUID that might be generated?
As far as I understand it: given a set of a few GUIDs, it might be possible to find out if they were generated on the same machine. But it's not easy to find out, and certainly not for the average user.
Now I guess that given only one GUID (the newsletter subscription ID from the example), it will be very hard to guess any other GUID.
If (and only if) it's really possible, you probably need a fast machine and in-depth knowledge about the algorithms used to create GUIDs.
Finally, you have to look at the context:
Even if it is possible to guess GUIDs (and I'm not really sure that it is - I'm sure that I couldn't do it), I can't imagine that someone will really do this in order to unsubscribe other people from your newsletter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Strange problem with simple multithreading program in Java
I am just starting play with multithreading programming. I would like to my program show alternately character '-' and '+' but it doesn't. My task is to use synchronized keyword. As far I have:
class FunnyStringGenerator{
private char c;
public FunnyStringGenerator(){
c = '-';
}
public synchronized char next(){
if(c == '-'){
c = '+';
}
else{
c = '-';
}
return c;
}
}
class ThreadToGenerateStr implements Runnable{
FunnyStringGenerator gen;
public ThreadToGenerateStr(FunnyStringGenerator fsg){
gen = fsg;
}
@Override
public void run() {
for(int i = 0; i < 10; i++){
System.out.print(gen.next());
}
}
}
public class Main{
public static void main(String[] args) throws IOException {
FunnyStringGenerator FSG = new FunnyStringGenerator();
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 20; i++){
exec.execute(new ThreadToGenerateStr(FSG));
}
}
}
EDIT: I also testing Thread.sleep in run method instead for loop.
A:
Your synchronized block in FunnyStringGenerator.next() is working fine. It will return '+' and '-' alternately.
However you have a race condition in ThreadToGenerateStr.run():
System.out.print(gen.next());
This is equivalent to:
char c = gen.next(); // Synchronized
System.out.print(c); // Not synchronized
The problem occurs when:
Thread 1 calls gen.next(), getting a result of '-'
Thread 2 calls gen.next(), getting a result of '+'
Thread 2 calls System.out.print(), writing '+'
Thread 1 calls System.out.print(), writing '-'
The result is that the '+' and '-' are written in the opposite order.
There are various possible workarounds, e.g.:
Call both gen.next() and System.out.print() in a single synchronized block (as in dogbane's answer)
Make gen.next() write the character to the stream instead of returning it
Make gen.next() append the character to a shared BlockingQueue and have a dedicated I/O thread taking characters from this queue and printing them.
A:
Instead of synchronizing the method, do this:
synchronized (gen) {
System.out.print(gen.next());
}
You need to wrap the entire print statement in a synchronized block so that another thread cannot change the value of c before you print it.
Think of it as two statements:
char n = gen.next();
System.out.print(n);
| {
"pile_set_name": "StackExchange"
} |
Q:
assert function could not be resolved in eclipse c++
guys! I am trying to do some test functions using assertions:
test.h
#include <assert.h>
void testTheMedicine(){
Medicine m = Medicine(1, "para", 30, 40);
assert(m.getName()="para");// Function 'assert' could not be resolved
}
Why am I getting that error? I am using Eclipse for C++
A:
This is not how you compare Strings in C++.
Instead of the = operator, you should use ==:
m.getName()="para" should be m.getName() == "para"
| {
"pile_set_name": "StackExchange"
} |
Q:
git worktrees vs "clone --reference"
What are the pros-cons of using git worktrees vs maintaining multiple clones with --reference flag? The main scenario I am considering is when a developer needs to maintain multiple git repositories on the disk for old releases (release/1.0, release/2.0, release/3.0) because switching branches on a single git repo and rebuilding would be costly.
Using worktrees the developer could have a single clone of the repo, and any old releases could be created as worktrees of the repo using cd /opt/main/, git worktree add /opt/old_release_1 release/1.0. Using reference clones, the developer maintains a main clone somewhere, and uses cd /opt/old_release_1, git clone --reference /opt/main/.git ssh://[email protected]/myrepo.git to create clone repositories for the old releases.
It seems like they can both accomplish the same goal. Are there benefits to one over the other in terms of speed, disk space... other things?
A:
They all have a few issues that matter, but using git worktree is probably going to be your best bet.
A clone, let's call this AD for after-dependency clone, made with --reference local-path but without --dissociate uses objects from local-path. By "objects", I mean literal Git objects (stored loosely and/or in pack files). The other Git repository—the one in local-path—has no idea that AD is using these.
Let's call the base clone BC. Now, suppose something happens in BC so that an object is no longer needed, such as deleting a branch name or a remote-tracking name. At this point, a git gc run in BC may garbage-collect and delete the object.
If you now switch to the AD clone and run various Git operations, they may fail due to the removed object. The problem is that the older BC clone has no idea that the newer AD clone depends on it.
Note that AD has, embedded in it, the path name of BC. If you move BC you must edit the .git/objects/info/alternates file in AD.
A work-tree made with git worktree add also uses objects from the original clone. Let's still call the original clone BC, with the added work-trees just called Wb. There are two key differences from the BC/AD setup above:
Each new work-tree Wb literally uses the entire .git directory from BC.
The BC repository records the path of each Wb, so it knows about each Wb. You won't have the problem of objects disappearing unexpectedly.
However, since BC records each Wb and all the branch names actually live inside BC itself, there's a constraint imposed: whatever branch is checked out in BC cannot be checked out in any Wb. Moreover, Wb1 must be "on" (as in git status says on branch ...) a different branch than Wb2, and so on. (You can be in "detached HEAD" mode, i.e., not on any branch at all, in any or all of BC and each Wb.)
Since BC records each Wb path (and vice versa), if you want to move any of these repositories, you must adjust the paths.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to paste character string based on 'this' condition in r?
I have this data frame df
df
col1 col2
Engraulis encrasicolus Engraulis encrasicolus
Sardina pilchardus Sardina pilchardus
Scomber spp Scomber
Spicara Spicara
class(df)
"factor"
I would like paste letters 'spp' in col2 every time that is present in col1
for example:
col1 col2
Engraulis encrasicolus Engraulis encrasicolus
Sardina pilchardus Sardina pilchardus
Scomber spp Scomber spp
Spicara Spicara
I tried with:
df.res <- ifelse(df$col1 %like% "spp"==T,
paste("spp",collapse=NULL) %in% df$col2,df$col1)
but the result is a similar data frame df with character string and value logic FALSE:
df.res
"Engraulis encrasicolus"
"Sardina pilchardus"
"FALSE"
"Spicara"
A:
Using Base R:
df.res <- ifelse(grepl("spp", df$col1),
paste0(df$col2, " spp"), df$col2)
Or as an additional column in the original data frame:
df$col3 <- ifelse(grepl("spp", df$col1),
paste0(df$col2, " spp"), df$col2)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use regular expression in java manifest classpath?
I need to make use of additional jars during the execution of the program. I manually add the jars to the relative ./lib folder and then execute the program. How should I define the classpath in the manifest file?
A:
You can't use regular expressions or other wildcards in the Class-Path attribute of your manifest.
There is only one supported wildcard in Java, and that only works on if specified on the commandline on a "manual" java invocation (i.e. not using -jar): using directoryname/*.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I notify candidate about the fragile state of my company?
I'm running a small IT startup (private firm), funded from my own pocket. We are working on a development project, which is not yet generating income. So far I've hired 3 employees with a 1-year contract. This was the "budget" I was willing to commit to. Current progress is OK but could be better.
Now, I've received an open application from a young, but promising candidate. (Based on CV). I have the feeling his skills can speed things up. Hiring him would also imply increasing my risk, so he better be good.
Basically, I'm interested in a conversation but I'm not sure if I'm willing to hire altogether. Also, I feel responsible for my employees. This person seems to be leaving a job with a career possibility behind for something riskier. (Unlike the current employees)
Should I inform the candidate about this situation? Perhaps before the interview, to manage expectations?
Edit
Current employees are aware of the company's state. They joined at the beginning of this production and are also involved in design decisions. This is more about the "new" candidate, which seems to be very motivated to join my company (at least on paper). I wonder if he's aware what he's getting into and at which stage I should ask/tell him.
A:
Should I inform the candidate about this situation? Perhaps before the
interview, to manage expectations?
Yes.
You'll find the best employees if they join your company knowing what's ahead. They will decide if this is the kind of company they want to work for - with all the unknowns that entails.
The worst case would be to hire someone who doesn't know what they are getting themselves into, and who decides to leave early. That wastes their time and yours.
It's something I'd discuss early on, probably in the first interview, since it's likely to be an important decision point. And if you aren't even sure you want to hire anyone, I'd mention it before that - so that the candidate could decide if the talk is worthwhile or not.
As with your current employees, you want to potentially hire someone who comes in with eyes wide open and eager for the challenge. Not someone who will be surprised and leave.
When I was hired as employee number eight in a startup, I was told all the details behind the company's hiring plans, financial situation, funding sources, and vision for the future. I had to leave a good job and take a 15% pay cut as well. I appreciated the transparency, since it helped me make a well-informed decision. I felt that the founders were being open and honest with me, and that goes a long way with me.
A:
Yes, I think it will in best interest for the company, candidate and yourself if the candidate knows the truth about current state of the company before joining as he is risking a lot by leaving other options.
Sooner or later the candidate might find it from you or others and when they do it might be worse than him not joining initially.
But this shouldn't be disclosed before the interview but after the interview if you wish to hire them.
A:
I'm always in favor of transparency and honesty. Tell him the truth, and let him make an informed decision to take the risk or not. If he doesn't, you've lost nothing. If he does, you've gained a motivated employee who understands the situation.
Now take it the other way. If you don't tell him, and he finds out- he may quit immediately, which means you've invested time in him that won't bear fruit. He may quit as soon as he gets another offer, same result. He may stay there but be demotivated, reducing his output and possibly poisoning the culture. He may tell others about how he was tricked, causing you a bad reputation in the area. There's really no positive outcome to not telling.
| {
"pile_set_name": "StackExchange"
} |
Q:
SystemVerilog constraint for mapping between two 2D arrays
There are two MxN 2D arrays:
rand bit [M-1:0] src [N-1:0];
rand bit [M-1:0] dst [N-1:0];
Both of them will be randomized separately so that they both have P number of 1'b1 in them and rest are 1'b0.
A third MxN array of integers named 'map' establishes a one to one mapping between the two arrays 'src' and 'dst'.
rand int [M-1:0] map [N-1:0];
Need a constraint for 'map' such that after randomization, for each element of src[i][j] where src[i][j] == 1'b1, map[i][j] == M*k+l when dst[k][l] == 1. The k and l must be unique for each non-zero element of map.
To give an example:
Let M = 3 and N = 2.
Let src be
[1 0 1
0 1 0]
Let dst be
[0 1 1
1 0 0]
Then one possible randomization of 'map' will be:
[3 0 1
0 2 0]
In the above map:
3 indicates pointing from src[0,0] to dst[1,0] (3 = 1*M+0)
1 indicates pointing from src[0,2] to dst[0,1] (1 = 0*M+1)
2 indicates pointing from src[1,1] to dst[0,2] (2 = 0*M+2)
A:
This is very difficult to express as a SystemVerilog constraint because
there is no way to conditionally select elements of an array to be unique
You cannot have random variables as part of index expression to an array element.
Since you are randomizing src and dst separately, it might be easier to compute the pointers and then randomly choose the pointers to fill in the map.
module top;
parameter M=3,N=4,P=4;
bit [M-1:0] src [N];
bit [M-1:0] dst [N];
int map [N][M];
int pointers[$];
initial begin
assert( randomize(src) with {src.sum() with ($countones(item)) == P;} );
assert( randomize(dst) with {dst.sum() with ($countones(item)) == P;} );
foreach(dst[K,L]) if (dst[K][L]) pointers.push_back(K*M+L);
pointers.shuffle();
foreach(map[I,J]) map[I][J] = pointers.pop_back();
$displayb("%p\n%p",src,dst);
$display("%p",map);
end
endmodule
| {
"pile_set_name": "StackExchange"
} |
Q:
Unified Authentication between Windows AD and Linux LDAP Server
Does anyone know of a solution that would allow me to do user account synchronization between Windows Active Directory and an LDAP Server hosted on a Linux Server? I'm currently looking at FreeIPA (www.freeIPA.org) and 389DS (http://directory.fedoraproject.org).
I'm looking to do account synchronization because the AD server is being deployed at our HQ which is not hardened (no generator backing and only 1 internet connection) whereas the Linux LDAP server is being deployed into a hardened datacenter. All the machines in the datacenter are Linux based and 90% of the machines at HQ are Windows. I understand that 389DS and FreeIPA have the synchronization for users, but they require a separate program to be installed to do the passwords as well. I was curious if anyone knew how to get a Kerberos slave in Linux to be mated to the Linux LDAP server for password auth and receive its updates from the Windows server, so that no extra applications would need to be installed, and so that if the AD server goes down the Linux hosts will still be able to authenticate against the Linux LDAP server.
About 50% of our users are solely Windows based, 45% of our users deal with both Windows and Linux, and the last 5% use Apple solely, and I'm currently trying to get a system that will allow a user to only know 1 username and password to log into all of our systems.
A:
If you really want to do this correctly you should deploy a domain controller in your datacenter and have your Linux systems authenticate against it (add the POSIX extensions to AD, and extend each AD account that needs Unix access to be a POSIXAccount).
Trying to make AD subservient to another authentication/authorization store is exceedingly difficult and failure prone. In contrast Unix systems are usually able to authenticate against AD (by treating it as plain vanilla LDAP) without too much effort.
Taking this route has a number of benefits - among them you have a secondary AD domain controller (at the datacenter, on battery/UPS), and you get a working single authentication store..
A:
There is more to Active Directory than just a bunch of LDAP objects and attributes. Some of the interop protocols are proprietary, many security-sensitive attributes and APIs are locked, are not extensible by any kind of hooks and can only be called by trusted code. Using a different GINA to handle password updates is what is commonly done (tm) in the Windows world if you have any secondary directory to write your password change to.
You might want to look into Novell's eDirectory / NDS and the SSO featureset - it has been pretty much designed with heterogeneous Linux/Windows envoronments in mind.
| {
"pile_set_name": "StackExchange"
} |
Q:
System.NullPointerException: Attempt to de-reference a null object
this error is occurring ??
Here is my code.Where i mistook ?
public PageReference find()
{
for(Account c : [SELECT BillingCountry, Industry, (SELECT Id, Name,Amount , StageName FROM Opportunities) FROM Account WHERE BillingCountry = 'USA'])
{
ResultWrapper result = new ResultWrapper(c,c.Opportunities);
lstResultWrapper.add(result);
system.debug('=============lstResultWrapper================='+lstResultWrapper);
}
return null;
}
public class ResultWrapper{
public Account account {get;set;}
public Opportunity opportunity {get;set;}
public ResultWrapper(Account acc,Opportunity opt)
{
this.account = acc;
this.opportunity = opt;
}
}
Thanks in Advance
A:
Seems you have a type mismatch
c.Opportunities is of type List<Opportunity>, but your constructor uses just one opportunity: public ResultWrapper(Account acc,Opportunity opt)
Also, add lstResultWrapper = new List() before your loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way for my ISP or LAN admin to learn my Gmail address as a result of me logging into Gmail's web interface through via their network?
The title says it all, really. I'm Alice, and I want to login to Gmail's web interface through my browser. Ike, the internet service provider, and Adam, the local network administrator, would like to know what my Gmail email address (username) is. Is there any conceivable way for things to happen so that either one of them could possibly learn it?
A:
For your average home user, services like GMail (that are run over TLS) would not leak information like the username to the ISP or network administrator.
If you're using a machine that is also administered by the LAN administrator (e.g., a work computer attached to a domain run by the company), then you have to assume they can read anything you do on it. They could have software to log your activity (browsing and/or keystrokes), they could have installed extra SSL certificates that allow them to MITM your connection to GMail (or any other site).
If you believe your computer has not been tampered with and is not under the control of someone you don't trust (i.e., the LAN admin doesn't control your machine), then you can connect to GMail over https. (At this point, the LAN admin is equivalent to an attacker on the internet.) Ensure that you connect to https://mail.google.com with a valid certificate, and then all your traffic between your computer and the GMail servers are encrypted. This would include all information about your account, including the username with which you are logged in.
A:
To complement @David's and @Steve's answers:
If the attacker ("Adam", in your case) has administrative access to your machine, then he can learn all your secrets. Installing an extra root CA, under his control, to run routine MitM interception on your SSL connections is a popular tools for honest (but nosy) sysadmins: it is a one-time installation which won't be jeopardized by software updates, and won't incur compatibility issues with other software such as antivirus. However, a nosier sysadmin who wants his spying to remain discreet has a lot of other options, such as installing keyloggers, screen capture tools, and generally plundering the data right from the RAM of the machine.
If the attacker does not have access to your machine's innards, then he should be kept out of your SSL exchanges. He will still be able to notice when you connect to Gmail, and can observe the exact size of the data elements exchanged with Gmail. He can probably work out the length (in characters) of your Gmail address.
As @Steve observes, a Gmail address is not designed to be a secret, and will leak in many places. In any case, as an email address, it is necessarily shared with other people (those who send emails to you), and therefore cannot be considered truly secret.
If you use Google+ (indexed by your email address), the evil sysadmin will notice your activity, and may correlate it with visible activity on some candidate Google+ accounts. After all, if he is after you, then he is interested in you, and may as well show some dedication and track you competently.
A:
As David says, the provider of your network usually can't see data passed over https connections.
However, your Gmail address is not necessarily passed only over https connections. For example, if you log into StackExchange using your secret Gmail account and visit the http (not https) version of your user profile page, then your Gmail address is sent to you unsecured in the contents of that page. The provider of your network connection could then see it. The same may be true of other sites that use https for OAuth login but not for all traffic.
Also, as user49372 points out, if Adam is willing to mount an active man-in-the-middle attack, and if you log into StackExchange using your secret Gmail address, he could inject stuff into your normal http traffic that would redirect your browser to the http version of your StackExchange profile page.
So yes, there are conceivable ways Adam or Ike could learn it even assuming that they can't interfere with your machine or otherwise overcome the security provided by https.
| {
"pile_set_name": "StackExchange"
} |
Q:
Make this code pylint correct
def scanDevices(self):
""" Start 2 threads, one for scanning devices and other for displaying device list on UI
"""
self.counter = self.counter + 1
deviceListChangedEvent = threading.Event()
threadToScanDevices = threading.Thread(target=test_ssdp.main, args=(self.getHostIP(), self.counter, deviceListChangedEvent,))
threadToScanDevices.setDaemon(True)
threadToScanDevices.start()
threadToDisplayDevices = threading.Thread(target=self.displayDevices, args=(deviceListChangedEvent,))
threadToDisplayDevices.setDaemon(True)
threadToDisplayDevices.start()
self.scan.setEnabled(False)
self.cw.btnPushProfile.setEnabled(False)
How to make this code pylint correct ?
error - line too long
A:
You can make the line shorter by splitting it over multiple lines, using Python's implicit line continuation inside parentheses/brackets/braces:
threadToScanDevices = threading.Thread(target=test_ssdp.main,
args=(self.getHostIP(),
self.counter,
deviceListChangedEvent,))
(Note the use of alignment to make it clear which sub-lines belong together).
Alternatively, split the line into more than one statement:
args = self.getHostIP(), self.counter, deviceListChangedEvent
threadToScanDevices = threading.Thread(target=test_ssdp.main, args=args)
You should limit to 79 characters per PEP-0008:
Maximum line length
Limit all lines to a maximum of 79 characters.
For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
Limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.
| {
"pile_set_name": "StackExchange"
} |
Q:
Store and Use Regex Const Validator in Angular 8 Reactive Formbuilder
How do I store a Regex Validator pattern for reuse and Dry principal in Angular?
Have a reactive formbuilder with Regex validator pattern below for ZipCode.
Need to apply to multiple address forms, curious how to save /^\d{1,5}$/
So we can write Validators.pattern(zipcode), or any syntax utilized in Angular?
Company has more complicated long patterns for phone numbers, customer number, etc.
'ZipCode': [null, [Validators.maxLength(16), Validators.pattern(/^\d{1,5}$/)]],
Looking for a way to store and utilize maybe in constants.
This is for Angular 2:
ng-pattern to use regex from angular constants
A:
You can store your validations in some .ts files, suppose validations.ts.
Then use these validations wherever required. You can also have parameter Validators.
validation.ts
export const ZipValidation = Validators.pattern(/^\d{1,5}$/);
export const EmailValidation = Validators.pattern(/*some regex*/);
export const UsernameValidation = Validators.pattern(/*some regex*/);
export const ValidWithParam = (param: number) => {
return Validators.pattern('/\d' + param + '/g');
}
In Component
import { ZipValidation, EmailValidation, UsernameValidation } from './validation';
'ZipCode': [null, [Validators.maxLength(16), ZipValidation]],
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use bootstrap date picker to get correct date format on your application?
I have a small problem i am using Boostrap DatePicker, the problem is the format of the date on input-daterange. eg. 01/08/2020. It should read the following format and to be understood by the user well. e.g 09/01/2020. Below is my logic for using Bootstrap DatePicker, i am open to better approach to use date from start to end date.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker3.min.css">
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.min.js"></script>
<!---DatePicker for startDate and endDate.
---->
<div class="d-flex justify-content-start">
<div class = "col-xl-10.5 col-lg-10.5 col-md-10 col-sm-10.5 col-10.5">
<div class="input-daterange input-group" id="datepicker">
<input type="text" class="input-sm form-control" name="from" placeholder="startdate"/>
<span class="input-group-addon">To</span>
<input type="text" class= "input-sm form-control" placeholder="enddate"/>
</div>
</div>
</div><br>
// date functionality
$(document).ready(function() {
var year = (new Date).getFullYear();
$('.input-daterange').datepicker({
dateFormat: "dd-mm-yy",
autoclose:true,
minDate: new Date(year, 0, 1),
maxDate:new Date(year, 11, 31)
});
});
A:
You can achieve this by using format option instead of dateFormat
$(document).ready(function() {
var year = (new Date).getFullYear();
$('.input-daterange').datepicker({
format: "dd-mm-yy",
autoclose:true,
minDate: new Date(year, 0, 1),
maxDate:new Date(year, 11, 31)
});
});
$(document).ready(function() {
var year = (new Date).getFullYear();
$('.input-daterange').datepicker({
format: "dd-mm-yyyy",
autoclose:true,
minDate: new Date(year, 0, 1),
maxDate:new Date(year, 11, 31)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker3.min.css">
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.min.js"></script>
<!---DatePicker for startDate and endDate.
---->
<div class="d-flex justify-content-start">
<div class = "col-xl-10.5 col-lg-10.5 col-md-10 col-sm-10.5 col-10.5">
<div class="input-daterange input-group" id="datepicker">
<input type="text" class="input-sm form-control" name="from" placeholder="startdate"/>
<span class="input-group-addon">To</span>
<input type="text" class= "input-sm form-control" placeholder="enddate"/>
</div>
</div>
</div><br>
Hope this Helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding normal mapping
I am trying to understand the basics of normal mapping using this tutorial : http://ogldev.atspace.co.uk/www/tutorial26/tutorial26.html
What I don't get there is the following equation :
E1 = ( U1 - U0 ) * T + ( V1 - V0 ) * B
How do they came to this equation? This it out of nowhere for me. What is E1?
The tutorial say that E1 is one edge of the triangle. But I don't get it, in the equation E1 seems to be a real number, not a vector ( which an edge is supposed to be right? he have a x and y component ).
A:
You have 3 points, P01, P1 and P2. (Look at the figure right above the equation.) The points create a triangle. This triangle lies on a plane and on this plane are the two vectors T and B. (Tangent and Bitangent) These vectors are more or less random, optimally they are at a right angle, but this may not be the case, the only requirement is that they are not the same.
With all this you can define the edges (E1 and E2) in respect to T and B.
P0 = (U0, V0)
P1 = (U1, V1)
P3 = (U2, V2)
E1 = (U1 - U0) * T + (V1 - V0) * B
E2 = (U0 - U2) * T + (V0 - V2) * B
Going from there:
Now since you know T and B in world space (and the normal N), you can construct the matrix TBN that will convert the normal from tangent space (as in the normal map) into world space (as required from lighting). The following equations basically outline the mathematical principles based on TB matrix. (The normal N is added later to also account for Z value of the normal.)
For arbitrary meshes the tangent and bitangent are vectors along the surface of the mesh. These need to be computed during construction/loading of the mesh. (You can skip the bitangent if you allow to simply do B = T x N)
| {
"pile_set_name": "StackExchange"
} |
Q:
Did any manufacturer ever try using more, but lighter spokes to minimize weight?
Wheels generally used to have more spokes.
As technology improved and markets changed, manufacturers have taken to making wheels with fewer (and often heavier spokes). I've been told this comes at the expense of having a slightly heavier rim to maintain strength and stiffness.
I realize that aerodynamics generally has more impact on performance than shaving a few grams, but I was wondering if any manufacturer ever tried making wheels with more, but finer spokes, perhaps to save on rim weight rather than spoke weight. Was this ever done?
A:
To the best of my knowledge, and my ability to find reference in any old catalog or tech manual, no, that concept has not been tried on a commercial scale at least. It may have been tried on a local scale.
I don't have the math to prove it, but I suspect the balance point between how thin the spokes would need to be to reduce the weight enough to offset the additional weight of more spokes, and the tensile strength those spokes would require to maintain the strength of the wheel without breaking would prevent any weight benefit from being gained, and I know that spokes thinner than 1.8mm have a far greater likelihood of breakage. The butted 2.0/1.5mm spokes which were popular in the late 90's for XC racing wheels proved that to me.
Perhaps we could get the Math or engineering SE guys to comment here?
| {
"pile_set_name": "StackExchange"
} |
Q:
Did Samuel Clemens ever get his watch back?
In Star Trek: The Next Generation episode(s) Time's Arrow we learn of time travel shenanigans happening on earth in the 1800s through various artifacts discovered in an abandoned mine. One of these was a watch. We learn later that it's Samuel Clemens' watch when he winds up in the 24th century. However, when he gets back to the past he sees his watch in the mine and picks it up, thinks about it and puts it back.
Did he already get back his watch when he was in the future, or did he go on watch-less?
A:
The implication is that the watch, which would have contained steel parts and that had been left for centuries in an unsealed cave, was rusted or decayed beyond reasonable repair and Clemens simply left it to be disposed of or kept as a curio by the crew.
Clemens notices something on a nearby table... picks up the watch from the cavern.
CLEMENS: My watch...
GEORDI: It was found in the cavern... near Data's head.
(beat)
After five hundred years, I doubt that it'll work either.
Clemens puts the watch back and regards the lifeless android sadly.
CLEMENS: Mister Data... I fear I sadly misjudged you.
(beat)
As I have misjudged many things.
Times Arrow, Part II - Original Screenplay
In real life, Clemens (Twain) is known to have owned multiple pocket-watches. There are several numbered among his stored personal effects on display at the Mark Twain Museum and at least two are on current display.
It might also interest you to learn that he gave his name to a shady pocket-watch mail order company that marketed a patented "Mark Twain" watch (that stopped regularly and failed to keep correct time). After the failure of this pyramid scheme, he was utterly scathing about watchmakers as a profession.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to read a file as a bytestring in a scala?
I want to make TCP-IO in scala. And the data type will be bytestring.
Then, I want to read a file as a bytestring type in a scala, intellij, akka 2.3.14.
A:
Assuming you're talking about akka.util.ByteString you could make 1 ByteString for the entire file:
import akka.util.ByteString
import scala.io.Source
def fileToByteStr(filename : String) : ByteString =
ByteString(Source.fromFile(filename).mkString)
Or, if you want 1 ByteString for each line in your file which lazily remains "on the plate" until the Iterator is drained:
def fileToMultipleByteStr(filename : String) : Iterator[ByteString] =
Source.fromFile(filename)
.getLines()
.map(ByteString.apply)
If you want the data in memory you can drain the Iterator to a Seq:
val memoryHog = fileToMultipleByteStr("foo.txt").toSeq
| {
"pile_set_name": "StackExchange"
} |
Q:
Printing name and value of a macro
I have a C program with a lot of optimizations that can be enabled or disabled with #defines. When I run my program, I would like to know what macros have been defined at compile time.
So I am trying to write a macro function to print the actual value of a macro. Something like this:
SHOW_DEFINE(X){\
if( IS_DEFINED(X) )\
printf("%s is defined and as the value %d\n", #X, (int)X);\
else\
printf("%s is not defined\n", #X);\
}
However I don't know how to make it work and I suspect it is not possible, does anyone has an idea of how to do it?
(Note that this must compile even when the macro is not defined!)
A:
As long as you are willing to put up with the fact that SOMESTRING=SOMESTRING indicates that SOMESTRING has not been defined (view it as the token has not been redefined!?!), then the following should do:
#include <stdio.h>
#define STR(x) #x
#define SHOW_DEFINE(x) printf("%s=%s\n", #x, STR(x))
#define CHARLIE -6
#define FRED 1
#define HARRY FRED
#define NORBERT ON_HOLIDAY
#define WALLY
int main()
{
SHOW_DEFINE(BERT);
SHOW_DEFINE(CHARLIE);
SHOW_DEFINE(FRED);
SHOW_DEFINE(HARRY);
SHOW_DEFINE(NORBERT);
SHOW_DEFINE(WALLY);
return 0;
}
The output is:
BERT=BERT
CHARLIE=-6
FRED=1
HARRY=1
NORBERT=ON_HOLIDAY
WALLY=
A:
Writing a MACRO that expands to another MACRO would require the preprocessor to run twice on it.
That is not done.
You could write a simple file,
// File check-defines.c
int printCompileTimeDefines()
{
#ifdef DEF1
printf ("defined : DEF1\n");
#else // DEF1
printf ("undefined: DEF1\n");
#endif // DEF1
// and so on...
}
Use the same Compile Time define lines on this file as with the other files.
Call the function sometime at the start.
If you have the #DEFINE lines inside a source file rather than the Makefile,
Move them to another Header file and include that header across all source files,
including this check-defines.c.
Hopefully, you have the same set of defines allowed across all your source files.
Otherwise, it would be prudent to recheck the strategy of your defines.
To automate generation of this function,
you could use the M4 macro language (or even an AWK script actually).
M4 becomes your pre-pre-processor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can we simulate real time traffic on e-commerce application thru jmeter with users drop at each steps
Eg : Let say we have following rest API steps in my flow:
1. Login
2. Addtocart
3. Increment item qty
4. Applying voucher in cart
5. Updating shipping address
6. Placing order.
Now in above flow, let say I want to start with 300 concurrent users and at every step I want 5-10% users drop like:
1. Login - 300 users will do
2. Addtocart - 270 users will do
3. Increment item quantity : 243 users will do
.
.
.
And so on
A:
Create multiple thread groups. For example:
Thread group 1- Login
-Login Request
Thread group 2- Addtocart
-Addtocart Request
Thread group 3- item quantity
-item quantity Request
Now you can set manually the number of threads for each thread group. Set it manually as 300,270 and 243 and corresponding ramp up time.
Only thing you need to be taken care is passing the cookie from login thread group to the other two thread group.
For this Add a beanshell postprocessor as a child of login request and add the following code
props.put("yourcookiename1","${COOKIE_yourcookiename1}");
props.put("yourcookiename2","${COOKIE_yourcookiename2}");
props.put("yourcookiename3","${COOKIE_yourcookiename3}");
Now add a Beanshell PostProcessor as a child of addtokart request and increment qualtity request and add the following code:
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
CookieManager manager = sampler.getCookieManager();
Cookie cookie = new Cookie("yourcookiename1",props.get("yourcookiename1"),"abc.com","/",false,0);
manager.add(cookie);
Cookie cookie1 = new Cookie("yourcookiename2",props.get("yourcookiename2"),"abc.com","/",false,0);
manager.add(cookie1);
Cookie cookie2 = new Cookie("yourcookiename3",props.get("yourcookiename3"),"abc.com","/",false,0);
manager.add(cookie2);
This will pass cookie to your 2nd and 3rd request which is under different thread groups.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bent molecular geometry of water
Could you please explain how the bent molecular geometry of water is due to hydrogen bonding? I was under the impression that it was because of the lone pairs (VSEPR Theory).
A:
Your understanding is correct. The usual explanation given in introductory classes is VESPR theory. The oxygen atom has four bond-like "things" coming out of it. Two of those are the covalent bonds with the hydrogen bonds. The other two are the two lone pairs. VESPR theory calls this a steric number of four.
The slightly more advanced explanation comes from molecular orbital theory. Oxygen's valence electrons are all $2\text{p}$ electrons; hydrogen's electron is $1\text{s}$. The only way to mix those orbitals to get enough bonding orbitals is by using two $\text{sp}^3$ hybrid orbitals to generate the two bonds. The $\text{sp}^3$ orbitals are arranged in a tetragonal geometry.
| {
"pile_set_name": "StackExchange"
} |
Q:
Beginner Objective-C, references to memory and pointers
So this is an exercise in a book I am learning from. I got the exercise working fine, and I understand most of it, except, and, I don't know if I am completely missing something here but...
How in the world does the compiler know that:
x = 168.354 and y = 987.259 belong to (XYPoint) pt*
and that
x = 10.00 and y = 10.00 belong to (XYPoint) t*
I understand how myPoint and myTranslate are separate objects in the XYPoint class and whatnot, and that they point to memory references where X and Y are stored, but how does it assign the above values to pt and t. Am I missing something huge here?
Thanks in advance.
Here's the code:
Interface
#import "XYPoint.h"
#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
@property float width, height;
-(XYPoint*) origin;
-(void) translate: (XYPoint *)t;
-(void) setOrigin: (XYPoint *) pt;
-(float) area;
-(float) perimiter;
-(void) setHeight:(float) h andWidth: (float) w;
@end
Implementation
#import "Rectangle.h"
#import "XYPoint.h"
@implementation Rectangle
{
XYPoint *origin ;
}
@synthesize height, width;
-(void) setHeight: (float) h andWidth: (float) w;
{
width = w;
height = h;
}
-(void) setOrigin:(XYPoint *)pt
{
if (! origin)
origin = [[XYPoint alloc]init];
origin.x = pt.x;
origin.y = pt.y;
}
-(void) translate: (XYPoint*)t
{
origin.x = origin.x + t.x;
origin.y = origin.y + t.y;
}
-(float) area
{
return width * height;
}
-(float) perimiter
{
return (width + height) * 2;
}
-(XYPoint *) origin
{
return origin;
}
@end
Main
#import "XYPoint.h"
#import "rectangle.h"
#import "Square.h"
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
Rectangle *myRect = [[Rectangle alloc]init];
XYPoint *myPoint = [[XYPoint alloc]init];
XYPoint *myTranslate = [[XYPoint alloc] init];
[myPoint setX: 168.354 andY: 987.259];
[myTranslate setX: 10.00 andY: 10.00 ];
myRect.origin = myPoint;
NSLog (@"Origin at %f, %f", myRect.origin.x, myRect.origin.y);
[myRect translate: myTranslate];
NSLog (@"Origin at %f, %f", myRect.origin.x, myRect.origin.y);
}
return 0;
}
Output:
Origin at 168.354004, 987.258972
Translated to 178.354004, 997.258972
A:
t and pt are not being assigned here, they are parameters to the functions setOrigin: and translate:.
they are the variables doing the assigning in the functions and not the other way round. they are used to update your origin XYPoint.
you dont seem to have a function that maps to this code here (well that i can see)
[myPoint setX: 168.354 andY: 987.259];
so im not sure if that function would call setOrigin: or translate: but that would 'assign' t and pt (as in they are arguments to your functions)
or regardless of that, you could set pt for example by just calling
[myPoint setOrigin:someOtherXYPointObject]; // someOtherXYPointObject here IS pt in this case
not sure if this answers your question
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible names for a process Linux?
I am trying to write a script in which I read from /proc/.../stat. One of the values in the space separated list is the name of the process, which does not interest me for the time being. I would like to read some other value after it. My idea was to move forward a certain number of values using spaces as the separator. A potential problem with this though is that I could have /proc/.../stat containing something like 1234 (asdf asdf) S .... The space in the process name would cause the program to read asdf) instead of S as intended.
So my question is can the process name have spaces in it? If so how could I differentiate between the values in /proc/.../stat?
A:
I, personally, hate the way this file is laid out for precisely the reason you stated. With that said, it is possible to parse it uniquely no matter what the process name is. This is important, because not only the process name may contain spaces, it may also contain the close bracket character.
The method I suggest is to manually parse out the process name, and use space delimiting for everything else.
The process name should be defined as starting at the first open-bracket character on the line and ending at the last close bracket on the line. Since the other fields on the line don't have user-controlled format, this should reliably single the process name out, no matter what weird ways the proces is named.
| {
"pile_set_name": "StackExchange"
} |
Q:
my localstorage font size not working initially
my localstorage font size + - well in general, however, after loading initially font size + 2 get string value, for example, initial font size (16) + 2 = 162.
I think the initial size value should be a variable, not a mere string. However, the initial font size, localstorage getitem value is a string.
After then it works well. How can I convert the initial font size value into a variable?
Thank you in advance for your answer.
<div id="font-size-change">
<span class="font-size-label">font size</span>
<button id="fs_up">+</button>
<span id="fs_write" style="width:15px;"></span>
<button id="fs_down">-</button>
</div>
<script>
$(document).ready(function() { // === Font Size Control =============================================================
var reset = $('#stx').css('fontSize'); // Grab the default font size
var elm = $('#stx'); // Font resize these elements
var size = localStorage.getItem('size');
var size = parseInt(size, 10);
if (size) {
elm.css('font-size', size + 'px');
$( "#fs_write" ).text(size); //
} else {
size = str_replace(reset, 'px', ''); //set the default font size and remove px from the value
$( "#fs_write" ).text(size); //
}
var min = 12; //min
var max = 56; //max
var p = 4; //increase
var m = 4; //decrease
$('#fs_up').click(function() { //Increase font size
if (size <= max) { //if the font size is lower or equal than the max value
size = size + p; //increase the size
elm.css({ //set the font size
'fontSize': size
});
$( "#fs_write" ).text(size); //
localStorage.setItem('size', size);
}
return false; //cancel a click event
});
$('#fs_down').click(function() {
if (size >= min) { //if the font size is greater or equal than min value
size = size - m; //decrease the size
elm.css({ //set the font size
'fontSize': size
});
$( "#fs_write" ).text(size); //
localStorage.setItem('size', size);
}
return false; //cancel a click event
});
$('#fs_write').click(function() { //Reset the font size
elm.css({ //set the default font size
'fontSize': reset
});
size = str_replace(reset, 'px', '');
$( "#fs_write" ).text(size); //
localStorage.setItem('size', size);
});
});
//A string replace function
function str_replace(haystack, needle, replacement) {
var temp = haystack.split(needle);
return temp.join(replacement);
}
</script>
A:
Explanation:
It's because the + operator is used both as an arithmithic operator (if both operands are numbers), and as a string concatenation operator (if at least one of the operand is a string).
Your size variable is initially a number as you are using parseInt at the begining of your code to get its value. But in the #fs_write click event listener you tranform it back into a string:
size = str_replace(reset, 'px', ''); // size is now a string because the return value of str_replace is a string
then when the #fs_up click happens, you add p to size (which is now a string):
size = size + p; // string concatenation is chosen over arithmitic addition because one of the operands (size) is a string
which causes the problem.
Solution:
Just transform size into a number before using the + operator using: Number, parseInt or the unary + operator:
size = +size + p; // using the unary + (now size is a number and p is also a number thus the arithmitic addidtion is chosen over the string concatenation)
// or
size = Number(size) + p; // using Number
Notes:
The #fs_down click event listener doen't cause the problem because the - operator is used only as an arithmitic operator. So when one or both operands is a string, it is automatically used as a number ("55" - "10" === 45 but "55" + 10 === "5510").
You are redeclaring size at the begining of your code wich is unecessary. Leave the first var size = ...; and use the second size = ...; whithout the var.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I find an average of values in dataset2 for each individual contained in dataset1, who have unique start and end dates?
I am looking to find the average of valueZ for each individual based on their unique start and end date. Exposure X has numerous values for each day, for each location, as such (There are actually 23 locations with over 300 values & dates per site):
data dataset2;
input date location valueZ;
datalines;
1/1/2016 1 0.028
1/1/2016 1 0.022
...
2/8/2016 1 0.041
2/8/2016 1 0.044
1/1/2016 2 0.056
...
8/8/2016 2 0.089
1/1/2016 3 0.029
...
11/8/2016 3 0.083
...
1/1/2016 4 0.081
...
12/8/2016 4 0.019
...
10/30/2016 23 0.063
;
The individuals in dataset1 are linked to dataset 2 by the location as such:
data dataset1;
input individual location start_date end_date;
datalines;
1 1 1/1/2016 12/31/2016
2 1 3/12/2016 9/4/2016
3 2 2/5/2016 11/5/2016
4 19 9/30/2016 10/3/2016
5 23 4/12/2016 12/12/2016
...
305 16 1/20/2016 5/15/2016
;
So, I would like to end up with the average of valueZ based on the location indicated in dataset2 from start_date to end_date for each individual. Can someone please help!
A:
Something like this?
proc sql;
create table want as
select d1.individual
,d1.location
,avg(d2.valueZ) as avg_value
from dataset2 d2
join dataset1 d1
on d1.location=d2.location
and d2.date between d1.start_date and d2.end_date
group by d1.individual, d1.location
quit;
| {
"pile_set_name": "StackExchange"
} |
Q:
Get offset of current buffer in vim (in particular, via python scripting)
i want to get the offset of
the current cursor position
the current selection range
in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful.
I have used vim.current.. before for doing scripting, but it uses lines and columns rather than a general offset.
Would i have to calculate the amount of all preceding line lengths + the current row, or is there a simpler method ?
A:
If your vim is compiled with the +byte_offset option, then in a Python script after the usual import vim, you can use, e.g.:
vim.eval('line2byte(line("."))+col(".")')
to get the byte offset from start of file of the cursor position, and similarly for other marks. More generally, if you have a line/column pair this (assuming +byte_offset is how your vim was compiled with) is the way to get a byte offset (there's also a byte2line function to go the other way).
While the vim module does make a lot of functionality available directly to Python scripts in vim, I've found that vim.eval and vim.command are often the handiest (and sometimes the only;-) way to get in just as deep as needed;-). Oh, and I always try to have a vim compiled with +justabouteverything whenever I can;-).
A:
You may also want to look at the statusline setting. This will add the bye offset to the statusline:
set statusline+=%o
See :h statusline
Just be careful because the default statusline is blank, and by appending the %o to it, you loose all the defaults.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why isn't my UserControl keeping its initialization?
I have a UserControl for which I think I'm initializing some of the members:
// MyUserControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyNamespace
{
public partial class MyUserControl : UserControl
{
private string m_myString;
private int m_myInt;
public string MyString
{
get { return m_myString; }
set { m_myString = value; }
}
public int MyInt
{
get { return m_myInt; }
set { m_myInt = value; }
}
public MyUserControl()
{
InitializeComponent();
MyString = ""; // was null, now I think it's ""
MyInt = 5; // was 0, now I think it's 5
}
// .........
}
}
When I insert this control into my main form, though, and call a function that checks values within MyUserControl, things don't look like they're initialized:
// MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyProgram
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MyButton_Click(object sender, EventArgs e)
{
// this prints 0 rather than 5
MessageBox.Show(this.theUserControl.MyInt.ToString());
}
}
}
I'm guessing this is a really simple error but I don't know where. I've tried prepending this. to things, but this probably isn't the way to go about fixing code. :)
Thanks as always!
EDIT: Stepping into the designer code as Pete suggested showed me where the write-over was happening. First I called the constructor of the user control, and then later, the values got overwritten with default values. I hadn't specified any default values (Sanjeevakumar Hiremath's suggestion) so the default values were those of the primitive types (for int this was 0).
A:
What you're likely seeing here is an artifact of the designer. If you ever opened up MainForm in a designer after you added MyUserControl it likely recorded the default values of MyUserControl in the generated InitializeComponent method of MainForm. These recorded values are re-assigned after the constructor of MyUserControl runs hence they're overwriting the values you set.
You can control this behavior via the use of the DesignerSerializationVisibilityAttribute
http://msdn.microsoft.com/en-us/library/system.componentmodel.designerserializationvisibilityattribute.designerserializationvisibilityattribute.aspx#Y375
| {
"pile_set_name": "StackExchange"
} |
Q:
Cython extension types attributes misunderstanding
I'm trying to grant python access for a member inside a cython class. The member type is basic (e.g. int or float)
As I read in the documentation, you can use properties to give access to the underlying C++ member:
cdef class myPythonClass:
# grant access to myCppMember thanks to myMember
property myMember:
def __get__(self):
return self.thisptr.myCppMember # implicit conversion
# would somehow be the same logic for __set__ method
Now this works.
However, as far as I understand, for basic types you can just use extension types. In this case, you make the member public to make it accessible and/or writable. You don't need properties:
cdef class myPythonClass:
cdef public int myCppMember # direct access to myCppMember
But when I use this second option, it does not work. The variable is never updated. Is there something I'm missing or I did not fully understood?
Thanks for you input.
A:
You already found the solution, using property is the way to go.
A public attribute can be accessed outside a class method, while a private attributes can only be used by the class methods.
But even public attributes defined at the C++ level cannot be accessed from Python. And exposing either a private or a public attribute using property will make it available to Python.
| {
"pile_set_name": "StackExchange"
} |
Q:
use select() to listen on both tcp and udp message
I only get the TCP message when I try this code:
from socket import *
from select import select
def read_tcp(s):
while True:
client,addr = s.accept()
data = client.recv(8000)
client.close()
print "Recv TCP:'%s'" % data
def read_udp(s):
while True:
data,addr = s.recvfrom(8000)
print "Recv UDP:'%s'" % data
def run():
host = ''
port = 8888
size = 8000
backlog = 5
# create tcp socket
tcp = socket(AF_INET, SOCK_STREAM)
tcp.bind(('',port))
tcp.listen(backlog)
# create udp socket
udp = socket(AF_INET, SOCK_DGRAM)
udp.bind(('',port))
input = [tcp,udp]
while True:
inputready,outputready,exceptready = select(input,[],[])
for s in inputready:
if s == tcp:
read_tcp(s)
elif s == udp:
read_udp(s)
else:
print "unknown socket:", s
if __name__ == '__main__':
run()
And the client is like this:
from socket import *
def send_tcp():
s = socket(AF_INET,SOCK_STREAM)
s.connect(('localhost',8888))
data="TCP "*4
s.send(data)
s.close()
def send_udp():
s = socket(AF_INET,SOCK_DGRAM)
data="UDP "*4
s.sendto(data, ('localhost',8888))
s.close()
if __name__ == '__main__':
send_tcp()
send_udp()
A:
Get rid of the 'while' loops in read_tcp() and read_udp(). The select() loop is the only loop you need: it will call the read_XXX() methods as often as required. The read_XXX() methods should handle exactly one event.
Your read_tcp() method should be split into two parts: one to accept a socket and add it to the selection set, and another to read an accepted socket. Adjust the select loop accordingly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find out what submit handler an HTML FORM has?
I am using Chrome where pressing enter automatically submits a form.
I have two forms on different pages, and neither has a submit INPUT/BUTTON. Both forms have similar (text) inputs in them.
FORM 1 automatically submits its data when pressing enter. FORM 2 on the other hand doesn't. I have to find out why this happens. Is there a way to find out what submit handlers are there attached to the two forms?
myForm.get(0).onsubmit (using jQuery) returns null in both cases.
Or is there another way to debug this issue? (Chrome DevTools, etc)
A:
I have researched the problem some more and the issue was around the FORMs having ONLY one text input.
FORM 1 has only one text input. FORM 2 has 2 text inputs. Therefore, in Chrome, FORM 1 will submit on Enter. I have already asked this question here.
So in my case, it is NOT a script that was adding submit handlers to the forms, but simply the browser specific implementation of forms. IE, for example does not behave like this.
PS: @KevinB It also makes sense why Visual Effects was not showing any handlers. Because there were none on the forms.
| {
"pile_set_name": "StackExchange"
} |
Q:
apache mod_rewrite not working with mod proxy
I have a Rails 2.3.18 application running on http://0.0.0.0:3004/, it is running with Passenger module, and is deploying on Apache server with proxy module using the following configuration:
<VirtualHost *:80>
<Proxy *>
AllowOverride All
Allow from all
</Proxy>
ServerName mydomain.com
ServerAlias www.mydomain.com
DocumentRoot /path/to/my/app/public
<Directory /path/to/my/app/public>
Options +FolowSymLinks
AllowOverride All
Order allow, deny
Allow from all
RewriteEngine On
RewriteBase /
RewriteRule ^folder/(.*)$ /$1 [P]
</Directory>
ProxyPass / http://0.0.0.0:3004/
ProxyPassReverse / http://0.0.0.0:3004/
</VirtualHost>
In the configuration I put the following rule of Rewrite module:
RewriteRule ^folder/(.*)$ /$1 [P]
This would redirect all request that goes to http://mydomain.com/folder/... to http://mydomain.com/... but the rule is not working because.
For example, I request the images from:
http://mydomain.com/folder/images/image.jpg
the objective is to redirect to
http://mydomain.com/images/image.jpg
but it is not working, it always uses the first path.
Thank you very much.
JT
A:
Your requests don't begin with folder, they begin with a forward slash.
RewriteRule ^/folder/(.*)$ /$1 [P]
| {
"pile_set_name": "StackExchange"
} |
Q:
Asynchron Errorhandling inside $.each
I am on server side Node.js and somehow caught up in the callbacks. I use the following function to insert data in the Table with the mysql pkg:
connection.query('INSERT INTO tableName SET ?', post, function(err, result)
{
if (err) {
if (err.code === 'ER_DUP_ENTRY')
{ }
else
{ throw err; }
}
});
I want to log how many duplicate entries are there without stoping the loop which calls this above function by an $.each.
It says here that I have 3 possibilities: throw, callbacks and EventEmitter. Throwing won't work, since this stops everything. I tried it with callbacks, but because I am in the callback from the $.each I couldn't find away in the above scope. I didn't try with a static EventEmitter since I don't know how to return any value from an $.each selector, except the selected data.
Any suggestions would be appreciated.
A:
Nest everything in a closure and count the finished queries in the callback, so that you know when is the last query finished:
(function(){
var errors = 0;
var started = 0;
var successful = 0;
$.each(..., function(){
started++;
connection.query('INSERT INTO tableName SET ?', post, function(err, result)
{
if (err) {
if (err.code === 'ER_DUP_ENTRY')
{ errors++; }
else
{ throw err; }
} else { successful++;}
if (started == successful + errors) {
// all done
console.log(errors + " errors occurred");
}
});
});
})();
| {
"pile_set_name": "StackExchange"
} |
Q:
R reshape dataset
I am trying to reshape to wide a dataset using R, this is the code, I would like to have df2 but I am struggling a bit.
value <- seq(1,20,1)
country <- c("AT","AT","AT","AT",
"BE","BE","BE","BE",
"CY","CY","CY", "CY",
"DE","DE","DE","DE",
"EE", "EE","EE","EE")
df <- data.frame(country, value)
df
# country value
# 1 AT 1
# 2 AT 2
# 3 AT 3
# 4 AT 4
# 5 BE 5
# 6 BE 6
# 7 BE 7
# 8 BE 8
# 9 CY 9
# 10 CY 10
# 11 CY 11
# 12 CY 12
# 13 DE 13
# 14 DE 14
# 15 DE 15
# 16 DE 16
# 17 EE 17
# 18 EE 18
# 19 EE 19
# 20 EE 20
#new dataset
AT <- seq(1,4,1)
BE <- seq(5,8,1)
# etc
df2 <- data.frame(AT, BE)
df2
# AT BE
# 1 1 5
# 2 2 6
# 3 3 7
# 4 4 8
Any help?
A:
Using the tidyverse (dplyr and tidyr)
df %>% group_by(country) %>%
mutate(row=row_number()) %>%
pivot_wider(names_from = country,values_from=value)
# A tibble: 4 x 6
row AT BE CY DE EE
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 5 9 13 17
2 2 2 6 10 14 18
3 3 3 7 11 15 19
4 4 4 8 12 16 20
| {
"pile_set_name": "StackExchange"
} |
Q:
Redirecionar HTTPS para HTTP no Centos
Tenho um domínio a qual não tenho mais o certificado ssl dele, o domínio está apontando para um servidor Centos 6. Toda vez que alguém tenta acessar ele utilizando HTTPS ele vai mostrar no navegador que aquele dominio não é seguro pois não tem um certificado válido ativo.
Minha dúvida é: Existe a possíbilidade de eu redirecionar o usuário quando tentar acessar através do HTTPS jogar ele para o HTTP, sem que tenha que aparecer aquela tela no navegador falando que é inseguro?
A:
Existe sim.
Vá até a pasta onde o seu domino(site) se encontra, exemplo: /var/www/html/meusite.com.br/:
vim .htaccess:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
| {
"pile_set_name": "StackExchange"
} |
Q:
Center of a 4 point square
Hello I have 4 3D points in a square, I would like to calculate the center of the square.
[http://i.stack.imgur.com/zQ9wg.png][1]
this is very easy I know, I know, but it's been a while and I simply can't wrap my head around it
I am looking for a formula on how to find point E e.g. the center of this square. I've also provided a quick illustration
Thanks
A:
Add up all the points and divide by $4$. Nothing could be easier.
A:
First determine (unless this was already specified) which order the points are in in the square. (That is, in the right triangle formed by the threee given points, which point has the right angle.)
The way to do this is that if $C$ is the right angle point, then the dot product
of $C-A$ with $C-B$ will be zero. I assume calculating a dot product is easy for you.
Second: Now that we know which point is the girth angle (say point $C$), Then the center of the square is at
$$
C+(A-C)/2 + (B-C)/2
$$
Remember, this is to be done as vector addtions and divisions by 2.
Example:
$$ A = (3,0,4)\\B = (2,5,7) \\ C = (1,2,3)$$
We notice that $$(C-A) \cdot (C-B) = (-2,2,-1)\cdot (-1,-3,-4)=2-6+4=0$$
so $C$ is our corner among these three points.
Then the center is at $$P = (1,2,3) + \frac12 (2,-2,1) + \frac12 (1,3,4) = (\frac52,\frac52,\frac{11}{2})$$
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS IAM Policy: Tag only untagged resources
We have an AWS user, who should be able to Create different resources like Instances, Volumes and SecurityGroups but not modify resources that are not part of its project.
For this purpose we allow the creation of resources and let the user CreateTags his resources with a Project tag and a value of <user's team name here>. He should not be able to tag already tagged resources and so, not the resources of other teams. (Every single resource is properly tagged here).
I have created a policy with statement:
[...]
{
"Effect": "Allow",
"Action": "ec2:CreateTags",
"Resource": "*",
"Condition": {
"Null": {
"ec2:ResourceTag/Project": "true"
}
}
}
[...]
If I use the Policy Simulator by AWS, I am allowed to call CreateTags on a resource without a Project tag.
If I simulate it with setting a Project tag, the action is denied just as expected.
Unforunately, if I use the same actions from the AWS CLI with this policy, CreateTags is allowed every time. Even if the tag is already set and even on foreign instances the user should not be able to modify:
as user with mentioned policy
aws ec2 create-security-group --group-name "test-sg" --description "test" # creation of a new resource
(AWS answer){
"GroupId": "sg-4a3151aa"
}
.
aws ec2 create-tags --resources sg-4a31513c --tags Key=Project,Value=web-performance # this should work, ResourceTag Project is Null
(success)
aws ec2 create-tags --resources sg-4a31513c --tags Key=Project,Value=web-performance # should *not* work, ResourceTag Project is already set and not Null
(success)
As you can see, it works both times and it works also on foreign Projects where the tag is already set.
I also tried it with
"Condition": {
"StringNotLike": {
"ec2:ResourceTag/Project": "*"
}
}
This behaves exactly like the "Null" Condition, even in the Policy Simulator.
Do you have any ideas? Thanks in advance.
A:
Amazon EC2 has partial support for resource-level permissions. At the time of writing, the CreateTags action does not support resource-level permissions. You can see the list of actions that support resource-level permissions here.
You can verify this by changing your policy to specify StopInstances (which supports resource-level permissions) in place of CreateTags. Your IAM user will only be able to stop an EC2 instance if the instance does not have a Project tag. Alternatively, if you change the Null condition to false, then the IAM user will only be able to stop an EC2 instance if the instance does have a Project tag.
So, your policy will presumably be correct at some point in the future, when CreateTags supports resource-level permissions.
| {
"pile_set_name": "StackExchange"
} |
Q:
QJsonArrays are not properly retrieved from QJsonObject
In the project I'm currently working on there I use Qt's JSON functionality to store the state of a graph, where every component of the system recursively calls the toJson-functions of its members for serialization. This works fine, but I run into a weird issue when deserializing the JSON file.
As a test that illustrates the problem, I've created the following example code:
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtDebug>
int main() {
auto document{QJsonDocument::fromJson("{\n"
" \"o1\" : {\n"
" \"i1\" : [\"l1\", \"l2\", \"l3\"],\n"
" \"i2\": 3.14\n"
" },\n"
" \"o2\" : {\n"
" \"i2\": 2.718,\n"
" \"i1\" : [\"l1\", \"l2\", \"l3\"]\n"
" }\n"
"}")};
qDebug() << "is the document an object:" << document.isObject();
auto document_object{document.object()};
auto object_1_value{document_object.value("o1")};
qDebug() << "is o1 an object:" << object_1_value.isObject();
auto object_1{object_1_value.toObject()};
auto inner_1_value{object_1.value("i1")};
qDebug() << "is i1 an array:" << inner_1_value.isArray();
auto inner_1{inner_1_value.toArray()};
qDebug() << "i1:" << inner_1;
auto inner_1_inner_value{inner_1.at(0)};
qDebug() << "is i1[0] an array:" << inner_1_inner_value.isArray();
auto inner_1_inner{inner_1_inner_value.toArray()};
qDebug() << "i1[0]:" << inner_1_inner;
return 0;
}
Here, I am first querying o1, then try to get the array stored under i1.
However, I get the following output:
is the document an object: true
is o1 an object: true
is i1 an array: true
i1: QJsonArray([["l1","l2","l3"]])
is i1[0] an array: true
i1[0]: QJsonArray([["l1","l2","l3"]])
It seems like Qt stores the returned array into a useless one-element array; in my other code, at(0) solved the issue, but here even that does not work.
I would be very glad if someone could help me find a solution to reliably (and preferably hacklessly) read nested JSON arrays with Qt, as I truly do not understand the issue.
I am on Linux 5.6.11 with gcc 9.3.0 and Qt 5.14.2.
A:
Your problem is the brace initialization. When you do assignment-style initialization instead, it works.
// instead of
auto inner_1{inner_1_value.toArray()};
// use
auto inner_1 = inner_1_value.toArray();
// same for all other brace inits
What I think happens is the classic clash between brace initialization and list initialization via a std::initializer_list constructor, in this case this one:
QJsonArray::QJsonArray(std::initializer_list<QJsonValue> args);
You want to brace-init a QJsonArray, but std::initializer_list takes precedence and what you actually instantiate is a QJsonArray with one item which is again a QJsonArray.
Often you see this problem explained with std::vector<int> and the two clashing ctors:
vector(size_type count);
vector(std::initializer_list<int> init);
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery forms and a hrefs
So i wanted to make some pretty buttons like http://www.oscaralexander.com/tutorials/how-to-make-sexy-buttons-with-css.html and everything is working fine. I wanted my forms to be able to be submitted with these sexy buttons.
So i started to use jQuery to handle all my "a" click actions.
$(document).ready(function() {
$("a").click(function() {
alert("a");
var a = $(this);
var id = a.attr("id");
switch (id) {
case "formSubmit":
a.parents("form:first").submit();
return false;
});
one more question... How do i get that code above to be highlighted in javascript? or any code like formating? Sorry for the crappy spaces, the second i find out how, i will edit it.
I got distracted and forgot to ask the original question. Now with jQuery it is easy to add in new information through $.post and other information. HOW do i add in a new a href link so that the $("a").click catches it?
A:
Use a .live() handler to handler clicks on new and future elements by replacing this:
$("a").click(function() {
With this:
$("a").live("click", function() {
This way a handler on document listens for clicks from <a> elements to bubble up...which happens for current and new elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Querydsl update clause populate skips bean null value properties
I have problem with SQLUpdateClause when using populate call with bean's null value properties. It just skips null value properties from generated update SQL instead of setting corresponding fields to NULL.
Example:
public class Bean {
private Long id;
private String value;
private String value2;
...
}
Bean bean = ...
bean.setValue(null);
bean.setValue("value2");
SQLUpdateClause update = new SQLUpdateClause(connection, dialect, qBean);
update.populate(bean).where(qBean.id.eq(...)).execute();
Will produce SQL:
update bean set value2 = 'value2' where bean.id = ...
Instead of desired:
update bean set value = null, value2 = 'value2' where bean.id = ...
Any help here? ... please
A:
When checked querydsl source code, found out solution:
...
update.populate(bean, DefaultMapper.WITH_NULL_BINDINGS)
.where(qBean.id.eq(...))
.execute();
...
Hope it helps someone
| {
"pile_set_name": "StackExchange"
} |
Q:
If a function $f$ is bounded in $[a,b]$ and if for each $x\in(a,b)$, $f$ is integrable over $[x,b]$, Then $f$ is integrable over $[a,b]$
I got this question which popped up in my mind:
Prove or disprove:
If a function $f$ is bounded in a closed interval $[a,b]$ and if for each $x\in(a,b)$, $f$ is integrable over $[x,b]$, Then $f$ is integrable over $[a,b]$
Note:
This question rose from the following problem that I've come across:
Let $f$ be a function defined on the interval $[0,1]$ that satisfy $\forall x\in[0,1], 4<f(x)<5$. If for each $x\in(0,1)$, $f$ is integrable over $[x,1]$, Then $f$ is integrable over $[0,1]$.
Here's my answer:
We must show that for each $0<\epsilon$ there exist a partition $P$ of the interval $[0,1]$ such that $S(P)-s(P)<\epsilon$ (Where $S(P)$ is the upper sum and $s(P)$ is the lower sum).
Lets take $\epsilon\in(0,2)$, Then $\frac{\epsilon}{2} \in (0,1)$ which implies that $f$ is integrable over $[\frac{\epsilon}{2},1]$, and hence
we get that for each $0<\kappa$ there exist a partition $Q$ of the interval $[\frac{\epsilon}{2},1]$ such that $S(Q)-s(Q)<\kappa$.
Now because $0<\frac{\epsilon}{2}$, we get that there exist a partition $Q$ of the interval $[\frac{\epsilon}{2},1]$ such that $S(Q)-s(Q)<\frac{\epsilon}{2}$
If we take $P=Q\cup \{0\}$, we get that $P$ is a partition of $[0,1]$
And hence we get that $ S(P)-s(P)=(sup f([0,\frac{\epsilon}{2}] - inf f([0,\frac{\epsilon}{2}])*\frac{\epsilon}{2}+S(Q)-s(Q)$
Now because $\forall x\in[0,\frac{\epsilon}{2}], 4<f(x )<5$, we get that $sup f([0,\frac{\epsilon}{2}]\leq 5$ and $4\geq inf f([0,\frac{\epsilon}{2}])$, And so $sup f([0,\frac{\epsilon}{2}] - inf f([0,\frac{\epsilon}{2}])\leq 1$ Which implies that $(sup f([0,\frac{\epsilon}{2}] - inf f([0,\frac{\epsilon}{2}]))*\frac{\epsilon}{2}\leq \frac{\epsilon}{2}$, and because $S(Q)-s(Q)<\frac{\epsilon}{2}$, We get that $(sup f([0,\frac{\epsilon}{2}] - inf f([0,\frac{\epsilon}{2}])*\frac{\epsilon}{2}+S(Q)-s(Q)<\epsilon$ And so $S(P)-s(P)<\epsilon$.
Therefore. We've shown that for each $\epsilon\in(0,2)$ there exist a partition $P$ of $[0,1]$ such that $S (P)-s(P)<\epsilon$.
Now if $\epsilon\in[2,\infty)$ we can take the partition that corresponds to $\frac{1}{2}$ and get that there exist a partition $P$ of $[0,1]$ such that $S (P)-s(P)<\frac{1}{2}<2\leq\epsilon$.
And so we've shown that for each $0<\epsilon$ there exist a partition $P$ of $[0,1]$ such that $S(P)-s(P)<\epsilon$ Which implies that $f$ is integrable over $[0,1]$ as was to be shown.
Now how can we generalize this result to the original question ?
A:
Your proof is correct. To generalize it, give names $M$ and $m$ to the sup and inf of $f$ over $[a,b]$. Then break the interval into $I_1 = [a,a+\alpha]$ and $I_2 = [a+\alpha,b]$, where $\alpha = \min(b-a,\epsilon/2(M-m))$. Choose a partition Q of $I_2$ for which $S(Q) - s(Q) < \epsilon/2$, then continue as above.
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace fourth occurrence of a character in a string
I was trying to replace fourth occurrence of '_' in a string. For example,
Input
AAA_BBB_CCC_DD_D_EEE
Output
AAA_BBB_CCC_DDD_EEE
Can anyone please suggest a solution?
A:
You could use a back-reference....
gsub( "(_[^_]+_[^_]+_[^_]+)_" , "\\1" , x )
# [1] "AAA_BBB_CCC_DDD_EEE"
EDIT
And thanks to @SonyGeorge below this could be further simplified to:
gsub( "((_[^_]+){3})_" , "\\1" , x )
A:
don know in which platform you are going to use
pattern = (([^_]+_){3}[^_]+)_(.*)
replacement = $1.$2 // concat 1 and 2
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML Canvas: Fill() not working with no errors in console
Hello I am making a polygon and want to fill it up. But whatever I try to do I can't seem to make it work.
If anyone can point me in the right direction I appreciate it.
https://jsfiddle.net/ygesj1do/4/
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
op = {
"pts": [{
"x": 40,
"y": 13.5
}, {
"x": 60,
"y": 27.75
}, {
"x": 60,
"y": 56.25
}, {
"x": 40,
"y": 70.5
}, {
"x": 20,
"y": 56.25
}, {
"x": 20,
"y": 27.75
}],
"color": "#00F",
"fillcolor": "#FF0000",
"lineWidth": 1
};
ctx.save();
ctx.strokeStyle = op.color;
ctx.fillStyle = op.fillcolor;
ctx.lineWidth = op.lineWidth;
ctx.beginPath();
for (i = 1; i <= op.pts.length; i++) {
if (i == op.pts.length) {
ctx.moveTo(op.pts[i - 1].x, op.pts[i - 1].y);
ctx.lineTo(op.pts[0].x, op.pts[0].y);
} else {
ctx.moveTo(op.pts[i - 1].x, op.pts[i - 1].y);
ctx.lineTo(op.pts[i].x, op.pts[i].y);
}
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
A:
You only need to use moveTo() once for each path after beginPath() then just use lineTo() after that. Once you do all of the lineTo()'s in the for loop, then you can do the ctx.fill() to get it to work.
Here's the updated part of the code:
/* set moveTo() once before for loop */
ctx.moveTo(op.pts[0].x,op.pts[0].y);
/*then in the for loop just use lineTo(), using lineTo() will keep track of the last endpoint on the current path so you don't need to use moveTo() unless you are starting a new path.*/
for (i=1;i<=op.pts.length;i++) {
if (i==op.pts.length) {
ctx.lineTo(op.pts[0].x,op.pts[0].y);
} else {
ctx.lineTo(op.pts[i].x,op.pts[i].y);
}
}
/* now the following will work */
ctx.closePath();
ctx.fill();
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to change which work item is associated with a check-in?
In MS Team Foundation Server 2010 is it possible to update the work items that a check-in is associated with? I was working late yesterday and checked in against the wrong items and would like to re-associate with the right work items.
A:
Work items are associated by linking them to the changesets. All you have to do is remove the link to the wrong work items and add the links to the new ones.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error when using mv module to rename a file with buffer data
I am using mv module for express js, and i am having an issue with saving my uploaded file to a certain directory of my choosing.
when i access my file data i have this info:
fieldname : 'file',
originalname : ....,
encoding :7bit,
mimetype 'image/jpeg',
buffer : <Buffer ff d8 ff e1 ...>
when i use mv to do the following:
mv( req.file.buffer , path.normalize(__dirname+'/public/uploads/'+ p._id +'.jpg'), {mkdirp: true} ,function(err){
if(err) console.log(err);
res.json({});
});
I see an error saying:
"Path must be a string without null bytes."
What am i doing wrong? how can i fix it?
A:
var fs = require('fs');
var OS = require('os');
var path = require('path');
var tmpPath = path.join(OS.tmpdir(), Date.now());
//saving file to tmp dir with random name
fs.writeFile(tmpPath, req.file.buffer, function(err) {
if (err) {
return res.error(err);
}
//moving file somewhere else
mv(tmpPath, path.normalize(__dirname+'/public/uploads/'+ p._id +'.jpg'), {mkdirp: true} ,function(err){
if(err) console.log(err);
res.json({});
});
})
| {
"pile_set_name": "StackExchange"
} |
Q:
Concatenar dois arrays 2D paralelamente
Como concatenar dois arrays 2D paralelamente retornando um array 1D, exemplo:
ARRAYS/LISTAS
lista 1 = [['a'],['b'],['c']]
lista 2 = [['A'],['B'],['C']]
OBJETIVO:
lista 3 = ['a:A','b:B','c:C']
Tentativa:
concat_array = [itm + ':' if not itm.endswith(':') else itm for itm in lista1 + lista2]
A:
Você pode usar o a função zip para iterar sobre as duas listas e depois concatenar o primeiro elemento de cada sublista.
lista_1 = [['a'],['b'],['c']]
lista_2 = [['A'],['B'],['C']]
concat = [f"{x[0]}:{y[0]}" for x, y in zip(lista_1, lista_2)]
print(concat)
# ['a:A', 'b:B', 'c:C']
Código rodando no Repl.it
Edit:
Luis, se precisar de mais informações sobre o zip, esta resposta a sua própria pergunta pode ajudar.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# script accessing previously compiled methods
I'm looking to move a scripting solution that I currently have over to C# as I believe as this will solve some of the issues which I am currently facing when it comes to running on different platforms. I can call functions which are within the script and access their variables, however, one thing that I would like to be able to do is call a function from the class that the script resides in. Does anyone know how I would be able to do this?
Here is my code at the minute which is working for calling and access objects within the script, but I would like to be able to call the method "Called" from within the script, but cannot:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.CSharp;
namespace scriptingTest
{
class MainClass
{
public static void Main (string[] args)
{
var csc = new CSharpCodeProvider ();
var res = csc.CompileAssemblyFromSource (
new CompilerParameters ()
{
GenerateInMemory = true
},
@"using System;
public class TestClass
{
public int testvar = 5;
public string Execute()
{
return ""Executed."";
}
}"
);
if (res.Errors.Count == 0) {
var type = res.CompiledAssembly.GetType ("TestClass");
var obj = Activator.CreateInstance (type);
var output = type.GetMethod ("Execute").Invoke (obj, new object[] { });
Console.WriteLine (output.ToString ());
FieldInfo test = type.GetField ("testvar");
Console.WriteLine (type.GetField ("testvar").GetValue (obj));
} else {
foreach (var error in res.Errors)
Console.WriteLine(error.ToString());
}
Console.ReadLine ();
}
static void Called() // This is what I would like to be able to call
{
Console.WriteLine("Called from script.");
}
}
}
I am attempting to do this in Mono, however, I don't believe this should affect how this would be resolved.
A:
There are a handful of things you need to change.
MainClass and Called need to be accessible to other assemblies so make them public. Additionally, you need to add a reference to the current assembly to be able to access it in your script code. So essentially your code will end up looking like:
public class MainClass
public static void Called()
var csc = new CSharpCodeProvider();
var ca = Assembly.GetExecutingAssembly();
var cp = new CompilerParameters();
cp.GenerateInMemory = true;
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("mscorlib.dll");
cp.ReferencedAssemblies.Add(ca.Location);
var res = csc.CompileAssemblyFromSource(
cp,
@"using System;
public class TestClass
{
public int testvar = 5;
public string Execute()
{
scriptingTest.MainClass.Called();
return ""Executed."";
}
}"
);
The output of running the test looks like:
Called from script.
Executed.
5
| {
"pile_set_name": "StackExchange"
} |
Q:
Does triply transitive mean there are three orbits?
If a group action is transitive, it possesses a single orbit. Does that mean a group action that is doubly transitive has two orbits, and so on?
http://mathworld.wolfram.com/TransitiveGroupAction.html
A:
No. Multiple transitivity is more restrictive than single transitivity, rather than a broader concept. If we can send three arbitrary elements to three elements we choose, we can certainly send a single element anywhere we want it to go.
There are significant restrictions on the form of multiply transitive groups as a result - and some of the special ones (eg Matthieu Groups) are at the heart of the 26 exceptional simple groups.
| {
"pile_set_name": "StackExchange"
} |
Q:
English idiom for 'Fry the fish using fish's own oil'
Please help me to find out the appropriate English idiom for Fry the fish using fish's own oil. This is a Bengali proverb/idiom whose word meaning 'When you are frying some sea fish, initially cook use some oil for frying but within few minute fish emit it's own body oil, and the remaining frying is done by this oil. Literally, this means Somebody has invested some amount of money in some particular purpose but get some extra benefit, as an add-on that save his/her initial investments. Please help me. If I'm not clarify well please ask me. Thanks!
A:
After (as rileywhite says) you have 'primed the pump', the enterprise will hopefully carry on under its own steam.
But avoid mixed metaphors even more than 'hopefully' as a pragmatic marker.
A:
You may be looking for something along the lines of "prime the pump", meaning that you put some intial investment into something to get it started, and then it can continue on its own. This is often used in reference to Keynesian economics, but it can be applied more generally, as well.
Literally, it is an expression referring to adding water into a water pump so that water can be extracted from, for example, a well. See this instructional guide.
A:
You might want a to use an actual, well-known economics term:
R.O.I: "Return On Investment"
Or
"Pays for itself"
You would then explain how the subject does this.
Or you might want
"you can't make an omlette without breaking a few eggs"
suggesting that a price MUST be paid to get the intended benefit.
or
"Killer app", short for "killer application"
which refers to the fact that the very first spreadsheet program for a personal computer allowed accountants|book keepers to justify the entire cost of purchasing an entire expensive PC system because it would divide their workload by a factor of 10 or more. If the computer ONLY ran a spreadsheet, it was worth the price to them. But a computer also does much, much more, like print layout for documents, art, e-Mail, etc..
You might want:
"Get the ball rolling"
Which conjures the image of giving a boulder a tiny initial push to start it rolling down a hill, after which gravity will take over & keep it rolling.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do we really need EOL related announcements hanging about in the unanswered meta questions queue?
I've noticed a couple of these: For example,
EOL Notice: Precise Pangolin (12.04) will be End of Life starting April 28, 2017
Non-EOL Notice: Quantal (12.10) remains supported through April 2014
Since statements of fact are unlikely to result in much discussion and the EOL dates are published upon release at https://wiki.ubuntu.com/Releases are notifications like this necessary?
A:
Necessary? No.
Possibly helpful? Yes, as some members may not pay close attention to the schedule linked in the question. I do think it's important to re-iterate what I said here
| {
"pile_set_name": "StackExchange"
} |
Q:
How to transform a Custom Object List by excluding particular property in Kotlin?
How to transform a List into a new List by excluding a property in T.
For instance if User data class has 10 properties, I need to transform List into a new List without one particular property in User . New List like List
data class User(val name: String, val age: Int)
var userList = mutableListOf<User>()
var nameList= userList.map { it.name }
If a List to be created without property 'age'. Like
var withoutAgeList
A:
In your first example:
var userList = mutableListOf<User>()
var nameList= userList.map { it.name }
The question "What's the type of nameList?" has a simple answer: List<String>. So let me ask you a similar question: What's the type of withoutAgeList? The answer to that question informs the answer to your question.
Perhaps a user without the age property is a separate AgelessUser class, meaning withoutAgeList is of type List<AgelessUser>. In that case, I suggest either a constructor or a factory function that builds AgelessUser from User, and you want one of these:
val withoutAgeList = userList.map { AgelessUser(it) } // constructor
val withoutAgeList = userList.map { agelessUserOf(it) } // factory
Alternatively, maybe the age property in User is nullable and immutable, and you want to represent users without an age as a regular User where age=null. In this case, you could copy the Users and override the age field
// TODO: pass all the other fields too
val withoutAgeList = userList.map { User(it.name, null) }
Assuming Users is a data class, we can avoid explicitly naming all fields by making use of copy():
val withoutAgeList = userList.map { it.copy(age = null) }
Maybe the age property is nullable and mutable — and you actually want to change the users in place instead of copying them. This is somewhat risky and I don't advocate doing it this way unless you really know what you're doing though.
userList.forEach { it.age = null }
// They're actually the same list!
val withoutAgeList = userList
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check aes-ni are supported by CPU?
I searching for solution, how to check aes-ni are available on CPU. I need to put this information in my application, so i'm not looking for any CPU-Z, bash commands or something.
I know that it is seen as aes flag. I have no idea how to check it in assembly or c. Main application is written in C#, but it doesn't matter.
A:
This information is returned by the cpuid instruction. Pass in eax=1 and bit #25 in ecx will show support. See the intel instruction set reference for more details. Sample code:
mov eax, 1
cpuid
test ecx, 1<<25
jz no_aesni
Also, you might just try executing it and catch the exception.
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with UICollectionView delegate methods
I'm trying to use an UICollectionView, it's being shown on the view, but the delegate methods are not being called. Here's how I'm trying to do:
On Storyboard, I have a UITableViewController which has a TableView and a UIView like this:
I've created an outlet for the UIView on my UITableViewController class:
class FeedTableViewController: UITableViewController {
@IBOutlet weak var bannerView: UIView!
}
And on viewDidLoad() function, I'm instantiating the UIViewController class which will be the delegate and datasource of my UICollectionView:
override func viewDidLoad() {
let bannerViewController = BannerViewController()
bannerView.addSubview(bannerViewController.view)
bannerViewController.view.translatesAutoresizingMaskIntoConstraints = false
bannerViewController.view.leadingAnchor.constraint(equalTo: bannerView.leadingAnchor).isActive = true
bannerViewController.view.trailingAnchor.constraint(equalTo: bannerView.trailingAnchor).isActive = true
bannerViewController.view.topAnchor.constraint(equalTo: bannerView.topAnchor).isActive = true
bannerViewController.view.bottomAnchor.constraint(equalTo: bannerView.bottomAnchor).isActive = true
}
Here's the full code of BannerViewController class:
class BannerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 125)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .cyan
view.addSubview(collectionView)
}
}
extension BannerViewController: UICollectionViewDataSource {
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
cell.backgroundColor = .red
return cell
}
}
extension BannerViewController: UICollectionViewDelegateFlowLayout {
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
}
}
The UICollectionView is being instantiated and appears on the view, as we can see on the cyan box here:
But the delegate methods numberOfItemsInSection and cellForItemAt are not being called. And I have registered BannerViewController as the datasource and delegate of the UICollectionView, so I don't know why it's not working.
A:
You need to hold a strong reference to ( make it as instance var )
var bannerViewController:BannerViewController!
Also properly add it
bannerViewController = BannerViewController()
addChildViewController(bannerViewController)
view.addSubview(bannerViewController.view)
bannerViewController.view.translatesAutoresizingMaskIntoConstraints =false
NSLayoutConstraint.activate([
bannerViewController.view.leadingAnchor.constraint(equalTo: bannerView.leadingAnchor),
bannerViewController.view.trailingAnchor.constraint(equalTo: bannerView.trailingAnchor),
bannerViewController.view.topAnchor.constraint(equalTo: bannerView.topAnchor),
bannerViewController.view.bottomAnchor.constraint(equalTo: bannerView.bottomAnchor)
])
bannerViewController.didMove(toParentViewController: self)
Also don't forget
extension BannerViewController: UICollectionViewDelegate {
| {
"pile_set_name": "StackExchange"
} |
Q:
Type mismatch convert char[] to an object
I'm sure I'm missing something simple but this problem seems absolutely stupid.
private static void method501(char ac[])
{
char ac1[] = ac.clone();
}
My problem is that the char ac1[] = ac.clone(); is throwing a type mismatch error in eclipse telling me that I can't convert a char array to an Object?
Any reason why this is? It was not giving me the same error on the newest version of eclipse so wondering if it's just this older version is giving me the problem.
A:
This happens in Eclipse if you've got your compiler settings to target very old source compatibility.
With a compatibility level of 1.5 or above, it's fine - but if you set the source compatibility level to 1.3 or 1.4, you'll get this error, as early versions of the Java Language Specification didn't specify that T[].clone() returns T[].
Text from JLS 1.0 section 10.7:
The members of an array type are all of the following:
[...]
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions
The equivalent text from the Java 8 JLS:
The members of an array type are all of the following:
[...]
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
Go into the project properties and check whether it's using the default settings or project-specific settings, and fix the appropriate settings (either the project-specific ones or your workspace settings) to use a more up-to-date source compatibility.
I suspect you'll find that with your current settings you won't be able to use generics or other 1.5+ features either.
| {
"pile_set_name": "StackExchange"
} |
Q:
Testing module results in different outputs depending on testing environment
Test Introduction
I have been given a module to work with so it passes the attached Jest test. Currently, I am stuck at the following test rule:
describe(`TWO TIMES the SAME product ADDED`, () => {
const _VATRate = 20;
const _product = {
name: 'product1',
price: 1.50,
quantity: 1
};
let _instance;
let _cart;
beforeEach(() => {
_instance = window[NAMESPACE][MODULE_NAME]();
_instance.init(_VATRate);
_cart = _instance.addProducts([_product, _product]);
});
test(`cart's products`, () => {
const result = Object.assign({}, _product, {'quantity': 2});
expect(_cart.products).toEqual([result]);
});
})
Expected value to be:
[{"name": "product1", "price": 1.5, "quantity": 2}]
Implementing module in the browser (works)
function CartModule() {
var _Cart = {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: [],
VATRate: null
};
var _getCart = function() {
return {
total: _Cart.total,
products: _Cart.products
};
};
var _updateTotalPrice = function() {
let invoice = _Cart.total;
invoice.beforeVAT = 0;
invoice.afterVAT = 0;
invoice.VAT = 0;
let roundDecimals = number => +number.toFixed(2);
_Cart.products.forEach(product => {
invoice.beforeVAT = roundDecimals(
product.price * product.quantity + invoice.beforeVAT
);
});
invoice.VAT = roundDecimals(_Cart.total.beforeVAT / 100 * _Cart.VATRate);
invoice.afterVAT = invoice.VAT + invoice.beforeVAT;
};
return {
init: function(VATRate) {
return (_Cart.VATRate = VATRate || 0);
},
getCart: _getCart,
addProducts: function(recievedProducts) {
let products = Array.from(arguments),
updatedProduct,
cartProducts = _getCart().products,
existingProduct;
products.forEach(product => {
existingProduct = cartProducts.findIndex(
existing => existing.name === product.name
);
if (existingProduct >= 0) {
updatedProduct = cartProducts[existingProduct];
updatedProduct.quantity++;
cartProducts[existingProduct] = updatedProduct;
} else {
updatedProduct = product;
updatedProduct.quantity = 1;
cartProducts.push(product);
}
});
// Update Total Price
_updateTotalPrice();
return _getCart();
},
changeProductQuantity: function(product, newQuantity) {
let products = _Cart.products,
productIndex = products.findIndex(
existing => existing.name === product.name
);
products[productIndex].quantity = +newQuantity;
_updateTotalPrice();
return _getCart();
},
removeProducts: function(product) {
let products = _Cart.products,
productIndex = products.findIndex(
existing => existing.name === product.name
);
products.splice(productIndex, 1);
_updateTotalPrice();
return _getCart();
},
destroy: function() {
/* Module = null */
}
};
}
var shoppingCart = CartModule(),
_product = {
name: 'product1',
price: 1.50,
quantity: 1
};
shoppingCart.init(20);
shoppingCart.addProducts(_product, _product)
console.log(shoppingCart.getCart().products)
Jest Testing
But things are different in testing environments. In addition the error output of the sandbox and local version are different:
Local version
Expected value to equal:
[{"name": "product1", "price": 1.5, "quantity": 2}]
Received:
[{"name": "product1", "price": 1.5, "quantity": 1}, {"0": {"name": "product1", "price": 1.5, "quantity": 1}, "1": {"name": "product1", "price": 1.5, "quantity": 1}, "quantity": 1}]
While sandbox version output is:
Expected value to equal:
[{"name": "product1", "price": 1.5, "quantity": 2}]
Received:
[{"0": {"name": "product1", "price": 1.5, "quantity": 1}, "1": {"name": "product1", "price": 1.5, "quantity": 1}, "quantity": 1}]
Testing Environments
Sandbox working environment
P.S: I will appreciate a lot if you could look and explain what I've done wrong at this point, or what also might be wrong?
A:
I think it's this line:
let products = Array.from(arguments),
This will produce an array of product arrays, due to this line:
_cart = _instance.addProducts([_product, _product]);
You might want to use something like this:
addProducts: function(recievedProducts) {
let products = recievedProducts,
Of if your addProducts can handle both an object as an array, you might want to do :
addProducts: function(recievedProducts) {
let products = Array.isArray(recievedProducts) ? receivedProducts : [receivedProducts],
| {
"pile_set_name": "StackExchange"
} |
Q:
How to format a line with Sed
I have a variable in a script, lets assume it looks like this
$x= /w =
I want to use it in a sed expression sed -i '/he/c\he = "'$x'"' /home/1.txt
But for correct work it must look like this $x='\s''/w\''\s''=\'
So I want fist go trough the variable with sed and make the variable look correct for the next use.
But I am quite new with sed, and cant do a correct syntax.
If possible give an example based on my variable and link to read-out about such things will be good to :)
A:
try something like this.
var='$x= /w ='
Tempo="$( printf "%s" "${var}" | sed 's/["\\]/\\&/g' )"
sed -i "/he/c\\
he = \"${Tempo}\"" /home/1.txt
Escaping some char. Just look at correct simple and double quote between escaping and your sed that need a double quote.
| {
"pile_set_name": "StackExchange"
} |
Q:
LINQ Select Statement. Anonymous Method Returns Exception
When using an anonymous method in a LINQ Select statement does the anonymous method have to return a value?
When I do the following I get no errors:
await Task.WhenAll(list.Select(a => doSomething(a)));
But when I do this I get an error that says type arguments cannot be inferred from the usage:
await Task.WhenAll(list.Select(a => {
doSomething(a);
Log("Log Something");
UpdateUI();
}));
Why does the first work and the second doesn't?
Here is the doSomething method:
private async Task doSomething(string a)
{
HttpClient client = new HttpClient;
// Do stuff
string source = await client.PostAsync(a, content);
// Extract data from source and store in text file.
}
A:
When using an anonymous method in a LINQ Select statement does the anonymous method have to return a value?
Yes. The signature of the Select method is:
public IEnumerable<TResult> Select<TSource, TResult>(
IEnumerable<TSource> source,
Func<TSource, TResult> selector)
so the selector must return a value.
With your first code snippet the return statement is implicit. doSomething returns a value, and that value is what each item is projected to.
When you use a statement lambda, instead of an expression lambda, there is no implicit return statement. Since your second code block is not returning anything, it doesn't match what Select expects.
Now, as for your actual problem. What you want to do is project each task into a task that does something, then writes to the log when it's done and updates the UI. You can use an async lambda to do this. In an async lambda when there are no return statement it will still be returning a Task (just without a Result) instead of void. And that's exactly what you want to do, project each task into another task.
await Task.WhenAll(list.Select(async a => {
await doSomething(a);
Log("Log Something");
UpdateUI();
}));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to have non-const access to object held by a container when the container is const in C++
I have a relationship between two classes and some additional functional code illustrated in the below example. The MiddleMan class holds a couple of containers of pointers to DataObject class instances. I want to enforce read-only access to the data objects in one container, while allowing write access to the data containers in the other. Users of MiddleMan should never be able to modify the containers themselves directly (the ptr_vector members).
I guess there is const promotion happening to the DataObject pointers when accessed through the MiddleMan const member function. How can I avoid this? In my object relationship, MiddleMan does not logically own the DataObject instances. Thus, I do not want the DataObject instances const-protected.
I have used the boost::ptr_vector container as I understand the STL containers can be more problematic for this sort of thing. Didn't solve my problem though.
I am happy to use const_cast in MiddleMan, but I don't see how to.
// const correctness access through middleman example
// g++ -I/Developer/boost ptr_container_ex.cc
#include <boost/ptr_container/ptr_vector.hpp>
struct DataObject
{
DataObject(size_t n) : _data(new float[n]) {}
~DataObject() {delete _data;}
float * dataNonConst() { return _data; }
const float * dataConst() const { return _data; }
float * _data;
};
struct MiddleMan
{
typedef boost::ptr_vector<DataObject> containerVec_t;
const containerVec_t & inputVars() const { return _inputVars; }
const containerVec_t & outputVars() const { return _outputVars; }
void addInputVar( DataObject * in ) { _inputVars.push_back( in ); }
void addOutputVar( DataObject * out ) { _outputVars.push_back( out ); }
containerVec_t _inputVars, _outputVars;
};
// just an example that the DataObject instances are managed externally
DataObject g_dataInstances[] = {DataObject(1), DataObject(2), DataObject(3)};
MiddleMan theMiddleMan;
int main()
{
theMiddleMan.addInputVar( &g_dataInstances[0]); // this is just setup
theMiddleMan.addOutputVar( &g_dataInstances[1]);
const MiddleMan & mmRef = theMiddleMan; // I actually only have a const ref to work with
// read data example
const MiddleMan::containerVec_t & inputs = mmRef.inputVars();
float read = inputs[0].dataConst()[0];
// write data example
const MiddleMan::containerVec_t & outputs = mmRef.outputVars();
float * data_ptr = outputs[0].dataNonConst(); // COMPILER ERROR HERE:
return 0;
}
I'm getting the compiler output:
ptr_container_ex.cc: In function ‘int main()’:
ptr_container_ex.cc:49: error: passing ‘const DataContainer’ as ‘this’ argument of ‘float* DataContainer::dataNonConst()’ discards qualifiers
A:
One working scenario uses const_cast in accessing the outputVars. I'm not able to return a reference to the whole container, but I can get the functionality I need returning begin and end iterators.
// const correctness access through middleman example
// g++ -I/Developer/boost ptr_container_ex.cc
#include <boost/ptr_container/ptr_vector.hpp>
struct DataObject
{
DataObject(size_t n) : _data(new float[n]) {}
~DataObject() {delete _data;}
float * dataNonConst() { return _data; }
const float * dataConst() const { return _data; }
float * _data;
};
struct MiddleMan
{
typedef boost::ptr_vector<DataObject> containerVec_t;
containerVec_t::iterator outputVarsBegin() const { return const_cast<containerVec_t&>(_outputVars).begin(); }
containerVec_t::iterator outputVarsEnd() const { return const_cast<containerVec_t&>(_outputVars).end(); }
const containerVec_t & inputVars() const { return _inputVars; }
void addInputVar( DataObject * in ) { _inputVars.push_back( in ); }
void addOutputVar( DataObject * out ) { _outputVars.push_back( out ); }
containerVec_t _inputVars, _outputVars;
};
// just an example that the DataObject instances are managed externally
DataObject g_dataInstances[] = {DataObject(1), DataObject(2), DataObject(3)};
MiddleMan theMiddleMan;
int main()
{
theMiddleMan.addInputVar( &g_dataInstances[0]); // this is just setup
theMiddleMan.addOutputVar( &g_dataInstances[1]);
const MiddleMan & mmRef = theMiddleMan; // I actually only have a const ref to work with
// read data example
const MiddleMan::containerVec_t & inputs = mmRef.inputVars();
float read = inputs[0].dataConst()[0];
// write data example
float * data_ptr2 = mmRef.outputVarsBegin()->dataNonConst(); // WORKS
return 0;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I import audio sequentially in Audacity?
I am currently work on a large recording project. It consists of various telephone recordings that I then narrate in separate files.
Each recording and corresponding narrated it saved in a separate file for ease of editing. The first file is 001_name, the second is 002_name, and so on.
The idea is, when I am done, I can simply import all the files in numerical order and then export one large file. This is much more manageable than trying to do this huge recording project in one single Audacity file which would be incredibly complex.
I thought I could combine them by going to Open → selecting files. That opened each in a separate window. I then tried importing the files:
But when I do that, instead of going to separate windows, they go to separate tracks:
What I would like is for them to import one after the other in the same track, joined end to end. The spacing between files is already taken into account in each file itself. So I would like something like this, without anything in the 2nd track at all:
There does not seem to be an easy way to do this. I've looked online and not been able to find anything. Even clicking at the end of the the selection and importing puts an import in a separate track.
The only way to fix this is to manually cut and paste each track to the very first one, one after the other. This is not an option for me. I am going to have hundreds of files by the end of this project, and I don't have 4 hours to waste doing this manually. Furthermore, if I listen to the result and find something needs tweaking, and I modify an individual file, then I would have to do the whole process all over again. This is unacceptable.
How can I force Audacity to import files to the same track instead of a new one?
A:
As it happens, I found a hacked-together solution from Audacity themselves:
Import all files at once by using Import
From the menu, click Select → All
From the menu, click Tracks → Align Tracks → Align End To End
From the menu, click Tracks → Mix → Mix and Render
You would think there would be an option to do all this in one step but there is not.
The only downside is that all files are imported to separate tracks and then combined in order later. While resource-intensive, this is not labor-intensive, so it works for my purposes since the result is exactly the same.
Source: https://manual.audacityteam.org/man/faq_editing.html#join
| {
"pile_set_name": "StackExchange"
} |
Q:
monogodb get sum of one field of in sub document
I'm pretty new with monogodb and I'm trying to use the aggregation framework to get the sum of revenue for each agent.
My data looks like this:
{
"_id" : ObjectId("56ce2ce5b69c4a909eb50f22"),
"property_id" : 5594,
"reservation_id" : "3110414.1",
"arrival" : "2016-02-24",
"los" : 1,
"updated" : ISODate("2016-02-24T22:21:27.000Z"),
"offer_list" : {
"68801" : {
"pitched" : "yes",
"accepted" : "yes",
"prime_price" : "3",
"agent_price" : "",
"price_per" : "night"
},
"63839" : {
"pitched" : "yes",
"accepted" : "yes",
"prime_price" : "8",
"agent_price" : "",
"price_per" : "night"
}
},
"status" : "accepted",
"comments" : [],
"created" : ISODate("2016-02-24T22:21:18.000Z"),
"agent_id" : 50941
}
For each agent_id, I would like to get the sum of all "agent_price" (or "prime_price" if "agent_price" is None) multiplied by field "los" when "accepted"=="yes".
For the example above the expected output would be:
{'sum':11, 'agent_id": 50941}
The sum is the two "accepted" "prime_price" (8+3) times los (1) = 11.
I tried to use $unwind but it only works for a list, not object. Can anyone help on that?
A:
I doubt it is possible with aggregation, yet should be straightforward with mapreduce:
db.collection.mapReduce(
function(){
for(key in this.offer_list) {
if (this.offer_list[key].accepted == 'yes') {
if (this.offer_list[key].agent_price == '') {
emit(this.agent_id, this.los * this.offer_list[key].prime_price);
} else {
emit(this.agent_id, this.los * this.offer_list[key].agent_price);
}
]
}
},
function(agent, values) {
return Array.sum(values);
}
)
For real-life code, I would also add a query option for data sanitation.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.