source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0014169113.txt"
] | Q:
Provides implicit functions for a code block in Scala
Suppose a class defines an implicit function that converts an integer to a String:
class Dollar() {
implicit def currency(num: Int): String = "$" + num.toString
def apply(body: => Unit) {
body
}
}
and we also have a function that prints a number transformed by the implicit function:
def printAmount(num: Int)(implicit currency: Int => String) {
println(currency(num))
}
then we can call the method printAmount() in the constructor of the class Dollar:
val dollar = new Dollar {
printAmount(32) // prints "$32"
}
However, if we want to provide the implicit function for a code block, a compilation error occurs because the implicit value does not applied:
dollar {
printAmount(14) // Error: No implicit view available from Int => String
}
As I know, Groovy has a keyword use for the case like this. Is there any way to provide implicit functions for a certain code block in Scala?
A:
You can change dollar such that it takes a function from a conversion function to Unit.
dollar(f:(Int => String) => Unit) = {
//...
}
Then you can use dollar like this:
dollar ( implicit conversion => {
printAmount(14)
})
|
[
"mathematica.stackexchange",
"0000014581.txt"
] | Q:
How do I construct a "named character" programmatically?
Why am I getting the error
Syntax::sntunc: Unicode longname in the string is unterminated.
from the following?
astroSymbol[name_String] := ToString[ToExpression["\[" <> name <> "]"]] <> "" ;
Is there something I need to do to wrap the escape sequence to avoid this error?
A:
To include a backslash in a string, you need to escape it, like so:
"\\[" <> name <> "]"
|
[
"stackoverflow",
"0044462399.txt"
] | Q:
How to handle DuplicateKeyError in MongoDB (pyMongo)?
Could anybody please tell me how to handle DuplicateKeyError in MongoDB?
I am writing a python script, where I move several docs from two different collections into a third one. There is a small overlap between the two collections due to having a few identical documents (with identical ObjectId). This results in the following:
DuplicateKeyError: E11000 duplicate key error collection: admin.collection_test index: id dup key: { : ObjectId('593a920b529e170d4b8fbf72') }
In order to get rid of the error I use:
try:
do something
except pymongo.errors.DuplicateKeyError:
pass
I expect by using of the "try-except" to move all non-crossing documents to the third collection, but instead the script just peacefully stops running once a first overlap (an already existing document in the collection) appears.
Would appreciate any help a lot!
A:
If you're iterating over the documents, try using continue instead of pass.
for doc in documents:
try:
# insert into new collection
except pymongo.errors.DuplicateKeyError:
# skip document because it already exists in new collection
continue
A:
for doc in documents:
client.update_one({'_id': doc['_id']}, doc, upsert=True)
You can use update_one with upsert=True. This updates doc with new doc if doc exists already otherwise it creates new doc.
|
[
"stackoverflow",
"0057158315.txt"
] | Q:
When I try to use ``` ...``` decorator doesn't work
I am trying to do this :
setMyState(prevState=> {...prevState, name: e.nativeEvent.text });
While the console says src/components/addItem.js: Unexpected token
And it doesn't work :(
While using a js file .. I tried with .jsx too and same error :(.
Also I found an answer here WebStorm error: expression statement is not assignment or call
but it didn't solve my problem since when I run the app now it crashes exactly there ...
A:
If you use an arrow function and want to return an object you need to wrap your object with (). If you don't use, arrow function thinks {} is the body block. So, try using:
setMyState(prevState=> ({...prevState, name: e.nativeEvent.text }));
|
[
"english.stackexchange",
"0000149485.txt"
] | Q:
Single word for someone having a fetish for watching women breastfeed?
My wife was wondering if there were people out there who have a thing for watching women breast feed their kids. I went to google it but nothing really came up (So I'm posting here to look for the right keyword), the only close Wikipedia article was for 'Erotic Lactation', which isn't really what I'm referring to.
A:
Fetish for watching women breastfeed falls under Lactophilia.
|
[
"math.stackexchange",
"0001151581.txt"
] | Q:
Prove that $int(A)=A\setminus bd(A)$
$A$ is a subset of a metric space $M$.
I know I will need to prove $A$ is a subset of $M$. As well as $M$ is a subset of $A$.
So for, $A$ is a subset of $A$: $int(A)$ implies that it is a subset of $A$ itself. Thus if $x$ is in $int(A)$ it must also be in $A$. Not sure if I'm off to right track any help is great
A:
Suppose $ x\in int(A) $. Then there exists an open neighbourhood $ U_{x} $ of $ x $ such that $ x\in U_{x}\subseteq A $.
So we have $ U_{x}\cap A^{c}=\varnothing $.
Now assume that $ x\in bd(A) $.
Then for all neighbourhood $ U $ of $ x $, $ U\cap A\neq \varnothing $ and $ U\cap A^{c}\neq \varnothing $.
But this is a contradiction, since $ U_{x}\cap A^{c}=\varnothing $.
So $ x\notin bd(A) $ and hence $ x\in A\setminus bd(A) $.
That is $ int(A)\subseteq A\setminus bd(A) $.
Now conversely suppose $ y\in A\setminus bd(A) $.
Then $ y\in A $ and $ y\notin bd(A) $.
Then there exist a neighbourhood $ U_{y} $ of $ y $ such that $ U_{y}\cap A^{c}= \varnothing $.
So $ y\in U_{y}\subseteq A $ and hence $ y\in int(A) $.
Therefore $ A\setminus bd(A)\subseteq int(A) $.
Thus $ int(A)= A\setminus bd(A) $. $\square$
|
[
"stackoverflow",
"0028168040.txt"
] | Q:
SQL AND OR query
I am trying to select some messages from our customer service queries, WHERE Mmessage owner is ABC, data are LIKE ABCDEF AND message ... AND where the message is either from Customer to CSservice or from CSservice to Customer.
How can I do that?
SELECT Date, From, To, Data
FROM Ccustomers WITH (NoLock)
WHERE MSGowner = 'ABC' AND Data LIKE '%ABCDEF%' AND
([From] ='Customer' AND [To] = 'CSservice') OR ([From] ='CSservice' AND [To] = 'Customer')
ORDER by Date
A:
SELECT Date, From, To, Data
FROM Ccustomers WITH (NoLock)
WHERE MSGowner = 'ABC'
AND Data LIKE '%ABCDEF%'
AND
(
([From] = 'Customer' AND [To] = 'CSservice') OR
([From] = 'CSservice' AND [To] = 'Customer')
)
ORDER by Date
|
[
"stackoverflow",
"0006781106.txt"
] | Q:
Force axis to use given number of major tick marks in Visiblox chart
When using a LinearAxis for the Y axis in a Visiblox chart, I would like to force the axis to use a given number of major tick marks while still having the toolkit automatically calculate the axis range and tick mark locations. For instance, I may have a primary and secondary Y axis and I want both axes to use the same number of major ticks so that their horizontal gridlines overlap. Is this possible?
A:
There are a couple of options. Firstly you can set the MajorTickInterval to force the distribution of major ticks. Depending on your use-case you may need to look at the actual range of the axis, and divide by the number of ticks you want to get a sensible interval.
The other alternative is to subclass the axis and override the GetMajorTickValues method which is what the axis uses to determine where to place ticks.
A:
If you need to enforce a relationship between the values on your primary and secondary axis, this can be achieved via ElementName binding. For example, you can bind the secondary axis MajorTickInterval to the computed tick interval of the primary axis, ActualMajorTickInterval as follows:
<Grid x:Name="LayoutRoot" Background="White">
<vis:Chart x:Name="chart">
<vis:Chart.YAxis>
<vis:LinearAxis x:Name="primaryAxis"/>
</vis:Chart.YAxis>
<vis:Chart.SecondaryYAxis>
<vis:LinearAxis MajorTickInterval="{Binding ElementName=primaryAxis, Path=ActualMajorTickInterval}"/>
</vis:Chart.SecondaryYAxis>
</vis:Chart>
</Grid>
However, depending ion your data, having the same tick interval for each axis may not cause your major tick gridlines to coincide. In this case, you might want to bind the range alse:
<Grid x:Name="LayoutRoot" Background="White">
<vis:Chart x:Name="chart">
<vis:Chart.YAxis>
<vis:LinearAxis x:Name="primaryAxis"/>
</vis:Chart.YAxis>
<vis:Chart.SecondaryYAxis>
<vis:LinearAxis Range="{Binding ElementName=primaryAxis, Path=ActualRange}"
MajorTickInterval="{Binding ElementName=primaryAxis, Path=ActualMajorTickInterval}"/>
</vis:Chart.SecondaryYAxis>
</vis:Chart>
</Grid>
If you need more complex logic, it might be possible to do this via value converters.
|
[
"stackoverflow",
"0028798538.txt"
] | Q:
Set cookie only when onclick and hide the message
I'm trying to set up a cookie message on a page. What I want is when the cookie does not exist, the message is displayed. And when the user clicks on "I Accept" button, the cookie is set. And that the message is no longer displayed when user returns to the page/website.
But what it does now is setting the cookie immediately when the user visits the we page.
$(document).ready(function() {
var visit=GetCookie("AMIR86");
if (visit==null){
cookiebar();
}
var expire=new Date();
expire=new Date(expire.getTime()+7776000000);
document.cookie="AMIR86=here; expires="+expire;
$('#close-cookies').click(function(){
$('#cookiebar').addClass('close-cookies');
});
});
function GetCookie(name) {
var arg=name+"=";
var arglen=arg.length;
var dclen=document.cookie.length;
var i=0;
while (i<dclen) {
var j=i+arglen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0)
break;
}
return null;
}
function cookiebar() {
$('#cookiebar').addClass('display');
}
And my working jsfiddle: http://goo.gl/61aLuS
A:
This chunk of code sets the cookie. For readability and clean coding practice, move it into its own function.
function setAgreeCookie() {
var expire=new Date();
expire=new Date(expire.getTime()+7776000000);
document.cookie="AMIR86=here; expires="+expire;
}
Then, set up a click handler on your "I agree" button to set the cookie.
$('#close-cookies').click(function(){
setAgreeCookie();
$('#cookiebar').addClass('close-cookies');
});
|
[
"stackoverflow",
"0052148545.txt"
] | Q:
How to initialize Email without hardcoding using sendgrid with java
How can I initialize email in my service class without hardcoding(eg : Email to = new Email("[email protected]"). I use the following code to initialize my email but it returns some error. Help me to fix this. I'm using SendGrid API. Here is my service code:
Email to = new Email();
to.setEmail(emailIDTO.getTO()); //emailIDTO is an object of IDTO class
// IDTO class takes the value from the JSON request body and initializes it to the email object
And the relevant IDTO snippet:
public Email getTo(){
return to;
} // method getTo return the mail id of the recipient.
public Email createTo(EmailIDTO emailIDTO){
to.setName(emailIDTO.getName();
to.setEmail(emailIDTO.getEmail());
return null;
}
Error :
setEmail (java.lang.String) in Email cannot be applied to (com.sendgrid.Email)
A:
Your code is failing because your emailIDTO.getTO() method is returning Email object, which you are trying to assign using method that accepts String parameter. The error is pretty self-explanatory in this case.
You can try one of the following:
Option 1 - set object directly from IDTO:
Email to = emailIDTO.getTO();
Option 2 - extract the string value:
Email to = new Email();
to.setEmail(emailIDTO.getTO().getEmail());
Caution - your IDTO.createTo() method returns null, which may have unexpected consequences. Perhaps you wanted to return to?
|
[
"stackoverflow",
"0015407235.txt"
] | Q:
EditorFor/CheckBoxFor boolean adds data-val-required attribute to HTML without required attribute being added to model
My model class has a bool property without a Required attribute:
public class Test
{
public bool TestBool1 { get; set; }
}
Then in my razor view I am using EditorFor (Same thing happens with CheckBoxFor as well):
<div>
@Html.LabelFor(m => m.TestBool1)
@Html.EditorFor(m => m.TestBool1)
</div>
This results in the following HTML:
<div>
<label for="TestBool1">TestBool1</label>
<input class="check-box" data-val="true" data-val-required="The TestBool1 field is required." id="TestBool1" name="TestBool1" type="checkbox" value="true">
<input name="TestBool1" type="hidden" value="false">
</div>
Where is the data-val-required html attribute coming from?
Is there a way to stop it doing this without using @Html.CheckBox("TestBool1", Model.TestBool1) and setting the type to bool??
A:
from this answer Data annotations, why does boolean prop.IsRequired always equal true
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Add this to your application_start. By default MVC adds [Required] to non-nullable value types (because you can't convert null into a bool, it must be a bool?)
you can prevent it happening, but as you will always send the bool (true or false) I usually leave it
|
[
"stackoverflow",
"0020659227.txt"
] | Q:
Configure the isolation level to allow ReadUncommited while updating data
I begin a transaction with SqlConnection.BeginTransaction() and I do a DELETE and some INSERTs. There is any configuration I can do on the isolation level to allow any query to read the data on a "dirty way" during the transaction?
Basically I want to prevent locks while I update the data. The problem is; I can't control the SELECTs. If I define a ReadUncommited isolation level on my transaction will the external querys have rights to read the data without waiting or is required to define it on this querys?
For example:
try
{
connection.Open();
transaction=connection.BeginTransaction(IsolationLevel.ReadUncommited);
// DELETE
foreach (int i in fibarray)
{
// INSERTS
}
transaction.Commit();
}
catch (Exception ex)
{
if (transaction.Connection != null)
transaction.Rollback();
}
Meanwhile, the SELECTS on another machine I have not the access.
A:
Each connection/session establishes for itself what level of dirtiness it's willing to put up with. There's no way for a different connection to suddenly force a connection to see dirtier data (or, conversely, to be more strict)
The SELECTs have all of the control over their own locking/blocking behaviour. And UPDATEs always have to apply some exclusive locks to complete successfully. So if you cannot change the SELECTs, then you can't overcome your current situation.
|
[
"stackoverflow",
"0001006653.txt"
] | Q:
Extending System.Data.Linq.DataContext
I have a class reflecting my dbml file which extends DataContext, but for some strange reason it's telling me
System.Data.Linq.DataContext' does not contain a constructor that takes '0' arguments"
I've followed various tutorials on this and haven't encountered this problem, and VS doesn't seem to able to fix it.
Here's my implementation
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Text;
using IntranetMvcAreas.Areas.Accounts.Models;
namespace IntranetMvcAreas
{
partial class ContractsControlDataContext : DataContext
{
[FunctionAttribute(Name="dbo.procCC_Contract_Select")]
[ResultType(typeof(Contract))]
[ResultType(typeof(ContractCostCentre))]
[ResultType(typeof(tblCC_Contract_Data_Terminal))]
[ResultType(typeof(tblCC_CDT_Data_Service))]
[ResultType(typeof(tblCC_Data_Service))]
public IMultipleResults procCC_Contract_Select(
[Parameter(Name = "ContractID", DbType = "Int")] System.Nullable<int> ContractID,
[Parameter(Name = "ResponsibilityKey", DbType = "Int")] System.Nullable<int> ResponsibilityKey,
[Parameter(Name = "ExpenseType", DbType = "Char")] System.Nullable<char> ExpenseType,
[Parameter(Name = "SupplierID", DbType = "Int")] System.Nullable<int> SupplierID)
{
IExecuteResult result = this.ExecuteMethodCall(this, (MethodInfo)(MethodInfo.GetCurrentMethod()), ContractID, ResponsibilityKey, ExpenseType, SupplierID);
return (IMultipleResults)result.ReturnValue;
}
}
}
And it's ContractsControlDataContext that's pointed at as the problem
(btw, this has no relation to a very recent post I made, it's just I'm working on the same thing)
EDIT
It's probably worth clarifying this, so please read very carefully.
If you do not extend DataContext in the partial class, then ExecuteMethodCall isn't accessible.
'Intranet.ContractsControlDataContext' does not contain a definition for 'ExecuteMethodCall' and no extension method 'ExecuteMethodCall' accepting a first argument of type 'Intranet.ContractsControlDataContext' could be found (are you missing a using directive or an assembly reference?)
Maybe I'm missing something incredibly stupid?
SOLVED
I think perhaps Visual Studio struggled here, but I've relied entirely on auto-generated code. When right clicking on the database modeling language design view and hitting "View Code" it automagically creates a partial class for you within a specific namespace, however, this namespace was wrong. If someone could clarify this for me I would be most appreciative.
The .designer.cs file sits in namespace Intranet.Areas.Accounts.Models, however the .cs file (partial class generated for the .designer.cs file by Visual Studio) was in namespace Intranet. Easy to spot for someone more experienced in this area than me.
The real problem now is, who's answer do I mark as correct? Because many of you contributed to finding this issue.
A:
The object DataContext for linq does not have an empty constructor. Since it does not have an empty constructor you must pass one of the items it is excepting to the base.
From the MetaData for the DataContext.
// Summary:
// Initializes a new instance of the System.Data.Linq.DataContext class by referencing
// the connection used by the .NET Framework.
//
// Parameters:
// connection:
// The connection used by the .NET Framework.
public DataContext(IDbConnection connection);
//
// Summary:
// Initializes a new instance of the System.Data.Linq.DataContext class by referencing
// a file source.
//
// Parameters:
// fileOrServerOrConnection:
// This argument can be any one of the following: The name of a file where a
// SQL Server Express database resides. The name of a server where a database
// is present. In this case the provider uses the default database for a user.
// A complete connection string. LINQ to SQL just passes the string to the
// provider without modification.
public DataContext(string fileOrServerOrConnection);
//
// Summary:
// Initializes a new instance of the System.Data.Linq.DataContext class by referencing
// a connection and a mapping source.
//
// Parameters:
// connection:
// The connection used by the .NET Framework.
//
// mapping:
// The System.Data.Linq.Mapping.MappingSource.
public DataContext(IDbConnection connection, MappingSource mapping);
//
// Summary:
// Initializes a new instance of the System.Data.Linq.DataContext class by referencing
// a file source and a mapping source.
//
// Parameters:
// fileOrServerOrConnection:
// This argument can be any one of the following: The name of a file where a
// SQL Server Express database resides. The name of a server where a database
// is present. In this case the provider uses the default database for a user.
// A complete connection string. LINQ to SQL just passes the string to the
// provider without modification.
//
// mapping:
// The System.Data.Linq.Mapping.MappingSource.
public DataContext(string fileOrServerOrConnection, MappingSource mapping);
Something as simple as this would work. Any class that inherits from the DataConext must pass to the base constructor at least one of the types it is excepting.
public class SomeClass : System.Data.Linq.DataContext
{
public SomeClass(string connectionString)
:base(connectionString)
{
}
}
A:
I'm assuming that the namespace and (data-context) type name are correct... double check that first.
It sounds to me like the codegen has failed, and so you only have your half of the data-context (not the half that the IDE is meant to provide). There is a known bug in LINQ-to-SQL where this can fail if (as in your case) the using declarations are above the namespace. No, I am not joking. Try changing the code:
namespace IntranetMvcAreas
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Text;
using IntranetMvcAreas.Areas.Accounts.Models;
// the rest of your code
Now go into the designer, tweak something (for example, change the name of a property and change it back again) and hit save (this forces the codegen). Now see if it works.
|
[
"unix.stackexchange",
"0000337768.txt"
] | Q:
How to make clean commits with etckeeper?
I would like to make clean commits with etckeeper. Here is what happens:
1) Check the status of the repository :
git status
On branch master
nothing to commit, working directory clean
2) Modify a configuration file :
vi myfile.conf
3) Add it to the index
git add myfile.conf
4) Make a commit
git commit -m"Add this ... to myfile.conf"
5) Observe the commit :
git log -p -1
[...]
maybe chmod 0644 'magic.mime'
-maybe chmod 0644 'mail.rc'
maybe chmod 0644 'mailcap'
maybe chmod 0644 'mailcap.order'
maybe chmod 0644 'mailname'
+maybe chmod 0644 'mail.rc'
maybe chmod 0644 'manpath.config'
maybe chmod 0644 'matplotlibrc'
maybe chmod 0755 'maven'
[...]
(My modification to myfile.conf)
[...]
I understand that etckeeper need to keep track of file permissions in the git repository even if I don't understand the purpose of this reordering. I would like to separate in distinct commits all modifications related to the ./etckeeper directory and modifications related to the content of the configuration files.
How to do it?
A:
Etckeeper sets up a git hook to commit the file containing metadata information whenever metadata changes. This is usually the right thing. If you really want to bypass the commit hook, you can run git commit --no-verify.
The metadata file is sorted by file name. The sorting order depends on the ambient locale. In your case, the file appears to have been sorted in a pure byte lexicographic order (with mail.rc before mailcap since . is before c in ASCII), but you are now running git in a locale where sorting is done in a somewhat human-friendly way, with punctuation ignored except as a last resort (probably a UTF-8 locale) (with mail.rc after mailname since n is before r). Run LC_ALL=C git commit to do the sorting in pure lexicographic order. It would make sence to add export LC_COLLATE=C to /etc/etckeeper/etckeeper.conf to force a consistent sorting order.
|
[
"stackoverflow",
"0001828237.txt"
] | Q:
check if jquery has been loaded, then load it if false
Does anyone know how to check if jquery has been loaded (with javascript) then load it if it hasnt been loaded.
something like
if(!jQuery) {
//load jquery file
}
A:
Maybe something like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
A:
Avoid using "if (!jQuery)" since IE will return the error: jQuery is 'undefined'
Instead use: if (typeof jQuery == 'undefined')
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
You'll also need to check if the JQuery has loaded after appending it to the header. Otherwise you'll have to wait for the window.onload event, which is slower if the page has images. Here's a sample script which checks if the JQuery file has loaded, since you won't have the convenience of being able to use $(document).ready(function...
http://neighborhood.org/core/sample/jquery/append-to-head.htm
A:
Method 1:
if (window.jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
Method 2:
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
} else {
// jQuery is loaded
}
If jquery.js file is not loaded, we can force load it like so:
if (!window.jQuery) {
var jq = document.createElement('script'); jq.type = 'text/javascript';
// Path to jquery.js file, eg. Google hosted version
jq.src = '/path-to-your/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
|
[
"stackoverflow",
"0011096947.txt"
] | Q:
Optional argument in Drupal hook_menu implementation
How can I set one of the page arguments in my drupal menu item as an optional page argument?
I have
$items['activities_list/%/%']=array(
'title callback' => 'activities_list_title',
'title arguments' =>array(1),
'description' =>'All the Indicators divided by Coutry',
'page callback' => 'activities_list',
'access arguments' => array('access ppi'),
'page arguments' => array(1,2)
);
If I call activities_list/76 for example without a third argument I will receive a page not found error. How Can I set the Third parameter as an optional one?
Thanks!
A:
It's easier than you think :). Don't set any arguments in your path and just pass them to your "page callback" function.
$items['activities_list']=array(
'title callback' => 'activities_list_title',
'description' =>'All the Indicators divided by Coutry',
'page callback' => 'activities_list',
'access arguments' => array('access ppi'),
);
And the page callback function would look like this:
function activities_list($arg1, $arg2)
{
// Your code goes here...
drupal_set_title(activities_list_title($arg1, $arg2));
}
You can alter the page title using the following code. (Not tested, kindly let me know if it worked):
function activities_list_title($arg_1, $arg_2)
{
$title = "";
// Your code goes here
return $title;
}
Hope this helps... Muhammad.
A:
I don't think you can. If you did this instead with only one wildcard:
$items['activities_list/%']=array(
'title callback' => 'activities_list_title',
'title arguments' =>array(1),
'description' =>'All the Indicators divided by Coutry',
'page callback' => 'activities_list',
'access arguments' => array('access ppi'),
'page arguments' => array(1,2)
);
This will then work for a URL like activities_list/foo, but if you then had a URL like activities_list/foo/bar you can still get the value of bar in the page callback as it is still passed to that function by 'page arguments' => array(1,2).
Or alternatively you can call it by using arg(2) in your page callback.
|
[
"stackoverflow",
"0017684657.txt"
] | Q:
Get current sound volume windows 8
The result of the sound level is always 0, wether i have the sound muted or at max volume.
What is wrong ?
[DllImport("winmm.dll")]
private static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
public int GetCurrentSoundValue()
{
uint currentVolume;
int result = waveOutGetVolume(IntPtr.Zero, out currentVolume);
return result;
}
A:
Ever since Windows 7/Vista, microsoft changed the permissions to modify low level audio. Instead you have to use CoreAudio API. I can't provide too much info as I haven't really played around with it, but here's a link: CoreAudio API
Good luck!
|
[
"stackoverflow",
"0002923586.txt"
] | Q:
what is the best and easiest to draw a multi bar chart in php
i want to display the results of students scores in a multi-vertical bar chart (red bar for correct , green bar for false) for each question,,
i already tried Google chart, but it gives me result in this way:link text
note: the bars that reached the top , should not be at top ,, only because they have the highest value (75%), Google chart makes it at top which i don't want..
any suggestions about how to draw simple vertical bar chart with php
A:
http://www.ebrueggeman.com/phpgraphlib/
http://jpgraph.net/
|
[
"stackoverflow",
"0051606363.txt"
] | Q:
Laravel Echo Server giving Error Unhandled error event: Error: connect ECONNREFUSED
i am trying to install Laravel Echo Server on Laravel 5.5 with the help of thie Article
https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b
All things is going right but when i
laravel-echo-server start
Error comes with
[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
i install laravel 5.6 but still i face the same error
Thanks in advance who can guide me how can i handle this error
A:
Seems like Redis is not installed or the Redis server is not running.
Download and install the server from https://redis.io/
And then run the service with "redis-server".
After that you can smoothly run "laravel-echo-server start"
|
[
"gardening.stackexchange",
"0000025267.txt"
] | Q:
Diatomaceous earth: food grade or not?
I have been told that Diatomaceous earth will help with the many slugs that enjoy the buffet that is my garden, since the micro-fossils irritate their slimy bodies. But will it help with other insects and caterpillars, especially gypsy moths? I purchased a bag that says "food grade" but I don't know if it is as effective as non-food grade DE. Any experience in this area would help. This is turning out to be an expensive organic garden this year!
A:
I do not use this in my gardens. I only use it sparingly, in certain areas, for serious infestations.
Slugs love beer. I pour a bit of beer in a shallow bowl, and they crawl in at night and drunkenly drown. (Recycled cat food or tuna tins work well, because you can just throw out the whole ugly mess.) If you don't drink beer, there are slug baits for sale. That being said...
Yes. Food grade Diatomaceous Earth will nonselectively kill all insects and caterpillars (both bad and good). But, it has to be dry in order to work. Even a slight dew will make it ineffective. It does not harm the earthworms under the soil when they eat it.
Do not use the pool grade stuff! It is only meant for use in swimming pool filters, has been linked to health risks and might kill your plants. (In fact, it's recommended that you avoid inhaling even the food grade kind, as it can cause respiratory distress in some people. I just avoid getting it in my eyes.) You are probably (harmlessly) eating some food grade Diatomaceous Earth every day, because grain and vegetables, etc., are stored in it, in the warehouses.
I put a small amount in a "puff" bottle so I can apply it very selectively, and keep the bag sealed against moisture. I bought a plastic bottle for $1 (the type use for ketchup or salad dressing) and that works really well. Some people use a shaker bottle for large areas.
While it supposedly is effective on gypsy moth caterpillars, unfortunately I have been unable to find any sites dealing directly with that ugly problem for advice.
This site is very informative about food grade Diatomaceous Earth. http://www.richsoil.com/diatomaceous-earth.jsp
This one discusses the pros and cons (like concerns about bees), and has suggestions on how to apply it to a garden. http://www.theprairiehomestead.com/2015/07/diatomaceous-earth-garden.html
This site discusses avoiding putting it on the flowers to try and protect the pollinators. http://homeguides.sfgate.com/diatomaceous-earth-garden-pests-84812.html
Used to control slugs https://www.diatomaceousearth.com/natural-slug-control/
|
[
"meta.stackexchange",
"0000133457.txt"
] | Q:
Why do I require 15 reputation to just up-vote something?
I've been lurking Stack Overflow whenever I had a problem for at least the last 2+ years. More times than not, I find my solution (or cobble one together) before I get frustrated enough to have the innernets help me with my specific custom problem. Many times, the only commentary I would be able to add would be "thanks!" which really only wastes bits and bandwidth.
I understand implementing measures to keep the bots and SEO kids out, but sometimes it's a PITA to start participating in a community.
If you couldn't extract my question from the above rant (or title), this might be a little more clear:
Why do I require 15 reps to just up-vote something?
I feel like it's kinda silly.
Additionally, I noticed the quote off to the left:
We prefer questions that can be answered, not just discussed.
yet I have looked around here and haven't been able to find any justifiable explanation.
A:
Basically, voting is an integral part of the SE mechanism. One needs to know the significance of voting before one votes--and newbies don't know the significance.
Additionally, allowing everyone to vote will lead to (more) gaming of the system via sockpuppets and the like.
15 rep is easy to get. One good question/answer is enough. Why whine about it?
I understand implementing measures to keep the bots and SOA kids out
Any other ideas to do this?
but sometimes its a PITA to start participating in a community.
Initially, you accumulate privileges pretty quickly if you write a few good posts. Additionally, as @animuson said above, once you reach 200 rep on a site, you get +100 on every site, which removes most newbie barriers.
Many times, the only commentary I would be able to add would be "thanks!" which really only wastes bits and bandwidth.
You can use this:
It doesn't notify the user{*}, but it's a compromise.
*It doesn't act as a vote, but it is recorded. Anon-"voting" trends are accessible to mods.
|
[
"stackoverflow",
"0013042008.txt"
] | Q:
java.util.NoSuchElementException - Scanner reading user input
I'm new to using Java, but I have some previous experience with C#. The issue I'm having comes with reading user input from console.
I'm running into the "java.util.NoSuchElementException" error with this portion of code:
payment = sc.next(); // PromptCustomerPayment function
I have two functions that get user input:
PromptCustomerQty
PromptCustomerPayment
If I don't call PromptCustomerQty then I don't get this error, which leads me to believe I am doing something wrong with scanner. Below is my full code sample. I appreciate any help.
public static void main (String[] args) {
// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");
// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99);
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);
// Define internal variables
// ## DONT CHANGE
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output
// Add objects to list
ProductList.add(Computer);
ProductList.add(Monitor);
ProductList.add(Printer);
// Ask users for quantities
PromptCustomerQty(customer, ProductList);
// Ask user for payment method
PromptCustomerPayment(customer);
// Create the header
PrintHeader(customer, formatString);
// Create Body
PrintBody(ProductList, formatString);
}
public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList) {
// Initiate a Scanner
Scanner scan = new Scanner(System.in);
// **** VARIABLES ****
int qty = 0;
// Greet Customer
System.out.println("Hello " + customer.getName());
// Loop through each item and ask for qty desired
for (Product p : ProductList) {
do {
// Ask user for qty
System.out.println("How many would you like for product: " + p.name);
System.out.print("> ");
// Get input and set qty for the object
qty = scan.nextInt();
}
while (qty < 0); // Validation
p.setQty(qty); // Set qty for object
qty = 0; // Reset count
}
// Cleanup
scan.close();
}
public static void PromptCustomerPayment (Customer customer) {
// Initiate Scanner
Scanner sc = new Scanner(System.in);
// Variables
String payment = "";
// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");
payment = sc.next();
} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));
// Check/set result
if (payment.toLowerCase() == "yes") {
customer.setPaidInFull(true);
}
else {
customer.setPaidInFull(false);
}
// Cleanup
sc.close();
}
A:
This has really puzzled me for a while but this is what I found in the end.
When you call, sc.close() in first method, it not only closes your scanner but closes your System.in input stream as well. You can verify it by printing its status at very top of the second method as :
System.out.println(System.in.available());
So, now when you re-instantiate, Scanner in second method, it doesn't find any open System.in stream and hence the exception.
I doubt if there is any way out to reopen System.in because:
public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**
The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:
main method related code block:
Scanner scanner = new Scanner(System.in);
// Ask users for quantities
PromptCustomerQty(customer, ProductList, scanner );
// Ask user for payment method
PromptCustomerPayment(customer, scanner );
//close the scanner
scanner.close();
Your Methods:
public static void PromptCustomerQty(Customer customer,
ArrayList<Product> ProductList, Scanner scanner) {
// no more scanner instantiation
...
// no more scanner close
}
public static void PromptCustomerPayment (Customer customer, Scanner sc) {
// no more scanner instantiation
...
// no more scanner close
}
Hope this gives you some insight about the failure and possible resolution.
A:
The problem is
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
Thus scan.close() closes System.in.
To fix it you can make
Scanner scan static
and do not close it in PromptCustomerQty. Code below works.
public static void main (String[] args) {
// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");
// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99);
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);
// Define internal variables
// ## DONT CHANGE
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output
// Add objects to list
ProductList.add(Computer);
ProductList.add(Monitor);
ProductList.add(Printer);
// Ask users for quantities
PromptCustomerQty(customer, ProductList);
// Ask user for payment method
PromptCustomerPayment(customer);
// Create the header
PrintHeader(customer, formatString);
// Create Body
PrintBody(ProductList, formatString);
}
static Scanner scan;
public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList) {
// Initiate a Scanner
scan = new Scanner(System.in);
// **** VARIABLES ****
int qty = 0;
// Greet Customer
System.out.println("Hello " + customer.getName());
// Loop through each item and ask for qty desired
for (Product p : ProductList) {
do {
// Ask user for qty
System.out.println("How many would you like for product: " + p.name);
System.out.print("> ");
// Get input and set qty for the object
qty = scan.nextInt();
}
while (qty < 0); // Validation
p.setQty(qty); // Set qty for object
qty = 0; // Reset count
}
// Cleanup
}
public static void PromptCustomerPayment (Customer customer) {
// Variables
String payment = "";
// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");
payment = scan.next();
} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));
// Check/set result
if (payment.toLowerCase() == "yes") {
customer.setPaidInFull(true);
}
else {
customer.setPaidInFull(false);
}
}
On a side note, you shouldn't use == for String comparision, use .equals instead.
|
[
"math.stackexchange",
"0002789536.txt"
] | Q:
The Galois group of a specialized polynomial
Let $P(t,x)\in\mathbb Q[t,x]$ be irreducible with Galois group $G$ over $\mathbb Q(t)$. It is known that if $t_0\in\mathbb Q$ is such that $P(t_0,x)$ is separable, then the Galois group of this specialized polynomial is isomorphic to a subgroup of $G$. Is this true also if $P(t_0,x)$ is not separable? I haven't been able to find a proof or a counterexample.
A:
There's something a little misleading about the formulation of this question. Given such a polynomial $P(t,x)$, one has not only a Galois group $G$, but a natural action of $G$ on $d = \mathrm{deg}(P)$ points well defined up to conjugation. Given a separable specialization $P(t_0,x)$, it is true that the Galois group $H$ of this specialization is isomorphic (abstractly) to a subgroup of $G$, but it is also true that there is an inclusion $H \rightarrow G$ such that the action of $H$ on the $d$ roots of $P(t_0,x)$ is the restriction of the given permutation representation of $G$. When $P(t_0,x)$ is not separable, the Galois group $H$ no longer has any obvious action on $d$ points, and so one must settle for your weaker formulation that there merely exists an abstract inclusion from $H$ to $G$.
Still, the answer to this weaker formulation is still no. The easiest way to construct a counterexample is to consider isotrivial covers. Let $K/\mathbf{Q}$ be any field of degree $d$ with Galois group $G$. Let $\theta \in K$ be a primitive element. Let $\alpha \in K$ be any element at all. Now consider the minimal polynomial of $t \theta + \alpha$ over $\mathbf{Q}(t)$. This will define a degree $d$ polynomial $P(t,x)$. For a generic specialization $t = t_0 \in \mathbf{Q}$, the element $t_0 \theta + \alpha \in K$ will also be a primitive root, and so the Galois group will be $G$. But the specialization at $t = 0$ will have $\alpha$ as a root. In fact, the corresponding polynomial will be a power of the minimal polynomial of $\alpha$. So your claim is now the following: if $H$ is the Galois group of the splitting field of the minimal polynomial of $\alpha$, then $H$ is a subgroup of $G$. But this is absurd --- by Galois theory, $H$ is transparently a quotient of $G$. So it suffices to consider an example of a pair $(G,H)$ with $H$ a quotient of $G$ so that $H$ is not a subgroup of $G$. This doesn't happen for groups $G$ of extremely low order which perhaps indicate why you failed to find a counterexample. Perhaps the easiest example is $G = \mathrm{GL}_2(\mathbf{F}_3)$, which acts faithfully on $8$ points, and is a central extension of $\mathrm{PGL}_2(\mathbf{F}_3) = S_4$. If $S_4$ was a subgroup of $G$, it would have to be normal, but then $S_4$ has no automorphisms, so since $Z(S_4)$ is trivial this would force $G$ to be $S_4 \times \mathbf{Z}/2\mathbf{Z}$, which it is not. Thus the answer is no.
You can also easily write down an explicit example if you like. First write down a $G$-extension (say coming from the $y$-coordinate of the $3$-torsion of the elliptic curve $y^2 = x^3 + x + 1$)
$$K = \mathbf{Q}[\theta]/(961 - 558\theta^4 - 216 \theta^6 - 27 \theta^8),$$
which has Galois closure with Galois group $G = \mathrm{GL}_2(\mathbf{F}_3)$,
and then let $\alpha = \theta^2$, whose Galois closure has Galois group $S_4$. Then let $P(t,x)$ be the minimal polynomial of $\alpha + t \theta$, which is:
$$923521 - 536238*t^4 - 207576*t^6 - 25947*t^8 - 2144952*t^2*x - 1245456*t^4*x -
207576*t^6*x - 1072476*x^2 - 1868184*t^2*x^2 - 518940*t^4*x^2 - 415152*x^3 -
415152*t^2*x^3 + 259470*x^4 + 120528*t^2*x^4 + 15066*t^4*x^4 + 241056*x^5 +
60264*t^2*x^5 + 76788*x^6 + 5832*t^2*x^6 + 11664*x^7 + 729*x^8$$
Then $P(t,x)$ has Galois group $G$ but $P(0,x) = (27x^4 + 216x^3 + 558x^2 - 961)^2$ has Galois group $S_4$.
|
[
"stackoverflow",
"0045330058.txt"
] | Q:
Vaadin Grid how to wrap long text in columns
I have a Vaadin grid with 7 columns:
Grid grid = new Grid<>();
grid.setSizeFull();
grid.addColumn(User::getUserName).setCaption("Name").setExpandRatio(2);
grid.addColumn(User::getLastName).setCaption("Last Name").setExpandRatio(1);
grid.addColumn(User::getAge).setCaption("Age").setExpandRatio(2);
grid.addColumn(User::getWork).setCaption("Work").setExpandRatio(1);
grid.addColumn(User::getJobTitle).setCaption("Job Title").setExpandRatio(1);
grid.addColumn(User::getSalary).setCaption("Salary").setExpandRatio(1);
grid.addColumn(User::getOther).setCaption("Other").setExpandRatio(1);
What I need is to set columns width in a way - that all 7 will have be shown on a screen.
With my code now it works in a way that if text content of any column cell is very long - the last columns are not shown on the screen and screen must be scrolled horizontally.
I tried to use method setWidth() and as it takes value in pixels the grid view may differ on various browsers and screens.
What I need is to be sure that my grid looks the same way on different screens and with different cell values.
A:
Recently I had the same situation, this was my solution:
Grid configuration
Grid<Item> gridItem = new Grid<>();
gridItem.setRowHeight(50.0);
Column configuration
gridItem.addComponentColumn(item -> {
Label label = new Label();
label.setValue(item.getText());
label.setWidthUndefined();
label.setStyleName(ValoTheme.LAYOUT_HORIZONTAL_WRAPPING);
return label;
})
.setCaption("Item")
.setWidth(380.0);
Result:
|
[
"stackoverflow",
"0014201645.txt"
] | Q:
C Struct Clarification
I was reading through the aircrack-ng source code and noticed many different uses of struct.
For example:
struct option {...} opt;
typedef struct {...} vote;
I thought that the general format of struct was
struct var {...};
or
typedef struct var {...} foo;
What is the purpose of opt and how come vote doesn't have type defined?
A:
typedef creates a type alias. With:
typedef struct { /* ... */ } vote;
We create an anonym structure, from which vote is an alias.
struct option { /* ... */ } opt;
It declares the type struct option, and a variable opt of type struct option.
|
[
"stackoverflow",
"0003482887.txt"
] | Q:
what would make the "this" clause different?
I have the following code:
CustomerService service;
public CustomerService Service
{
get
{
if (this.service == null)
{
this.service = new CustomerService();
}
return this.service;
}
}
public DataTable GetCustomers()
{
return this.Service.GetCustomers();
}
Now the question is: if I wrote the above method as follow (without "this"), it's giving me an error : instance is not reference to an object.
public DataTable GetCustomers()
{
return Service.GetCustomers(); // this will spell the error "instance is not reference to an object"
}
Does anyone know? also it only happens while running via IIS and not from casini web server (VS 2010).
A:
The presence or absence of this cannot explain the error you are witnessing. In this situation they mean exactly the same thing and will compile to the same IL code. Check the assembly using .NET Reflector to verify this if you wish. The error is occurring at random, probably due to a race condition.
One thing I can immediately see is that if you are running this code from multiple threads then it looks like you have a race condition here:
if (this.service == null)
{
this.service = new CustomerService();
}
return this.service;
In the multithreaded case you would need to lock otherwise you could get two CustomerService objects. I'm not sure if this explains your error, but it certainly could create confusion. Race conditions can occur in one environment but not in another as the frequency of the error can depend on the type of the hardware and on what other processes are running on the server.
You may also have other race conditions in the code you haven't posted. Don't use this lazy initialization technique without locking unless you are sure that you have only one thread.
|
[
"stackoverflow",
"0058337468.txt"
] | Q:
undefined method `match?' for true:TrueClass (NoMethodError)
I am trying to return a list/array of values from a range of (100..1000) that match the following criteria:
3 digit value
All the digits in each value are unique.
$global_range = Array (100..999)
$fun = []
def listOfFunPossibilities
# FUN values should meet the criteria below:
# 1. 3 digit value
# 2. All are unique
$global_range.each do |i|
if (!(/([0-9]).*?\1/)).match?(i)
$fun.push(i)
end
end
return $fun
end
listOfFunPossibilities()
A:
You apply negation ! too early:
if (!(/([0-9]).*?\1/)).match?(i)
so you first negate a regex (that is true for some reason) and then you try to call match on true value
Use instead:
if !(/([0-9]).*?\1/.match?(i))
or even
if !/([0-9]).*?\1/.match?(i)
|
[
"math.stackexchange",
"0003265143.txt"
] | Q:
A line is specified by two parameters (the two independent ratios $\{a : b : c \}$)
My projective geometry textbook says the following:
Degrees of freedom (dof). It is clear that in order to specify a point two values must be provided, namely its $x$- and $y$-coordinates. In a similar manner a line is specified by two parameters (the two independent ratios $\{a : b : c \}$) and so has two degrees of freedom.
The author has not defined "independent" in "independent ratios". What makes these ratios "independent"? In what sense are they "independent"? For instance, let's say we have $\dfrac{a}{b}$ and $\dfrac{c}{b}$; how are these "independent" when they have $b$ in common?
Thank you.
A:
Pick any two numbers at all -- call them $p$ and $q$. For example, you might like to choose $p = 3/4$ and $q = 19$. The numbers are independent in the sense that choosing one number imposes no restrictions whatsoever on the choice of the other number.
Now (to take your example) it is always possible to find three numbers $a, b, c$ with $\frac ab = p$ and $\frac cb = q$. For example, with $ p = 3/4$ and $q = 19$ as above, we could choose $a = 3, b = 4$ and $c = 76$. This is not the only possible choice of $a, b, c$, however, we could also choose $a = 6, b = 8, c = 152$, or $a = \frac 32, b = 2, c = 38$. In any of these choices, we would still have $\frac ab = p$ and $\frac cb = q$.
What the excerpt you quoted is trying to say is that regardless of which specific choices of $a, b, c$ we make, we end up with the same line. The triplets
$$[3 : 4 : 76]$$
$$[6 : 8 : 152]$$
$$\left[\frac 32 : 2 : 38\right]$$
all determine the same line.
Remember, just because you have chosen the ratio $\frac ab = \frac 34$ does not mean you have chosen $a$ and $b$!
|
[
"physics.stackexchange",
"0000185668.txt"
] | Q:
Franck-Hertz experiment what transition takes place?
For the Franck-Hertz experiment there is a voltage drop at $4.9\rm\,V$. What transition does this represent in the mercury? Looking at the energy levels it seems to be from the ground to the 2nd excited state. But would this state not be occupied by other electrons? Any references would also be great.
A:
According to a list of levels from NIST, the ground state for mercury has quantum numbers $^1S_0$ (with the electron in the 6th shell). I usually have to look up how to read those symbols: the $^1$ tells you it's a spin singlet, the $S$ tells you that the orbital angular momentum $L=0$, and the $_0$ tells you the value of the total angular momentum quantum number $J$. The first excited states are a $^3P$ triplet (spin triplet, $L=1$) with
\begin{align}
\begin{array}{cc}
J & \text{Wavenumber }\mathrm{(cm^{-1})} & \text{Energy (eV)} \\
\hline
0 & 37\,600 & 4.66
\\
1 & 39\,400 & 4.88
\\
2 & 44\,000 & 5.45
\end{array}
\end{align}
The selection rules for atomic transitions forbid transitions where $J$ goes from zero to zero.
In photon-mediated transitions this is pretty easy to understand: the photon must carry away one unit of angular momentum. (You can have transitions with $\Delta J=0$ for nonzero $J$; in that case you can imagine that the orientation $m_J$ of the atom's spin must change.) Apparently the same rules apply to the collisional transitions seen in the Franck-Hertz experiment — otherwise you could excited the $^3P_0$ first excited state and the energy involved would be $4.7\rm\,V$. Very interesting observation!
In your question you ask,
would this state not be occupied by other electrons?
Here the answer is no. In that same list of levels you can see that the ground state configuration is $5d^{10}({}^1S)6s^2$, while the first excited states have $5d^{10}({}^1S)6s6p$ (on top of a xenon-like core of 54 inert electrons).
|
[
"stackoverflow",
"0052172835.txt"
] | Q:
Run docker container from Jenkins pipeline
I currently run a Jenkins instance inside a Docker container. I've been doing some experimenting with Jenkins and their pipelines. I managed to make my Maven app build successful using a Jenkinsfile.
Right now I am trying to automatically deploy the app I built to a docker container that's a sibling to the Jenkins container. I did already mount the /var/run/docker.sock so I have access to the parent docker. But right now I can't seem to find any good information to guide me through the next part, which is modifying the Jenkinsfile to deploy my app in a new container.
How would I go over and run my Maven app inside a sibling docker container?
A:
It might be more appropriate to spin up a slave node (a physical or virtual box) and then run something in there with docker.
If you check your instance URL: https://jenkins.address/job/myjob/pipeline-syntax/
You will find more information about what are the commands you need for this.
Anyway best way to do this is to actually create a dockerfile and as a step copy the artifact in it, push the image to a registry and then find somewhere to deploy the just built image
|
[
"stackoverflow",
"0005927122.txt"
] | Q:
Images and animated transformation
For images static transformations it is the AForge framework developed, but what to use if I need dynamic (animated) transormation?
For example: I have a picture and I need to make some its part to become brighter, not instantly but with animation, from current state to expected value for some period of time.
A:
If anyone is interested - I found 2 solutions:
Modify in the runtime and swap images
(The one I've chosen) Move to WPF
|
[
"stackoverflow",
"0021399483.txt"
] | Q:
PHP server side timer
I need to make a page that has a timer counting down. I want the timer to be server side, meaning that when ever a user opens the page the counter will always be at the same time for all users. When the timer hits zero I need to be able to run another script, that does some stuff along with resetting the timer.
How would I be able to make something like this with php?
A:
Judging from "when ever a user opens the page" there should not be an auto-update mechanism of the page? If this is not what you meant, look into AJAX (as mentioned in the comments) or more simply the HTML META refresh. Alternatively, use PHP and the header()
http://de2.php.net/manual/en/function.header.php
method, described also here:
Refresh a page using PHP
For the counter itself, you would need to save the end date (e.g. a database or a file) and then compare the current timestamp with the saved value.
Lets assume there is a file in the folder of your script containing a unix timestamp, you could do the following:
<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;
if($difference <= 0)
{
echo 'time is up, BOOOOOOM';
// execute your function here
// reset timer by writing new timestamp into file
file_put_contents($timestamp_file, time()+$timer);
}
else
{
echo $difference.'s left...';
}
?>
You can use http://www.unixtimestamp.com/index.php to get familiar with the Unix Timestamp.
There are many ways that lead to rome, this is just one of the simple ones.
|
[
"stackoverflow",
"0031380876.txt"
] | Q:
Angular .ng-hide-remove animation doesn't work
I have this CSS:
#platinumHeader.ng-hide-remove {
-webkit-animation: fadeInDown 0.5s!important;
-moz-animation: fadeInDown 0.5s!important;
-o-animation: fadeInDown 0.5s!important;
animation: fadeInDown 0.5s!important;
}
And this HMTL:
<header class="navbar-fixed-top header-floating" data-ng-show="isHeader" id="platinumHeader">
<div class="container">
...
</div>
</header>
But when my header is shown (i.e. isHeader is set to true) it just appears without animation.
But if I write CSS like this (without #platinumHeader selector):
.ng-hide-remove {
-webkit-animation: fadeInDown 0.5s!important;
-moz-animation: fadeInDown 0.5s!important;
-o-animation: fadeInDown 0.5s!important;
animation: fadeInDown 0.5s!important;
}
It works fine. What am I doing wrong ?
A:
Try with ngClass directive
<header class="navbar-fixed-top header-floating" ng-class="{'ng-hide-remove' : isHeader}" data-ng-show="isHeader" id="platinumHeader">
<div class="container">
</div>
</header>
|
[
"stackoverflow",
"0011303935.txt"
] | Q:
PERSISTENT message have much slower performance than NON_PERSISTENT message
I found that PERSISTENT message have much slower performance than NON_PERSISTENT message.
I sent and received non_persistent messages and the performance is as follows.
Method Number of Msg Elapsed Time
Sending - 500 messages - 00:00:0332
Receiving - 500 messages - 00:00:0281
I sent and received persistent messages and the performance is as follows.
Sending - 500 messages - 00:07:0688
Receiving - 500 messages - 00:06:0934
This behavior happens in both MQMessage and JMSMessage.
Thank all people helping me out the problem.
Special thanks to Shashi, T.Rob and Pangea.
A:
Given the new title, I find I now have a response to this question.
Yes, persistent messages will always take longer than non-persistent messages with all other aspects being equal. The degree to which they are slower is highly tunable, though. In order to get the results that you are seeing it is likely that the queue manager has many of the worst-case tunings. Here are some of the factors that apply:
Whether the disk is local or networked. For 100MBS and slower connections talking to NFS mounted over spinning disks, a local drive is almost always much faster. (Mounts to SAN with fiber channel and battery-backed cached controllers are nearly always faster than local spinning drives, however.) A common example is use of consumer-grade NAS drives. As great as home NAS units are, throughput is always slower than local disk.
For local drives, the speed of the drive. Newer 'green' drives vary rotational speed to conserve power. Even 7200RPM disks can exhibit performance degredation compared to a 10k RPM drive.
For local drives, the degree of fragmentation. Even though the messages are small, they are placed into pre-allocated log files that may be highly fragmented.
Putting disk and log files on the same local volume. This causes head contention because a single message is written to both files before control returns to the application.
Linear versus circular logs. Linear are slower because the log formatter must allocate them new each time.
Whether syncpoint is used or not. If many messages are written in a single unit of work, WMQ can use cached writes and optimize the sector put operations. Only the COMMIT need ever be a blocking call.
Since non-persistent messages are handled entirely in memory, or overflowed to at most one disk file, then they are not affected by most of these issues.
|
[
"stackoverflow",
"0037852550.txt"
] | Q:
Common Argument Pass in Method
I have a method called makePersistent in my DAO class.
Currntly we have this method in all dao classes and what i need to do is convert this method to common format. So is there any way to do it?
Method in UserDao Class
public void makePersistent(User model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Method in HolidayDao Class
public void makePersistent(Holiday model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Please help me to get rid of this redundant coding.
Thank you.
A:
Just use Object the hibernate will persist it.
public void makePersistent(Object model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdaed"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
|
[
"stackoverflow",
"0002377549.txt"
] | Q:
Sqlalchemy file organization
Does anyone has any insight on organizing sqlalchemy based projects? I have many tables and classes with foreign keys, and relations. What is everyone doing in terms of separating classes, tables, and mappers ? I am relatively new to the framework, so any help would be appreciated.
Example:
classA.py # table definition and class A definition
classB.py # table definition and class B definition
### model.py
import classA,classB
map(classA.classA,clasSA.table)
map(classB.classB,clasSB.table)
Including mappers inside classA, and classB works, but poses cross import issues when building relations.. Maybe I am missing something :)
A:
Take a look at Pylons project including SA setup.
meta.py includes engine and metadata objects
models package includes declerative classes (no mapper needed). Inside that package, structure your classes by relavance into modules.
Maybe a good example would be reddit source code:)
A:
There are two features in SQLAlchemy design to avoid cross imports when defining relations:
backref argument of relation() allows you to define backward relation.
Using strings (model class and their fields names). Unfortunately this works for declarative only, which is not your case.
See this chapter in tutorial for more information.
|
[
"stackoverflow",
"0060430250.txt"
] | Q:
Can't play video from URL using AVPlayer, Error: NSOSStatusErrorDomain Code=-2
I have used a library https://github.com/VeinGuo/VGPlayer to play video in my custom view. But I faced error
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (-2), NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x281933e40 {Error Domain=NSOSStatusErrorDomain Code=-2 "(null)"}}
I have just implemented Embed in cell of tableView in my project from GitHub example. For getting error reason I have just created new empty project and do same thing in that and I just shocked It is working fine in that (Same device, same xcode). I have researched lot of but I couldn't found what is actual problem in my project. Please help me!
I have used this url for playing video. It is working fine in my new project but not in my actual project.
Below is the addPlayer method from VGEmbedTableViewController file. and other code is same as gitHub repository's example. I have only changed url.
func addPlayer(_ cell: UITableViewCell) {
if player != nil {
player.cleanPlayer()
}
configurePlayer()
cell.contentView.addSubview(player.displayView)
player.displayView.snp.makeConstraints {
$0.edges.equalTo(cell)
}
player.replaceVideo(URL(string:"https://s3.eu-west-2.amazonaws.com/gymstar-app/7A77786B4870594D7165625046614E74/post_videos/postVideo1582781434.005436.mp4")!)
player.play()
}
A:
My issue is solved by clearing cache which are saved by VGPlayer library. They provides methods for clear cache and delete files,
open func cleanAllCache() {
ioQueue.sync {
do {
let cacheDirectory = VGPlayerCacheManager.cacheDirectory()
try fileManager.removeItem(atPath: cacheDirectory)
} catch { }
}
}
open func cleanOldFiles(completion handler: (()->())? = nil) {
ioQueue.sync {
let cacheDirectory = VGPlayerCacheManager.cacheDirectory()
var (URLsToDelete, diskCacheSize, cachedFiles) = self.cachedFiles(atPath: cacheDirectory, onlyForCacheSize: false)
for fileURL in URLsToDelete {
do {
try fileManager.removeItem(at: fileURL)
} catch _ { }
}
if cacheConfig.maxCacheSize > 0 && diskCacheSize > cacheConfig.maxCacheSize {
let targetSize = cacheConfig.maxCacheSize / 2
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1.contentAccessDate,
let date2 = resourceValue2.contentAccessDate
{
return date1.compare(date2) == .orderedAscending
}
return true
}
for fileURL in sortedFiles {
let (_, cacheSize, _) = self.cachedFiles(atPath: fileURL.path, onlyForCacheSize: true)
diskCacheSize -= cacheSize
do {
try fileManager.removeItem(at: fileURL)
} catch { }
URLsToDelete.append(fileURL)
if diskCacheSize < targetSize {
break
}
}
}
DispatchQueue.main.async {
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map { $0.lastPathComponent }
NotificationCenter.default.post(name: .VGPlayerCacheManagerDidCleanCache, object: self, userInfo: [VGPlayerCacheManager.VGPlayerCleanCacheKey: cleanedHashes])
}
handler?()
}
}
}
|
[
"stackoverflow",
"0013728286.txt"
] | Q:
PHP To Monitor Server Statistics
Is there a way with PHP to get statistics about external servers such as:
Download/Upload speed
Up-time
Online/Offline
If not with PHP any other web language?
I would like to have a subdomain servers.domain.com which has login authentication where it will list all servers (about 10) and have the statistics above shown. They are not all on the same network, about 3 are.
A:
It sounds like you want either a monitoring package like Nagios, or a statistics tracking tool like Cacti, or both.
|
[
"stackoverflow",
"0027356790.txt"
] | Q:
c++ Lithuanian language, how to get more than ascii
I am trying to use Lithuanian in my c++ application, but every try is unsuccesfull.
Multi-byte character set is used. I have tryed everything i have tought of, i am new in c++. Never ever tryed to do something in Lithuanian.
Tryed every setlocale(LC_ALL, "en_US.utf8"); setlocale(LC_ALL, "Lithuanian");...
Researched for 2 hours and didnt found proper examples, solution.
I do have a average sized project which needs Lithuanian translation from database and it cant understand most of "ĄČĘĖĮŠŲŪąčęėįšųū".
Compiler - "Visual studio 2013"
Database - sqlite3.
I cant get simple strings to work(defined myself), and output as Lithuanian to win32 application, even.
A:
In Windows use wide character strings (1UTF-16 encoding, wchar_t type) for internal text handling, and preferably UTF-8 for external text files and networking.
Note that Visual C++ will translate narrow text literals from the source encoding to Windows ANSI, which is a platform-dependent usually single-byte encoding (you can check which one via the GetACP API function), i.e., Visual C++ has the platform-specific Windows ANSI as its narrow C++ execution character set.
But also do note that for an app restricted to non-Windows platforms, i.e. Unix-land, it makes practical sense to do everything in UTF-8, based on char type.
For the database communication you may need to translate to and from the program's internal text representation.
This depends on what the database interface requires, which is not stated.
Example for console output in Windows:
#include <iostream>
#include <fcntl.h>
#include <io.h>
auto main() -> int
{
_setmode( _fileno( stdout ), _O_WTEXT );
using namespace std;
wcout << L"ĄČĘĖĮŠŲŪąčęėįšųū" << endl;
}
To make this compile by default with g++, the source code encoding needs to be UTF-8. Then, to make it produce correct results with Visual C++ the source code encoding needs to be UTF-8 with BOM, which happily is also accepted by modern versions of g++. For otherwise the Visual C++ compiler will assume the Windows ANSI encoding and produce an incorrect UTF-16 string.
Not coincidentally this is the default meaning of UTF-8 in Windows, e.g. in the Notepad editor, namely UTF-8 with BOM.
But note that while in Windows the problem is that the main system compiler requires a BOM for UTF-8, in Unix-land the problem is the opposite, that many old tools can't handle the BOM (for example, even MinGW g++ 4.9.1 isn't yet entirely up to speed: it sometimes includes the BOM bytes, then incorrectly interpreted, in error messages).
1) On other platforms wide character text can be encoded in other ways, e.g. with UTF-32. In fact the Windows convention is in direct conflict with the C and C++ standards which require that a single wchar_t should be able to encode any character in the extended character set. However, this requirement was, AFAIK, imposed after Windows adopted UTF-16, so the fault probably lies with the politics of the C and C++ standardization process, not yet another Microsoft'ism.
|
[
"stackoverflow",
"0063680452.txt"
] | Q:
TypeScript claims Function is not Calalble
For whatever reason, TypeScript isn't detecting that something of instance Function is not callable.
type Constructable = { new(...args: any[]): any }
function isClass(func: any) {
return (
typeof func === 'function' &&
/^class\s/.test(Function.prototype.toString.call(func))
)
}
function coerceOne(data: any, fn: Function | Constructable) {
if (isClass(fn)) {
const constructor = fn as Constructable
return new constructor(data)
} else {
return fn(data) // <-- ERROR
}
}
Error:
This expression is not callable.
No constituent of type 'Function | Constructable' is callable.(2349)
https://www.typescriptlang.org/play?ssl=14&ssc=11&pln=14&pc=6#code/C4TwDgpgBAwg9gOwM7AE4FcDGwCGAjAG2gF4oBvKBCAdwAoA6RnVAcyQC4ocEQBtAXQCUnbiCgBfAFCSAZugTYAloiiKkMAjiRJachSJ6DykqFFQRg6VAii0TpqKEhwZUPZijEvUAOTvgygg+UABkIfamAPQAepia2gA6SJH0wBAotABi8kqI9GCocMBF4BCpcADKaIoILPSYOAQEujmCgvbtUrI5ASqYcBComBAA8lS0ACY4uAYgADRuCJzZCr02AD6wiCgY2PhERmT2iq60ahpaOjIIbcYOUP3IwA-baFjFqJ6LXEhbT7u4QgQCJmCxWGxUagvf7vOCoSbTHDtUziKAQAhIaBHe7mSzWRYI3DIiSSKRAA
Any ideas on how to resolve this?
A:
Your type guard isClass needs a predicate return type: : func is Constructable
type Constructable = { new(...args: any[]): any }
function isClass(func: any): func is Constructable {
return (
typeof func === 'function' &&
/^class\s/.test(Function.prototype.toString.call(func))
)
}
function coerceOne(data: any, fn: Function | Constructable) {
if (isClass(fn)) {
const constructor = fn as Constructable
return new constructor(data)
} else {
return fn(data)
}
}
console.log(coerceOne('works', console.log))
https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gOwM7AE4FcDGwCGAjAG2gF4oBvKBCAdwAoA6RnVAcyQC4ocEQBtAXQCUnbiCgBfAFCSAZugTYAloiiKkMAjiRJachSJ7CoezKqSxEKDNnxFykqFFQRg6VAii0HjqKEhwZY3lTYlCoAHITYGUEcKgAMnjvRwB6AD1MTW0AHSQU+mAIFFoAMWDoxHowVDhgWvAIArgAZTRFBBZ6TBwCAl1gwUFvIalZcpioTDgIVEwIAHkqWgATHFwDEAAaYwROMoUKjwAfC2Q0LFxCCEF7R0VA2jUNLR0ZBEHbnymzyctz7DgqCgpDeXHM8DO1kuRGSThcbg8VGov0hF0BKzWOCGjnEUAgBCQ0DIsOcrncOwxuGxEkko2+SDgRHoBDgLFoUxmc0WEFo4WogIA1khwtt6YzGiyWINJEA
|
[
"math.stackexchange",
"0000408995.txt"
] | Q:
How find $\int(x^7/8+x^5/4+x^3/2+x)\big((1-x^2/2)^2-x^2\big)^{-\frac{3}{2}}dx$
How can I compute the following integral:
$$\int \dfrac{\frac{x^7}{8}+\frac{x^5}{4}+\frac{x^3}{2}+x}{\left(\left(1-\frac{x^2}{2}\right)^2-x^2\right)^{\frac{3}{2}}}dx$$
According to Wolfram Alpha, the answer is
$$\frac{x^4 - 32x^2 + 20}{2\sqrt{x^4 -8x^2 + 4}} + 7\log\bigl(-x^2 - \sqrt{x^4 - 8x^2 + 4} + 4\bigr) + C$$
but how do I get it by hand?
A:
Perform the substitutions $y=\frac{x^2}{2}, y=2+\sqrt{3}\sec{\theta}$ to get:
\begin{align}
&\int{\frac{\frac{x^7}{8}+\frac{x^5}{4}+\frac{x^3}{2}+x}{((1-\frac{x^2}{2})^2-x^2)^{\frac{3}{2}}} dx} \\
& =\int{\frac{y^3+y^2+y+1}{(y^2-4y+1)^{\frac{3}{2}}} dy} \\
&=\int{\left(\frac{y+5}{\sqrt{(y-2)^2-3}}+\frac{20y-4}{\sqrt{((y-2)^2-3)^3}}\right) dy} \\
&=\int{\left[\frac{7+\sqrt{3}\sec{\theta}}{\sqrt{3}\tan{\theta}}+\frac{36+20\sqrt{3}\sec{\theta}}{3\sqrt{3}\tan^3{\theta}}\right](\sqrt{3}\sec{\theta}\tan{\theta}) d\theta} \\
&=\int{\left(7\sec{\theta}+\sqrt{3}\sec^2{\theta}+12\csc{\theta}\cot{\theta}+\frac{20}{\sqrt{3}}\csc^2{\theta}\right) d\theta} \\
&=7\ln{|\tan{\theta}+\sec{\theta}|}+\sqrt{3}\tan{\theta}-12\csc{\theta}-\frac{20}{\sqrt{3}}\cot{\theta}+c \\
&=7\ln{|\frac{\sqrt{y^2-4y+1}+y-2}{\sqrt{3}}|}+\sqrt{y^2-4y+1}-\frac{12(y-2)}{\sqrt{y^2-4y+1}}-\frac{20}{\sqrt{y^2-4y+1}}+c \\
&=7\ln{|\frac{\sqrt{y^2-4y+1}+y-2}{\sqrt{3}}|}+\frac{y^2-16y+5}{\sqrt{y^2-4y+1}}+c \\
&=7\ln{|\sqrt{x^4-8x^2+4}+x^2-4|}+\frac{x^4-32x^2+20}{2\sqrt{x^4-8x^2+4}}+c'
\end{align}
where $c,c'$ are arbitrary constants of integration.
|
[
"stackoverflow",
"0030539002.txt"
] | Q:
polymer string concatenation for template repeat in v 1.0
I'm not sure if the following is possible with a "computed" and a dom-repeat template. I was binding with child and parent properties prior to .9/.8/1.0
<template is="dom-repeat" as="agreementTypeCount" index-as="agreementTypeCountI" items="{{agreementTypeCounts}}">
<a href="/{{style_domain}}/agreements/#/table/country/{{selectedCountryCode}}/type/{{agreementTypeCount.type}}/sort/start-desc/size/10/page/1/">{{agreementTypeCount.type}}</a>
</template>
Are there any plans to implement string concatenation? It would make life so much easier!
A:
It's currently on the roadmap. However you can also use computed bindings for this.
<template is="dom-repeat" as="agreementTypeCount" index-as="agreementTypeCountI" items="{{agreementTypeCounts}}">
<a href$="{{computeAgreementUrl(style_domain, selectedCountryCode, agreementTypeCount.type)}}">{{agreementTypeCount.type}}</a>
</template>
and then declare it
Polymer({
...
computeAgreementUrl(styleDomain, countryCode, type){
return "/"+styleDomain+"/agreements/#/table/country/"+countryCode+"/type/"+type+"/sort/start-desc/size/10/page/1/";
}
})
Please take note of the $ character next to href. It is recommended that you use attribute binding ($=) to native elements' attributes.
|
[
"meta.stackexchange",
"0000265841.txt"
] | Q:
Can we have an option to disable the new badge & privilege section in the achievements dropdown?
At the bottom of the "Achievements" dropdown, there is a new section displaying the next privilege & badge, similar to the profile page ones:
It's nice, but for experienced users I don't really see it being that useful, as it adds clutter to an already packed UI, and hides information which I do want to see, forcing me to scroll. Especially on Meta sites, the information it shows may not be very useful for me:
In some cases it may even be bad: reminding me that I only have to upvote 14 more things in order to get the electorate badge, and new or badge-hungry users may go and upvote something just to get the badge. (I believe this has been discussed before, but seeing the "reminder" every time you open the achievements dropdown would make this worse.)
Also, as mentioned in the answer, if it's showing a gold badge, it draws your attention even if you're not directly looking at it, thus being somewhat distracting.
Is it really necessary ? - Looks like feature creep to me.
Could we get an option to disable this ? - I know I could write a userscript of some kind, but still.
A:
I agree; this takes a lot of space away from stuff I'd much rather see (more of the regular notifications). It's especially annoying when it covers up new notifications.
This also violates the design intent of the global-notifications pane. That stuff is supposed to be, well, global; nothing else there changes as I move around the network. So the distracting thing that covers up the content I want to see is also dynamic, which draws my attention to it.
It's also peculiar that a notification about badge progress -- that is, stuff about a badge I don't have yet -- is much much bigger than the notification of a badge I actually earned.
If I want my badge progress on my current site it's one click away. I guess the theory is that this might get the attention of people who aren't paying attention to badges, but how many of them are going to start just because they started getting a persistent notification?
If the "next badge" information is important enough to notify in some manner (I'm not convinced it is, but if), how about generating an actual notification for it? So when you get the badge you were working toward, you'd get two notifications, the usual one and then this one, normal-sized and governed by the scrollbar. The notifications would be branded with the site logos, and the notification list would remain global. Just a thought.
A:
I find this particularly distracting when the next badge is a gold one: the color is bright enough and the rectangle is large enough to demand my attention even if I am not looking directly at it.
The boxes appear to be a continuation of Stack Exchange: where shiny pixels are earned rebranding that began with user profile redesign. Presumably, this is an attempt to make users care about the aforementioned pixels.
The current stage appears to be A/B testing (I see the boxes on one computer but not another), so there is a hope of it being ditched; though given the general direction of Stack Exchange UI, the hope is slim.
A:
I don't think we should have a option to disable it.
Ergonomics options are often the consequence of application designers being unable to choose and this would be no exception.
We shouldn't have an option to disable it because this tracker should really not be here. There's no reason to put it with the notifications of things really happening.
If we want to see the badge tracker, and it's not every few minutes even for the most addicted users, there's already a perfect location where it belongs, near the progress of all our tags and other badges.
Please don't clutter the interface, and don't clutter the options, simply remove this tracker from the achievements notifications dropdown.
|
[
"stackoverflow",
"0043085071.txt"
] | Q:
Kafka consumer exception and offset commits
I've been trying to do some POC work for Spring Kafka. Specifically, I wanted to experiment with what are the best practices in terms of dealing with errors while consuming messages within Kafka.
I am wondering if anyone is able to help with:
Sharing best practices surrounding what Kafka consumers should do
when there is a failure
Help me understand how AckMode Record works, and how to prevent commits to the Kafka offset queue when an exception is thrown in the listener method.
The code example for 2 is given below:
Given that AckMode is set to RECORD, which according to the documentation:
commit the offset when the listener returns after processing the
record.
I would have thought the the offset would not be incremented if the listener method threw an exception. However, this was not the case when I tested it using the code/config/command combination below. The offset still gets updated, and the next message continues to be processed.
My config:
private Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.1:9092");
props.put(ProducerConfig.RETRIES_CONFIG, 0);
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}
@Bean
ConcurrentKafkaListenerContainerFactory<Integer, String> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(consumerConfigs()));
factory.getContainerProperties().setAckMode(AbstractMessageListenerContainer.AckMode.RECORD);
return factory;
}
My code:
@Component
public class KafkaMessageListener{
@KafkaListener(topicPartitions = {@TopicPartition( topic = "my-replicated-topic", partitionOffsets = @PartitionOffset(partition = "0", initialOffset = "0", relativeToCurrent = "true"))})
public void onReplicatedTopicMessage(ConsumerRecord<Integer, String> data) throws InterruptedException {
throw new RuntimeException("Oops!");
}
Command to verify offset:
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group test-group
I'm using kafka_2.12-0.10.2.0 and org.springframework.kafka:spring-kafka:1.1.3.RELEASE
A:
The container (via ContainerProperties) has a property, ackOnError which is true by default...
/**
* Set whether or not the container should commit offsets (ack messages) where the
* listener throws exceptions. This works in conjunction with {@link #ackMode} and is
* effective only when the kafka property {@code enable.auto.commit} is {@code false};
* it is not applicable to manual ack modes. When this property is set to {@code true}
* (the default), all messages handled will have their offset committed. When set to
* {@code false}, offsets will be committed only for successfully handled messages.
* Manual acks will be always be applied. Bear in mind that, if the next message is
* successfully handled, its offset will be committed, effectively committing the
* offset of the failed message anyway, so this option has limited applicability.
* Perhaps useful for a component that starts throwing exceptions consistently;
* allowing it to resume when restarted from the last successfully processed message.
* @param ackOnError whether the container should acknowledge messages that throw
* exceptions.
*/
public void setAckOnError(boolean ackOnError) {
this.ackOnError = ackOnError;
}
Bear in mind, though, that if the next message is successful, its offset will be committed anyway, which effectively commits the failed offset too.
EDIT
Starting with version 2.3, ackOnError is now false by default.
|
[
"stackoverflow",
"0052996263.txt"
] | Q:
Is there any resource (PDF or Videos serires) on lotus domino application development
I need a book reference or video course reference on lotus domino development (application development).
A:
I assume you are talking about web applications rather than noted client applications. These are some very useful sites:
David Leedy has published many many videos around the whole topic of XPages app dev:
http://www.notesin9.com/
Open source community around IBM domino app dev:
https://openntf.org/main.nsf
IBM Domino Application Development Wiki:
https://www-10.lotus.com/ldd/ddwiki.nsf/m_Home.xsp#mobileCategoryList
XPages chest sheets (also David keedy‘s work):
http://xpagescheatsheet.com/
IBM published a few books (packt publishing):
Mastering XPages
XPages Extension Library
There is a lot more around , I find these particularly helpful.
There is a vivid community available with many user groups, blogs etc.
http://planetlotus.org/ is a good starting point to check out what is going ...
HTH!
|
[
"rpg.stackexchange",
"0000059381.txt"
] | Q:
How does Gunnery work when Jumped In
I could have sworn that this rule is SOMEWHERE in the book, but I can't seem to find it. Gunnery, as a skill, is linked to Agility for use. However, when a rigger jumps into the device that has the weapon on it, I remember hearing that they use Logic instead of their Agility.
Because I am horrible at finding this ruling, can someone point me to the page I need in the book? Or confirm that people still use Agility?
A:
Page 183, GUNNERY section:
Vehicle-mounted weapons are
fired using Weapon Skill Gunnery + Agility [Accuracy] for manual
operation, like door guns on mounts, or Gunnery + Logic
[Accuracy] for remote operated systems.
Note: The strikethrough marks errata.
Since you are a rigger remotely operating the weapon (even if you use a direct connection to connect to the rigger interface) the dice pool is Gunnery + Logic and not Gunnery + Agility.
It also would make absolutely no sense to use Agility if you think about it. After all you are using the vehicle "as body" which means the Agility of your own body is irrelevant.
A:
Your confusion is well-justified
Vehicles, drones and other devices have four operation modes (p. 265):
Manual Control, which requires physical control, like turning a wheel, hitting buttons or operating levers;
Remote Control, which happens when you use matrix actions (like Control Device, p238);
Rigger Control, which happens when a rigger is jumped-in a device;
Autopilot: The device operate autonomously.
Gunnery is linked to Agility when it requires physical manipulation of a mounted gun, as described by the skill (p. 146):
Gunnery (Agility)
Gunnery is used when firing any vehicle-mounted weapon, regardless of how or where the weapon is mounted. This skill extends to manual and sensor-enhanced gunnery.
However, on the rules about using Gunnery (p. 183), it clarifies that remote-operated guns will use Logic instead of Agility:
The rules and modifiers for ranged combat apply to vehicle-mounted weapons. Vehicle-mounted weapons are fired using Gunnery + Agility [Accuracy] for manual operation, like door guns on mounts, or Gunnery + Logic [Accuracy] for remote operated systems.
While drones operating autonomously will use [Weapon] + Pilot [Accuracy/Sensor] when attacking, where [Weapon] is the weapon autosoft installed on the drone, and the limit on the check is either the weapon's Accuracy or the drone Sensor if the drone managed to lock on a target (see Sensor Attacks p184).
Drones attack using their Pilot + [Weapon] Targeting autosoft rating (p. 269), limited by Accuracy.
Which leaves us with the question of how Rigger Control works, which can be seen on the matrix chapter under Drone Combat (p. 270):
Rules for drone combat are the same as those for regular flesh-and-blood characters and can be found in the Combat chapter (p. 158). Specific rules for using Gunnery and Sensors in combat can be found there as well (p. 202).
So, not only it gives you the wrong page (202 is about vehicle combat), but doesn't really clarify how riggers do it differently than manual or remote operation.
Additionally, when we read about Remote Control (p. 265) as I mentioned earlier, it points us to the Control Device matrix action (p. 238), which says:
You perform an action through a device you control (or at least control sufficiently), using your commlink or deck like a remote control or video-game controller. The dice pool of any test you make using this action uses the rating of the appropriate skill and attribute you would use if you were performing the action normally. For example, firing a drone-mounted weapon at a target requires a Gunnery + Agility test
Wait, what? Wasn't agility for manual operation and logic for remote operation? Good job, Catalyst.
This topic is frequently discussed when someone creates a rigger (which is often), and the closest we got to an official answer, is a playtester/moderator saying that the rules are in conflict, and as of today, there is no official errata about this.
Fixing this mess
There is blending between the physical attributes and mental attributes that are specific to riggers and wasn't properly addressed by the writters (like astral combat was). You become the machine, and the control rig essentially intercepts your brain's signals to your meat body and returns the signals from the machine as if they came from your meat body.
Using a Logic or Intuition in place of Agility or Reaction is really how they should have done it, and it makes the most sense considering the flavor given to the matrix, virtual realities and how riggers are described to possess their drones.
So, personally, I would use Agility when the operation requires physical control, either manually, or removelly through a physical controller, such as using your commlink, cyberdeck or RCC using augmented reality. And use Logic whenever your character is in full virtual reality, meaning that your muscles have really no importance in whatever you are doing, and all you need is your brain power.
This interpretation is also suggested by the moderator I mentioned earlier. But in the same topic, he also points out that the german version of the game changed it to Gunnery+Agility:
By the way, page 183's German equivalent has Gunnery+Agility so they cleared that out, and unfortunately in the direction I feared.
A:
You're mistaken, I'm afraid. Page 238:
You perform an action through a device you control (or at least control sufficiently), using your commlink or deck like a remote control or video-game controller. The dice pool of any test you make using this action uses the rating of the appropriate skill and attribute you would use if you were performing the action normally. For example, firing a drone-mounted weapon at a target requires a Gunnery + Agility test, and using a remote underwater welder calls for a Nautical Mechanic + Logic test.
What you're thinking of is Drones Passively Targeting using their Sensors. Those use Gunnery + Logic. (p.184)
|
[
"stackoverflow",
"0030168905.txt"
] | Q:
Mystery element pushing extra width on mobile
Just wondering if someone had a minute to stop me ripping my hair out, trying to adapt a site for mobile (http://tinyurl.com/oc4uvlk) and there is something on this page pushing the width across but have looking in Opera & Chrome Web inspectors and just can't find the problem, it doesn't happen on the other pages.
Any help appreciated
Adrian
A:
It's element with class=".vc_custom_1430292196306", in styles (index, line 116 in generated HTML) it has padding-left: 385px !important.
|
[
"stackoverflow",
"0053415596.txt"
] | Q:
registerMailPartials() and registerMailLayouts()
I want to register my own e-mail layout at octobercms. Template registration works great. However, the use of registerMailLayouts and registerMailPartials methods does not work. I have no errors or the expected result. In the System\Classes\PluginBase class, there are no registerMailLayouts and registerMailPartials method.
I use the documentation:
https://octobercms.com/docs/services/mail#mail-template-registration
Any idea?
A:
This functionality was introduced in https://github.com/octobercms/october/pull/3850. It is still in the develop branch, it hasn't been added to master yet. See https://octobercms.com/docs/console/commands#console-install-composer for how to switch your project to use the develop branch so that you can always have the latest additions and bug fixes available.
|
[
"stackoverflow",
"0061548212.txt"
] | Q:
What are the additional features available in Core Activiti 6, and Activiti 7 with respect to Activiti 5
We are currently using core Activiti 5.22.0.5 version for orchestration of spring-boot microservices, and now there is a requirement to upgrade Activiti to latest version of Activiti which is Activiti 7.x
Can someone please let me know what are the additional features available in latest version and also let me know if we can directly upgrade it to latest version or not?
If not possible then what should be our up-gradation flow?
(Example: Activiti 5.22.0.5 -> Activiti 6.x -> Activiti 7.x or anything else)
Please help me if anyone have worked on any similar requirement?
If not then At list let me know the difference between these versions and features available in latest versions.
Thanks in advance
A:
I'm surprised no-one picked up the ball on this question.
Activiti 5 was superseded by Activiti 6 and has basically the same architecture with a new and improved user interface. Activiti 6 also introduced a form editor if I remember as well as basic decision (DMN) support.
Development on Activiti 6 pretty much froze when the core team moved to Flowable. Development continued at Flowable and has gone on to include some rearchitecting of the entity (persistence) model, the event model, improvements in DMN support, some seperating of components and better Spring support. There are other changes but I think this is the majority. Flowable is a very active project and if you want to maintain an on premise "Activiti" project I would recommend you move to Flowable (or Camunda who branched at Activiti version 5 and maintain a similar Architecture).
Activiti 7 was a complete rewrite specifically for cloud deployments.
Activiti 7 is architected as a set of microservices (12 factor application) that implement each of the functions (event manager, Rest interface, notification, identity management, runtime server, log server). Components are "wired" together using zookeeper as a set of individual modules that can be independently deployed.
If you are running Activiti 5 on premise, I'm not sure Activiti 7 is a good fit.
Also, the Activiti 7 project development appears to have slowed significantly recently.
For you, I would look at either Flowable (closest to Activiti 5) or Camunda.
|
[
"stackoverflow",
"0027168886.txt"
] | Q:
angular-dimple error TypeError: Cannot read property '_hasCategories' of null
I am trying to build stacked-bar chart using dimple.js I need to do this through angular directives so I am using angular-dimple
here is what I have coded to run their sample example:
<script type="text/javascript">
var app = angular.module("dimpleTestApp", ['angular-dimple']);
app.controller('myCtrl', ['$scope', 'dataService', function($scope, dataService) {
dataService.getData().then(function(response) {
$scope.graphData = response.data;
console.log($scope.graphData);
});
}])
.service('dataService', ['$http', function($http) {
return {
getData: function() {
return $http.get('data.json');
}
};
}]);
</script>
</head>
<body ng-app='dimpleTestApp'>
<div ng-controller="myCtrl">
<graph data="graphData" orientation="horizontal">
<x-axis field="Month"></x-axis>
<y-axis field="Sales"></y-axis>
<stacked-bar field="storeId" value="2"></stacked-bar>
</graph>
</div>
</body>
but I am getting this error while running this code:
TypeError: Cannot read property '_hasCategories' of null
at null.<anonymous> (http://dimplejs.org/dist/dimple.v2.0.0.min.js:1:10314)
at Array.forEach (native)
at _getSeriesData (http://dimplejs.org/dist/dimple.v2.0.0.min.js:1:9714)
at draw (http://dimplejs.org/dist/dimple.v2.0.0.min.js:1:20275)
at draw (http://localhost/angular-dimple/bower_components/angular-dimple/lib/angular-dimple.js:175:15)
at addBar (http://localhost/angular-dimple/bower_components/angular-dimple/lib/angular-dimple.js:428:25)
at Object.fn (http://localhost/angular-dimple/bower_components/angular-dimple/lib/angular-dimple.js:433:11)
at g.$get.g.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.min.js:110:464)
at g.$get.g.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.min.js:113:468)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.min.js:73:183)
can anybody tell me what is wrong with this application and how can I make this running.
A:
I have solved this by doing getting deeper into angular-dimple library.
There was mistake in their documentation directive is created using x and y elements while in example they have mentioned x-axis and y-axis, so when I changed it to correct one it worked.
Here is the modified code:
<graph data="graphData" orientation="horizontal">
<x field="Month"></x>
<y field="Sales"></y>
<stacked-bar field="storeId" ></stacked-bar>
</graph>
|
[
"stackoverflow",
"0053088369.txt"
] | Q:
Zapier: from spreadsheet to Facebook Offline events tracking
I've got a database containing offline conversions (email, phone, name, purchase_amount, etc). I can export this database in .csv or .xls and I can also email this file on a daily basis to a Gmail account.
As Zapier has a Google Sheet to "Facebook offline event" API, I tried this workflow with Zapier.com:
Export my database in .xls: OK
Mail it to my Gmail account as an email attachment: OK
Grab the attachment and upload file to Google Drive using Zapier: OK
This is the part where I'm in trouble: I want to copy the content of the .xls file that is on Google Drive to a new Google Sheet. I can't figure out how to do this in Zapier.
Finally, on every new spreadsheet created or new row added (depending on how I configure the Zap) , pushing the data to Facebook API.
I'm not a developer so I want to avoid coding if possible. I tought I could easily do it with zapier but it seems that working with data inside a file is not so easy.
Any help would be much appreciated.
Thank you,
Best regards,
Tim.
A:
If it were me I would look into the scripting capabilities of Google Sheets to try and achieve this, having your code execute from a single place eliminates other possible points of failure. That said, I have put together a somewhat hacky, code free solution that should set you up to do what you are looking to achieve. I break it down step by step below:
Step 1: Export database as .csv file. I could only get this to work with .csv files and not .xlsx files. There may be the ability to do so but it would require further trial and error.
Step 2: Mail it to your Gmail account where I assume there is a Zap which triggers to upload the attachment to your drive account automatically.
Step 3: Setup a second Zap that is connected to your Gmail account
that triggers when you receive an email with an attachment.
Step 4: Isolate the attachment file from the results of the triggered Zap and use it as input for the following formatter action step.
Step 5: Setup your formatter action step using the text option. Within the formatter template select trim white space and use the attachment, isolated from the trigger step, as its input. See example photo here.
Step 6: Setup your final step which is the create Google Sheet function of the Google Sheets Zap. Enter a title for your new sheet, it will probably need to be a unique value I used the attachment ID from step one as my title but you can set it to whatever you would like. In the headers section type =IMPORTDATA("") . Between the two quotation marks place the output of the previous formatter step and then run the Zap. See example photo here.
Explanation: When Zapier catches the attachment file from your inbound email it seems to be stored as raw data. Given this we cannot simply dump this information into a spreadsheet as it would be unreadable. However it seems Zapier has a method for converting this raw data through the endpoint https://zapier.com/engine/hydrate. When we input the raw attachment data into the formatter step Zapier provides a link pointing to the URL for converting the data into its original format. We take this URL and using the Google worksheet function IMPORTDATA() we are able to import the file using Zapier's file conversion engine. Now that the data is in your new sheet you can set up an additional Zap to do something with it. Also note that the Zap to upload the attachment to your Google Drive is not necessary with this setup. That said if you are looking to keep backups of your data then keep it on otherwise you may have the opportunity to save yourself some zaps.
Hope this helps!
|
[
"stackoverflow",
"0038854178.txt"
] | Q:
suggestion about how to read RDF using c# and asp.net
I'm new to the semantic web topic, and I created an ontology which I need to develop a website that can read the ontology and extract the information from the OWL file and display it in the website
I did some research about which library i need to use, So i found that RDFdotnet in the best library i need to use it for reading the owl file
also i found a code but i need some one explain or help me with this code for reading my owl file. I wanna use dropdown list and button
please any suggestion ???
this is the code
//Define your Graph here - it may be better to use a QueryableGraph if you plan
//on making lots of Queries against this Graph as that is marginally more performant
IGraph g = new Graph();
//Load some data into your Graph using the LoadFromFile() extension method
g.LoadFromFile("myfile.rdf");
//Use the extension method ExecuteQuery() to make the query against the Graph
try
{
Object results = g.ExecuteQuery("SELECT * WHERE { ?s a ?type }");
if (results is SparqlResultSet)
{
//SELECT/ASK queries give a SparqlResultSet
SparqlResultSet rset = (SparqlResultSet)results;
foreach (SparqlResult r in rset)
{
//Do whatever you want with each Result
}
}
else if (results is IGraph)
{
//CONSTRUCT/DESCRIBE queries give a IGraph
IGraph resGraph = (IGraph)results;
foreach (Triple t in resGraph.Triples)
{
//Do whatever you want with each Triple
}
}
else
{
//If you don't get a SparqlResutlSet or IGraph something went wrong
//but didn't throw an exception so you should handle it here
Console.WriteLine("ERROR");
}
}
catch (RdfQueryException queryEx)
{
//There was an error executing the query so handle it here
Console.WriteLine(queryEx.Message);
}
A:
For your ASP.NET application you probably need a more abstract model than the RDF graph that dotNetRDF produces. When you parse the OWL file you get a graph which contains a collection of triples, but for your application you probably want something more like a list or a dictionary of objects that represent the bits of the ontology you are displaying.
In the dotNetRDF API there are various methods for reading triples from the graph and you can use these to find the OWL classes and their properties. See https://bitbucket.org/dotnetrdf/dotnetrdf/wiki/UserGuide/Working%20with%20Graphs for more information about working with the IGraph interface. Alternatively you could extract information from the graph using SPARQL queries (see https://bitbucket.org/dotnetrdf/dotnetrdf/wiki/UserGuide/Querying%20with%20SPARQL).
So in summary dotNetRDF provides the tools to parse your OWL file into a graph and then to query or navigate around that graph to extract information from it. From there I think it is completely up to you about how exactly you structure the model for your application - based on your application requirements.
|
[
"stackoverflow",
"0032619642.txt"
] | Q:
Adding multiple words to a word document in a sentence using an array with VBA
My question pertains to the Do While loop in my code, but I posted the whole thing to show you what I'm doing. This code will compare two documents. The object is to have blue text in a revision document added into the sentences of the original document and have that become a new third document. The functionality I am having trouble accomplishing is adding multiple words within a sentence. Right now I can add a word anywhere in a sentence as long as it is the only instance of blue text within that sentence. The program finds blue text and selects the entire sentence of that particular blue word. This is the only way I have thought how to reference where to add the new text to the third document. The blue text is removed from the sentence and that sentence is taken and found in the original document that has been copied. The blue text is then added back and saved to the new document. Here is a rundown of why one blue word per sentence will work and not two or more:
Does not work:
Original Document: "This String Is."
Revision Document: "This New String Is New."
The first blue word is found and taken out to compare the string to the original document but..... "This String Is New" does not match with "This String Is"
This works though with just one blue word per sentence:
Original Document: "This String Is."
Revision Document: "This String Is New."
"New" is removed "This String Is." = "This String Is."
The sentence is found in the original document and the blue word is added to the copied original document and is saved. The program then moves onto the next blue word and repeats the process till no more blue text is found. However, without removing all instances of blue text within a sentence at once, there will not be a match in the orignal document. That is what I need help accomplishing, probably with an array.
Sub ArrayTest()
MsgBox "Welcome to the word document automatic modifier", vbInformation + vbOKOnly
MsgBox "Please open the revision file", vbInformation + vbOKOnly
Dim strfilename1 As String
Dim fd1 As Office.FileDialog
''''''Browsing/Opening the change request'''''''
Set fd1 = Application.FileDialog(msoFileDialogFilePicker)
With fd1
.AllowMultiSelect = False
.Title = "Open the modified word document."
.Filters.Clear
.Filters.Add "Word 2010", "*.docx"
.Filters.Add "All Files", "*.*"
If .Show = True Then
strfilename1 = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
End With
''''''''''' Browsing/Opening the original Design Manual'''''''''''''''''''''''''''
MsgBox "Open the orginal document", vbInformation + vbOKOnly
Dim strfilename2 As String
Dim fd2 As Office.FileDialog
Set fd2 = Application.FileDialog(msoFileDialogFilePicker)
With fd2
.AllowMultiSelect = False
.Title = "Please select the original file."
.Filters.Clear
.Filters.Add "Word 2010", "*.docx"
.Filters.Add "All Files", "*.*"
If .Show = True Then
strfilename2 = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
End With
MsgBox "Please enter the file name with which you want to store the new updated file", vbInformation + vbOKOnly
''''''''''''''''''Asking user to input name to the new revised document'''''''''''''''''''''''''''''''''''''
Dim strfilename3 As String
Dim fd3 As Office.FileDialog
Set fd3 = Application.FileDialog(msoFileDialogSaveAs)
With fd3
.AllowMultiSelect = False
.Title = "Please select the name to be given to the new file."
If .Show = True Then
strfilename3 = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
End With
Dim strg1 As String
Dim strg2 As String
Dim strg3 As String
Dim count As Integer
Dim strgArray()
FileCopy strfilename2, strfilename3
Set objWordChange = CreateObject("Word.Application")
Set objWordorig = CreateObject("Word.Application")
objWordChange.Visible = False
objWordorig.Visible = False
Set objDocChange = objWordChange.Documents.Open(strfilename1)
Set objSelectionChange = objWordChange.Selection
Set objDocOrig = objWordorig.Documents.Open(strfilename3)
Set objSelectionOrig = objWordorig.Selection
count = 0
objSelectionChange.Find.Forward = True
objSelectionChange.Find.Format = True
objSelectionChange.Find.Font.Color = wdColorBlue
Do While True
objSelectionChange.Find.Execute
If objSelectionChange.Find.Found Then
strg2 = objSelectionChange.Sentences(1).Text
count = count + 1
ReDim strgArray(count)
strgArray(count) = objSelectionChange.Text
MsgBox strgArray(count) & " Located In Array Index # " & count
MsgBox strg2
strg3 = Replace(strg2, strgArray(count), "")
strg3 = Replace(strg3, " ", " ")
strg3 = Mid(strg3, 1, Len(strg3) - 2)
strg4 = strg3
MsgBox strg4
Set objRangeOrig = objDocOrig.Content
'''''Search the string in the original manual'''''
With objRangeOrig.Find
.MatchWholeWord = False
.MatchCase = False
.MatchPhrase = True
.IgnoreSpace = True
.IgnorePunct = True
.Wrap = wdFindContinue
.Text = strg4
.Replacement.Text = Left(strg2, Len(strg2) - 2)
.Execute Replace:=wdReplaceOne
objDocOrig.Save
End With
Else
Exit Do
End If
Loop
objDocChange.Close
objDocOrig.Save
objDocOrig.Close
objWordChange.Quit
objWordorig.Quit
End Sub
Edit: This is the newer code as suggested by Dick, however it is still not completely working.
Sub WordReplaceSentence()
MsgBox "Welcome to the word document automatic modifier", vbInformation + vbOKOnly
MsgBox "Please open the revision file", vbInformation + vbOKOnly
Dim strfilename1 As String
Dim fd1 As Office.FileDialog
''''''Browsing/Opening the change request'''''''
Set fd1 = Application.FileDialog(msoFileDialogFilePicker)
With fd1
.AllowMultiSelect = False
.Title = "Open the modified word document."
.Filters.Clear
.Filters.Add "Word 2010", "*.docx"
.Filters.Add "All Files", "*.*"
If .Show = True Then
strfilename1 = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
End With
''''''''''' Browsing/Opening the original Design Manual'''''''''''''''''''''''''''
MsgBox "Open the orginal document", vbInformation + vbOKOnly
Dim strfilename2 As String
Dim fd2 As Office.FileDialog
Set fd2 = Application.FileDialog(msoFileDialogFilePicker)
With fd2
.AllowMultiSelect = False
.Title = "Please select the original file."
.Filters.Clear
.Filters.Add "Word 2010", "*.docx"
.Filters.Add "All Files", "*.*"
If .Show = True Then
strfilename2 = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
End With
MsgBox "Please enter the file name with which you want to store the new updated file", vbInformation + vbOKOnly
''''''''''''''''''Asking user to input name to the new revised document'''''''''''''''''''''''''''''''''''''
Dim strfilename3 As String
Dim fd3 As Office.FileDialog
Set fd3 = Application.FileDialog(msoFileDialogSaveAs)
With fd3
.AllowMultiSelect = False
.Title = "Please select the name to be given to the new file."
If .Show = True Then
strfilename3 = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
End With
FileCopy strfilename2, strfilename3
Set objWordChange = CreateObject("Word.Application")
Set objWordorig = CreateObject("Word.Application")
objWordChange.Visible = False
objWordorig.Visible = False
Set objDocChange = objWordChange.Documents.Open(strfilename1)
Set objSelectionChange = objWordChange.Selection
Set objDocOrig = objWordorig.Documents.Open(strfilename3)
Set objSelectionOrig = objWordorig.Selection
Dim rSearch As Range
Dim dict As Scripting.Dictionary
Dim i As Long
'Set up the documents - you already have this part
'We'll store the sentences here
Set dict = New Scripting.Dictionary
Set rSearch = objDocChange.Range
With rSearch
.Find.Forward = True
.Find.Format = True
.Find.Font.Color = wdColorBlue
.Find.Execute
Do While .Find.Found
Dim strg1
Dim strg2
strg1 = rSearch.Sentences(1).Text
MsgBox strg1
'key = revised sentence, item = original sentence
'if the revised sentence already exists in the dictionary, replace the found word in the entry
If dict.Exists(.Sentences(1).Text) Then
dict.Item(.Sentences(1).Text) = Replace$(Replace$(dict.Item(.Sentences(1).Text), .Text, vbNullString), Space(2), Space(1))
Else
'if the revised sentence isn't in the dict, then this is the first found word, so add it and replace the word
dict.Add .Sentences(1).Text, Replace$(Replace$(.Sentences(1).Text, .Text, vbNullString), Space(2), Space(1))
End If
.Find.Execute
Loop
End With
'Loop through all the dictionary entries and find the origial (item) and replace With
'the revised (key)
For i = 1 To dict.Count
Set rSearch = objDocOrig.Range
With rSearch.Find
.MatchWholeWord = False
.MatchCase = False
.MatchPhrase = True
.IgnoreSpace = True
.IgnorePunct = True
.Wrap = wdFindContinue
.Text = dict.Items(i - 1)
.Replacement.Text = dict.Keys(i - 1)
.Execute Replace:=wdReplaceOne
End With
Next i
objDocChange.Close
objDocOrig.Save
objDocOrig.Close
objWordChange.Quit
objWordorig.Quit
End Sub
A:
This uses a Scripting.Dictionary - set a reference using Tools - References to Microsoft Scripting Runtime.
It saves the sentence of each found entry as an entry to the dictionary. It only saves each sentence once. When it finds the second word, it replaces that word within what's already in the dictionary.
Sub MergeRevision()
Dim dcOrig As Document
Dim dcRev As Document
Dim dcNew As Document
Dim rSearch As Range
Dim dict As Scripting.Dictionary
Dim i As Long
'Set up the documents - you already have this part
Set dcOrig = Documents("Document1.docm")
Set dcRev = Documents("Document2.docx")
Set dcNew = Documents("Document3.docx")
dcOrig.Content.Copy
dcNew.Content.Paste
'We'll store the sentences here
Set dict = New Scripting.Dictionary
Set rSearch = dcRev.Range
With rSearch
.Find.Forward = True
.Find.Format = True
.Find.Font.Color = wdColorBlue
.Find.Execute
Do While .Find.Found
'key = revised sentence, item = original sentence
'if the revised sentence already exists in the dictionary, replace the found word in the entry
If dict.Exists(.Sentences(1).Text) Then
dict.Item(.Sentences(1).Text) = Replace$(Replace$(dict.Item(.Sentences(1).Text), .Text, vbNullString), Space(2), Space(1))
Else
'if the revised sentence isn't in the dict, then this is the first found word, so add it and replace the word
dict.Add .Sentences(1).Text, Replace$(Replace$(.Sentences(1).Text, .Text, vbNullString), Space(2), Space(1))
End If
.Find.Execute
Loop
End With
'Loop through all the dictionary entries and find the origial (item) and replace With
'the revised (key)
For i = 1 To dict.Count
Set rSearch = dcNew.Range
With rSearch.Find
.MatchWholeWord = False
.MatchCase = False
.MatchPhrase = True
.IgnoreSpace = True
.IgnorePunct = True
.Wrap = wdFindContinue
.Text = dict.Items(i - 1)
.Replacement.Text = dict.Keys(i - 1)
.Execute Replace:=wdReplaceOne
End With
Next i
End Sub
|
[
"stackoverflow",
"0040160808.txt"
] | Q:
Python Turtle color change
im currently playing around with pythons turtle module and im trying to make a grid of opaque square shapes, say 30x30 that can change color based on some property (doesn't matter what property) my question is, is there anyway to change the color of a shape once its already been drawn down on the canvas?
Ive tried adding all the square shapes to an array, both stamps and polygons, but it seems impossible to change the color of any of them once they have been drawn.
i know stamp doesn't work because its like a footprint of where the turtle was but is there any method at all that allows for this with polygons or some other method im not aware of?
I didn't add any snippets of code because its a pretty basic question and can be used for many things.
A:
Yes, you can do it. The key to this, and many complicated turtle problems, is using stamps. They are individually, or collectively, removable. And since they take on the shape of the turtle itself, they can be images or arbitrary polygons of any size or color you wish:
from turtle import Turtle, Screen
from random import randrange, choice
from collections import namedtuple
from math import ceil
GRID = 15 # GRID by GRID of squares
SIZE = 30 # each square is SIZE by SIZE
INCREASE = 1.5 # how much to lighten the square's color
WHITE = [255, 255, 255] # color at which we stop changing square
DELAY = 100 # time between calls to change() in milliseconds
DARK = 32 # range (ceil(INCREASE) .. DARK - 1) of dark colors
def change():
block = choice(blocks)
blocks.remove(block)
color = [min(int(primary * INCREASE), WHITE[i]) for i, primary in enumerate(block.color)] # lighten color
turtle.color(color)
turtle.setposition(block.position)
turtle.clearstamp(block.stamp)
stamp = turtle.stamp()
if color != WHITE:
blocks.append(Block(block.position, color, stamp)) # not white yet so keep changing this block
if blocks: # stop all changes if/when all blocks turn white
screen.ontimer(change, DELAY)
HALF_SIZE = SIZE // 2
screen = Screen()
screen.colormode(WHITE[0])
screen.register_shape("block", ((HALF_SIZE, -HALF_SIZE), (HALF_SIZE, HALF_SIZE), (-HALF_SIZE, HALF_SIZE), (-HALF_SIZE, -HALF_SIZE)))
screen.tracer(GRID ** 2) # ala @PyNuts
turtle = Turtle(shape="block", visible=False)
turtle.speed("fastest")
turtle.up()
Block = namedtuple('Block', ['position', 'color', 'stamp'])
blocks = list()
HALF_GRID = GRID // 2
for x in range(-HALF_GRID, HALF_GRID):
for y in range(-HALF_GRID, HALF_GRID):
turtle.goto(x * SIZE, y * SIZE)
color = [randrange(ceil(INCREASE), DARK) for primary in WHITE]
turtle.color(color)
blocks.append(Block(turtle.position(), color, turtle.stamp()))
screen.ontimer(change, DELAY)
screen.exitonclick()
|
[
"stackoverflow",
"0001652848.txt"
] | Q:
MySQL+PHP: Can anyone tell me what is wrong with this code?
I am having problems running this script, but i keep on getting the same error message. Could someone point out where I am going wrong? Thanks.
Error message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
$datenow = date("Y-m-d") . " " . date("H:i:s");
$conn = mysql_connect('localhost', 'admin', 'root') or die(mysql_error());
mysql_select_db('main') or die(mysql_error());
$queryh = "INSERT INTO user_comments (posted_by, posted_to, comment, date_posted) ".
" VALUES ('{$postman}', '{$id}', '{$comment}', '{$datenow}' ";
$result = mysql_query($queryh) or die(mysql_error());
echo "posted";
A:
You are missing the close-parenthesis on your values list.
" VALUES ('{$postman}', '{$id}', '{$comment}', '{$datenow}' ";
^
Close-parenthesis goes here
As a tip,
$datenow = date("Y-m-d") . " " . date("H:i:s");
can be shortened to be:
$datenow = date("Y-m-d H:i:s");
|
[
"stackoverflow",
"0045630712.txt"
] | Q:
How to prevent transfer of values once there are some errors in the xslt file using javascript?
This is my onsubmit function where i have problem. Hope you guys will help.
function editme() {
var peru=document.editform.user_nam.value;
var mailu=document.editform.user_mai.value;
if (peru==null || peru==""){
alert("Name can't be blank");
return false;
}
if(!/(?=.{0,20}$)\S+\s\S+/.test(peru)){
document.getElementById("eredit").innerHTML="1.Value entered in the Name field is invalid;"
}
if(!/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(mailu)){
document.getElementById("erredit").innerHTML="2.Value entered in the E-mail field is invalid";
}
var aa=document.getElementById("ename").value;
var bb=document.getElementById("email").value;
var cc=document.getElementById("sele").value;
var tab=document.getElementById("myTable");
tab.rows[ind].cells[1].innerHTML=aa;
tab.rows[ind].cells[2].innerHTML=bb;
tab.rows[ind].cells[3].innerHTML=cc;
}
Here, even if there are any validation messages, my values are getting submitted to a table.I want to stop the function where there are error messages. How to do that?
A:
Have you tried adding return false, in to the both ifs? Like this:
if(!/(?=.{0,20}$)\S+\s\S+/.test(peru)){
document.getElementById("eredit").innerHTML="1.Value entered in the Name field is invalid;"
return false;
}
if(!/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(mailu)){
document.getElementById("erredit").innerHTML="2.Value entered in the E-mail field is invalid";
return false;
}
Also would be much helpful if you can post your whole code, so I can replicate the problem to see and work with it.
|
[
"stackoverflow",
"0020110824.txt"
] | Q:
SQL select from list where white space has been added to end
I'm trying to select some rows from an Oracle database like so:
select * from water_level where bore_id in ('85570', '112205','6011','SP068253');
This used to work fine but a recent update has meant that bore_id in water_level has had a bunch of whitespace added to the end for each row. So instead of '6011' it is now '6011 '. The number of space characters added to the end varies from 5 to 11.
Is there a way to edit my query to capture the bore_id in my list, taking account that trialling whitespace should be ignored?
I tried:
select * from water_level where bore_id in ('85570%', '112205%','6011%','SP068253%');
which returns more rows than I want, and
select * from water_level where bore_id in ('85570\s*', '112205\s*','6011\s*', 'SP068253\s*');
which didn't return anything?
Thanks
JP
A:
You should RTRIM the WHERE clause
select * from water_level where RTRIM(bore_id) in ('85570', '112205','6011');
To add to that, RTRIM has an overload which you can pass a second parameter of what to trim, so if the trailing characters weren't spaces, you could remove them. For example if the data looked like 85570xxx, you could use:
select * from water_level where RTRIM(bore_id, 'x') IN ('85570','112205', '6011');
|
[
"stackoverflow",
"0037563367.txt"
] | Q:
Convert ECC PKCS#8 public and private keys to traditional format
I have ECC public and private generated with BouncyCastle:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable
.getParameterSpec("secp192r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(ecSpec, new SecureRandom());
KeyPair pair = g.generateKeyPair();
System.out.println(Arrays.toString(pair.getPrivate().getEncoded()));
System.out.println(Arrays.toString(pair.getPublic().getEncoded()));
byte[] privateKey = new byte[]{48, 123, 2, 1, 0, 48, 19, 6, 7, 42, -122, 72, -50, 61, 2, 1, 6, 8, 42, -122, 72, -50, 61, 3, 1, 1, 4, 97, 48, 95, 2, 1, 1, 4, 24, 14, 117, 7, -120, 15, 109, -59, -35, 72, -91, 99, -2, 51, -120, 112, -47, -1, -115, 25, 48, -104, -93, 78, -7, -96, 10, 6, 8, 42, -122, 72, -50, 61, 3, 1, 1, -95, 52, 3, 50, 0, 4, 64, 48, -104, 32, 41, 13, 1, -75, -12, -51, -24, -13, 56, 75, 19, 74, -13, 75, -82, 35, 1, -50, -93, -115, -115, -34, -81, 119, -109, -50, -39, -57, -20, -67, 65, -50, 66, -122, 96, 84, 117, -49, -101, 54, -30, 77, -110, -122}
byte[] publicKey = new byte[]{48, 73, 48, 19, 6, 7, 42, -122, 72, -50, 61, 2, 1, 6, 8, 42, -122, 72, -50, 61, 3, 1, 1, 3, 50, 0, 4, 64, 48, -104, 32, 41, 13, 1, -75, -12, -51, -24, -13, 56, 75, 19, 74, -13, 75, -82, 35, 1, -50, -93, -115, -115, -34, -81, 119, -109, -50, -39, -57, -20, -67, 65, -50, 66, -122, 96, 84, 117, -49, -101, 54, -30, 77, -110, -122}
How to convert them into traditional format which can be reused later in https://github.com/kmackay/micro-ecc/blob/master/uECC.h? I need 24 bytes private and 48 public key while now it is 125 and 75.
A:
Gives 24 and 48, sometimes when 0 is added at the beginning 25 or 49:
ECPrivateKey ecPrivateKey = (ECPrivateKey)privateKey;
System.out.println(ecPrivateKey.getS().toByteArray().length);
ECPublicKey ecPublicKey = (ECPublicKey)publicKey;
System.out.println(ecPublicKey.getW().getAffineX().toByteArray().length + ecPublicKey.getW().getAffineY().toByteArray().length);
|
[
"stackoverflow",
"0061087356.txt"
] | Q:
SubTotal Query based on condition of other column
I am creating a spare part management database in Microsoft Access. I have two table which are ItemTable and EntryTable. ItemTable holds information about each item with unique ItemID and EntryTable holds information of each items usage. I need to calculate the total stock left for each items based on the usage.
So as you can see, for the ItemID with 2, i need to calculate the total stock left based on the usage of In or Out of Status field.
If status is In then plus elseif status is Out then minus. Then total the stock of ItemID 2. Thus the total stock for ItemID 2 will be 3. I have figured out by total and group by for the ItemID but i cannot figure out the way to subtotal based on condition from other column. Thank you.
A:
You can do it with conditional aggregation:
select itemid,
sum(iif(status = 'In', 1, -1) * quantity) as total
from entrytable
group by itemid
|
[
"stackoverflow",
"0013408659.txt"
] | Q:
Build ASP.Net application with Web API and database first strategy
I am new to ASP.NET MVC 4 and Web API.
What I want to achieve is to create a CRUD web application that is able to manipulate the data tables in a simple existing SQL Server 2008 database.
I thought about the new MVC 4 with Web API and Entity Framework. There are a number of samples and examples about code first data access pattern but very few about database first.
Can anyone help with any brief idea how to achieve this with database first and Entity Framework and repository pattern please?
A:
What you've described (CRUD operations, SQL Server, Entity Framework) is the assumed default for MVC4 projects. This should be very straightforward for you to set up given a database-first approach.
Create the MVC4 project in Visual Studio
Under the Models folder, create a new Entity Framework class (ADO.Net Entity Framework Model). Choose "generate from database" and follow the instructions
Build the project
Right click on the Controllers folder and add a new controller. Choose "MVC controller with read/write actions and views, using Entity Framework". For the Model class, select the table entities you want to target. For the Data context class, select the Entity Framework class you created in step 2.
That's it. You should be able to run the project and have scaffolded CRUD forms fully operational (navigate to /YourControllerName to see a list of rows from the table). You can repeat step 4 as needed to add other table controllers.
A:
I started down this path a few months ago: learning ASP.Net, MVC3, using an existing database to build an App.
This is what I found (I'm happy to be corrected):
Don't learn VB, learn C#. There are very few VB samples around.
I followed a 'database first' tutorial. There are many tutorials on the web, just get started and follow one and don't be afraid to start over
If you want anything remotely flashy you need to use JQuery - this is basically a javascript library. MVC / ASP.Net offers very little in the way of interactive grids and pages.
It turns out that MVC is a bit of a misnomer. Often you need 5 layers, not 3:
Model (The M in MVC, generally generated for you by some code generation tool like Entity Framework, maps directly to tables)
ViewModel (wrapper classes around your autogenereated table classes that add more useful data) - this post is where I came accross them:
MVC dbContext find parent record when current record has no elements
Controller (The C in MVC)
View (The View in MVC)
Javascript (If you want anything beyond a basic HTML form, like a gird or a date picker you need to use javascript)
Like I say I'm happy to be corrected on any of these points. This is just my viewpoint at this stage of my journey. I have to say I have only investigate jqGrid as a grid solution and I'm just about ready to try something else.
|
[
"stackoverflow",
"0053688140.txt"
] | Q:
How to get a screen resize dimension from a service in angular 2+?
First this not duplicated take time to read, because there is lot of similar question but they are in the @Component decorator
I got the idea to catch screen resizing in a service then sharing some css value by an observable, but it seem that my service is not working (not able to catch screen resize event).
Here is my code
import { Injectable, HostListener } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class BreakPointService {
normal: {
background: 'w3-teal',
inputColor: 'w3-light-grey',
css_parent: 'w3-container w3-teal'
};
breakpoint: {
background: 'w3-dark-blue',
inputColor: 'w3-white',
css_parent: 'w3-container w3-light-grey'
};
breakPointValue: number;
css_behaviour = new BehaviorSubject(JSON.stringify(this.breakpoint));
current_css = this.css_behaviour.asObservable();
@HostListener('window:resize', ['$event'])
onResize(event) {
console.log();
this.breakPointValue = window.innerWidth;
console.log(this.breakPointValue);
if (this.breakPointValue > 768) {
console.log(JSON.stringify(this.normal));
this.css_behaviour.next(JSON.stringify(this.normal));
} else {
console.log(JSON.stringify(this.breakpoint));
this.css_behaviour.next(JSON.stringify(this.breakpoint));
}
}
public css() {
if (this.breakPointValue > 768) {
return this.normal;
}
return this.breakpoint;
}
constructor() { }
}
Is there any way to do this or this is incheavable from a service ?
A:
So I did not see in your OP where you are initializing the service. I had to do this almost exact thing in one app. We watch for screen size changes which triggers changes in some user preferences in local storage:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { TableViewTypes, MediaSizes, UserPreferencesDefaults, TableView, getTableViewDefaults } from '../models/user-preferences.model';
import { StorageService } from './storage.service';
@Injectable()
export class UserPreferencesService {
private tableViewSubject = new BehaviorSubject<TableView>(UserPreferencesDefaults.tableView);
tableView$ = this.tableViewSubject.asObservable();
constructor(
private storageService: StorageService
) {}
init() {
this.tableViewSubject.next(
!(window.outerWidth > MediaSizes.sm) ?
getTableViewDefaults(false) :
UserPreferencesDefaults.tableView
);
window.addEventListener('resize', () => {
this.tableViewSubject.next(
!(window.outerWidth > MediaSizes.sm) ?
getTableViewDefaults(false) :
this.storageService.userPreferences.tableView
);
});
}
storeTableView(tableType: TableViewTypes, value: boolean) {
this.storageService.userPreferences = {
...this.storageService.userPreferences,
tableView: {
...this.storageService.userPreferences.tableView,
[tableType]: value
}
};
}
toggleTableView(tableType: TableViewTypes, value?: boolean) {
value = value !== undefined && value !== null ? value : !this.storageService.userPreferences.tableView[tableType];
this.tableViewSubject.next({
...this.storageService.userPreferences.tableView,
[tableType]: value
});
this.storeTableView(tableType, value);
}
}
Then in order for the service to work it is initialized by injecting it into the app.component.ts in the constructor param
constructor(
private userPreferenceService: UserPreferencesService,
) {this.userPreferenceService.init();}
|
[
"stackoverflow",
"0021629828.txt"
] | Q:
Is it possible to identify the format of a string?
Is it possible to recognize if a string is formatted as a BSON ObjectID?
For strings we could do:
"hello".is_a?(String) # => true
That would not work since the ObjectID is a String anyway. But is it possible to analyze the string to determine if it's formatted as a BSON ObjectID?
Usually, ObjectIDs have this format.
52f4e2274d6f6865080c0000
The formatting criteria is stated in the docs:
ObjectId is a 12-byte BSON type, constructed using:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
A:
Any 24 chararcters long hexadecimal string is a valid BSON object id, so you can check it using this regular expression:
'52f4e2274d6f6865080c0000' =~ /\A\h{24}\z/
# => 0
Both the moped (used by mongoid) and the bson (used by mongo_mapper) gems encapsulates this check in a legal? method:
require 'moped'
Moped::BSON::ObjectId.legal?('00' * 12)
# => true
require 'bson'
BSON::ObjectId.legal?('00' * 12)
# => true
|
[
"stackoverflow",
"0060419343.txt"
] | Q:
Get AddressPO from an AddressBo object
I have an instance of an AddressBO in my code and i want to get corresponding AddressPO without using the AddressPOFactory. Is that possible ?
Thanks
A:
In java code try following:
addressBO.getExtension(PersistentObjectBOExtension.class).getPersistentObject()
In pipeline/ISML:
AddressBO:Extension("PersistentObjectBOExtension"):PersistentObject
|
[
"stackoverflow",
"0009091991.txt"
] | Q:
SQL - How to match on string pattern starting at random index inside string
I have the following pattern;
AA(AA)–NBXXYYY–CCCCCCC(CC)–DD(D)
Where the values in brackets are optional and may not exist.
I want to select only the XX part of the string. Could it be done with clever use of substring? I would appreciate any good input here.
Edit:
A hint might be that I can always skip the stuff before the first hyphen (-), which will always be there... but still not sure how to implement it.
A:
declare @S varchar(100) = 'AA(AA)-NBXXYYY-CCCCCCC(CC)-DD(D)'
-- First two characters after –NB
select substring(@S, charindex('-NB', @S)+3, 2)
-- Or if it is not always NB just find the first –
select substring(@S, charindex('-', @S)+3, 2)
With your sample data:
;with C(col) as
(
select '10-1R22345-33PY101-N4' union all
select '100-1R22345-33PY101Z-N4' union all
select '1000-1R22345-33PY101ZZ-N4'
)
select substring(col, charindex('-', col)+3, 2)
from C
|
[
"stackoverflow",
"0011932334.txt"
] | Q:
Cannot deploy xcode project in iphone
I would need your help if possible please.
I'm trying to deploy axcode project in an iphone. I followed all the steps, but when i try to deploy it i get this message:
Choose a destination with a supported architecture in order to run on this device.
Now, i've read a lot on the internet and i didn't come up with a good choice...
The main settings are:
Deployment Target 3.2
Architectures: Armv7
I am currently trying to install it in a iphone 3...
Thanks
A:
iphone 3 needs armv6 support im sure,
You can set this in your Target Build Settings in Xcode
Check out my screen grab.
Cheers,
LB
|
[
"stackoverflow",
"0013543423.txt"
] | Q:
how to sum 2d array
Good evening
I have a question here. i have two arrays: $duration_c[$k][$s]. it prints all ok
$duration_c[0][0]="19:30:00";
$duration_c[0][1]="00:10:00";
$duration_c[1][0]="00:30:00";
$duration_c[1][1]="00:20:00";
than to sum
$times=$duration_c[$k][$s];
function sum_the_time($times) {
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
echo sum_the_time($times);
how to sum $duration_c[0][0]+$duration_c[0][1] and $duration_c[1][0]+$duration_c[1][1], and how to print?
there is error Invalid argument supplied for foreach()
A:
you are sending only one value to sum_the_time function as $times=$duration_c[$k][$s];
$times has only one value you can print and check what value is going to the function by writing like this
$times=$duration_c[$k][$s];
echo $times;
use
$times=$duration_c[$k];
so that you can send array to your function and foreach will not give you error
$times=$duration_c[$k]; // contains array of times
function sum_the_time($times) {
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
echo sum_the_time($times);
|
[
"stackoverflow",
"0059964378.txt"
] | Q:
How I can split my array to multiple arrays based in a value with Javascript?
I have an array and I want to split it to multiple arrays based on the value 'Finished', when I find it, I split the array.
My code is :
var input = ['urlGettingF', '├─BROKEN─aquaHTTP_404', '├─BROKEN─url1HTTP_404' , 'ok', 'urlok', 'Finished',
'urlGettingF2', '├─BROKEN─url1HTTP_404','├─BROKEN─url21HTTP_404', 'Finished',
'urlGettingF3', '├─BROKEN─url3HTTP_404','├─BROKEN─url213HTTP_404', 'Finished'
];
function chunkArray(array, size) {
let result = []
for (value of array) {
let lastArray = result[result.length - 1]
if (!lastArray || lastArray.length == size) {
result.push([value])
} else {
lastArray.push(value)
}
}
return result
}
const x = input.findIndex(element => element.indexOf('Finished') > -1)
console.log(chunkArray(input, x + 1));
when I run it I get :
But I want the result will be :
[["urlGettingF", "├─BROKEN─aquaHTTP_404", "├─BROKEN─url1HTTP_404", "ok", "urlok", "Finished"], ["urlGettingF2", "├─BROKEN─url1HTTP_404", "├─BROKEN─url21HTTP_404", "Finished"], ["urlGettingF3", "├─BROKEN─url3HTTP_404", "├─BROKEN─url213HTTP_404", "Finished"]]
When I find Finished, I split my array based on her index, you can see my code in jsbin
https://jsbin.com/benozuyutu/1/edit?js,console
How I can fix it ?
A:
var input = ['urlGettingF', '├─BROKEN─aquaHTTP_404', '├─BROKEN─url1HTTP_404', 'ok', 'urlok', 'Finished',
'urlGettingF2', '├─BROKEN─url1HTTP_404', '├─BROKEN─url21HTTP_404', 'Finished',
'urlGettingF3', '├─BROKEN─url3HTTP_404', '├─BROKEN─url213HTTP_404', 'Finished'
];
function chunkArray(arr) {
let result = [
[]
];
let index = 0;
arr.forEach((x, i) => {
result[index].push(x);
if ((i + 1) < arr.length && x.includes('Finished')) {
index++;
result[index] = [];
}
});
return result
}
console.log(chunkArray(input));
|
[
"stackoverflow",
"0013235835.txt"
] | Q:
Prefill then lock
We have a library of PDF forms that contain fillable fields and that can be opened in Adobe Reader and filled out by our end users. Note that we are NOT generating PDFs but simply using existing PDFs. All of these forms are protected against editing non-fillable fields in Acrobat by means of a password.
The problem is that when we open the PDF in our code to prefill some of the fields the password protection is lost and the form that is served up is editable in Acrobat.
So:
Is there a way to prefill fillable fields using iTextSharp without unlocking the PDF and the resulting output stream?
Is there a way to relock the form while still allowing an end user
to open in Reader, fill fillable fields, print, etc., without
requiring a password?
Here is a simplified example of the code we are currently using. We have tried locking the output stream (code not currently available) but the file could not then Reader prompted the user for a password.
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] password = encoding.GetBytes("secretPassword");
PdfReader reader = null;
MemoryStream outputStream = null;
PdfStamper stamper = null;
pdfStream.Seek(0, SeekOrigin.Begin);
reader = new PdfReader(pdfStream, password);
outputStream = new MemoryStream();
stamper = new PdfStamper(reader, outputStream);
AcroFields fields = stamper.AcroFields;
fields.SetField("prefillField1", "Some text");
stamper.Close();
outputStream.Close();
reader.Close();
// outputStream sent to user/browser. PDF opens in Reader, but the form can be opened in
// Acrobat without a password and edited.
A:
You cannot edit a PDF if it is password protected. You will like you are doing have to open it with the password to edit it. With that it looks like you are creating a copy of that document and presenting to the user. You can encrypt the PDF with an edit password. Here is a copy of a method that I found that I use with itextsharp. If you set the editPassword while leaving the openPassword null then your users should be able to view the pdf and interact with it but won't be able to edit it based on the permissions you set. Hope this helps.
/// <summary>
/// Adds the given Open (User) and Edit (Owner) password to the PDF and optionally sets
/// the various Allow/Not Allowed restrictions
/// </summary>
/// <param name="openPassword">Open/User password</param>
/// <param name="editPassword">Edit/Owner password</param>
/// <param name="allowAssemply">Assembly means merging, extracting, etc the PDF pages</param>
/// <param name="allowCopy">Copy means right-click copying the content of the PDF to the system</param>
/// <param name="allowDegradedPrinting">Can print low quality version of the PDF</param>
/// <param name="allowFillIn">Can insert data into any AcroForms in the PDF</param>
/// <param name="allowModifyAnnotations">Modification of any annotations</param>
/// <param name="allowModifyContents">Modification of any content in the PDF</param>
/// <param name="allowPrinting">Allows printing at any quality level</param>
/// <param name="allowScreenReaders">Allows the content to be parsed/repurposed for screen readers</param>
public byte[] GetEncryptedPDF(byte[] pdf,
string openPassword, string editPassword,
bool allowAssemply, bool allowCopy,
bool allowDegradedPrinting, bool allowFillIn,
bool allowModifyAnnotations, bool allowModifyContents,
bool allowPrinting, bool allowScreenReaders)
{
int permissions = 0;
if (allowAssemply)
permissions = permissions | PdfWriter.ALLOW_ASSEMBLY;
if (allowCopy)
permissions = permissions | PdfWriter.ALLOW_COPY;
if (allowDegradedPrinting)
permissions = permissions | PdfWriter.ALLOW_DEGRADED_PRINTING;
if (allowFillIn)
permissions = permissions | PdfWriter.ALLOW_FILL_IN;
if (allowModifyAnnotations)
permissions = permissions | PdfWriter.ALLOW_MODIFY_ANNOTATIONS;
if (allowModifyContents)
permissions = permissions | PdfWriter.ALLOW_MODIFY_CONTENTS;
if (allowPrinting)
permissions = permissions | PdfWriter.ALLOW_PRINTING;
if (allowScreenReaders)
permissions = permissions | PdfWriter.ALLOW_SCREENREADERS;
PdfReader reader = new PdfReader(pdf);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfEncryptor.Encrypt(reader, memoryStream, true, openPassword, editPassword, permissions);
reader.Close();
return memoryStream.ToArray();
}
}
|
[
"mathematica.stackexchange",
"0000061065.txt"
] | Q:
My Baum-Welch algorithm is very slow. Is it due to Mathematica?
I've also posted this question here, since I'm not sure which community is more adequate for this type of question.
I've programmed imperatively the Baum-Welch algorithm for a 2 state hidden Markov model (HMM), as is explained in this book. When I try it with a size sample of 100, I usually get a decent estimate after 18 seconds. However, when I use a sample size of 500, it takes me between 290-350 seconds to get an improved estimation of the HMM parameters.
I get the impression the algorithm should not perform this badly. However I'm not sure why it does.
One thing I've discovered is that Mathematica is more functional oriented, so when I program iteratively I'm losing some computation 'power'. But is this really enough for this bad performance??
What is your experience with this algorithm?
I'm using as stopping criterion when the norm of the difference between the current estimate and the previous one is less than $10^{-3}$. This criterion just seemed simple enough. I'm also trying to use other stopping criteria, but it doesn't seems to alter much. The problem is each iteration of the algorithm, in a sample size of 500, takes almost 20 seconds more or less... This worries me.
Any help would be appreciated.
Here is my code.
EM1[y_, ite_] :=
Module[{n, listainicial, teta0, teta1, teta2, likeham, likehamtotal,
pimattotal, sigmatotal, tetatotal, θk1, θk2,
listak, listbk, fikyj, iterations},
n = Length[y] - 1;
listainicial = N[Table[0, {j, 1, n}]];
pimattotal = listainicial;
tetatotal = listainicial;
sigmatotal = listainicial;
likehamtotal = listainicial;
likeham[pimat_, fiyj_] := Module[{pizero, Pmat, counter, mult},
pizero = pimat[[1]];
Pmat = {pimat[[2]], pimat[[3]]};
counter = 1;
mult = IdentityMatrix[2];
While[counter <= n,
mult =
Dot[mult,
Dot[Pmat, {{fiyj[[1, counter]], 0}, {0, fiyj[[2, counter]]}}]];
counter = counter + 1;
];
Dot[Dot[pizero, mult], {1, 1}]
];
iterations = 1;
While[iterations <= ite,
(*initialization*)
pim0 = RandomVariate[UniformDistribution[{0, 1}]];
pim1 = RandomVariate[UniformDistribution[{0, 1}]];
pim2 = RandomVariate[UniformDistribution[{0, 1}]];
pimatk = N[{{pim0, 1 - pim0}, {pim1, 1 - pim1}, {pim2, 1 - pim2}}];
fikyj = N[Table[Table[1/n, {j, 1, n}], {i, 1, 2}]];
ak = N[Table[Table[0.1, {j, 1, n}], {i, 1, 2}]];
bk = N[Table[Table[1, {j, 1, n}], {i, 1, 2}]];
θk1 = {0.1, 0.1, 0.1};
θk2 = {0.5, 0.5, 0.5};
listak = listainicial;
listbk = listainicial;
While[Norm[θk1 - θk2] > 10^-3,
θk1 = θk2;
ak[[1, 1]] = pimatk[[1, 1]]*fikyj[[1, 1]];
ak[[2, 1]] = pimatk[[1, 2]]*fikyj[[2, 1]];
ak[[1, 1]] = ak[[1, 1]];
ak[[2, 1]] = ak[[2, 1]];
(*Induction*)
counterE = 1;
While [counterE <= n - 1,
ak[[1,
counterE +
1]] = (pimatk[[1 + 1, 1]]*ak[[1, counterE]] +
pimatk[[2 + 1, 1]]*ak[[2, counterE]])*
fikyj[[1, counterE + 1]];
ak[[2,
counterE +
1]] = (pimatk[[1 + 1, 2]]*ak[[1, counterE]] +
pimatk[[2 + 1, 2]]*ak[[2, counterE]])*
fikyj[[2, counterE + 1]];
ak[[1, counterE + 1]] = ak[[1, counterE + 1]];
ak[[2, counterE + 1]] = ak[[2, counterE + 1]];
bk[[1, n - counterE]] =
pimatk[[1 + 1, 1]]*fikyj[[1, n - counterE + 1]]*
bk[[1, n - counterE + 1]] +
pimatk[[1 + 1, 2]]*fikyj[[2, n - counterE + 1]]*
bk[[2, n - counterE + 1]];
bk[[2, n - counterE]] =
pimatk[[2 + 1, 1]]*fikyj[[1, n - counterE + 1]]*
bk[[1, n - counterE + 1]] +
pimatk[[2 + 1, 2]]*fikyj[[2, n - counterE + 1]]*
bk[[2, n - counterE + 1]];
bk[[1, n - counterE]] = bk[[1, n - counterE]];
bk[[2, n - counterE]] = bk[[2, n - counterE]];
counterE = counterE + 1;
];
τhijk =
Table[Table[
Table[(ak[[h, j]]*pimatk[[h + 1, i]]*fikyj[[i, j + 1]]*
bk[[i, j + 1]])/(Sum[
Sum[ak[[hh, j]]*pimatk[[hh + 1, ii]]*fikyj[[ii, j + 1]]*
bk[[ii, j + 1]], {ii, 1, 2}], {hh, 1, 2}]), {j, 1,
n - 1}], {i, 1, 2}], {h, 1, 2}];
τijk =
Table[Table[
ak[[i, j]]*
bk[[i, j]]/(Sum[
ak[[h, j]]*10^listak[[j]]*bk[[h, j]], {h, 1, 2}]), {j, 1,
n}], {i, 1, 2}];
(*M-step*)
teta0 = (Sum[
Sum[(Sum[
y[[j + 1]]*τijk[[i, j]], {j, 1, n}])*τijk[[i,
k]]*y[[k]]/(Sum[τijk[[i, j]], {j, 1, n}]) -
y[[k + 1]]*y[[k]]*τijk[[i, k]], {i, 1, 2}], {k, 1,
n}])/(Sum[
Sum[(Sum[
y[[j]]*τijk[[i, j]], {j, 1,
n}]/(Sum[τijk[[i, j]], {j, 1, n}]) -
y[[k]])*τijk[[i, k]]*y[[k]], {i, 1, 2}], {k, 1, n}]);
teta1 =
Sum[τijk[[1, j]]*(y[[j + 1]] - teta0*y[[j]]), {j, 1, n}]/
Sum[τijk[[1, j]], {j, 1, n}];
teta2 =
Sum[τijk[[2, j]]*(y[[j + 1]] - teta0*y[[j]]), {j, 1, n}]/
Sum[τijk[[2, j]], {j, 1, n}];
sigmaest =
Sqrt[Sum[((y[[j + 1]] - teta1 - teta0*y[[j]])^2*τijk[[1,
j]] + (y[[j + 1]] - teta2 - teta0*y[[j]])^2*τijk[[2,
j]]), {j, 1, n}]/(n)];
θk2 = {teta0, teta1, teta2};
(*Q[θ_,σ_]:=(τijk[[1,1]]*Log[pimatk[[1,
1]]]+τijk[[2,1]]*Log[pimatk[[1,2]]])+Sum[Sum[
Sum[τhijk[[h,i,j]]*Log[pimatk[[h+1,i]]],{j,1,n-1}],{i,1,
2}],{h,1,2}]+Sum[Sum[τijk[[i,j]]*Log[1/(Sqrt[2*
Pi]*σ)]*(-(y[[j+1]]-θ[[i+1]]-θ[[1]]*y[[
j]])^2/(2*σ^2)),{j,1,n}],{i,1,2}];*)
(*updates on remaining parameters*)
pimatk[[1, 1]] = τijk[[1, 1]];
pimatk[[1, 2]] = τijk[[2, 1]];(*π_ 0i=τijk[[i,
1]]*)
pimatk[[2, 1]] =
Sum[τhijk[[1, 1, j]], {j, 1, n - 1}]/
Sum[τijk[[1, j]], {j, 2, n}];
pimatk[[2, 2]] =
Sum[τhijk[[1, 2, j]], {j, 1, n - 1}]/
Sum[τijk[[1, j]], {j, 2, n}];
pimatk[[3, 1]] =
Sum[τhijk[[2, 1, j]], {j, 1, n - 1}]/
Sum[τijk[[2, j]], {j, 2, n}];
pimatk[[3, 2]] =
Sum[τhijk[[2, 2, j]], {j, 1, n - 1}]/
Sum[τijk[[2, j]], {j, 2, n}];(*π_hi=(\!\(
\*UnderoverscriptBox[\(∑\), \(j = 2\), \(n\)]
\*SubscriptBox[\(τ\), \(hij\)]\))/\!\(
\*UnderoverscriptBox[\(∑\), \(j = 2\), \(n\)]
\*SubscriptBox[\(τ\), \(hj\)]\)*)
(*Print["pimatk =",pimatk];*)
counterM = 1;
While[counterM <= n,
fikyj[[1, counterM]] = (1/(Sqrt[2*Pi]*sigmaest))*
E^(-(y[[counterM + 1]] - θk2[[2]] - θk2[[1]]*
y[[counterM]])^2/(2*sigmaest^2));
fikyj[[2, counterM]] = (1/(Sqrt[2*Pi]*sigmaest))*
E^(-(y[[counterM + 1]] - θk2[[3]] - θk2[[1]]*
y[[counterM]])^2/(2*sigmaest^2));
counterM = counterM + 1;
];
];
likehamtotal[[iterations]] = likeham[pimatk, fikyj];
pimattotal[[iterations]] = pimatk;
tetatotal[[iterations]] = θk2;
sigmatotal[[iterations]] = sigmaest;
iterations = iterations + 1;
];
iterations = 1;
pos = 1;
While[iterations <= ite ,
If[likehamtotal[[iterations]] > likehamtotal[[pos]],
pos = iterations];
iterations = iterations + 1
];
{pimattotal[[pos]], tetatotal[[pos]], sigmatotal[[pos]]}
];
A:
A very clear description of a Mathematica implementation of BW is given by Robert J Frey here. He seems to not have performance issues.
|
[
"stackoverflow",
"0032039041.txt"
] | Q:
Excel. Worksheet Change to Worksheet Calculate
I have code that runs perfectly on "Worksheet_Change" event.
The value in cell "A1" changes frequently from a live feed.
I need help to adapt the code from this event to work with "Worksheet_Calculate" event.
Every time Cell value A1 changes, automatically the Old value must be shown in A2.
A1 New Value
A2 Old Value
Here is the code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim NewValue, OldValue
If Target.Address <> "$A$1" Then Exit Sub
Application.EnableEvents = False
With Target
NewValue = .Value
Application.Undo
OldValue = .Value
.Value = NewValue
End With
Range("a2").Value = OldValue
Application.EnableEvents = True
End Sub
A:
For one sheet place this code in the Sheet module (initial Old value will be empty)
Option Explicit
Private oldVal As String
Private Sub Worksheet_Calculate()
updateOldValue Me.Range("A1")
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
updateOldValue Target
End Sub
'------------------------------------------------------------------------------------------
Public Sub updateOldValue(ByVal Target As Range)
With Target
If .CountLarge = 1 Then
If .Address = "$A$1" Then
.Offset(1, 0) = oldVal
oldVal = .Value2
End If
End If
End With
End Sub
.
For multiple sheets, place this code in a new VBA module, and call it the same way:
updateOldValue Me.Range("A1") or updateOldValue Target:
Option Explicit
Private oldVal As String
Public Sub updateOldValue(ByVal Target As Range)
With Target
If .CountLarge = 1 Then
If .Address = "$A$1" Then
.Offset(1, 0) = oldVal
oldVal = .Value2
End If
End If
End With
End Sub
|
[
"stackoverflow",
"0022963054.txt"
] | Q:
Video not Buffereing
I am currently building a website opensourceeducation.in. It is a video hosting website. I am using flowplayer for playing videos. My problem is when i play the video it takes alot of time to load. On doing inspect element i can see the whole video is loaded into the cache and then played, instead of buffereing the video part by part. I am using godaddy hosting to host my website. Any help welcome. Thank you.
Below given is my player code.
<div id="flow" class="flowplayer aside-time play-button center is-splash" data-ratio="0.5625" data-volume="0.5" style="background:black;width: 100%;margin-top:2em;">
<video >
<source id="palyer" type="video/mp4" src="<?php echo $result->location?>"></source>
Your Browser Is Not Supported
</video>
</div>
A:
What you describe seems to indicate a problem with the format of your mp4. It needs to be optimized for streaming (aka fast start).
Have a look at this post. I solved it already for another stacker.
Let us know if it works for you
|
[
"stackoverflow",
"0023574206.txt"
] | Q:
Holder JS not working in ASP.net update panel
I am using Holder.js to genearte client side images.
If I write
<img src="holder.js/300x200">
it works..!
But if I write the same thing in an update panel the image is not generated.
When I inspect the element using chrome tools, the image is rendered with correct Image URL but does not display the image.
Why is this happening? and any solutions to it?
My Code:
<asp:UpdatePanel ID="updatepnlReppeaterSummary" runat="server">
<ContentTemplate>
<asp:Repeater ID="repeaterSummary" runat="server">
<ItemTemplate>
<div class="row">
<div class="col-sm-12">
<img src="holder.js/300x200">
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Any help appreciated...
A:
You have to execute Holder.run after every DOM update. Make sure to call Holder.run on the pageLoad event or another callback.
|
[
"stackoverflow",
"0007528023.txt"
] | Q:
Recipe linkandpostlink failed with exit code 1 error
When I try to run a qt application on a Symbian device (N8 for example), I receive the following:
warning: Missing dependency detected: C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/kqoauthd0.dso
error: Recipe linkandpostlink failed with exit code 1.
Any one hear about that type of error?
A:
Solved !!! The problem was that I am including a .dll library, this works great for the simulator but not for the device, so the idea was to include all .h and .cpp files if the target is a symbian device, and the .dll library if the target is the simulator.
|
[
"unix.stackexchange",
"0000250750.txt"
] | Q:
What is happening behind the scenes for these basic Unix commands?
I was just playing with some basic Unix commands with following operations
create a file 'one'
create a link 'two' to 'one' (ln one two)
Edit the file 'one' and put words - one, two, three, four on separate lines.
Checked contents of 'two' - it has the same contents, so far so good.
Create a soft link 'three' to one. three also has same contents
Verified the number of links using ls -l.
Edited file 'one' and added word 'five' on a separate line.
Checked that files 'two' and 'three' have the same contents - so far so good
Edited soft link three (vim three) and added the word 'six' at the end.
Checked all the three files now have one to six in words.
Question - I understand if file 'one' gets contents of file 'three'. But why does file 'two' also get them?
If I do ls -l, I see that files one and two have 28 bytes, whereas file three has only 3 bytes (maybe for six). What is the reason for this?
Now if I remove file 'one', I see that three is still shown to be linked to one, but I cannot cat three and get error that file does not exist. But then why it is shown in the ls command?
A:
why does file 'two' also get them?
cause ln(1) make hard links by default, and 'two' is a hard link of 'one', according to the man page:
A hard link to a file is indistinguishable from the original directory entry; any changes to a file are effectively independent of the name used to reference the file.
If I do ls -l, I see that files one and two have 28 bytes, whereas file three has only 3 bytes (maybe for six). What is the reason for this?
cause the file content has 28 bytes, like this:
$ wc -c <<<'one two three four five six'
28
except new line char replaced by space.
for the file 'three', it's a symbol link. a symbol link contains the name of the file to which it is linked. so 'three' would have size of the name of file 'one', and it's 3 bytes.
Now if I remove file 'one', I see that three is still shown to be linked to one, but I cannot cat three and get error that file does not exist. But then why it is shown in the ls command?
If you remove file 'one', 'three' becomes a broken symbol link. Symbol links are a specific file type, unless you remove it explicitly, it would not disappear when the file it linked to is removed.
|
[
"stackoverflow",
"0023204328.txt"
] | Q:
Reduce a sparse matrix in numpy
It seems that I am missing something very basic here.
I have a large square matrix which is mostly zeros. What I want is to reduce it to a matrix that contains all rows and columns with non-zero entries.
For example:
1 1 0 1
1 1 0 1
0 0 0 0
1 1 0 1
Should be reduced to:
1 1 1
1 1 1
1 1 1
Is there a fast way to do this?
A:
How about something like this:
>>> arr
array([[ 1., 1., 0., 1.],
[ 1., 1., 0., 1.],
[ 0., 0., 0., 0.],
[ 1., 1., 0., 1.]])
>>> mask = (arr==0)
arr = arr[~np.all(mask,axis=0)]
arr = arr[:,~np.all(mask,axis=1)]
>>> arr
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
|
[
"diy.stackexchange",
"0000098130.txt"
] | Q:
Type of screws for 2x4 shelves and benches
I am making some shelves and workshop benches out of 2x4 and OSB, just the standard type you see in a lot of garages/workshops. I want them to be sturdy and support a good amount of weight.
My question is what type of screws should I use, drywall screws, decking screws, or something else; what about torx vs phillips? Would I need to predrill holes (OSB/2x4s), ideally I wouldn't so I could make quick work of the assembly. Also what length is good, some places have screws going through two 2x4, would 3 inch screws protrude the other side in that case?
A:
Do not use drywall screws. They are thin bodied and brittle. They hold because there is virtually no dynamic load and the load is spread over many screws on many studs.
I would favor construction screws, although deck screws would be fine. You can find both types with drill point tips that make predrilling unnecessary except in harder materials (such as hardwood or mdf).
Most carpenters have moved to star (Torx is a brand) over phillips, although some modified phillips (such as Pozidriv or Supadriv) have advocates, but they need special bits and screwdrivers to work at their best.
Length of screws should be determined by the thickness of the wood you are attaching. It is bad form (and dangerous) to leave tips protruding because of overlong screws. If you need to go through one 2x in places and two 2x in others, use different length screws. Usually if there is a pair of studs that are already attached, any OSB panels would likely only need to go through the stud it is facing, not the sister stud. Screws can probably be the thickness of the OSB + 1 to 1 1/4 inches. The screws to sister 2 2x studs should be 2 1/2 inches (2 3/4 would be fine, but an uncommon size)
|
[
"stackoverflow",
"0034291057.txt"
] | Q:
Undefined symbols for architecture x86_64 while trying to use swig to wrap c++ library to Python
I am trying to wrap a c++ class in Python using swig. I compiled the class and generated .o file and also the wrap file using swig but now when I try to create a library from the files I get the following error.
$g++ -lpython -dynamiclib vertex.o vertex_wrap.o -o _vertex.so
Undefined symbols for architecture x86_64:
"Cell::removeVertex(Vertex*)", referenced from:
Vertex::kill(Vertex*) in vertex.o
Vertex::~Vertex() in vertex.o
Vertex::~Vertex() in vertex.o
"Cell::addVertex(Vertex*)", referenced from:
Vertex::make(Cell*) in vertex.o
Vertex::Vertex(Cell*) in vertex.o
Vertex::Vertex(Cell*) in vertex.o
ld: symbol(s) not found for architecture x86_64
A:
Vertex makes calls to a Cell (probably, a Vertex is typically contained in a Cell), namely to Cell::removeVertex(Vertex*) and Cell::addVertex(Vertex*). These functions must be defined in some other source file (perhaps cell.cpp, just guessing).
So you need to compile the source file cell.cpp and link cell.o as well (and perhaps other source files if there are more dependencies)
This has nothing to do with SWIG or wrapping for python by the way.
|
[
"stackoverflow",
"0014585552.txt"
] | Q:
Applescript to open and save an Indesign Document not working
I'm currently playing around with creating an applescript droplet that will in the end allow me to drop multiple files to be opened and then saved. This is all I need to do as this updates the old indesign files to CS5 (we have a lot of them).
I'm able to create a droplet that opens multiple indesign files, but im having trouble with them being saved. Here is the script so far:
on open these
tell application "Adobe InDesign CS5"
open these
end tell
end open
tell application "Adobe InDesign CS5"
save these
end tell
At the moment its not executing the "save these" command. Seems like it would be straightforward enough but i'm findin it hard to get information how to tell indesign to save these opened documents that i've dropped in the droplet. I'm probably not using the right "selector" (if I can use that term). So i would like the script to "select" the open documents and these "selected" documents then need to be saved (a simple save command rather than a save as).
And ideally i would like for the script to open the first document and saving it before moving on to the second document and so forth. But that is secondary.
I've also tried this script:
on open these
tell application "Adobe InDesign CS5"
open these
end tell
end open
tell these
save
end tell
Same result here as well. I'm a bit of a beginner on this so I might've overlooked something very basic. Any help would be much appreciated!
Thank you.
Edit: Typo in the title, whoops!
A:
you can't just tell indesign to save "thees" you have to talk to each item specifying item and and location format etc for for saving
so you will have to loop through each one
pseudo code here
on open these
repeat with afile in these
tell application "Adobe InDesign CS5"
open afile
tell document 1
save afile to "/location/to/save"
close afile
end tell
end tell
end repeat
end open
here is the dictionary instructions for save
save v : Save the document
save specifier
[to alias or text] : Where to save the document. If the document is already saved, a copy is saved at this path, the original file is closed the new copy is opened
[stationery boolean] : Whether to save the file as stationery. Can accept: boolean (Default: FALSE).
[version comments text] : The comment for this version
[force save boolean] : Forcibly save a version. Can accept: boolean (Default: FALSE).
→ document : The saved document
as DigiMonk noted you may just be able to use close by itself
on open these
repeat with afile in these
tell application "Adobe InDesign CS5"
open afile
tell document 1
close afile saving yes
end tell
end tell
end repeat
end open
|
[
"stackoverflow",
"0020993040.txt"
] | Q:
information about this type of selection in jquery $('.myclass',obj).length;
anyone know where can I get information about this Type of selection in jquery
I found it in a .js file and I want to know about it.
I focus on Jquery api doc but in vain I dont find it.
var obj=$('#id1');
var t = $('.slidenews',obj).length;
exactly that what I want to know about.
var t = $('.slidenews',obj).length;
A:
$('...', element) looks for ... in element instead of the whole document. So in this case, it will look for all elements with class slidenews in the #id1 element.
.length returns the number of such elements found
Therefore, if obj contains the element with ID id1, then $('.slidenews',obj).length returns the number of elements with class slidenews that are contained inside the element with ID id1.
Relevant documentation:
jQuery(selector, [context])
selector
Type: Selector
A string containing a selector expression
context
Type: Element or jQuery
A DOM Element, Document, or jQuery to use as context
length
Description: The number of elements in the jQuery object
|
[
"stackoverflow",
"0014614994.txt"
] | Q:
SQLite Error 21 . "Misuse at line ... "
I'm using this code to store SQLite DB to sdcard location (location on device /mnt/sdcard/MiniMate ):
string libraryPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
libraryPath = System.IO.Path.Combine(libraryPath, "MiniMate");
if (!System.IO.Directory.Exists(libraryPath)) System.IO.Directory.CreateDirectory(libraryPath);
string path = System.IO.Path.Combine(libraryPath, sqliteFilename);
It works perfect when I using deploying from Visual studio to device; However if I create .apk and install it on device it gives me an error "21". Looks like it's not permissions to do something with DB, I have "Constraint" error when I trying to insert something in DB.
Does somebody know this issue?
I'm not looking to move DB to different default location, Thank you!
My Manifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="internalOnly" package="com.prismvs.minimate" android:versionCode="14" android:versionName="14">
<uses-sdk android:targetSdkVersion="12" android:minSdkVersion="12" />
<application android:icon="@drawable/icon" android:label="MiniMate">
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SET_ORIENTATION" />
<uses-permission android:name="android.permission.WRITE_OWNER_DATA" />
<uses-permission android:name="android.permission.READ_OWNER_DATA" />
</manifest>
A:
I posted this a few days ago and spent so much time for find a problem because I moved in wrong dirrection, so I want to share this experience maybe it will help somebody to fix their issues with SQLite + Mono for Android:
I had project what main app and user libraried in different project (common cross platform project)
SQLite was using in user library not in main application project
When I build Release (apk) for Google Play and install it on Android device I had error log: E/SQLiteLog(32375): (1) near ")": syntax error
E/SQLiteLog(32375): (21) API called with NULL prepared statement
E/SQLiteLog(32375): (21) misuse at line 63243 of [00bb9c9ce4]
It was not happen for debug version, so what I did for fixinfg this problem:
On Visual studion project properties -> Mono Android Options -> Linking: I set "SDK assemblies Only" instead of "SDK and User assemblies"
This error is disappear.
|
[
"stackoverflow",
"0060798879.txt"
] | Q:
XSLT: Processing hierarchical XML data using XSLT
I have the below XML document. Under each node there are many sub nodes, but I am interested only in few of them.
My target is to run xslt on it to generate a Json output contains only the elements I am interested in them.
The approach that I took is to process it as XML first (apply all data transformation, renaming, output only elements I am interested in ...etc) then apply another xslt to convert it to Json (I found some ready xslt online that can do that).
My issue right now mainly in the recursive part, I can't do it correct, I tried for-each/apply-templates/call-template but I still have hard time with it.
<MainDoc>
<MetaData>
<Name>MainDoc Name</Name>
<Date>MainDoc Date</Date> <!--not interested in this element-->
</MetaData>
<ContentList>
<Content/>
<Content/>
<Content><!--Want to process last content only-->
<BuildList>
<Build>
<Steps>
<Step><!--want to process all of them-->
<StepContentParent>
<StepContent>
<Title>myTitle1</Title>
<Details>myDetails1</Details>
<Date>Step Date</Date> <!--not interested in this element-->
</StepContent>
</StepContentParent>
<Steps><!--Could be empty or could be the same as the previous Steps (recursion ) -->
<Step><!--want to process all of them-->
<StepContentParent>
<StepContent>
<Title>myTitle1.1</Title>
<Details>myDetails1.1</Details>
</StepContent>
</StepContentParent>
<Steps/><!--Could be empty or could be the same as the previous Steps (recursion ) -->
<SubDoc><!-- could be empty -->
<SubDocInstance>
<DocInstance>
<MainDoc><!-- Same as Root (recursion ) -->
<MetaData>
<Name>Sub Doc Name</Name>
</MetaData>
<ContentList>
<Content/>
<Content/>
<Content><!--Want to process last content only-->
<BuildList>
<Build>
<Steps>
<Step><!--want to process all of them-->
<StepContentParent>
<StepContent>
<Title>Sub Doc myTitle1</Title>
<Details>Sub Doc myDetails1</Details>
</StepContent>
</StepContentParent>
<Steps><!--Could be empty or could be the same as the previous Steps (recursion ) -->
<Step><!--want to process all of them-->
<StepContentParent>
<StepContent>
<Title>Sub Doc myTitle1.1</Title>
<Details>Sub Doc myDetails1.1</Details>
</StepContent>
</StepContentParent>
<Steps/><!--Could be empty or could be the same as the previous Steps (recursion ) -->
<SubDoc><!-- could be empty -->
<SubDocInstance>
<DocInstance>
<MainDoc/><!-- Same as Root (recursion ) -->
</DocInstance>
</SubDocInstance>
</SubDoc>
</Step>
<step/>
<step/>
</Steps>
<SubDoc><!-- could be empty -->
<SubDocInstance>
<DocInstance>
<MainDoc/><!-- Same as Root (recursion ) -->
</DocInstance>
</SubDocInstance>
</SubDoc>
</Step>
</Steps>
</Build>
</BuildList>
</Content>
</ContentList>
</MainDoc>
</DocInstance>
</SubDocInstance>
</SubDoc>
</Step>
<step/>
<step/>
</Steps>
<SubDoc><!-- could be empty -->
<SubDocInstance>
<DocInstance>
<MainDoc/><!-- Same as Root (recursion ) -->
</DocInstance>
</SubDocInstance>
</SubDoc>
</Step>
<Step>
<StepContentParent>
<StepContent>
<Title>myTitle2</Title>
<Details>myDetails2</Details>
</StepContent>
</StepContentParent>
<Steps><!--Could be empty or could be the same as the previous Steps (recursion ) -->
<Step><!--want to process all of them-->
<StepContentParent>
<StepContent>
<Title>myTitle2.1</Title>
<Details>myDetails2.1</Details>
</StepContent>
</StepContentParent>
<Steps/><!--Could be empty or could be the same as the previous Steps (recursion ) -->
<SubDoc><!-- could be empty -->
<SubDocInstance>
<DocInstance>
<MainDoc/><!-- Same as Root (recursion ) -->
</DocInstance>
</SubDocInstance>
</SubDoc>
</Step>
<step/>
<step/>
</Steps>
</Step>
<step/>
<step/>
</Steps>
</Build>
</BuildList>
</Content>
</ContentList>
</MainDoc>
A:
As using the identity transformation with apply-templates has "recursion built-in" I am not sure what the problem is, you just use it as the starting point (e.g. in XSLT 3 with <xsl:mode on-no-match="shallow-copy"/>) and then add empty templates matching the elements you want to strip and/or templates matching for those elements you want to rename or transform otherwise:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="MainDoc/MetaData/Date"/>
<xsl:template match="StepContentParent/StepContent/Date"/>
<xsl:template match="ContentList/Content[not(position() = last())]"/>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/6pS26my
|
[
"stackoverflow",
"0015863279.txt"
] | Q:
Deallocating memory from a vector of vectors of pointers
I'm creating a particle physics simulator and I need to make proper memory management.
I've found convenient that my method propagates several particles at once so this method returns a vector of trajectories and each trajectory is a vector of Steps (thus getting a vector< vector<> >).
(Step is a class I created.)
vector< vector<Step*> > Propagator::Propagate (vector<TParticle*> vpart) {
vector< vector<Step*> > = vvsteps;
//vvsteps goes through physics and gets filled using push_back
//all of vvsteps' entries were filled with objects created with "new"
return vvsteps;
}
Each Step creates a vector of pointers to TParticle (created with new) and has the following destructor to deallocate it.
vector<TParticle*> vpart;
Step::~Step() {
for(int i=0; i<vpart.size(); i++) delete vpart[i];
vpart.clear();
}
After I get what I want I try to deallocate the whole thing by doing:
vector< vector<Step*> > vvstep = prop->Propagate(vpart);
/*PHYSICS GOES HERE*/
for(int i=0; i<vvstep.size(); i++) {
for(int j=0; j<vvstep[i].size(); j++)
delete (vvstep[i])[j];
vvstep[i].clear();
}
vvstep.clear();
This code for some reason doesn't work. It gives me the following error
*** glibc detected *** bin/rtest.exe: double free or corruption (fasttop): 0x0f7207f0 ***
edit: corrected a typo, the class is named Step and not Steps.
A:
Change your vector of vector type to:
`std::vector< std::vector<std::unique_ptr<Step>>>`
This does a few things. First, it blocks copying your std::vectors around, which is bad because such vectors represent both ownership and reference to data.
move is still available, and should generally occur. If you want to move one set of vectors of vectors to another spot, and it isn't happening automatically, insert a std::move( src ).
Second, when the vector of vector of data goes out of scope, the unique_ptr automatically cleans up the Step objects.
You may have to insert some .get() calls on the unique_ptr<Base> in cases where you are calling a function that takes a Base* directly. But it should otherwise be mostly transparent.
Note that the double deletion is probably occuring because you have duplicated one of these vectors of Base* -- the std::vector<std::unique_ptr<Base>> will complain when you tried to do that...
|
[
"stackoverflow",
"0046181808.txt"
] | Q:
symfony get parameters from parameters.yml
Hello im trying to make a project that communicate with riot API. Im new in symfony and i found a very good bundle which inspired me, but in Services he injected whole container and i read that its not good idea to inject the whole container, but i really need to getParameter from parameters.yml
How can i did it ? Im also getting this error:
Cannot autowire service "AppBundle\Controller\Service\ChampionService": argument "$container" of method "__construct()" references class "Symfony\Component\DependencyInjection\Container" but no such service exists. Try changing the type-hint to one of its parents: interface "Psr\Container\ContainerInterface", or interface "Symfony\Component\DependencyInjection\ContainerInterface".
My Service:
namespace AppBundle\Controller\Service;
use AppBundle\Controller\guzzleClient\GuzzleClient;
use Psr\Log\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Container;
use AppBundle\Entity\Champion;
class ChampionService
{
/**
* @var GuzzleClient
*/
private $guzzle;
/**
* @var Container
*/
private $container;
/**
* Constructor
* @param GuzzleClient $guzzle
* @param Container $container
*/
public function __construct(GuzzleClient $guzzle, Container $container) {
$this->guzzle = $guzzle;
$this->container = $container;
}
/**
* Retrieves all the champions
*
* @param $region string
* @param $freeToPlay boolean
* @throws \Symfony\Component\CssSelector\Exception\InternalErrorException
* @return array
*/
public function getChampions($region, $freeToPlay = null) {
$request = $this->container->getParameter('roots')['champion']['champions'];
if($freeToPlay == null) {
$champions = $this->guzzle->send($request, $region);
} else {
$champions = $this->guzzle->send($request, $region, array('freeToPlay' => $freeToPlay));
}
return $this->createChampions($champions->champions);
}
/**
* Retrieves one champion
*
* @param integer $id the id of the champion
* @param $region string
* @throws \Symfony\Component\CssSelector\Exception\InternalErrorException
* @return \AppBundle\Entity\Champion
*/
public function getChampionById($id, $region) {
if(!is_int($id)) {
throw new InvalidArgumentException('The "id" must be an int');
}
$request = $this->container->getParameter('roots')['champion']['championById'];
$request = str_replace('{id}', $id, $request);
$champion = $this->guzzle->send($request, $region);
return $this->createChampion($champion);
}
/**
* Create an array of champions
*
* @param array $champions an array of json object chamions
* @return array
*/
private function createChampions($champions) {
$return = array();
foreach($champions as $champion) {
$return[] = $this->createChampion($champion);
}
return $return;
}
/**
* Create a champion
*
* @param $object \stdClass
* @return Champion
*/
private function createChampion($object) {
$champion = new Champion();
$champion->setActive($object->active);
$champion->setBotEnabled($object->botEnabled);
$champion->setBotMmEnabled($object->botMmEnabled);
$champion->setFreeToPlay($object->freeToPlay);
$champion->setId($object->id);
$champion->setRankedPlayEnabled($object->rankedPlayEnabled);
return $champion;
}
}
A:
Other solution, in the service.yml
services:
your_service:
class: Your\Bundle\Service\YourService
arguments: [%param1%, %param2%]
In the class
public function __construct($param1, $param2){}
But you use container in the service, this is normal.
Change
Symfony\Component\DependencyInjection\Container;
to
Symfony\Component\DependencyInjection\ContainerInterface as Container;
Example from my project in Symfony V3.2 is ContainerInterface
use Symfony\Component\DependencyInjection\ContainerInterface;
class YourClassService {
/**
* @var ContainerInterface
*/
protected $serviceContainer;
/**
* @param ContainerInterface $serviceContainer
*/
public function __construct(ContainerInterface $serviceContainer)
{
$this->serviceContainer = $serviceContainer;
$param = $this->serviceContainer->getParameter('parameter');
}
}
In service.yml
services:
your.class.service.api:
class: YourClassService
arguments: ["@service_container"]
|
[
"stackoverflow",
"0039196530.txt"
] | Q:
Re-render does not occur when state changes
I have the following component...
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
register: false
}
}
handleClick(event)
{
console.log("link was clicked");
this.setState({register: true});
}
render(){
return (
<If condition={ this.state.register }>
<Then><Register /></Then>
<Else>{() =>
<Index event={this.handleClick} />
}</Else>
</If>
);
}
}
module.exports = App;
So my function handleClick is called whenever a link is clicked, this changes the state to true. However, the <IF> statement does not notice that state changed and so remains the same (only Index remains)
What I want is for <Register /> to be rendered whenever the link is clicked. So if the link is clicked, the state will change to true, and then the IF statement will catch this change and render the right component.
How can I do this? How can I get the IF statement to notice the change in state?
A:
Not sure what <Index> is or what is it doing with event. If it just calls the function that is passed as props.event, the handleClick function is called with the wrong this reference and doesn't set the state for the correct component.
If you're using Babel with stage-2 preset or lower, you can use syntax to bind this:
class App ... {
...
handleClick = (event) => { ... }
...
}
Yes, it's an arrow function definiton, but directly inside class. It will bind the correct this reference so it can be passed around and it will have proper this reference when called.
Alternatively, you can use bind directly when passing the function, as event={this.handleClick.bind(this)}. But beware, this creates a new function every time it's called, so it might impact performance if it's called very often. It's advised that you do not use this approach and airbnb's eslint config will mark this as an error. A better approach would be to do one time binding inside the constructor, as this.handleClick= this.handleClick.bind(this).
If you wish to know more, this Medium post covers 2 more ways to bind and explains all 5 options.
|
[
"math.stackexchange",
"0000106829.txt"
] | Q:
Is it possible to find an operator $T:C(\mathbb{R})\rightarrow C(\mathbb{R})$ such that $T=N+D$, where $N$ is nilpotent and $D$ is invertible?
Let $C(\mathbb{R})$ is the set of all continuous functions $\mathbb{R}\to\mathbb{R}$.
I want to find a linear operator $T:C(\mathbb{R})\rightarrow C(\mathbb{R})$, proper subspaces $W_{1}, W_{2}$ of $C(\mathbb{R})$ such that $C(\mathbb{R})=W_{1}\oplus W_{2}$ and $T|_{W_{1}}$ is nilpotent $( T|_{W_{1}}\neq 0)$ and $T|_{W_{2}}$ is invertible.
I've tried this one, but it didn't work.
Thanks for your kindly help.
A:
To expand on the other answers, I'll just note that this can be done constructively.
Let $f_1, f_2$ be any continuous functions with $f_1(1) = f_2(2) = 1$, $f_1(2) = f_2(1) = 0$. (For example, $f_1(x) = 2-x$, $f_2(x)=x-1$.) Set $W_1 = \mathrm{span}\{f_1, f_2\}$, and $W_2 = \{ f \in C(\mathbb{R}) : f(1) = f(2) = 0\}$. Then $C(\mathbb{R}) = W_1 \oplus W_2$: if $f \in C(\mathbb{R})$, we can write $$f = (f(1) f_1 + f(2) f_2) + (f - f(1) f_1 - f(2) f_2).$$ We can then define
$$Tf = f - f(1) f_1 - f(2) f_2 + f(1) f_2$$
and it is easy to check that $T$ has the desired properties.
A:
Take any non-zero $f_1, f_2\in C(\mathbb{R})$. Consder $W_1=\operatorname{span}\{f_1,f_2\}$. Since $W_1$ is finite dimensional there exist $W_2$ such that $W_1\oplus W_2=C(\mathbb{R})$. Define $N :W_1\to W_1$ by equalities $N(f_1)=f_2$, $N(f_2)=0$ and define $D:W_2\to W_2$ to be identity operator. Then
$T=N\oplus D$ is desired operator.
|
[
"stackoverflow",
"0040896162.txt"
] | Q:
Mex file building with Octave (issue with wrappers)
I am currently porting some code from Matlab to Octave. Some of the functions of the Matlab code use the Piotr's Computer Vision Matlab Toolbox (here) that includes some mex files.
In Matlab, everything is working like a charm but when I run my codes with Octave, it throws this error:
error: 'imResampleMex' undefined near line 50 column 5
However all the internal paths within the toolbox should be good. I figured out that the way Matlab and Octave handle mex files is different and tried to build one of the mex files from the C++ function within Octave like this:
mkoctfile --mex imResampleMex.cpp
It fails and throws the following error messages related to the C++ wrappers function:
In file included from imResampleMex.cpp:6:0:
wrappers.hpp:21:24: error: 'wrCalloc' declared as an 'inline' variable
inline void* wrCalloc( size_t num, size_t size ) { return calloc(num,size);
^
wrappers.hpp:21:24: error: 'size_t' was not declared in this scope
wrappers.hpp:21:36: error: 'size_t' was not declared in this scope
inline void* wrCalloc( size_t num, size_t size ) { return calloc(num,size);
^
wrappers.hpp:21:48: error: expression list treated as compound expression in initializer [-fpermissive]
inline void* wrCalloc( size_t num, size_t size ) { return calloc(num,size);
^
wrappers.hpp:21:50: error: expected ',' or ';' before '{' token
inline void* wrCalloc( size_t num, size_t size ) { return calloc(num,size);
^
wrappers.hpp:22:24: error: 'wrMalloc' declared as an 'inline' variable
inline void* wrMalloc( size_t size ) { return malloc(size); }
^
wrappers.hpp:22:24: error: 'size_t' was not declared in this scope
wrappers.hpp:22:38: error: expected ',' or ';' before '{' token
inline void* wrMalloc( size_t size ) { return malloc(size); }
^
wrappers.hpp: In function 'void wrFree(void*)':
wrappers.hpp:23:44: error: 'free' was not declared in this scope
inline void wrFree( void * ptr ) { free(ptr); }
^
wrappers.hpp: At global scope:
wrappers.hpp:28:17: error: 'size_t' was not declared in this scope
void* alMalloc( size_t size, int alignment ) {
^
wrappers.hpp:28:30: error: expected primary-expression before 'int'
void* alMalloc( size_t size, int alignment ) {
^
wrappers.hpp:28:44: error: expression list treated as compound expression in initializer [-fpermissive]
void* alMalloc( size_t size, int alignment ) {
^
wrappers.hpp:28:46: error: expected ',' or ';' before '{' token
void* alMalloc( size_t size, int alignment ) {
^
imResampleMex.cpp: In function 'void resampleCoef(int, int, int&, int*&, int*&, T*&, int*, int)':
imResampleMex.cpp:21:39: error: 'alMalloc' cannot be used as a function
wts = (T*)alMalloc(nMax*sizeof(T),16);
^
imResampleMex.cpp:22:43: error: 'alMalloc' cannot be used as a function
yas = (int*)alMalloc(nMax*sizeof(int),16);
^
imResampleMex.cpp:23:43: error: 'alMalloc' cannot be used as a function
ybs = (int*)alMalloc(nMax*sizeof(int),16);
^
imResampleMex.cpp: In function 'void resample(T*, T*, int, int, int, int, int, T)':
imResampleMex.cpp:48:43: error: 'alMalloc' cannot be used as a function
T *C = (T*) alMalloc((ha+4)*sizeof(T),16); for(y=ha; y<ha+4; y++) C[y]=0;
^
warning: mkoctfile: building exited with failure status
The wrappers.hpp file is looking like this:
#ifndef _WRAPPERS_HPP_
#define _WRAPPERS_HPP_
#ifdef MATLAB_MEX_FILE
// wrapper functions if compiling from Matlab
#include "mex.h"
inline void wrError(const char *errormsg) { mexErrMsgTxt(errormsg); }
inline void* wrCalloc( size_t num, size_t size ) { return mxCalloc(num,size); }
inline void* wrMalloc( size_t size ) { return mxMalloc(size); }
inline void wrFree( void * ptr ) { mxFree(ptr); }
#else
// wrapper functions if compiling from C/C++
inline void wrError(const char *errormsg) { throw errormsg; }
inline void* wrCalloc( size_t num, size_t size ) { return calloc(num,size); }
inline void* wrMalloc( size_t size ) { return malloc(size); }
inline void wrFree( void * ptr ) { free(ptr); }
#endif
// platform independent aligned memory allocation (see also alFree)
void* alMalloc( size_t size, int alignment ) {
const size_t pSize = sizeof(void*), a = alignment-1;
void *raw = wrMalloc(size + a + pSize);
void *aligned = (void*) (((size_t) raw + pSize + a) & ~a);
*(void**) ((size_t) aligned-pSize) = raw;
return aligned;
}
// platform independent alignned memory de-allocation (see also alMalloc)
void alFree(void* aligned) {
void* raw = *(void**)((char*)aligned-sizeof(void*));
wrFree(raw);
}
#endif
I imagine I need to modify this file but my knowledge of C++ and of mex files being close to non-existent, I am struggling figuring a way out of this mountain of errors. I don't even have a clue whether I'm going in the right direction or not... Any help is welcome!
Edit 1:
I modified my wrappers.hpp file adding #include <stdlib.h> to it. A mex file is now created. However, when running the function calling the file, I now get the following error:
error: failed to install .mex file function 'imResampleMex'
error: called from
imResample at line 50 column 4
A:
Here are the steps I used to solve the issue of creating the mex files from the Piotr's Computer Vision Matlab Toolbox for Octave (concerns the cpp files of the folder channels only).
The original mex files that come with the toolbox are built for Matlab and do not work with Octave. While building them from Octave a call is made to the file wrappers.hpp.
This file has to be modified by adding these two lines at the beginning of the file: #include <stdlib.h> and #include "mex.h".
For building the mex file, in the Octave prompt type (while being in the directory of the cpp file):
mkoctfile --mex -DMATLAB_MEX_FILE the_file.cpp
This way the Octave compatible mex file is created.
Edit 23/05/2017 - After receiving more questions from people having trouble generating these files I released the generated files on Github: https://github.com/Eskapp/Piotr_vision_extrafiles_Octave. Feel free to use them.
You'll need to add them manually to the Computer Vision toolbox.
|
[
"stackoverflow",
"0009046820.txt"
] | Q:
Fastest way to incrementally read a large file
When given a buffer of MAX_BUFFER_SIZE, and a file that far exceeds it, how can one:
Read the file in blocks of MAX_BUFFER_SIZE?
Do it as fast as possible
I tried using NIO
RandomAccessFile aFile = new RandomAccessFile(fileName, "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(CAPARICY);
int bytesRead = inChannel.read(buffer);
buffer.flip();
while (buffer.hasRemaining()) {
buffer.get();
}
buffer.clear();
bytesRead = inChannel.read(buffer);
aFile.close();
And regular IO
InputStream in = new FileInputStream(fileName);
long length = fileName.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File is too large!");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + fileName);
}
in.close();
Turns out that regular IO is about 100 times faster in doing the same thing as NIO. Am i missing something? Is this expected? Is there a faster way to read the file in buffer chunks?
Ultimately i am working with a large file i don't have memory for to read it all at once. Instead, I'd like to read it incrementally in blocks that would then be used for processing.
A:
If you want to make your first example faster
FileChannel inChannel = new FileInputStream(fileName).getChannel();
ByteBuffer buffer = ByteBuffer.allocateDirect(CAPACITY);
while(inChannel.read(buffer) > 0)
buffer.clear(); // do something with the data and clear/compact it.
inChannel.close();
If you want it to be even faster.
FileChannel inChannel = new RandomAccessFile(fileName, "r").getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
// access the buffer as you wish.
inChannel.close();
This can take 10 - 20 micro-seconds for files up to 2 GB in size.
A:
Assuming that you need to read the entire file into memory at once (as you're currently doing), neither reading smaller chunks nor NIO are going to help you here.
In fact, you'd probably be best reading larger chunks - which your regular IO code is automatically doing for you.
Your NIO code is currently slower, because you're only reading one byte at a time (using buffer.get();).
If you want to process in chunks - for example, transferring between streams - here is a standard way of doing it without NIO:
InputStream is = ...;
OutputStream os = ...;
byte buffer[] = new byte[1024];
int read;
while((read = is.read(buffer)) != -1){
os.write(buffer, 0, read);
}
This uses a buffer size of only 1 KB, but can transfer an unlimited amount of data.
(If you extend your answer with details of what you're actually looking to do at a functional level, I could further improve this to a better answer.)
|
[
"stackoverflow",
"0028100863.txt"
] | Q:
How to parse a mathematical expression with boost::spirit and bind it to a function
I would like to define a function taking 2 arguments
double func(double t, double x);
where the actual implementation is read from an external text file.
For example, specifying in the text file
function = x*t;
the function should implement the multiplication between x and t, so that it could be called at a later stage.
I'm trying to parse the function using boost::spirit. But I do not know how to actually achieve it.
Below, I created a simple function that implements the multiplication. I bind it to a boost function and I can use it. I also created a simple grammar, which parse the multiplication between two doubles.
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include <boost/spirit/include/qi_symbols.hpp>
#include <iostream>
#include <string>
namespace qi = boost::spirit::qi;
namespace ascii=boost::spirit::ascii;
using boost::spirit::ascii::space;
using boost::spirit::qi::symbols;
template< typename Iterator >
struct MyGrammar : public virtual qi::grammar< Iterator, ascii::space_type >
{
MyGrammar() : MyGrammar::base_type(expression)
{
using qi::double_;
//The expression should take x and t as symbolic expressions
expression = (double_ >> '*' >> double_)[std::cout << "Parse multiplication: " << (qi::_1 * qi::_2)];
}
qi::rule<Iterator, ascii::space_type> expression;
};
double func(const double a, const double b)
{
return a*b; //This is the operation to perform
}
int main()
{
typedef std::string::const_iterator iterator_Type;
typedef MyGrammar<iterator_Type> grammar_Type;
grammar_Type calc;
std::string str = "1.*2."; // This should be changed to x*t
iterator_Type iter = str.begin();
iterator_Type end = str.end();
bool r = phrase_parse(iter, end, calc, space);
typedef boost::function < double ( const double t,
const double x) > function_Type;
function_Type multiplication = boost::bind(&func, _1, _2);
std::cout << "\nResult: " << multiplication( 2.0, 3.0) << std::endl;
return 0;
}
If I modify the above code setting
std::string str = "x*t";
how can I parse such an expression and bind it to the function multiplication such that, if I call multiplication(1.0, 2.0), it associates t to 1.0, x to 2.0 and it returns the result of the operation?
A:
You're going to learn Spirit. Great!
It seems you're biting off more than you can chew here, though.
Firstly, your grammar doesn't actually parse an expression yet. And it certainly doesn't result in a function that you can then bind.
In fact you're parsing the input using a grammar that is not producing any result. It only creates a side-effect (which is to print the result of the simple binary expression with immediate simple operands to the console). This /resembles/ interpreted languages, although it would soon break up when
you try to parse an expression like 2*8 + 9
you would have input that backtracks (oops, the side effect already fired)
Next up you're binding func (which is redundant by the way; you're not binding any arguments so you could just say function_Type multiplication(func); here), and calling it. While cool, this has literally nothing to do with the parsing input.
Finally, your question is about a third thing, that wasn't even touched upon anywhere in the above. This question is about symbol tables and identifier lookup.
This would imply you should parse the source for actual identifiers (x or t, e.g.)
you'd need to store these into a symbol table so they could be mapped to a value (and perhaps a scope/lifetime)
There is a gaping logic hole in the question where you don't define the source of the "formal parameter list" (you mention it in the text here: function = x*t; but the parser doesn't deal with it, neither did you hardcode any such metadata); so there is no way we could even start to map the x and t things to the formal argument list (because it doesn't exist).
Let's assume for the moment that in fact arguments are positional (as they are, and you seem to want this as you call the bound function with positional arguments anyways. (So we don't have to worry about a name because no one will ever see a name.)
the caller should pass in a context to the functions, so that values can be looked up by identifier name during evaluation.
So, while I could try to sit you down and talk you through all the nuts and bolts that need to be created first before you can even dream of glueing it together in fantastic ways like you are asking for, let's not.
It would take me too much time and you would likely be overwhelmed.
Suggestions
I can only suggest to look at simpler resources. Start with the tutorials
The calculator series of tutorials is nice. In this answer I list the calculator samples with short descriptions of what techniques they demonstrate: What is the most efficient way to recalculate attributes of a Boost Spirit parse with a different symbol table?
The compiler tutorials actually do everything you're trying for, but they're a bit advanced
Ask freely if you have any questions along the way and you're at risk of getting stuck. But at least then we have a question that is answerable and answers that genuinely help you.
For now, look at some other answers of mine where I actually implemented grammars like this (somewhat ordered by increasing complexity):
Nice for comparison: This answer to Boost::spirit how to parse and call c++ function-like expressions interprets the parsed expressions on-the-fly (this mimics the approach with [std::cout << "Parse multiplication: " << (qi::_1 * qi::_2)] in your own parser)
The other answer there (Boost::spirit how to parse and call c++ function-like expressions) achieves the goal but using a dedicated AST representation, and a separate interpretation phase.
The benefits of each approach are described in these answers. These parsers do not have a symbol table nor a evaluation context.
More examples:
a simple boolean expression grammar evaluator (which supports only literals, not variables)
Building a Custom Expression Tree in Spirit:Qi (Without Utree or Boost::Variant)
|
[
"stackoverflow",
"0036012240.txt"
] | Q:
ControlConnection warning in datastax java driver
I am using cassandra 2.0.9 and datastax java driver 2.0.5 to query.
I had set rpc_address as 0.0.0.0 in cassandra. Sometimes I am getting this warning message from the client
4411 [Cassandra Java Driver worker-1] WARN com.datastax.driver.core.ControlConnection - Found host with 0.0.0.0 as rpc_address, using listen_address (/192.168.100.175) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.
I cannot find why this warning occured sometimes only. How can I solve this?
A:
The driver uses the rpc_address set in the system.peers table to find the address to connect to. When you configure the rpc address to 0.0.0.0 thats what gets put in the system table so the driver cant know for sure what IP to connect to.
If possible you should just set it to its actual IP 192.168.100.175, but if thats incorrect you may just want to add the actual address of more of your nodes to the host list the driver initially is provided.
|
[
"stackoverflow",
"0062070421.txt"
] | Q:
Loop over a List getting an increasing number of elements each time
Let's say I have a list that looks like
{A, B, C, D, E}
And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:
Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}
Currently I am accomplishing this with:
(1 to list.size).foreach( n => {
val elements = list.take(n)
// Do something with elements
})
But that feels messy. Is there a more 'scala' way of accomplishing this behavior?
A:
You could use list.inits :
scala> List(1,2,3,4,5).inits.foreach(println)
List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(1, 2, 3)
List(1, 2)
List(1)
List()
To get your desired out put you would need to create a list from the iterator, reverse it and take the tail to omit the empty list:
scala> List(1,2,3,4,5).inits.toList.reverse.tail.foreach(println)
List(1)
List(1, 2)
List(1, 2, 3)
List(1, 2, 3, 4)
List(1, 2, 3, 4, 5)
|
[
"math.stackexchange",
"0000136897.txt"
] | Q:
What is $\limsup\limits_{n\to\infty} \cos (n)$, when $n$ is a natural number?
I think the answer should be $1$, but am having some difficulties proving it. I can't seem to show that, for any $\delta$ and $n > m$, $|n - k(2\pi)| < \delta$. Is there another approach to this or is there something I'm missing?
A:
No, that's exactly how you should show it. You can get what you want by using this question:
For every irrational $\alpha$, the set $\{a+b\alpha: a,b\in \mathbb{Z}\}$ is dense in $\mathbb R$
|
[
"stackoverflow",
"0018301259.txt"
] | Q:
Button event on netduino 2
I have started hobby development on a netduino 2. I'm struggling with interrupts on the onboard button. My problem is, that the interrupt is called several times for each time i press the button.
public static void Main()
{
dac = new Dac();
InterruptPort button = new InterruptPort(Pins.ONBOARD_SW1, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh);
button.OnInterrupt += new NativeEventHandler(button_OnInterrupt);
Thread.Sleep(Timeout.Infinite);
}
static void button_OnInterrupt(uint data1, uint data2, DateTime time)
{
if(data2 == 1)
{
dac.nextDACState();
}
}
*Dac is a custom Digital To Analog Converter. Nothing fancy here.
Is this a implementation fault, og maybe a faulty button, that flickers?
A:
Welcome to the joy of embedded and electronics!
What you are experiencing is called contact bounce:
http://www.elexp.com/t_bounc.htm
It is typical in all uses of buttons and is caused by the electromechanical characteristics of the button.
There are 2 ways of dealing with this. Either add a debouncing circuitry or in software. Typically the software way this is to ignore all interrupts that occurs withing a few milliseconds of the first.
There is a very good paper on debouncing strategies here:
http://cseweb.ucsd.edu/classes/sp09/cse140L/slides/debouncing.pdf
|
[
"stackoverflow",
"0026497478.txt"
] | Q:
Using Fontawesome with SCSS, the :before content is changing
So I'm using SCSS and fontawesome and it starts like this in the .scss file:
$fa-var-bitbucket-square: "\f172";
And when it compiles the CSS it ends up like this:
content: "";
Not only squares, all kinds of weird characters.
If I view it in the browser it looks more like this:
content: "";
I'm not sure what is going on. The font is loading fine, the path is correct, etc. I've been scouring Google and haven't found an answer.
Thank you and let me know if you need any more information.
A:
Sorry people, I just needed
<meta charset='utf-8'>
In my html.
Embarrassed!
|
[
"stackoverflow",
"0009823142.txt"
] | Q:
Can't run app on iPhone 4.2.1 with Xcode 4.3.1 and IOS
I hope someone can help :) It's been troubling me for a while, this one.
I'm running Xcode 4.3.1 with base SDK iOS 5.1.
iPhone version is 4.2.1, an old 3S model I believe.
When hitting Run, Xcode compiles fine and says that it's running my app on the phone. Everything appears like it works, but the app does not launch on the phone. Anyone know what I'm doing wrong here? The app works fine in the simulator.
Also when I try to run the app on a 4S, version 5.1, Xcode says: "Xcode cannot run using the selected device. No provisioned iOS devices are available with a compatible iOS version. Connect an iOS device with a recent enough version of iOS to run your application or choose an iOS simulator as the destination.".
A:
You need to add armv7 and armv6 architectures both to the Architectures and you need to do this as armv6 is architecture supported by devices older than iPhone 3GS and hence if you need to compile or give support to devices prior than iPhone 3GS, you need to add armv6 to your architectures as shown below:
Hope this helps.
|
[
"stackoverflow",
"0041447097.txt"
] | Q:
dplyr mutate in place
Here is my example
library('dplyr')
a <- c(0.2,1.3)
df_test <- data.frame(a)
df_test %>% mutate(a =round(a,0))
it produces:
a
1 0
2 1
, but does not change original dataframe df_test. How do I assign results of mutate to the same dataframe?
A:
We can use the %<>% compound assignment operator from magrittr to change in place
library(magrittr)
df_test %<>%
mutate(a = round(a,0))
If we are using data.table, the assignment (:=) operator does this in place too without copying
library(data.table)
setDT(df_test)[, a := round(a,0)]
|
[
"stackoverflow",
"0048170343.txt"
] | Q:
AngularJS $routeParams is undefiend, but property is there
angular.module("newsApp",["ngRoute"])
.config($routeProvider=>{
$routeProvider.when("/edit",{
templateUrl : "views/addNewsView.html"
});
$routeProvider.when("/newsList",{
templateUrl : "views/newsList.html"
});
$routeProvider.when("/singleNews/:newsId",{
templateUrl : "views/singleNews.html"
});
$routeProvider.when("/",{
templateUrl : "views/newsList.html"
});
$routeProvider.otherwise({
redirectTo:"/newsList"
});
})
this is my module and config. i have simple app. i want to add functionality that when the user enters the url for example.com/singleNews/2 - it opens the news with ID - 2
.controller("newsAppCtrl",['$scope','$location','$routeParams',($scope, $location, $routeParams)=>{
console.log($routeParams); //empty object
setTimeout(function () {
console.log($routeParams); //in this case property is there
},100);
So when i enter the url
example.com/singleNews/2
the routeParams is empty object, although when i click to that empty object in chrome console the property is there and it says "value below was evaluated just now "
but when i add that console into TimeOut, it works and property is there. I know that using setTimeOut() is not recommended in angularjs, so using $timeout solved the problem, but i want to understand what is the problem.
A:
You should be getting an error in your console:
Function.prototype.bind.apply(...) is not a constructor
Simply avoid using (...)=>{...} syntax as AngularJS tried to call a function with new method() syntax and fails to do that with an arrow notation.
Switch .config($routeProvider=>{...} to .config(function($routeProvider){...} (and other similar cases).
Arrow notation can still be used and is useful with $http calls, e.g:
$http.get(url).then( (res)=>{...} );
|
[
"ell.stackexchange",
"0000197078.txt"
] | Q:
The function of "of" in phrases like "a country of wide lawns"
I understand the sentences perfectly but I have difficulty finding what are the exact functions of the prepositions (of) used in the following sentences.
We were sitting at a table with a man of about my age.
I had just left a country of wide lawns and friendly trees.
It was a mansion inhabited by a gentleman of that name.
A:
In all three examples, 'of' is performing a role indicating possession, though not in the way that of usually acts as a possessive/genitive indicator. This may be a source of confusion. In fact, they are indicating attributes rather than possession, but because we might say people or things have attributes, the matter can be confused.
So, here's a brief digression if you're interested in the normal sort of "possession". It's not really important to this answer - feel free to skip ahead. You would normally form possessives in English using a possessive pronoun (your, her, his) or the "Saxon genitive" -'s: Philip's, Barbara's, the Government's, and so on. In some cases, usually for poetic reasons or for the sake of euphony, you can use of - "the home of my aunt", "the banks of the Thames". (There are cases where the 'of' form is the only one available because there's no possessive version of, for example, some indicative pronouns).
However, in this case the thing before the 'of' is what possesses the thing after it - but as a characteristic, rather than an actual possession.
So, to answer your question, In phrases like these, "A of B" indicates that B is some sort of characteristic or attribute of A. "A man of about my age" is a man whose age is about the same as mine. A "country of wide lawns" is a country (which may mean an area of land that is not actually "a country" in the usual sense) which is characterised by wide lawns. A "gentleman of that name" is a gentleman whose name is whatever the indicative "that name" refers to.
Similarly, a "shape of ten sides" is a shape characterised by having ten sides (a decagon). A "bill of £42.50" is a bill stating that the amount owed is £42.50. Even the famous "writ of habeas corpus" is a legal writ to demand that whoever is holding a person produce them in court (habeas corpus meaning approximately "that you have the body", which is to say the person). A "woman of uncommon intellect" is an unusually smart woman, and a "man of habitual lateness" is a man who has difficulty turning up for anything on time.
|
[
"mathematica.stackexchange",
"0000069431.txt"
] | Q:
Normalize centrality measures
How I can normalise centrality measures? Can I use Normalize function? I give example of unnormalized measures
g = GridGraph[{5, 5}];
ClosenessCentrality[g] // Short
BetweennessCentrality[g] // Short
DegreeCentrality[g] // Short
Thanks in advance
A:
Normalize will give you vectors whose Norm is one.
g = GridGraph[{5, 5}];
ClosenessCentrality[g] // Normalize // Norm
1.
BetweennessCentrality[g] // Normalize // Norm
1.
DegreeCentrality[g] // Normalize // Norm
1
|
[
"stackoverflow",
"0016378806.txt"
] | Q:
Android: Nested Linearlayouts will not display a grid of buttons, Matching parent
I have an app under construction. In one of the sub-menus I have a need for generic display of buttons, and therefor I want to make an activity that can display the given number of needed buttons.
I have succesfully made this happen, programmatically, but I want the total grid of buttons to fill up the entire parent they are placed in, which happens to be 3/4 of a landscape screen. The number of buttons varies from 16-38.!
I have also succesfully made this happen with other grids of buttons, in xml, with weight values, and match_parent values of entries.
When I assign buttons or rows the match_parent value programatically, it occupies the entire parent layout, not sharing it like i expect it to do, even though they have the same weight value of 1.0f
The relevant code follows below. I would like to post images as well, but I have not the reputation to do so.
`LinearLayout layout = (LinearLayout) findViewById(R.id.linear_custom_draw);
layout.setOrientation(LinearLayout.VERTICAL);
int columns = Math.min(6, 4+category); //sets number of buttons per row to 4-6
for (int i = 0; i < 4+category; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.WindowManager.LayoutParams.MATCH_PARENT,
android.view.WindowManager.LayoutParams.MATCH_PARENT));
//the line above is the line that fills up the entirety of the linearlayout, even though there are more entries, unlike my xml-defined attempts.
row.setOrientation(LinearLayout.HORIZONTAL);
row.setWeightSum(1.0f);
if(i%2 == 0){
row.setBackgroundColor(getResources().getColor(R.color.listview_red_backgr_color));
}
for (int j = 0; j < columns; j++) {
int index = (i*columns)+j;
if(formations.size() > index){
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText(formations.get(index).getName());
btnTag.setTextColor(getResources().getColor(R.color.black_overlay));
btnTag.setId(formations.get(index).getId());
row.addView(btnTag);
}
}
layout.addView(row);`
A:
Try to use TableLayout. Each Row will enforce the entire elements to match the parent with the same wights. You can control number of Buttons into each Row programatically with counter. Loop for end of Counter adding your buttons then add new Table Row
TableLayout tbl=new TableLayout(context);//create table
TableRow tr=new TableRow(context);//create table row
tr.addView(view);//add your button instead of the view
tbl.addView(tr);//add the row into the Table
In the XML file
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/keypad"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:stretchColumns="*">
<TableRow>
<Button android:id="@+id/keypad_1" android:text="@string/_1"></Button>
<Button android:id="@+id/keypad_2" android:text="@string/_2"></Button>
<Button android:id="@+id/keypad_3" android:text="@string/_3"></Button>
</TableRow>
</TableLayout>
|
[
"stackoverflow",
"0011034261.txt"
] | Q:
How to get one specific windows service from GetObject("winmgmts:")?
To get windows service named "MyTestService" I create an instance of
Win32_Service object then I go through all the cases while find "MyTestService"
service. It is obvious that this is not optimal way.
Does somebody know how to get exactly one service without looping through all services?
var e = new Enumerator(GetObject("winmgmts:").InstancesOf("Win32_Service"));
for(;!e.atEnd(); e.moveNext()){
var service = e.item();
var serviceName = service.Name;
if(serviceName == "MyTestService"){
// do something with MyTestService
return;
}
}
A:
Try this:
GetObject("winmgmts:").ExecQuery("SELECT * FROM Win32_Service WHERE Name='MyTestService'")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.