_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d4501 | train | As the commenter who proposed an approach has not had the chance to outline some code for this, here's how I'd suggest doing it (edited to allow optionally signed floating point numbers with optional exponents, as suggested by an answer to Python regular expression that matches floating point numbers):
import re,sys
pat = re.compile("DV/DL += +([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)")
values = []
for line in open("input.out","r"):
m = pat.search(line)
if m:
values.append(m.group(1))
outfile = open("out.csv","w")
outfile.write(",".join(values[-2:]))
Having run this script:
$ cat out.csv
13.0462,3.7510
I haven't used the csv module in this case because it isn't really necessary for a simple output file like this. However, adding the following lines to the script will use csv to write the same data into out1.csv:
import csv
writer = csv.writer(open("out1.csv","w"))
writer.writerow(values[-2:]) | unknown | |
d4502 | train | extends and mixins merge options in a specified way, this is the official way to inherit component functionality. They don't provide full control over the inheritance.
For static data that may change between component definitions (Base and Extended) custom options are commonly used:
export default {
myName: 'Component',
data() {
return { name: this.$options.myName };
}
}
and
export default {
extends: Base,
myName: `Extended ${Base.options.myName}`
}
Notice that name is existing Vue option and shouldn't be used for arbitrary values.
Any reusable functions can be extracted from component definition to separate exports.
For existing components that cannot be modified data and other base component properties can be accessed where possible:
data() {
let name;
name = this.$data.name;
// or
name = Base.options.data.call(this).name;
return { name: `Extended ${name}` };
}
This approach is not future-proof and not compatible with composition API, as there's no clear distinction between data, etc, and this is unavailable in setup function. An instance can be accessed with getCurrentInstance but it's internal API and can change without notice.
A: The data object is a kind of state for a single component, hence the data object inside a component can only be accessed in that component and not from outside or other components.
For your specific requirement, you can use Vuex. It helps you access the state in multiple components. Simply define a state in the vuex store and then access the state in the component.
If you don't want to use Vuex, then another simple solution is to store the data in localStorage and then access the data in multiple components.
A: You can access your data, from child component. You can do that by this.$parent.nameOfTheDataYouHave.
This cheatsheet can help you with the basics of the component anatomy and lifecycle hooks(mounted,created,etc..).
And last this is the proper way of two-way binding data (parent-child). | unknown | |
d4503 | train | To fix MDL not scaling for different devices, add this line inside your HTML's <head> :
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | unknown | |
d4504 | train | A chained version can look like this without needing to set a table key:
result <- test[
# First, identify groups to remove and store in 'rowselect'
, rowselect := (0 < sum(w) & sum(w) < .N)
, by = .(y,z)][
# Select only the rows that we need
rowselect == TRUE][
# get rid of the temp column
, rowselect := NULL][
# create a new column 'u' to store the values
, u := x - x[max(v) == v]
, by = .(y,z)]
The result looks like this:
> result
v w x y z u
1: 1 TRUE 0.6870228 1 c 0.4748803
2: 3 FALSE 0.7698414 1 c 0.5576989
3: 7 FALSE 0.3800352 1 c 0.1678927
4: 10 TRUE 0.2121425 1 c 0.0000000
5: 8 FALSE 0.7774452 2 b 0.6518901
6: 12 TRUE 0.1255551 2 b 0.0000000 | unknown | |
d4505 | train | I got the solution:
GridFSFindIterable gridFSFile = gridFSBucket.find(eq("filename",listOfFiles.get(i).getName()));
// listOfFiles are a list which contains the names
gridFSBucket.delete(gridFSFile.cursor().next().getId());
I hope it is helpful. | unknown | |
d4506 | train | When displaying data fetched from an API it's good practice to implement a model controller view pattern where the date is downloaded by the controller (a service), saved in the model which is marked with the @Injectable() decortator and is injected in the view component you're displaying the data. So your fetched data is stored in the model and can be accessed everywhere you need it.
The controller can look something like that:
@Injectable({
providedIn: 'root'
})
export class StatusService{
constructor(private http : HttpClient)
{ }
public getStatus() : Observable<any>
{
return this.http.get('http://myapi.com/getstatus');
}
}
The model is just storing this data:
export class Status
{
public id : number;
public type: string;
}
@Injectable()
export class StatusModel
{
public statuses: Status[];
constructor(private statusService : StatusService)
{ }
public getStatus() : Observable<Status[]>
{
return this.statusService.getstatus().pipe(map((status: Status[]) =>
{
this.statuses = data;
return this.statuses ;
}));
}
}
In you component (view) you're injecting the StatusModel in the constructor and make the API request:
@Component({
selector: 'app-status',
templateUrl: './status.component.html',
styleUrls: ['./status.component.scss'],
})
export class StatusComponent implements OnInit {
constructor(public statusModel : StatusModel)
{
this.getStatus();
}
public getStatus() : void
{
this.statusModel.getStatus().subscribe(
(data) =>
{
console.log(data);
},
(error) =>
{
console.log(error);
}
);
}
}
In your HTML you can dispay these statuses stored in statusModel.statuses using *ngFor like that:
<div class="status" *ngFor="let status of statusModel.statuses">
<p>{{status.id}</p>
<p>{{status.type}}</p>
</div>
You can also use *ngIf to display different statuses differently or ngClass to set specific style classes for specific statuses. | unknown | |
d4507 | train | /badChars[item]/g looks for badChars, literally, followed by an i, t, e, or m.
If you're trying to use the character badChars[item], you'll need to use the RegExp constructor, and you'll need to escape any regex-specific characters.
Escaping a regular expression has already been well-covered. So using that:
fileName = fileName.replace(new RegExp(RegExp.quote(badChars[item]), 'g'), '');
But, you really don't want that. You just want a character class:
let fileName = title.replace(/[\/:*?"<>|]/g, '-').toLocaleLowerCase();
A: Found it ....
fileName = fileName.replace(/[-\/\\^$*+?.()|[\]{}]/g, ''); | unknown | |
d4508 | train | The correct way to do this would be to receive just one parameter
.border-radius(@px) {
-webkit-border-radius: @px;
-moz-border-radius: @px;
border-radius: @px;
}
Then you can call it with one parameter:
.border-radius(5px);
or with many. This requires you to either put them in a variable, or escape them:
@myradius: 5px 5px 10px;
.border-radius(@myradius);
or
.border-radius(~"5px 5px 10px");
I read that the Bootstrap project uses the latter version for brevity. | unknown | |
d4509 | train | You don't need separate form for dropzone. Use first form and give it class name dropzone.
<form method="POST" enctype="multipart/form-data" id="inputform" name="form1" class="dropzone">
{% csrf_token %}
<h4>Title</h4>
<input type="text" name="product_title" id="product_title" placeholder="Give your product a name">
<h4>Price</h4>
<input type="text" name="product_price" id="product_price" placeholder="0.00">
<h4>Description</h4>
<input type="text" name="product_description" id="product_description" placeholder="Write a description about your product">
<button type="submit" id="add">Save</button>
</form>
PS. In order to submit files you need to have
<input type="file" name="file" />
in your form. | unknown | |
d4510 | train | I assume you mean Text selected with the mouse or the keyboard? You can access that with
window.getSelection()
Then you can work your way up the DOM tree:
window.getSelection().anchorNode.parentNode.className
See https://developer.mozilla.org/en-US/docs/Web/API/Selection.anchorNode for documentation of the Selection class
A: Use className property.
Example:
var x = document.getElementsByTagName('span');
document.write("Body CSS class: " + x.className); | unknown | |
d4511 | train | The segfault was caused by the input file containing carriage return literals, without the C program being written to handle the case.
The "ambiguous redirect" was caused by passing a filename with spaces without correct quoting. Always quote your expansions: <"$file", not <$file. | unknown | |
d4512 | train | In Node.js, as of now, every file you create is called a module. So, when you run the program in a file, this will refer the module.exports. You can check that like this
console.log(this === module.exports);
// true
As a matter of fact, exports is just a reference to module.exports, so the following will also print true
console.log(this === exports);
// true
Possibly related: Why 'this' declared in a file and within a function points to different object | unknown | |
d4513 | train | I had this problem, the GAC'ed dlls arent included in the references.
Check out this post I made:
Add Reference in Framework 4 Application is not showing assemblies in GAC registered with GACUtil V 4
To make things easier, the link to the msdn article:
http://msdn.microsoft.com/en-us/library/wkze6zky(VS.100).aspx
And to paraphrase, create an entry along the lines of the following:
[HKEY_CURRENT_USER\SOFTWARE\Microsoft.NETFramework\v4.0.30319\AssemblyFoldersEx\MyMagicAssemblies] and then set the (Default) value to be a string with the value being the path you want searched. Look at your registry for examples of how this is set up (so the default value becomes: c:\dlls\
v4.0.30319 would be replaced with the framework version you want the dlls to show up against.
because your dlls are in the GAC it will use those as the actual reference and not the files you are showing in the reference list. Only if the version number of the dlls are different will it use your local version.
A: I've created a sexy visual studio extension that will help you to achieve your goal. Muse VSReferences will allow you to add a Global Assembly Cache reference to the project from Add GAC Reference menu item.
Regards...
Muse Extensions | unknown | |
d4514 | train | If you look at the code for SkewT.plot_dry_adiabats(), you can see that when calculating the dry adiabats the reference pressure is set to 1000 hPa. If you use that when doing your own calculation, the results then completely line up.
This could definitely be better documented. If being able to control that on the call to plot_dry_adiabats is important to you, feel free to open a feature request (or even better, contribute the enhancement yourself!). | unknown | |
d4515 | train | This is a browser bug/issue not a problem with TinyMCE. It's impossible to retain iframe contents in some browsers since once you remove the node from the dom the document/window unloads. I suggest first removing the editor instance then re-adding it instead of moving it in the DOM.
A: Had the same issue and here's how I resolved it...
Create the issue
I use jquery to move the dom element that contains the tinymce editor that causes it to lose all it's contents:
$('.form-group:last').after($('.form-group:first'))
After this point, the editor's iframe contents are removed.
The Solution
var textareaId = 'id_of_textarea';
tinyMCE.get(textareaId).remove();
tinyMCE.execCommand("mceAddEditor", false, textareaId);
There are times when the editor will add the iframe back, but not be visible. If that's the case, unhide the container:
$textarea = $('#' + textareaId)
$textarea.closest('.mce-tinymce.mce-container').show()
Note, this is using tinymce 4.x. | unknown | |
d4516 | train | On a side note why would you want 35 procedures to execute parallel ? to me this requirement sounds a bit unrealistic.
Even if you execute two stored procedures exactly at the same time, It is not guaranteed that they will go parallel.
Parallelism of executions is dependent on other factors like Query Cost, MXDOP(Maximum Degree of Parallelism), Threshold for Parallelism etc.
These properties are manipulated on the server level configuration (except the MAXDOP which can be specified on query.
I cannot go into too much details but my suggestion would, do not depend on Parallelism write your code in a way that it doesnt depend on queries being parallel, Also the somewhat simultaneous execution of queries is handled via Transactions.
Just as a hint to have 35 procedures being executed parallel you would need 35 cores on your Sql Server and MAXDOP Set to 1 and then have them 35 procs being executed at the exact time. Seems a lot of unrealistic requirements to me :)
A: You are right. Next iteration will start when the last is done. But here, you are running jobs in those iterations not the actual statements. So imagine it like sp_start_job is called in async manner. It will just start the job and return immediately. The job itself may continue to do it's steps.
A: The best, and easiest, way to do it is to create an SSIS project that has 35 Execute SQL tasks in parallel and then execute the job. The learning curve on using SSIS to do this is an hour or two and you can let SQL Server use as much resources as possible to execute the tasks as fast as possible. You don't have to mess around with maxops or anything else - SSIS will do it for you.
To see different ways to execute SSIS jobs try this link:
http://www.mssqltips.com/sqlservertip/1775/different-ways-to-execute-a-sql-server-ssis-package/ | unknown | |
d4517 | train | It's just the difference between the UTC and non-UTC representation.
new Date('2014-01-30').toString(); //Wed Jan 29 2014 19:00:00
new Date('2014-01-30').toUTCString(); //Thu, 30 Jan 2014 00:00:00
Try fechasPeriodo[0].toUTCString(); and I'm pretty sure it will return what you expect. | unknown | |
d4518 | train | If you want to yield, and prematurely exit the function, you can use a bare return after you yielded:
def function(ls):
for x in ls:
yield x
yield 4
return
some_code(that_wont, be_executed)
Generators don't return values, they yield them. The only reason to use return in a generator is to abort the execution / raise a StopIteration to signal to the caller that there are no more values. | unknown | |
d4519 | train | If you were to use a class instead of an ID, that is:
<tr class="google-visualization-table-tr-even google-visualization-table-tr-sel">
<td class="google-visualization-table-td"><input vr="2013-04-01" kol="John Deer n7" class="form-control costRedovi" value="0"></td>
<td class="google-visualization-table-td"><input vr="2013-04-01" kol="Laza Lazic" class="form-control costRedovi" value="0"></td>
</tr>
You could then retrieve the unfocused-input like so:
$(".costRedovi").focusout(function() {
var origval = $(this).attr('value');
var editedval = $(this).val();
console.log("before: " + origval + ", after:" + editedval);
}); | unknown | |
d4520 | train | Not sure what your problem is but if you want to convertdtypes to str the try this:
df.astype({'col_name': 'str'}) | unknown | |
d4521 | train | You can create elements in javascript using DOM by using the .createElement() method.
Example: Create a div for your menu and give it a css class name.
menudiv = document.createElement('div');
menudiv.className = 'menu';
Now you can plug your json data into it by creating other elements. For example if you would like to create a link using DOM.
link = document.createElement('a');
link.setAttribute('href', 'urlFromYourJsonData');
link.appendChild(document.createTextNode('Your Link Description'));
menudiv.appendChild(link);
and so on ...
I suggest you have a look at: https://developer.mozilla.org/en/DOM/document.createElement and make your way from there.
Edit: After seeing your second comment I also suggest you have a look at http://json.org to look up what JSON is. If you want to copy HTML code into your page you should use the innerHTML attribute.
Example:
div = document.createElement('div');
div.className = 'menu';
div.innerHTML = yourAjaxResponseHere; | unknown | |
d4522 | train | Your intuition is correct. According to facebook's developer doc's:
Never include your App Secret in client-side or decompilable code.
The reason for this is exactly what you said, even in compiled, obfuscated byte code, it is fairly trivial using modern methods to reverse engineer the app secret, even if you are using https.
The best practice in this situation would be to have a hosted api that would be used to proxy all logins through an external source, and to hide your app id and app secret in a separate config file. | unknown | |
d4523 | train | If the LIs/DIVs are floated elements, they'll naturally fall down to the next line as the width of their container gets smaller.
W3Schools has a nice example of exactly what you are describing, here:
http://www.w3schools.com/css/tryit.asp?filename=trycss_float_elements
That's from the main CSS Float topic page, here:
http://www.w3schools.com/css/css_float.asp | unknown | |
d4524 | train | No database query or method call is going to be cached automatically in your application, nor should it. Laravel and PHP aren't going to know how you want to use queries or methods.
Everytime you call customer(), you're building up and executing a new query. You could easily cache the result in a property if that's what you want, but you'd have watch the value of the $orderid property:
protected $customerCache;
public function customer()
{
if ($customerCache) return $customerCache;
$traderid = Order::where('id', $this->orderid)->value('traderid');
return $customerCache = Customer::where('id', $traderid)->where('tradertype', 'C')->first();
}
You're also performing too much in your constructor. I would highly recommend not performing queries in any constructors, constructors should be used to pass dependencies. The way you have it designed would make it very hard to unit test.
A: In Laravel 4.* there was a remember() method handling the cache in queries. It was removed from 5.1 with a valid reason that it's not the responsibility of Eloquent neither the query Builder to handle cache. A very very simplified version of a decorator class that could handle the caching of your queries:
final class CacheableQueryDecorator
{
private $remember = 60; //time in minutes, switch to load from config or add a setter
private $query = null;
public function __construct(Builder $builder)
{
$this->query = $builder;
}
private function getCacheKey(string $prefix = ''):string
{
return md5($prefix . $this->query->toSql() . implode(',', $this->query->getBindings()));
}
public function __call($name, $arguments)
{
$cache = Cache::get($this->getCacheKey($name), null);
if ($cache) {
return $cache;
}
$res = call_user_func_array([$this->query, $name], $arguments);
Cache::put($this->getCacheKey($name), $res, $this->remember);
return $res;
}
}
Using it:
$results = (new CacheableQueryDecorator($query))->get() | unknown | |
d4525 | train | Before I begin, you must understand that a char is of size sizeof(char) bytes and an int is of size sizeof(int) bytes, which in general is 1 byte and 4 bytes respectively. This means that 4 chars can make up 1 int.
Now if you look at file.write((char*)a, size);, you are converting the int* to char*, which means to look at the data in a as chars and not ints.
Performing some simple math, your array of 10 ints is of size 10 * 4 = 40 bytes. However, the amount of data you're writing to the file is of 10 chars which is only 10 bytes.
Next, you attempt to write arr to the file, and you read from the file back into arr. I assume you want to read into arrTest but as you've failed to do so, attempting to access the contents of arrTest will give you the output that you see, which as explained by the rest of the community is uninitialized memory. This is because arrTest[SIZE] defines an array of SIZE but the memory within it is uninitialized.
To sum it up, the cause of your current output is due to a problem in your program logic, and your incorrect usage of read and write poses a potential problem.
Thank you for reading.
A: file.write((char*)a, size);
writes size bytes to the file.
file.read((char*)a, size);
reads size bytes to the file.
You are using 10 for size. You are writing and reading just 10 bytes of data. You need to change those lines to:
file.write((char*)a, size*sizeof(int));
and
file.read((char*)a, size*sizeof(int));
And call fileToArray using the right argument. Instead of
if (fileToArray(file, arr, SIZE))
use
if (fileToArray(file, arrTest, SIZE))
without that, arrTest remains an uninitialized array. | unknown | |
d4526 | train | Really the best bet is to have the classes that are actually doing the custom painting override their own paintComponent() method. Let the AWT worry about the graphics contexts. | unknown | |
d4527 | train | This seems to do it (but I wonder about the purpose of it ):
WITH CTE AS (
SELECT 1 as ColA, 'X' as ColB,'Q' as ColC,'9' as ColD
UNION
SELECT 2,'Y','W',9
UNION
SELECT 3,'Z','E',9
UNION
SELECT 3,'X','R',9
UNION
SELECT 3,'Y','T',null
UNION
SELECT 2,'Z',null,null)
select
AA.ColA,
BB.ColB,
CC.ColC,
DD.ColD
from
(select ColA, ROW_NUMBER() over (order by ColA) RowA from (
select DISTINCT ColA from CTE) A) AA
FULL JOIN
(select ColB, ROW_NUMBER() over (order by ColB) RowB from (
SELECT DISTINCT ColB from CTE) B ) BB
ON BB.RowB = AA.RowA
FULL JOIN
(select ColC, ROW_NUMBER() over (order by ColC) RowC from (
SELECT DISTINCT ColC from CTE) C ) CC
ON CC.RowC = AA.RowA
FULL JOIN
(select ColD, ROW_NUMBER() over (order by ColD) RowD from (
SELECT DISTINCT ColD from CTE) D ) DD
ON DD.RowD = AA.RowA
DBFIDDLE
A: You want to suppress values when selecting data from the table? This is typically not done in SQL, but in the app displaying the data.
But if you want to, you can do this in SQL (using windw functions). For this to work you'd have to specify the order in which to select the rows. You say, you don't care about the order, so in below query I simply generate some row number we can base this on:
with numbered as
(
select t.*, row_number() over order by (newid()) as rn
from mytable
)
select
case when count(*) over (partition by cola order by rn) = 1 then cola end as a,
case when count(*) over (partition by colb order by rn) = 1 then colb end as b,
case when count(*) over (partition by colc order by rn) = 1 then colc end as c,
case when count(*) over (partition by cold order by rn) = 1 then cold end as d
from numbered
order by rn;
A: If you have a column that specifies the ordering, then you can use row_number():
select (case when row_number() over (partition by colA order by ordcol) = 1 then colA end),
(case when row_number() over (partition by colB order by ordcol) = 1 then colB end),
(case when row_number() over (partition by colC order by ordcol) = 1 then colC end),
(case when row_number() over (partition by colD order by ordcol) = 1 then colD end)
from tablename t;
If you don't have such a column, then it becomes tricker. You can generate one:
with t as (
select t.*,
row_number() over (order by (select null)) as ordcol
from tablename t
)
select (case when row_number() over (partition by colA order by ordcol) = 1 then colA end),
(case when row_number() over (partition by colB order by ordcol) = 1 then colB end),
(case when row_number() over (partition by colC order by ordcol) = 1 then colC end),
(case when row_number() over (partition by colD order by ordcol) = 1 then colD end)
from t; | unknown | |
d4528 | train | Create a second array of the same type as noteRecords and name it allRecords
Assign the complete set of records to allRecords and use noteRecords as data source array
Replace controlTextDidChange with
func controlTextDidChange(_ obj: Notification) {
let query = searchField.stringValue
if query.isEmpty {
noteRecords = allRecords
} else {
noteRecords = allRecords.filter { $0.title.localizedCaseInsensitiveContains(query)
}
tableView.reloadData()
}
A more sophisticated way is a diffable data source. | unknown | |
d4529 | train | Mike from http://mikeash.com - an amazing resource - provided me with the tip that solved this problem. The cause of the problem eludes me, but it was fixed by doing two things:
*
*In the Framework's project, setting its build location to @rpath as described in this article: http://mikeash.com/pyblog/friday-qa-2009-11-06-linking-and-install-names.html
*In the plugins loading the framework, weak reference during build, don't copy the framework during build, and then set the -rpath build setting to the location of the framework in the containing app. This ensures all items are using the same copy of the framework. | unknown | |
d4530 | train | Here's a couple of way to do this:
var employeeProducts = new List<EmployeeProduct>();
employeeProducts.Add(new EmployeeProduct(1, 2, "XYZ"));
employeeProducts.Add(new EmployeeProduct(1, 5, "ZXY"));
employeeProducts.Add(new EmployeeProduct(2, 2, "XYZ"));
var way1 = employeeProducts.Select(
ep => new ProductCount
{
ProductNumber = ep.ProductID,
EmployeeNumber = ep.EmployeeID,
CountProducts = employeeProducts.Count(epc => epc.ProductID == ep.ProductID)
});
var way2 = employeeProducts
.GroupBy(ep => ep.ProductID)
.SelectMany(epg => epg.Select(
ep => new ProductCount
{
ProductNumber = ep.ProductID,
EmployeeNumber = ep.EmployeeID,
CountProducts = epg.Count()
}));
A: I'm thinking the query will look something like this
EntityQuery<EmployeeProduct> query = from c in _employ.CountProduct()
group c by new {c.UserId, c.ProductId, c.Name}
into g
select new {
g.UserId,
g.ProductId,
g.Name,
Count = g.Count()
} | unknown | |
d4531 | train | You can use an UIScrollView (what you assumably already did for touch control) and control it using acceleration.
In
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
See UIAccelerometer and UIScrollView here on StackOverflow. | unknown | |
d4532 | train | If you convert your data into a pyspark Dataframe you could do it like this:
from pyspark.sql import functions as F, Window
(
df
.groupBy('teamId', 'player')
.agg(F.sum('minutesPlayed').alias('minutesPlayedTotal'))
.withColumn('rank', F.row_number().over(Window.partitionBy('teamId').orderBy(F.desc('minutesPlayedTotal')))
.where('rank <= 10')
.show()
)
A: If you want to use RDD then you can do something like this:
*
*reduce using teamId + player as key to calculate the total minutes played by each player
*reduce using this time only teamId as key to get the list of players with their count of minutes played for each team
*flatmap values to sort the list of (player, count) on descending order and take first 10 values
Example:
from operator import add
rdd = spark.sparkContext.parallelize([
(1, 'A', 33), (1, 'A', 12), (1, 'B', 5), (2, 'C', 22),
(2, 'C', 15), (2, 'C', 33), (2, 'D', 0)
])
rdd1 = rdd.map(lambda x: ((x[0], x[1]), x[2])) \
.reduceByKey(add) \
.map(lambda x: (x[0][0], [(x[0][1], x[1])])) \
.reduceByKey(add)\
.flatMapValues(lambda x: sorted(x, key=lambda a: a[1], reverse=True)[:10])
for p in rdd1.collect():
print(p)
#(1, ('A', 45))
#(1, ('B', 5))
#(2, ('C', 70))
#(2, ('D', 0)) | unknown | |
d4533 | train | There are various approaches you can take to yield the result you want. Some are:
*
*Store the authors's names in lowercase only (or at least in a consistent manner such that you do not have to transform their names to yield distinct ones among them in the first place) and in that case a distinct query alone is enough to get you the desired result.
*After you fetch the distinct authors's names from the current data, map their names to their respective lowercase version in-memory and then apply another distinct function on it to get all authors's names in lowercase and distinct form. That will look like:
var filter = ...
var cursor = await GetCollection().DistinctAsync(v => v.CreatedBy, filter);
var list = await cursor.ToListAsync();
var names = list.Select(v => v.ToLower()).Distinct().ToList();
*Use aggregation. Basically, you can project all authors's names to their respective lowercase form (see: toLower) and then group all the projected lowercase names to a set (see: addToSet). That set will be your result which you can extract from the aggregated result.
My opinion is that you should consider altering your data so as to not add unnecessary computational complexity which takes up valuable resources. If that is not possible, but the names themselves are relatively few, you can use the second approach. Use the third approach with the understanding that it is not the ideal and it will add to more processing on the part of your DBMS. | unknown | |
d4534 | train | If that is the way you wrote the program, then the error is correct. In Flex, the action for a rule must start on the same line as the pattern.
From the flex manual:
5.2 Format of the Rules Section
The rules section of the flex input contains a series of rules of the form:
pattern action
where the pattern must be unindented and the action must begin on the same line.
As written, you have supplied { as a pattern. That's not a valid pattern, and so flex complains. | unknown | |
d4535 | train | You can't specify the precision with std::to_string as it is a direct equivalent to printf with the parameter %f (if using double).
If you are concerned about not allocating each time the stream, you can do the following :
#include <iostream>
#include <sstream>
#include <iomanip>
std::string convertToString(const double & x, const int & precision = 1)
{
static std::ostringstream ss;
ss.str(""); // don't forget to empty the stream
ss << std::fixed << std::setprecision(precision) << x;
return ss.str();
}
int main() {
double x = 2.50000;
std::cout << convertToString(x, 5) << std::endl;
std::cout << convertToString(x, 1) << std::endl;
std::cout << convertToString(x, 3) << std::endl;
return 0;
}
It outputs (see on Coliru) :
2.50000
2.5
2.500
I didn't check the performance though... but I think you could even do better by encapsulating this into a class (like only call std::fixed and std::precision once).
Otherwise, you could still use sprintf with the parameters that suits you.
Going a little further, with an encapsulating class that you could use as a static instance or a member of another class... as you wish (View on Coliru).
#include <iostream>
#include <sstream>
#include <iomanip>
class DoubleToString
{
public:
DoubleToString(const unsigned int & precision = 1)
{
_ss << std::fixed;
_ss << std::setprecision(precision);
}
std::string operator() (const double & x)
{
_ss.str("");
_ss << x;
return _ss.str();
}
private:
std::ostringstream _ss;
};
int main() {
double x = 2.50000;
DoubleToString converter;
std::cout << converter(x) << std::endl;
return 0;
}
Another solution without using ostringstream (View on Coliru) :
#include <iostream>
#include <string>
#include <memory>
std::string my_to_string(const double & value) {
const int length = std::snprintf(nullptr, 0, "%.1f", value);
std::unique_ptr<char[]> buf(new char[length + 1]);
std::snprintf(buf.get(), length + 1, "%.1f", value);
return std::string(buf.get());
}
int main(int argc, char * argv[])
{
std::cout << my_to_string(argc) << std::endl;
std::cout << my_to_string(2.5156) << std::endl;
} | unknown | |
d4536 | train | As per the HTML:
<div id="WineDetailContent">
...
<span class="indigo-text descfont">Alsace</span>
<br>
...
<span class="indigo-text descfont">2014</span>
<br>
</div>
Both the desired texts are within the decendants <span class="indigo-text descfont"> of their ancestor <div id="WineDetailContent">
Solution
To print the texts from the <span class="indigo-text descfont"> elements you can use list comprehension and you can use either of the following locator strategies:
*
*Using CSS_SELECTOR:
print([my_elem.text for my_elem in driver.find_elements(By.CSS_SELECTOR, "div#WineDetailContent span.indigo-text.descfont")])
*Using XPATH:
print([my_elem.text for my_elem in driver.find_elements(By.XPATH, "//div[@id='WineDetailContent']//span[@class='indigo-text descfont']")])
A: find_element_by_xpath return single WebElement. You need to use find_elements_by_xpath to select both elements:
details = driver.find_element_by_xpath("//div[@id ='WineDetailContent']")
res = details.find_elements_by_xpath("./span[@class = 'indigo-text descfont']")
for i in res:
print(i.text)
A: I assume you are missing an (s) in find element, you need to use find_elements.
In general when we apply find element
element.find_element_by_xxxx(selector)
we will get back the first element that matches our selector.
however in case of more items you can use find elements
element.find_elements_by_xxxx(selector)
the find elements will return a list of all elements that matches our selector. | unknown | |
d4537 | train | u must specify the width and height also
<section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" >
A: Chrome 11 spits out the following in its debugger:
[Error] GET http://www.mypicx.com/images/logo.jpg undefined (undefined)
It looks like that hosting service is using some funky dynamic system that is preventing these browsers from fetching it correctly. (Instead it tries to fetch the default base image, which is problematically a jpeg.) Could you just upload another copy of the image elsewhere? I would expect it to be the easiest solution by a long mile.
Edit: See what happens in Chrome when you place the image using normal <img> tags ;)
A: it is working in my google chrome browser version 11.0.696.60
I created a simple page with no other items just basic tags and no separate CSS file and got an image
this is what i setup:
<div id="placeholder" style="width: 60px; height: 60px; border: 1px solid black; background-image: url('http://www.mypicx.com/uploadimg/1312875436_05012011_2.png')"></div>
I put an id just in case there was a hidden id tag and it works
A: As c-smile mentioned: Just need to remove the apostrophes in the url():
<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>
Demo here
A: I would like to add (in case someone came here looking for it) that it's not possible for url() to point a local image if you are trying to send an styled email. You have to deploy that image somewhere else. | unknown | |
d4538 | train | I think the general solution is to figure out where in world space the clicked coordinate falls, assuming the screen is a plane in the world (at the camera's location). Then you shoot a ray perpendicular to the plane, into your scene.
This requires "world-space" code to figure out which object(s) the ray intersects with; the solutions you mention as being unsuitable for OpenGL ES seem to be image-based, i.e. depend on the pixels generated when rendering the scene.
A: With OpenGL ES 2.0 you could use a FBO and render the depth values to a texture. Obviously, this wouldn't be exactly cheap (just a way around the restriction of glReadPixels)...
Further, since - as I understand it - you want to pick certain parts of your object you might want to do some sort of color-picking where each selectable portion of the object has an unique color (note that the Lighthouse 3D tutorial only shows the general idea behind color-picking, your implementation would probably be different). You could optimize a little by performing a ray/bounding-box intersection beforehand and only rendering the relevant candidates to the texture used for picking. | unknown | |
d4539 | train | Managed to solve it!
To anyone who might find this useful, i passed a dictionary with "symbolic_solver_labels" as an io_options argument for the method, like this:
instance.write(filename = str(es_) + ".mps", io_options = {"symbolic_solver_labels":True})
Now my variables are correctly labeled in the .mps file! | unknown | |
d4540 | train | What is your problem on this old loop-based approach?
var boolVals = new[] { true, false };
var intVals = new[] { 0, 1, 2, 3, 4, 5 };
var myList = new List<A>();
foreach(var foo in boolVals) {
foreach(var value in intVals) {
foreach(var bar in boolVals) {
foreach (var boo in boolVals) {
myList.Add(new A { value = value, foo = foo, bar = bar, boo = boo });
}
}
}
}
You have to add a new nesting for every property you add and loop the appropriate set of values this property might have.
This appraoch fils every possible permutation of your values within a few lines of easy to read code.
Of course it looks a bit ugly. But it increases only by one further nesting on every added property.
A: Since you don't explicitly ask for an all-permutation solution, I'd suggest going random. You could employ the constructor...
public class A
{
public int value {get; set;} //want to try beetween 0 and 5
public bool foo {get; set;}
public bool bar {get; set;}
public bool boo {get; set;}
public A()
{
// initialize value, foo, bar, boo with desired default / random here
}
}
var myList = new List<A>();
for (int i=0; i<=24; i++) myLyst.add(new A());
this seems quite readable and maintainable to me. You could also pass an argument to new A() and use it to calculate the n-th permutation if needed, but I guess this goes beyond the scope of the question.
A: You can do this using reflection and a data structure that keeps track of the value (via equivalent indices) for each property
This automatically accounts for all properties in the class and you can extend it for other property types by simply adding to the ValuesFor dictionary
using System;
using System.Collections.Generic;
using System.Reflection;
public class Program
{
private static Dictionary<string, object[]> ValuesFor = new Dictionary<string, object[]>()
{
{ typeof(int).ToString(), new object[] { 0, 1, 2, 3, 4, 5 } },
{ typeof(bool).ToString(), new object[] { true, false } }
};
public static void Main()
{
var properties = typeof(A).GetProperties(BindingFlags.Instance | BindingFlags.Public);
int[] valueIndices = new int[properties.Length];
do
{
createObject(properties, valueIndices);
} while (setNext(properties, valueIndices));
Console.ReadKey();
}
/// <summary>
/// This updates the valueIndex array to the next value
/// </summary>
/// <returns>returns true if the valueIndex array has been updated</returns>
public static bool setNext(PropertyInfo[] properties, int[] valueIndices)
{
for (var i = 0; i < properties.Length; i++)
{
if (valueIndices[i] < ValuesFor[properties[i].PropertyType.ToString()].Length - 1) {
valueIndices[i]++;
for (var j = 0; j < i; j++)
valueIndices[j] = 0;
return true;
}
}
return false;
}
/// <summary>
/// Creates the object
/// </summary>
public static void createObject(PropertyInfo[] properties, int[] valueIndices)
{
var a = new A();
for (var i = 0; i < properties.Length; i++)
{
properties[i].SetValue(a, ValuesFor[properties[i].PropertyType.ToString()][valueIndices[i]]);
}
print(a, properties);
}
public static void print(object a, PropertyInfo[] properties)
{
Console.Write("Created : ");
for (var i = 0; i < properties.Length; i++)
Console.Write(properties[i].Name + "=" + properties[i].GetValue(a) + " ");
Console.Write("\n");
}
public class A
{
public int value { get; set; }
public bool foo { get; set; }
public bool bar { get; set; }
public bool boo { get; set; }
}
}
Currently createObject, just creates the object and calls print to print out the object. Instead, you could add it to a collection and run your tests with it (or directly put your tests instead of print)
Fiddle - https://dotnetfiddle.net/oeLqc5 | unknown | |
d4541 | train | You should run the hive schema .sql scripts mentioned in $HIVE_HOME\scripts\metastore\upgrade\mysql.
NOTE: I was using MySql as the underlying db for hive. | unknown | |
d4542 | train | There is a problem about the visuality of these kind of characters on Smartface desktop ide. But actually it works fine. About the visual problem, there is a reported bug and it will be fixed with the new versions of Smartface.
But for now, you can show chinese characters on device without any problem.
I copied your code (the below code):
function Page1_Self_OnShow() {
//Comment following block for removing navigationbar/actionbar sample
//Copy this code block to every page onShow
header.init(this);
header.setTitle("Page1中国文字");
header.setRightItem("RItem");
header.setLeftItem();
this.statusBar.transparent = true;
/**/
}
And this code block looks wrong on ide (this is the bug):
It should be setTitle("Page1中国文字"); but it is lack of the last " character.
As I said before this is only a visual bug.
When I run this app on device (by using device emulator or publish), it is seen as in the below screenshot: | unknown | |
d4543 | train | you can simply do
if (number % 3 == 0) and (number % 5 == 0):
your code here...
A: With the Python syntax, you need to use an and instead of &.
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Source: https://www.w3schools.com/python/python_conditions.asp#:~:text=The%20and%20keyword%20is%20a%20logical%20operator%2C%20and%20is%20used%20to%20combine%20conditional%20statements
A: Does your program error at all? Python 3 allows keyword & as well as and to be used as "and" conditional statements. It should work either way...
A: You can use "and" or "or" operator, difference between them is that "and" should call True if all of the condition are True, "or" - if one of it is True.
example:
a = 1
b = 2
c = 'd'
if type(a) == int and type(b) == int:
# that will be printed
print("a, b are numbers")
if type(a) == int and type(c) == int:
# that will not be printed
print("a, c are numbers")
if type(a) == int or type(c) == int:
# that will be printed
print("a or c is number")
your code should look like:
Starting_Num = int(input('Please enter intial number: '))
Ending_Num = int(input('Please enter ending number: '))
for number in range(Starting_Num, (Ending_Num+1)):
if (number % 3 == 0):
print(number, '--', 3)
elif (number % 5 == 0):
print(number, '--', 5)
elif (number % 3 == 0) and (number % 5 == 0):
print(number, '-- both')
elif (number % 3 != 0) and (number % 5 != 0):
print(number)
A: The problem is where you position your 'and' condition. In your code, assuming the input fits the condition (e.g. the number is 15) what will happen is that you will enter the first condition: (if (number % 3 != 0):) and skip all the others, because you used [if / elif] statements. What you need to do is move the condition [elif (number % 3 != 0) & (number % 5 != 0):] to be the first condition, which will ensure that in case the number is divisible by both 3 and 5 - you will first check for both conditions.
Also, in case of logical and use the and operator.
It should look something like this:
Starting_Num = int(input('Please enter intial number: '))
Ending_Num = int(input('Please enter ending number: '))
for number in range(Starting_Num, (Ending_Num+1)):
if (number % 3 == 0) and (number % 5 == 0):
print(number, '-- both')
elif (number % 3 == 0):
print(number, '--', 3)
elif (number % 5 == 0):
print(number, '--', 5)
else:
print(number) | unknown | |
d4544 | train | select LawSchool, count(*) as cnt
from Judges
where LawSchool in ('Harvard','Yale')
Group By LawSchool
A: You can use a group by clause to separate the aggregate result per unique value:
SELECT LawSchool, COUNT(*)
FROM Judges
WHERE LawSchool IN ('Harvard', 'Yale')
GROUP BY LawSchool
A: You can use in and group by
select LawSchool, count(*) as cnt
from Judges where LawSchool in ( 'Harvard', 'Yale')
group by LawSchool | unknown | |
d4545 | train | Just add all your widgets into the layout and use QWidget::hide(), QWidget::show() when needed.
For more complex situations you can use The State Machine Framework. | unknown | |
d4546 | train | Use android:paddingTop attribute together with EditText view with negative dps.
Example:
<EditText android:id="@+id/edit_fname" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:hint="First Name (Required)" android:paddingTop=-3dp />
Based on your requirement you can apply to any of these attributes.
android:paddingLeft android:paddingRight android:paddingBottom android:paddingTop
A: use negative margins instead of padding... | unknown | |
d4547 | train | You have your constructor assignments backwards.
This:
public Weapon(string n, double d)
{
n = Name;
d = Damage;
}
public Weapon (string n, double r, double d)
{
n = Name;
r = Range;
d = Damage;
}
Should be this:
public Weapon(string n, double d)
{
Name = n;
Damage = d;
}
public Weapon (string n, double r, double d)
{
Name = n;
Range = r;
Damage = d;
}
A: Try this:
public class Weapon
{
private string _name;
private double _range;
private double _damage;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public double Range
{
get
{
return _range;
}
set
{
if (value >= 0)
_range = value;
else
throw new ArgumentException("Invalid Range");
}
}
public double Damage
{
get
{
return _damage;
}
set
{
if (value >= 0)
_damage = value;
else
throw new ArgumentException("Invalid Damage");
}
}
public Weapon(string n, double d)
{
Name = n;
Damage = d;
}
public Weapon(string n, double r, double d)
{
Name = n;
Range = r;
Damage = d;
}
} | unknown | |
d4548 | train | The data returned by the heroService.getHeroes method is plain JSON object (without the getter you defined in the Hero class). If you want to use the getter defined in the class you have to return an Array of real Hero instance.
1/ We add a constructor for the Hero class in app/hero.ts for convenience
constructor ({id,name} = {id: undefined, name: undefined}) {
this.id = id;
this.name = name;
}
2/ Instead of returning plain js data from heroService we map to obtain an array of Hero instance in dashboard.component.ts
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes =>
this.heroes = heroes
.slice(1, 5)
.map(hero => new Hero(hero))
);
}
And Tadaa !
Here is the stackblitz created upon your github repo
A: Well, your problem is that, though you're adding a new getter to the Hero class, in the dashboard you're listing the heroes coming from the service. The problem is that the service is mocking data, and that data is, in truth, a simple array of objects (defined in in-memory-data.service.ts):
const heroes = [
{ id: 11, name: 'Mr. Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
In the original example this does not matter as the Hero class is used there basically as an interface or type annotation. You, however, are giving that class methods, but those methods do not exist in the array.
So, basically, your template is trying to access a propname property from the items of this array. That property, as you see, is undefined. As a result, you don't see the name in the page. To avoid this, just change the definition of the array:
const heroes = [
Object.assign(new Hero(), { id: 11, name: 'Mr. Nice' }),
...
];
(you can also give Hero a constructor with parameters and use it instead of Object.assign). This way you'll get an array of true Hero objects. | unknown | |
d4549 | train | I think it is a TZ issue, b/c the difference between your GMT+0100 and your StartDate=2014-06-09T23:00:00.000Z is 5 hours.
.
The issue:
Your local time is currently BST (British Summer Time) equivalent to GMT +1
This is going to be the default time when you make your API call.
However, the API was written by Google in California, and they are rather egocentric. Therefore, they're automatically converting the time since you're not providing any date formatting "instructions".
In other words, Chrome does the conversion for you nicely when you print to the console.log(), but when you make your $http.put, Angular, without explicit formatting for you, makes the call using it's default TZ (which is PST)
.
Resolution
You need to force the date formatting to your locale.
*
*Angular template
{{ date_expression | date : 'yyyy-MM-dd HH:mm:ss'}}
*In JavaScript
$filter('date')(date, 'yyyy-MM-dd HH:mm:ss')
*using localization
<html>
<head>
<title>My Angular page</title>
<script src="angular-locale_en-uk.js"></script>
...
</head>
<body>
...
</body>
</html> | unknown | |
d4550 | train | First of all, the Log.d() method calls may be something like Log.d("MyAppName", "Message") not Log.d("Message", "Message") In this way you can create a filter in LogCat for your app and see only your messages. (Check this on Eclipse)
For your problem, try putting some useful message in the catch block, something like:
try{
...
} catch (IOException e){
Log.d("MyAppName", e.getMessage());
}
This will show you the problem that throw the exception.
Consider take a look to this sample code, the getUrlContent() do exactly what you wont.
Good luck
A: The first line of your stacktrace says:
java.net.UnknownHostException:
stanford.edu
You should learn to read stacktraces. A quick search for "UnknownHostException" tells you it is:
Thrown to indicate that the IP address
of a host could not be determined.
This means that it can't turn stanford.edu into an IP. You probably need www.stanford.edu or something like that. Try pinging the address on the command line ping www.stanford.edu , and make sure it resolves to an ip address.
A: I forgot to add the internet permission in my manifest file.
A: add to Manifest
<uses-permission android:name="android.permission.INTERNET" /> | unknown | |
d4551 | train | use this command
npm install --save-dev @angular-devkit/build-angular
A: If you are using Angular 8, you should ensure your Angular packages are safely updated to the current stable version by running the following command
ng update
Otherwise, you can try to manually update the @angular/cli and core framework package manually.
ng update @angular/cli @angular/core
A: It seems to be an issue with @angular-devkit/build-angular, try downgrading to a specific version
npm i @angular-devkit/[email protected]
This version worked for me.
A: I solved that problem by below comment. Hopefully, it will work for you too
npm i --save-dev @angular-devkit/build-angular@latest
A: I Have followed following steps and it worked for give it a try.
Delete current project if its new new one or get backup of your project.
update angular cli globally by
npm i -g @angular/[email protected]
then create a new project.
ng new name
ng serve
thats it. | unknown | |
d4552 | train | Your function have some strange methods such as _getContents, _getXrefStream and _updateStream, maybe they are deprecated or somthing, but here is working code for solving your problem:
import fitz
def remove_img_on_pdf(idoc, page):
img_list = idoc.getPageImageList(page)
con_list = idoc[page].get_contents()
for i in con_list:
c = idoc.xref_stream(i)
if c != None:
for v in img_list:
arr = bytes(v[7], 'utf-8')
r = c.find(arr)
if r != -1:
cnew = c.replace(arr, b"")
idoc.update_stream(i, cnew)
c = idoc.xref_stream(i)
return idoc
doc = fitz.open('ELN_Mod3AzDOCUMENTS.PDF')
rdoc = remove_img_on_pdf(doc, 0)
rdoc.save('no_img_example.PDF')
As you can see, I've used another methods instead of non-working ones. Also, here is documentation for PyMuPDF.
A: Ïf you print dir(idoc[0]) , you see a list of attributes. you should use idoc[page].get_contents() instead. | unknown | |
d4553 | train | Create a localstorage as
localStorage.setItem('key',value);
And get result from
localStorage.getItem('key'); | unknown | |
d4554 | train | This might be better, try it :
SELECT COUNT(container_no) FROM pier_date
WHERE container_no NOT IN
(
SELECT [Customer Box Nbr] FROM iron_mountain_data
);
Also, as it has been suggested, you could use a left join with a where clause like this :
SELECT COUNT(container_no) FROM pier_date pd
LEFT JOIN iron_mountain_data imd ON pd.container_no = imd.[Customer Box Nbr]
WHERE imd.[Customer Box Nbr] IS NULL
The use of keyword 'DISTINCT' might be useful too like
COUNT(DISTINCT container_no)
or
SELECT DISTINCT [Customer Box Nbr]
A: Assuming [container_no] and [Customer box nbr] captures the same information
SELECT COUNT(container_no)
FROM pier_date pd
WHERE container_no NOT IN (
SELECT DISTINCT [Customer Box Nbr]
FROM iron_mountain_data
)
A: Your query is fine, although I would use COUNT(*) and table aliases:
SELECT COUNT(*)
FROM pier_data as pd
WHERE NOT EXISTS (SELECT 1
FROM Iron_mountain_data as imd
WHERE pd.container_no = imd.[Customer Box Nbr]
);
(These changes have no impact on performance, except for a very, very, very minor check that container_no is not NULL for the COUNT().)
For performance, you want an index on Iron_mountain_data([Customer Box Nbr]):
create index idx_iron_mount_data_customer_box_nbr on Iron_mountain_data([Customer Box Nbr];
This should work for almost any way that you write the query. | unknown | |
d4555 | train | Here is what I ended up with, thanks to Meriton's pointers.
As he suggested, I changed my app-column component to a directive instead. That directive must appear on a ng-template element:
@Directive({
selector: 'ng-template[app-column]',
})
export class ColumnDirective {
@Input() title: string;
@ContentChild(TemplateRef) template: TemplateRef<any>;
}
The app-table component became:
@Component({
selector: 'app-table',
template: `
<table>
<thead>
<th *ngFor="let column of columns">{{column.title}}</th>
</thead>
<tbody>
<tr *ngFor="let row of data">
<td *ngFor="let column of columns">
<ng-container
[ngTemplateOutlet]="column.template"
[ngTemplateOutletContext]="{$implicit:row}">
</ng-container>
</td>
</tr>
</tbody>
</table>
`,
})
export class TableComponent {
@Input() data: any[];
@ContentChildren(ColumnDirective) columns: QueryList<ColumnDirective>;
}
While at first I was a bit turned off by having to expose ng-template to some of my teammates (not very Angular savvy team yet...), I ended up loving this approach for several reasons. First, the code is still easy to read:
<app-table [data]="data">
<ng-template app-column title="name" let-person>{{person.name}}</ng-template>
<ng-template app-column title="age" let-person>{{person.birthday}}</ng-template>
</app-table>
Second, because we have to specify the variable name of the context of the template (the let-person) code above, it allows us to retain the business context. So, if we were to now talk about animals instead of people (on a different page), we can easily write:
<app-table [data]="data">
<ng-template app-column title="name" let-animal>{{animal.name}}</ng-template>
<ng-template app-column title="age" let-animal>{{animal.birthday}}</ng-template>
</app-table>
Finally, the implementation totally retains access to the parent component. So, let say we add a year() method that extracts the year from the birthday, on the app-root component, we can use it like:
<app-table [data]="data">
<ng-template app-column title="name" let-person>{{person.name}}</ng-template>
<ng-template app-column title="year" let-person>{{year(person.birthday)}}</ng-template>
</app-table>
A: In Angular, content projection and template instantiation are separate things. That is, content projection projects existing nodes, and you will need a structural directive to create nodes on demand.
That is, column needs to become a structural directive, that passes its template to the parent smart-table, which can then add it to its ViewContainer as often as necessary. | unknown | |
d4556 | train | It would be tough for others to have debugged this, but when I created a byteStream, I used length, instead of length - 1. For some reason in almost all documents this is no problem, but office 2007 threw a fit. | unknown | |
d4557 | train | You haven't shown your mysite.urls, but from the error message it looks like you have done something like this:
(r'^events/$', include('events.urls')),
You need to drop the terminating $, since that means the end of the regex; nothing can match after that. It should be:
(r'^events/', include('events.urls')),
Note that you should also give your event URLs names, to make it easier to reference:
url(r'^$', views.events_list, name='events_list'),
url(r'^event/(?P<pk>[0-9]+)/$', views.event_detail, name='event_detail'),
so that you can now do:
{% url 'event_detail' pk=event.pk %} | unknown | |
d4558 | train | The encryption used for Forms Authentication is based on the <machineKey> element under <system.web>. Effectively you reconfigure the <machineKey> element to control the encryption.
See here for further information. | unknown | |
d4559 | train | Maybe you should initialize the pygame (which initialize SDL-> OpenGL) in each forked (child) process like in sample:
import multiprocessing
def f():
import pygame
pygame.init()
while True:
pygame.event.pump()
if __module__ == "__main__"
p = multiprocessing.Process(target=f)
p.start()
import pygame
pygame.init()
while True:
pygame.event.pump()
A: Try this link:
http://www.slideshare.net/dabeaz/an-introduction-to-python-concurrency#btnPrevious
It may help. The problem is that you are creating a process that never stops. This should be declared as a daemon:
p = multiprocessing.Process(target=f)
p.daemon = True
p.start()
Not sure if this will solve the problem, I'm just learning about the multiprocessing module as I'm posting this.
A: Have you tried using threads instead of processes? I've had issues before using the python multiprocessing module in OS X. http://docs.python.org/library/threading.html | unknown | |
d4560 | train | If you want to poll some external resource (with an AJAX call, for example) you can follow the "Recursive setTimeout pattern" (from https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval). Example:
(function loop(){
setTimeout(function(){
// logic here
// recurse
loop();
}, 1000);
})();
A: use setInterval() instead of setTimeout()
something like:
setInterval(function(){
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
//do something
});
},1000*60);
http://www.w3schools.com/jsref/met_win_setinterval.asp
https://api.jquery.com/jQuery.ajax/ | unknown | |
d4561 | train | First, to determine if the package is being detected or not you can check the log files in the temp directory of the current user. It will tell you whether or not the package has been detected.
Now to determine whether or not to go into maintenance mode vs. install mode, you can check the package state by subscribing to the DetectPackageComplete event. In the example below, my UI uses two properties, InstallEnabled and UninstallEnabled to determine what "mode" to present to the user.
private void OnDetectPackageComplete(object sender, DetectPackageCompleteEventArgs e)
{
if (e.PackageId == "DummyInstallationPackageId")
{
if (e.State == PackageState.Absent)
InstallEnabled = true;
else if (e.State == PackageState.Present)
UninstallEnabled = true;
}
}
The code sample above is from my blog post on the minimum pieces needed to create a Custom WiX Managed Bootstrapper Application.
A: An easy way to determine if your Bundle is already installed is to use the WixBundleInstalled variable. That will be set to non-zero after your Bundle is successfully installed.
Additionally, in WiX v3.7+ the OnDetectBegin callback now tells you if the bundle is installed so you don't have to query the variable normally.
These changes were made to make it easier to detect maintenance mode to avoid the completely reasonable solution that @BryanJ suggested. | unknown | |
d4562 | train | Angular distinguishes so-called boxed and unboxed values.
Boxed value is a value satisfying the following condition:
_isBoxedValue(formState: any): boolean {
return typeof formState === 'object' &&
formState !== null &&
Object.keys(formState).length === 2 &&
'value' in formState &&
'disabled' in formState;
}
https://github.com/angular/angular/blob/7c414fc7463dc90fe189db5ecbf3e5befcde6ff4/packages/forms/src/model.ts#L621-L624
As we can see we should provide both value and disabled properties for boxed value.
If you pass unboxed value then angular will treat it like a value.
More information could be found here
*
*https://github.com/angular/angular/blob/master/packages/forms/test/form_control_spec.ts#L50-L77 | unknown | |
d4563 | train | If you have XSLT 2.0, you can use date parsing and formatting functions.
If you have XSLT 1.0, but can use EXSLT, it provides similar functions.
These would be less transparent to use than @Peter's explicit code, but maybe more robust if your input format can vary.
A: Here is a most generic formatDateTime processing. Input and output format are completely configyrable and passed as parameters:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="convertDateTime">
<xsl:with-param name="pDateTime" select="."/>
</xsl:call-template>
</xsl:template>
<xsl:template name="convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat">
<year offset="0" length="4"/>
<month offset="4" length="2"/>
<day offset="6" length="2"/>
<hour offset="8" length="2"/>
<minutes offset="10" length="2"/>
<seconds offset="12" length="2"/>
<zone offset="15" length="5"/>
</xsl:param>
<xsl:param name="pOutFormat">
<y/>-<mo/>-<d/> <h/>:<m/>:<s/> <z/>
</xsl:param>
<xsl:variable name="vInFormat" select=
"document('')/*/xsl:template[@name='convertDateTime']
/xsl:param[@name='pInFormat']"/>
<xsl:variable name="vOutFormat" select=
"document('')/*/xsl:template[@name='convertDateTime']
/xsl:param[@name='pOutFormat']"/>
<xsl:apply-templates select="$vOutFormat/node()"
mode="_convertDateTime">
<xsl:with-param name="pDateTime" select="$pDateTime"/>
<xsl:with-param name="pInFormat" select="$vInFormat"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="y" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/year/@offset,
$pInFormat/year/@length)"/>
</xsl:template>
<xsl:template match="mo" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/month/@offset,
$pInFormat/month/@length)"/>
</xsl:template>
<xsl:template match="d" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/day/@offset,
$pInFormat/day/@length)"/>
</xsl:template>
<xsl:template match="h" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/hour/@offset,
$pInFormat/hour/@length)"/>
</xsl:template>
<xsl:template match="m" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/minutes/@offset,
$pInFormat/minutes/@length)"/>
</xsl:template>
<xsl:template match="s" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/seconds/@offset,
$pInFormat/seconds/@length)"/>
</xsl:template>
<xsl:template match="z" mode="_convertDateTime">
<xsl:param name="pDateTime"/>
<xsl:param name="pInFormat"/>
<xsl:value-of select=
"substring($pDateTime,
1+$pInFormat/zone/@offset,
$pInFormat/zone/@length)"/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied to the following XML document:
<dateTime>20101115083000 +0200</dateTime>
the wanted, correct result is produced:
2010-11-15 08:30:00 +0200
A: We use templates:
<xsl:template name="format-date-time">
<xsl:param name="date" select="'%Y-%m-%dT%H:%M:%S%z'"/>
<xsl:value-of select="substring($date, 9, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring($date, 6, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring($date, 1, 4)"/>
<xsl:text> </xsl:text>
<xsl:value-of select="substring($date, 12, 2)"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="substring($date, 15, 2)"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="substring($date, 18, 2)"/>
</xsl:template>
We call these templates like this:
<xsl:call-template name="format-date-time">
<xsl:with-param name="date" select="./Startdate"/>
</xsl:call-template>
./Startdate is an XML date, but with the substring technique, I think you could solve your problem too. | unknown | |
d4564 | train | This site has some information about the topic: http://www.tutorialforandroid.com/2009/01/changing-screen-brightness.html
The part what you need:
IHardwareService hardware = IHardwareService.Stub.asInterface(ServiceManager.getService("hardware"));
if (hardware != null)
hardware.setScreenBacklight(brightness);
I didn't test it but it should work
UPDATE:
Alternate solution:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params); | unknown | |
d4565 | train | Yes, one can expect a server to stop responding after causing too much traffic (whatever the definition of "too much traffic") to it.
One way to limit number of concurrent requests (throttle them) in such cases is to use asyncio.Semaphore, similar in use to these used in multithreading: just like there, you create a semaphore and make sure the operation you want to throttle is aquiring that semaphore prior to doing actual work and releasing it afterwards.
For your convenience, asyncio.Semaphore implements context manager to make it even easier.
Most basic approach:
CONCURRENT_REQUESTS = 200
@asyncio.coroutine
def worker(url, semaphore):
# Aquiring/releasing semaphore using context manager.
with (yield from semaphore):
response = yield from aiohttp.request(
'GET',
url,
connector=aiohttp.TCPConnector(share_cookies=True,
verify_ssl=False))
body = yield from response.read_and_close()
print(url)
def main():
url_list = [] # lacs of urls, extracting from a file
semaphore = asyncio.Semaphore(CONCURRENT_REQUESTS)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([worker(u, semaphore) for u in url_list])) | unknown | |
d4566 | train | Have you tried Media Queries?
Check out: http://www.w3.org/TR/css3-mediaqueries/
You can detect the screen size (or intervals of sizes) and apply different CSS to it, regarding element size in your page. | unknown | |
d4567 | train | I don't think you can put just the HintPath in the Choose. You have to put the entire ItemGroup within the When and Otherwise. Like this:
<Choose>
<When Condition="Exists('..\..\SharedLib\bin\Debug')">
<ItemGroup>
<Reference Include="SharedLib...">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\SharedLib\bin\Debug\SharedLib.dll</HintPath>
</Reference>
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Reference Include="SharedLib...">
<SpecificVersion>False</SpecificVersion>
<HintPath>.\SharedLib.dll</HintPath>
</Reference>
</ItemGroup>
</Otherwise>
</Choose> | unknown | |
d4568 | train | I am going to guess that the code in the answer to the other stack isn't quite correct, but is more of a concept for how things could be written (Edit - Or its written against an older version of EWS). Either way, there are some excellent examples here: http://msdn.microsoft.com/en-us/library/office/bb408521(v=exchg.140).aspx.
Taking the guts of it, you should probably end up with something like:
// Identify the service binding and the user.
ExchangeServiceBinding service = new ExchangeServiceBinding();
service.RequestServerVersionValue = new RequestServerVersion();
service.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010;
service.Credentials = new NetworkCredential("<username>", "<password>", "<domain>");
service.Url = @"https://<FQDN>/EWS/Exchange.asmx";
From there you can use the service to create requests or whatever it is you need to do. Note this code was copied from the msdn link above so you'll want to refer back to that for further explanation. Best of luck!
A: Instead of using the Add Web Reference tool to generate the Web service client, I highly suggest that you use the EWS Managed API instead. It is a much easier object model to use and it has some useful business logic built into it. It will save you time and lines of code. | unknown | |
d4569 | train | I've found that the issue can be solved by using MVEL notation instead of pure Java.
If in Data Outputs as a Target we use following expression:
#{CalcInter.axx}
The jBPM engine correctly updates the object property.
(How to use a Java style in the case and if it is possible — I still don't know.) | unknown | |
d4570 | train | I realized the issue was that I was still building the .xcodeproj file as shown below:
xcodebuild build-for-testing
-project ProjectName.xcodeproj
-scheme ProjectName
-destination 'platform=iOS Simulator,name=iPhone 12,OS=latest'
-testPlan UnitTests
| xcpretty
But since I was now using cocoa pods in my project, I needed to use the .xcworkspace file to build it:
xcodebuild build-for-testing
-workspace ProjectName.xcworkspace
-scheme ProjectName
-destination 'platform=iOS Simulator,name=iPhone 12,OS=latest'
-testPlan UnitTests
| xcpretty | unknown | |
d4571 | train | if you use this your app will not crash again. The problem is at **Environment.getExternalStorageDirectory()**you're missing **.getPath()**
use the code below as guide for your intent.
final Intent audIntent = new Intent(android.content.Intent.ACTION_SEND);
String audioName="kidi.mp3";
audIntent.setType("audio/mp3");
audIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file://"+"/Environment.getExternalStorageDirectory().getPath()/"+audioName));
startActivity(Intent.createChooser(audIntent, "Share Audio ")); | unknown | |
d4572 | train | You could make a string extension to strip the Html tags.
public static class StringExtensions
{
public static string StripHtml (this string inputString)
{
return Regex.Replace
(inputString, "<.*?>", string.Empty);
}
}
Then use it in your view
@myHtmlString.StripHtml()
You might need to declaring a using statement for the StringExtensions class or add it to the Web.Config file in your Views folder
@using My.Extensions.Namespace
OR
<system.web>
<pages>
<namespaces>
<add namespace="My.Extensions.Namespace" />
</namespaces>
</pages>
</system.web>
You could also make a Html Helper Extension
public static class HtmlExtensions
{
public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
{
return Regex.Replace
(htmlString, "<.*?>", string.Empty);
}
}
You can use this in your view like this
@Html.StripHtml(myHtmlString)
You will still need to add a reference to the namespace for your extension methods like above. Either adding to your Web.Config in your Views folder or adding a using statement in your view. The differences here is that adding it to your Web.Config file you will be able to use this extension method in all your views without adding the using statement. | unknown | |
d4573 | train | Something like this (you'll need to adjust the colors to suit your needs)
http://www.rapidtables.com/web/color/RGB_Color.htm
Sub ApplyColorScheme(cht As Chart, i As Long)
Dim arrColors
Select Case i Mod 2
Case 0
arrColors = Array(RGB(50, 50, 50), _
RGB(100, 100, 100), _
RGB(200, 200, 200))
Case 1
arrColors = Array(RGB(150, 50, 50), _
RGB(150, 100, 100), _
RGB(250, 200, 200))
End Select
With cht.SeriesCollection(1)
.Points(1).Format.Fill.ForeColor.RGB = arrColors(0)
.Points(2).Format.Fill.ForeColor.RGB = arrColors(1)
.Points(3).Format.Fill.ForeColor.RGB = arrColors(2)
End With
End Sub
Example usage:
chtMarker.SeriesCollection(1).Values = rngRow
ApplyColorScheme chtMarker, thmColor
chtMarker.Parent.CopyPicture xlScreen, xlPicture | unknown | |
d4574 | train | for plain implementation in server side rendering you need to have different app entry point with StaticRouter instead of BrowserRouter
react-routed-dom documentation with implementation:
https://reacttraining.com/react-router/web/guides/server-rendering/putting-it-all-together | unknown | |
d4575 | train | what does it means.. that I tried to read the position 68 of an array that has only 10 positions?
Exactly! Index = 9 is the maximal index you can access. | unknown | |
d4576 | train | Just tested it on the emulator and on my device. In the emulator it's like Mark is metioning it's always returning PotraitUp.
However if i test it on my device than the correct orientation is directly returned. So probably as Mark is suggesting it's a emulator bug.
A: This worked for me.. and it worked perfectly.. hope this helps others..
PageOrientation orient = Orientation;
CheckOrientation(orient);
The above code gets the orientation of the current page. Call it in method of your class. Then, you can perform the following
private void CheckOrientation(PageOrientation orient)
{
if (orient == PageOrientation.LandscapeLeft || orient == PageOrientation.LandscapeRight)
{
//Do your thing
}
else if (orient == PageOrientation.PortraitUp || orient == PageOrientation.PortraitDown)
{
//Do your thing
}
}
A: What I found out about this:
((PhoneApplicationFrame)Application.Current.RootVisual).Orientation does not have the correct orientation in PageLoaded.
It does not give back the correct orientation in the first LayoutUpdated event either. However there is a second LayoutUpdated event, in which it gives the correct one.
And between the two LayoutUpdated events, if the last page was in another orientation, then there will be an OrientationChanged event as well.
So there was no other solution for me then waiting for the OrientationChanged event to happen (because the only page the user can come to this page from supports only Portrait mode).
A: Your application must support Landscape orientation to receive it. If you support only Portrait, than you never get nor OrientationChanged event and Landscape orientation in provided property.
A: The solution is:
public YourPhonePage()
{
InitializeComponent();
Microsoft.Phone.Controls.PageOrientation currentOrientation = (App.Current.RootVisual as PhoneApplicationFrame).Orientation;
if (currentOrientation == PageOrientation.PortraitUp)
{
// Do something...
}
} | unknown | |
d4577 | train | At the top of the very page you linked, it tells you:
You may also specify attributes with ‘__’ preceding and following
each keyword. This allows you to use them in header files without
being concerned about a possible macro of the same name. For example,
you may use __aligned__ instead of aligned.
Identifiers containing double underscores (__) are reserved to the implementation. Hence no user program could legally define them as macros. | unknown | |
d4578 | train | Looks like your test file is a js file (src\__tests__\DatePicker.spec.js) instead of ts?x file which means this pattern will never meet "^.+\\.(ts|tsx)$": "ts-jest".
However, you might know tsc can also have capability to transpile your js code as well as long as you set allowJs: true as you already did. So I think your problem would be fixed as you refine your pattern to to transform above including jsx file:
{
transform: {
"^.+\\.(t|j)sx?$": "ts-jest",
}
} | unknown | |
d4579 | train | Solution
I changed the height of Gridview from wrap_content and set it about 200dp - the height of elements to be inflated multiplied by total no of rows. (you could set it dynamically or in the xml as per your requirements ). I hope this helps others as well | unknown | |
d4580 | train | SomeProp is instance property so you cannot use x:Static to access that. You can bind to it using combination of static Source and Path
<TextBox ...
Text="{Binding
Source={x:Static local:MainWindow.Boundie},
Path=SomeProp}"/>
A: <object property="{x:Static prefix:typeName.staticMemberName}" .../>
http://msdn.microsoft.com/en-us/library/ms742135.aspx | unknown | |
d4581 | train | I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "@Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}
A: @Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "@Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
}); | unknown | |
d4582 | train | You have a number of options here. The most straight forward is as Amit suggested in the comment, just return the total from each of the methods. This may or may not work depending on how you plan on using these methods. Something like the following should work for your purposes.
function ToyBox() {
this.total = 0;
}
ToyBox.prototype.addToy1 = function() {
var i = document.getElementById("qty_toy1");
var qtytoy1 = i.options[i.selectedIndex].text;
var qtytoy1tot = qtytoy1 * 26.99;
this.total += qtytoy1tot;
var generateTableToy1="<table width=\"210px\" border=\"0\">"
+" <tr>"
+" <td width=\"140\">Optimus Prime</td>"
+" <td width=\"25\">x " + qtytoy1 + "</td>"
+" <td width=\"45\">£" + qtytoy1tot + "</td>"
+" </tr>"
+"</table>";
document.getElementById("toy1_add").innerHTML=generateTableToy1;
};
ToyBox.prototype.addToy2 = function() {
var i = document.getElementById("qty_toy2");
var qtytoy2 = i.options[i.selectedIndex].text;
var qtytoy2tot = qtytoy2 * 14.39;
this.total += qtytoy2tot;
var generateTableToy2="<table width=\"210px\" border=\"0\">"
+" <tr>"
+" <td width=\"140\">Bumblebee</td>"
+" <td width=\"25\">x " + qtytoy2 + "</td>"
+" <td width=\"45\">£" + qtytoy2tot + "</td>"
+" </tr>"
+"</table>";
document.getElementById("toy2_add").innerHTML=generateTableToy2;
};
var toyBox = new ToyBox();
toyBox.addToy1();
toyBox.addToy2();
console.log(toyBox.total);
Keep in mind, you really just have one function here, and you should pass in the variable parts in as parameters to the function, but I think that may be beyond the scope of this question. | unknown | |
d4583 | train | pearl.229>awk '{a=$1;
b=$4;
c=$5;
d=$6;
e=$7;
f=$8;
getline;
if(a==$1)
print a,$2,$3,b"/"$4,c"/"$5,d"/"$6,e"/"$7,f"/"$8}' file3
1 51 Brahui A/A C/C A/A A/G T/T
3 51 Brahui A/A C/C A/G G/A C/T
5 51 Brahui A/A C/C G/G A/G T/C
7 51 Brahui A/A C/C G/G A/G T/T
9 51 Brahui A/A C/C G/G G/G T/T
pearl.230>
A: I like using fmt. It makes the code prettier.
[ghoti@pc ~]$ cat doit
#!/usr/bin/awk -f
BEGIN {
fmt="%s %s %s %s/%s %s/%s %s/%s %s/%s %s/%s\n";
}
one == $1 {
split(last,a);
printf(fmt, $1,$2,$3, a[4],$4, a[5],$5, a[6],$6, a[7],$7, a[8],$8);
}
{ last = $0; one = $1; }
[ghoti@pc ~]$ ./doit input.txt
1 51 Brahui A/A C/C A/A A/G T/T
3 51 Brahui A/A C/C A/G G/A C/T
5 51 Brahui A/A C/C G/G A/G T/C
7 51 Brahui A/A C/C G/G A/G T/T
9 51 Brahui A/A C/C G/G G/G T/T
[ghoti@pc ~]$ | unknown | |
d4584 | train | Could you explain why you are trying to do with all this javascript ?
Just doing the following is not enough for you ?
- (void) webViewDidFinishLoad:(UIWebView *) sender {
// Disable the defaut actionSheet when doing a long press
[webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}
A: You just need to subclass the UIWebView. In your custom view, just implement the method canPerformAction:withSender like this:
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return NO;
}
then all menu items will disappear. If you just wanna show some of items, you should return YES for the specified item.
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
BOOL ret = NO;
if (action == @selector(copy:)) ret = YES;
return ret;
}
That gives you only "copy" when you long press a word in the view. | unknown | |
d4585 | train | Inkscape works well, it was recommended to me here.
A: Irfanview (http://www.irfanview.com) supports many image formats (including .emf). It's also small, fast, and very full-featured. It is free for non-commercial and educational use. I use it for all my image-conversion needs as it will work on batches of files and can rename them as it saves.
A: Image Magick contains a tool called convert, that will convert from just about anything to EMF files. You can either use this as a separate application, or interface to it using an API that is available in several different languages.
A: XnView (http://www.xnview.com). Very good viewer and converter.
A: Try ImageConverter Plus
A: Try http://autotrace.sourceforge.net/. It is opensource and it has good results. Download from here: http://sourceforge.net/project/showfiles.php?group_id=11789
A: Really funny one Microsoft. Now this might seem outlandish but it works... (I have Visio2007). Just found this out from a colleague
You can drop a JPEG into Microsoft Visio (no less), Do a 'Save As' to .emf and voila! nice quality of a picture too. | unknown | |
d4586 | train | You'd send the data to your server by utalizing jQuery POST like this:
var postData = $("#ContactInfo").serializeArray();
$.post('ajax/test.html', postData, function(returnData) {
console.log(returnData);
}, "json");
From http://api.jquery.com/jQuery.post/
Put the path to your server endpoint, that handles the posted data in replacement of ajax/test.html.
I did assume #ContactInfo is your form element.
I did use $.serializeArray() to create a sendable JSON of your form content, as you can see here http://api.jquery.com/serializeArray/ | unknown | |
d4587 | train | Global scope (i.e. window in this case) already has a property name. You'll need to either create a new scope by wrapping your code with a function. Or use block scoped variable declaration let
console.log(typeof name); // string
var name = {
nameValue: 'John'
};
console.log(name.nameValue); // undefined
var surname = {
surnameValue: 'Doe'
};
Object.assign(name, surname);
console.log(name.surnameValue); // undefined
function run() {
var name = {
nameValue: 'John'
};
console.log(name.nameValue); // John
var surname = {
surnameValue: 'Doe'
};
Object.assign(name, surname);
console.log(name.surnameValue); // Doe
}
run();
A: Because 'name' is existed in window, you can use other name of variable
var name0 = {
nameValue: 'John'
};
console.log(name0.nameValue);
A: (Window.)name is a specific value of the global window object that can be used (but pretty uncommon) for setting forms and hyperlinks targets.
The name property is not read only but is limited to the primitive type string. Therefore, any value that you assign to window.name will turn into a string.
This is essentially why you got undefined when used name.nameValue. name is not an object.
var name = { hello: "world!" };
console.log(name + ' - ' + name.hello); // "[object Object] - undefined"
var name = "Hello World!"
console.log(name); // "Hello World!";
A: You are setting the variable name in the global scope in window object. When you set the value of name in window object, its get method will call the toString method.
As specified in here
var name = {first:"Vignesh"};
console.log(name); //(1)
console.log(name.first); //(2)
(1) will give the value [object Object] as string instead of {first: "Vignesh"}.
(2) depicts that you are accessing an unassigned property of a string. i.e., [object Object].first which becomes undefined.
You have to declare the name object in some other scope like if...else block, function block to achieve what you need. | unknown | |
d4588 | train | I notice nobody has actually answered the original question itself yet, specifically how to ignore errors (all the answers are currently concerned with only calling the command if it won't cause an error).
To actually ignore errors, you can simply do:
mv -f foo.o ../baz 2>/dev/null; true
This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.
A: -test -e "foo.o" || if [ -f foo.o ]; then mv -f foo.o ../baz; fi;
That should work
A: Errors in Recipes (from TFM)
To ignore errors in a recipe line, write a - at the beginning of the
line's text (after the initial tab).
So the target would be something like:
moveit:
-mv foo.o ../baz
A: +@[ -d $(dir $@) ] || mkdir -p $(dir $@)
is what I use to silently create a folder if it does not exist. For your problem something like this should work
-@[ -e "foo.o" ] && mv -f foo.o ../baz
A: Something like
test -e "foo.o" && mv -f foo.o ../baz
should work: the operator should be && instead of ||.
You can experiment with this by trying these commands:
test -e testfile && echo "going to move the file"
test -e testfile || echo "going to move the file"
A: I faced the same problem and as I am generating files, they always have different time. Workaround is set the same time to the files: touch -d '1 June 2018 11:02' file. In that case, gzip generates the same output and same md5sum. In my scenario, I don't need the time for the files. | unknown | |
d4589 | train | You compare pointer and integer, which won't lead you to the result you want.
Example:
NSNumber *boolean1 = [NSNumber numberWithBool:YES];
if (boolean1) {
// true
}
NSNumber *boolean2 = [NSNumber numberWithBool:NO];
if (boolean2) {
// this is also true
}
if ([boolean1 boolValue] && ![boolean2 boolValue]) {
// true
}
A: No, it isn't correct and it isn't going to generate the output you think it is. NSNumber * boolean is a pointer to an object in memory while YES is a scalar value; they should not be compared with ==.
If you type this code you'll also get the following warning:
The correct way to do it would be:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if ( [boolean boolValue] ) {
// do something
}
But this statement itself does not make much sense, since you should be comparing the BOOLs and not NSNumber -- there is no need to use the NSNumber in there.
A: This won't work. An instance of NSBoolean is an object, and will be non-NULL whether YES or NO.
There's two good ways to check the value of a NSBoolean.
The first is to use boolValue:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if ([boolean boolValue] == YES) ...
if ([boolean boolValue]) ... // simpler
The second is to use the identity of the object returned:
NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == (id)kCFBooleanTrue) ...
The latter is faster; it relies on there being only one each of NSBoolean YES and NSBoolean NO on the system. These have the same values as kCFBooleanTrue and kCFBooleanFalse. I've read this is safe forever, but I'm not sure it's part of Apple's published documentation. | unknown | |
d4590 | train | Well, first you should note what you are using is a really old AzureRm module command, it was deprecated and will not be updated. So I recommend you to use the new Az module, you could refer to the doc to migrate Azure PowerShell from AzureRM to Az.
Then use the script below, it will get all the resources from all the subscriptions your logged user account/service principals can access.
$subs= Get-AzSubscription
foreach($sub in $subs){
Set-AzContext -Subscription $sub.Id -Tenant $sub.TenantId
Write-Host "login to subscription - "$sub.Name
$groups = (Get-AzResourceGroup).ResourceGroupName
foreach($group in $groups){
Get-AzResourceGroupDeployment -ResourceGroupName $group | Where-Object {$_.Timestamp -gt '12/15/2020'}
}
}
If you still want to use the old AzureRm module, then the script should be:
$subs= Get-AzureRmSubscription
foreach($sub in $subs){
Set-AzureRmContext -Subscription $sub.Id -Tenant $sub.TenantId
Write-Host "login to subscription - "$sub.Name
$groups = (Get-AzureRmResourceGroup).ResourceGroupName
foreach($group in $groups){
Get-AzureRmResourceGroupDeployment -ResourceGroupName $group | Where-Object {$_.Timestamp -gt '12/15/2020'}
}
} | unknown | |
d4591 | train | Basically what you would use without your given annotation example is
public class Foo {
String foo;
Bar bar;
}
public class Bar{
String bar;
}
There is an open suggestion for it tho. | unknown | |
d4592 | train | If I am not mistaken, you must change the user in the database, odoo doesn't allow "postgres" as the user, you must create an "odoo user" to connect the application to the database like this:
db_user: odoo
db_password: yourpassword
Then in the postgres.conf file you must change this line:
listen_adresses = 'localhost'
I can't remember if something must be changed in the .hba
A: You need to change in pg_hba.conf file
In IPV4 section , you need to replace 1 line with below change.
host all all 0.0.0.0/0 trust
This is for first line in IPV4 section.
After Restart PostgreSQL , you can connect. | unknown | |
d4593 | train | Close all open projects so you get the opening screen.
Choose Configure -> Project-Default -> Project Structure
Then set the path to your SDK and JDK, respectively.
Mine are:
SDK: /Users//Development/android-sdk
JDK: /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
If you are on OSX, your JDK might be similar, your SDK will be wherever you put it.
A: Since the SDK doesn't come with Android Studio, you have to install it manually.
You can use brew with brew install android-sdk and then you can open it via android (All done in the terminal)
A: For me, I found that the android binary was missing from the Studio.
So I downloaded the SDK, and moved it in.
Path is as given by @Cory, /Users/<user>/Library/Android/sdk | unknown | |
d4594 | train | It's all about the data. If you have data which makes most sense relationally, a document store may not be useful. A typical document based system is a search server, you have a huge data set and want to find a specific item/document, the document is static, or versioned.
In an archive type situation, the documents might literally be documents, that don't change and have very flexible structures. It doesn't make sense to store their meta data in a relational databases, since they are all very different so very few documents may share those tags. Document based systems don't store null values.
Non-relational/document-like data makes sense when denormalized. It doesn't change much or you don't care as much about consistency.
If your use case fits a relational model well then it's probably not worth squeezing it into a document model.
Here's a good article about non relational databases.
Another way of thinking about it is, a document is a row. Everything about a document is in that row and it is specific to that document. Rows are easy to split on, so scaling is easier.
A: In CouchDB, like Lotus Notes, you really shouldn't think about a Document as being analogous to a row.
Instead, a Document is a relation (table).
Each document has a number of rows--the field values:
ValueID(PK) Document ID(FK) Field Name Field Value
========================================================
92834756293 MyDocument First Name Richard
92834756294 MyDocument States Lived In TX
92834756295 MyDocument States Lived In KY
Each View is a cross-tab query that selects across a massive UNION ALL's of every Document.
So, it's still relational, but not in the most intuitive sense, and not in the sense that matters most: good data management practices.
A: Document-oriented databases do not reject the concept of relations, they just sometimes let applications dereference the links (CouchDB) or even have direct support for relations between documents (MongoDB). What's more important is that DODBs are schema-less. In table-based storages this property can be achieved with significant overhead (see answer by richardtallent), but here it's done more efficiently. What we really should learn when switching from a RDBMS to a DODB is to forget about tables and to start thinking about data. That's what sheepsimulator calls the "bottom-up" approach. It's an ever-evolving schema, not a predefined Procrustean bed. Of course this does not mean that schemata should be completely abandoned in any form. Your application must interpret the data, somehow constrain its form -- this can be done by organizing documents into collections, by making models with validation methods -- but this is now the application's job.
A: may be you should read this
http://books.couchdb.org/relax/getting-started
i myself just heard it and it is interesting but have no idea how to implemented that in the real world application ;)
A: I think, after perusing about on a couple of pages on this subject, it all depends upon the types of data you are dealing with.
RDBMSes represent a top-down approach, where you, the database designer, assert the structure of all data that will exist in the database. You define that a Person has a First,Last,Middle Name and a Home Address, etc. You can enforce this using a RDBMS. If you don't have a column for a Person's HomePlanet, tough luck wanna-be-Person that has a different HomePlanet than Earth; you'll have to add a column in at a later date or the data can't be stored in the RDBMS. Most programmers make assumptions like this in their apps anyway, so this isn't a dumb thing to assume and enforce. Defining things can be good. But if you need to log additional attributes in the future, you'll have to add them in. The relation model assumes that your data attributes won't change much.
"Cloud" type databases using something like MapReduce, in your case CouchDB, do not make the above assumption, and instead look at data from the bottom-up. Data is input in documents, which could have any number of varying attributes. It assumes that your data, by its very definition, is diverse in the types of attributes it could have. It says, "I just know that I have this document in database Person that has a HomePlanet attribute of "Eternium" and a FirstName of "Lord Nibbler" but no LastName." This model fits webpages: all webpages are a document, but the actual contents/tags/keys of the document vary soo widely that you can't fit them into the rigid structure that the DBMS pontificates from upon high. This is why Google thinks the MapReduce model roxors soxors, because Google's data set is so diverse it needs to build in for ambiguity from the get-go, and due to the massive data sets be able to utilize parallel processing (which MapReduce makes trivial). The document-database model assumes that your data's attributes may/will change a lot or be very diverse with "gaps" and lots of sparsely populated columns that one might find if the data was stored in a relational database. While you could use an RDBMS to store data like this, it would get ugly really fast.
To answer your question then: you can't think "relationally" at all when looking at a database that uses the MapReduce paradigm. Because, it doesn't actually have an enforced relation. It's a conceptual hump you'll just have to get over.
A good article I ran into that compares and contrasts the two databases pretty well is MapReduce: A Major Step Back, which argues that MapReduce paradigm databases are a technological step backwards, and are inferior to RDBMSes. I have to disagree with the thesis of the author and would submit that the database designer would simply have to select the right one for his/her situation.
A: One thing you can try is getting a copy of firefox and firebug, and playing with the map and reduce functions in javascript. they're actually quite cool and fun, and appear to be the basis of how to get things done in CouchDB
here's Joel's little article on the subject : http://www.joelonsoftware.com/items/2006/08/01.html | unknown | |
d4595 | train | I don't think it's possible using CSV Data Set Config, it reads next line on each iteration of each virtual user (or according to Sharing Mode setting), but none of the Sharing Modes allows reading multiple lines in a single shot, moreover you need to pass them into single request somehow.
If you need to create one section like this:
{
"filePath": "filename from CSV here",
"orgId": "org123",
"Domain": "abcd.com",
}
per line in the CSV file you could do this using JSR223 PreProcessor and the following Groovy code:
def payload = []
new File('test.csv').readLines().each { line ->
payload.add([filePath: line, orgId: 'org123', Domain: 'abcd.com'])
}
vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString())
generated JSON could be accessed as ${payload} where required
A: You can create multiple variable names under CSV Data Set Config element(for FileName1,FileName2..etc)and use them. | unknown | |
d4596 | train | You could do something like this:
DataFrame Approach
grades = spark.read.option('header', 'true').csv('file.txt')
print(grades.collect())
grades_incr = grades.select(grades['student'], grades['grade'] + 2)
print(grades_incr.take(2))
RDD Approach
grades_report = sc.textFile('file.txt')
grades = grades_report.map(lambda x: x.split(','))
header = grades.first()
grades_incr = grades.filter(lambda x: x != header).map(lambda (_, grade): float(grade) + 2)
A: The problem is that you extract the header before you split on ,. You could change it to:
grades = grades_report.map(lambda x: x.split(','))
header = grades .first()
grades_incr = grades.filter(lambda x: x != header).map(lambda x : float(x[1]) + 2)
And I belive the int cast should be a float since you have doubles. | unknown | |
d4597 | train | Well today it worked! I have no idea what was happening maybe the page had a bug?
this piece of code did it which I tried yesterday!
await page.click('#react-select-7-input');
await delay(wait_time);
await page.click('#react-select-7-option-2');
await delay(wait_time); | unknown | |
d4598 | train | My proposition is following:
I would not mix validation of domain object with the object itself.
It would be a lot more cleaner if domain object would assume that the data passed to it are valid, and validation should be performed somewhere else (e.g. in a factory, but not necessary).
In that "factory" you would perform data preparation state (validation, vulnerability removal etc.) and then you would create a new object.
You will be able to test the factory (if it is validating properly) and not the domain object itself. | unknown | |
d4599 | train | Use requests.Response.json and you will get the chinese caracters.
import requests
import json
url = "http://www.biyou888.com/api/getdataapi.phpac=3005&sess_token=&urlid=-1"
res = requests.get(url)
if res.status_code == 200:
res_payload_dict = res.json()
print(res_payload_dict)
A: How to use response.encoding using Python requests?
For illustrate, let’s ping API of Github.
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com')
# print response
print(response)
# print encoding of response
print(response.encoding)
output:
<Response [200]>
utf-8
So, in your example, try res.json() instead of res.text?
As in:
# encoding of your response
print(res.encoding)
res.encoding='utf-8-sig'
print(res.json())
sig in utf-8-sig is the abbreviation of signature (i.e. signature utf-8 file).
Using utf-8-sig to read a file will treat BOM as file info instead of a string.
A: import requests
import json
url = "http://www.biyou888.com/api/getdataapi.php?ac=3005&sess_token=&urlid=-1"
res = requests.get(url)
res_dict = {}
if res.status_code == 200:
print type(res.text)
print res.text
res_dict = json.loads(res.text) # get a dict from parameter string
print "Dict:"
print type(res_dict)
print res_dict
print res_dict['info']
Use json module to parse that input. And the prefix u just means it is a unicode string. When you use them, the u prefix won't affect, just like what I show at the last several lines. | unknown | |
d4600 | train | It worked now.
the server which I created from snapshot I should not create the file system. I have to remove this command
sudo mkfs.ext4 /dev/xvdb
from the user data. just create the folder and mount it. then it worked. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.