id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_4400
|
Here is a link to a jsfiddle that recreates the problem
On Chrome it renders properly
On Firefox only part of the star renders
The other strange thing is that if I duplicate the path within the clipPath of the image seems to work in Firefox (jsfiddle example here) - which makes no sense to me.
<clipPath clipPathUnits="objectBoundingBox" id="clipPathMask-0f05a0aa-4fb7-420f-aea5-ad7fc9c9a127" transform="scale(0.005784982935153583 0.0038563296140941045)">
<path d="M20.9,95.6l5.6-32.8L2.7,39.6l32.9-4.8L50.3,5L65,34.8l32.9,4.8L74.1,62.8l5.6,32.8L50.3,80.1L20.9,95.6z"></path>
<path d="M20.9,95.6l5.6-32.8L2.7,39.6l32.9-4.8L50.3,5L65,34.8l32.9,4.8L74.1,62.8l5.6,32.8L50.3,80.1L20.9,95.6z"></path>
</clipPath>
Has anyone come across this before and knows whats happening here?
| |
doc_4401
|
I've 4 distinct Result category: Normal, Mild, Moderate and Severe
I want to get count of patients for each categories and
in case of severe category, I want to further divide it into more categories based on its corresponding Result value (e.g., Severe_500_to_599, Severe_600_to_699, Severe_700_to_799 and severe_>800) and then get the count of these sub categories.
So my Results should look like this,
Currently I'm taking individual count by putting the specific condition,
select count(distinct SOURCE_PATIENT_ID)
from Table1
where RESULT_CATEGORY = 'SEVERE' and RESULT_VALUE_STANDARDIZED between '1100' and '1199' and RESULT_UNIT <> 'MG/DL';
Is there any way to get all the results in one single query?
Thanks!
A: Window function with QUALIFY clause can be used here to divide data sets into individual buckets and then get single value out of those bucket.
Following query -
with data (patient_id, result_category, result_value) as (
select * from values
(110,'Normal',35),
(123,'Normal',135),
(111,'Mild',151),
(191,'Mild',199),
(112,'Moderate',211),
(113,'Severe',501),
(115,'Severe',500),
(144,'Severe',723),
(146,'Severe',801)
)
select
case
when result_category = 'Severe'
AND result_value between 500 and 599
then
'Severe Bucket (500-599)'
when result_category = 'Severe'
AND result_value between 700 and 799
then
'Severe Bucket (700-799)'
when result_category = 'Severe'
AND result_value between 800 and 899
then
'Severe Bucket (800-899)'
else
result_category
end new_result_category,
sum(result_value) over (partition by new_result_category) patient_count
from data
qualify row_number() over (partition by new_result_category
order by patient_id desc) = 1;
Will give result as below -
NEW_RESULT_CATEGORY
PATIENT_COUNT
Mild
350
Moderate
211
Severe Bucket (700-799)
723
Severe Bucket (500-599)
1001
Normal
170
Severe Bucket (800-899)
801
A: May I suggest the underrated grouping sets?
with cte as
(select *, case when result_value between 500 and 599 then 'Severe Bucket (500-599)'
when result_value between 700 and 799 then 'Severe Bucket (700-799)'
when result_value between 800 and 899 then 'Severe Bucket (800-899)'
end as breakdown
from data)
select coalesce(result_category,breakdown) as category,
count(distinct patient_id) as patient_count
from cte
group by grouping sets (result_category,breakdown)
having coalesce(result_category,breakdown) is not null
A: you can use Union all to combine your query´s
select 'SEVERE-599' as ResultCategory,
count(distinct SOURCE_PATIENT_ID)
from Table1
where RESULT_CATEGORY = 'SEVERE' and RESULT_VALUE_STANDARDIZED between '500' and '599' and RESULT_UNIT <> 'MG/DL'
Union ALL
select 'SEVERE-699' as ResultCategory,
count(distinct SOURCE_PATIENT_ID)
from Table1
where RESULT_CATEGORY = 'SEVERE' and RESULT_VALUE_STANDARDIZED between '600' and '699' and RESULT_UNIT <> 'MG/DL'
| |
doc_4402
|
I have an array dogArray which takes ( name, secondname, dogname )
I want to be able to change the dogname:
here's my attempt :
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
String namgeChange = rp.next(); {
for (int i = 0; i < dogArray.length; i++){
for (int j = 0; j < dogArray[i].length; j++){
if (dogArray[i][j] == name){
dogArray[i][j] = nameChange;
}
}
}
}
For a start it doesn't like the fact I've used ' name ' although it is defined in the dogArray. I was hoping this would read input so that users are able to change 'name' to whatever they input. This will change the value of name in the array.
Do you guys think I'm getting anywhere with my method or is it a pretty stupid way of doing it?
A: Only one loop is necessary, also move your call to next.
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
for (int i = 0; i < dogArray.length; i++){
String nameChange = rp.next(); {
if(!dogArray[i].name.equals(nameChange)){
dogArray[i].name = nameChange;
}
}
}
You might want to make this function static as well and use accessors and mutators to change and get the name. Might want to tell the user what you want them to type as well. Also there is no point in testing if the name changed, if it changed then set it, if it didnt change then set it (it doesnt hurt). Just get rid of if and keep the code inside.
| |
doc_4403
|
id_x
type
timestamp1
timestamp2
1
A
08.01.2022
1
B
31.02.2021
01.01.2022
2
B
28.01.2017
25.07.2021
2
A
25.07.2021
I am looking for a query that can return all id_x where there exists multiple entries for id_x where one is of type A and one is of type B AND timestamp1 of the row of type A is not the same as timestamp2 of the row with type B.
So in the example above it should return only id_x=1 but not id_x=2, because the timestamp1 in the id_x=2 row with type A is the same as the timestamp2 of the row of id_x=2 with type B.
A: SELECT id_x
FROM test
GROUP BY id_x
-- where one is of type A and one is of type B
HAVING GROUP_CONCAT(type ORDER BY type) = 'A,B'
-- timestamp1 of the row of type A is not the same as timestamp2 of the row with type B
AND NOT MAX(CASE WHEN type='A' THEN timestamp1 END) <=> MAX(CASE WHEN type='B' THEN timestamp2 END)
If timestamp1 is defined as NOT NULL then
AND MAX(CASE WHEN type='A' THEN timestamp1 END) <> MAX(CASE WHEN type='B' THEN timestamp2 END)
| |
doc_4404
|
<ion-list>
<ion-item *ngFor="let item of editLists,index as i">
<ion-input [(ngModel)]="editLists[i]"></ion-input>
</ion-item>
</ion-list>
<ion-input [(ngModel)]="foo"></ion-input>
it'ok type words when ion-input outside ngFor;
but when inside it will lose focus when i type one word
how?
many thanks
A: Use trackBy along with ngFor to avoid re rendering input whenever input changes.
component.html
<ion-list>
<ion-item *ngFor="let item of editLists,index as i;trackBy:trackEditList">
<ion-input [(ngModel)]="editLists[i]"></ion-input>
</ion-item>
</ion-list>
</ion-content>
component.ts
trackEditList(index,item){
return index;
}
Working Example
| |
doc_4405
|
Class object
import java.util.*;
public class LetterInventory{
private ArrayList<Integer> array;
private int size;
public LetterInventory(String input){
size = input.length();
array = new ArrayList<Integer>();
for(int i = 0;i<input.length();i++){
array.add(i,(int)input.charAt(i));
}
}
public LetterInventory(){
size = 0;
array = new ArrayList<Integer>();
}
public int size(){
return size;
}
public LetterInventory add(LetterInventory other){
LetterInventory temp = new LetterInventory();
temp.array.addAll(array);
return temp;
}
public String toString(){
String result = "[";
for(int i = 0;i<=size-1;i++){
int temp = array.get(i);
result += (char)temp;
}
return result += "]";
}
}
and my Client code
import java.util.*;
public class Practice {
public static void main (String[] args){
LetterInventory l1 = new LetterInventory("aaa");
LetterInventory l2 = new LetterInventory("bbb");
System.out.println(l1);
System.out.println(l2);
LetterInventory sum = l1.add(l2);
System.out.println(sum);
}
}
And the output is always [ ] no matter what i do. I despretly need help on this. As i've spent the vast majority of this day trying to fix this issue.
A: You are tracking size separately from the actual size of the list. This is OK in your constructor, but your add method copies the list, but doesn't set size. Try not using a size variable and use array.size() which will always be correct.
ps. there is another bug in your add method as noted by Kylar above
A: Your toString() method's for loop have the issue. You haven't set the value to size variable other than 0 in no argument Constructor, so it won't execute the for loop
public String toString(){
String result = "[";
for(int i = 0;i<=size-1;i++){
int temp = array.get(i);
result += (char)temp;
}
return result += "]";
}
Change the add() method like below
public LetterInventory add(LetterInventory other){
LetterInventory temp = new LetterInventory();
temp.array.addAll(array);
temp.size = temp.array.size();
return temp;
}
A: You toString() method uses the member size to iterate over array elements. But when you add you are not updating the size.
My suggestion would be to remove the size member variable and use array.size() instead
A: public LetterInventory add(LetterInventory other){
LetterInventory temp = new LetterInventory();
temp.array.addAll(this.array);
temp.array.addAll(other.array);
temp.size = this.size + other.size;
return temp;
}
this is the answer
| |
doc_4406
|
Anyway. I keep getting this error notice "Undefined index: type in c:\x\calculator.php on line 33", but it still echoes "You forgot to pick mathtype!" and the calculator works fine. This error notice occurs only when I don't select any radio box for math type (+-/*).
//Part of the form
<form action="calculator.php" method="post">
<input type="text" name="1stnumber">
<input type="text" name="2ndnumber">
<input type="radio" name="type" value="addition">
<input type="radio" name="type" value="subtraction">
<input type="submit" name="send">
<?php
//My variables
$number = $_POST['1stnumber']
$numbero = $_POST['2ndnumber']
$mathtype = $_POST['type'] /* **<-line 33** */
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if(is_null($mathtype)){
echo "You forgot to pick mathtype!"
}
?>
Tried with elseif as well.. I don't see what's wrong between line 33 and the if(is_null()) line!
Sorry if it looks poor, messy, or if something doesn't make sense. Might be a few typos as well. Any help is appreciated.
A: Simply check if type is posted before you pick it up
if(isset($_POST['type']))
{
$mathtype = $_POST['type'];
}
else
{
echo "Type was not selected";
}
A: Set a default selected option, using the checked attribute.
<label><input type="radio" name="type" value="addition" checked="checked"> +</label>
<label><input type="radio" name="type" value="subtraction"> -</label>
Don't forget inputs needs labels in html if left out you can use a placeholder attribute, but that's clearly not possible with type="radio"; therefore wrap the input in a label with the text description next to it eg + or -
Also, is this a copy and paste error, bc all php statements must be terminated with a semicolon ;
$number = $_POST['1stnumber']; // <- terminate
$numbero = $_POST['2ndnumber']; // <- terminate
$mathtype = $_POST['type']; // <- terminate
echo "You forgot to pick mathtype!"; // <- terminate
A: Check if the form is posted:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//My variables
$number = $_POST['1stnumber']
$numbero = $_POST['2ndnumber']
$mathtype = $_POST['type'] /* **<-line 33** */
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if(is_null($mathtype)){
echo "You forgot to pick mathtype!"
}
}
?>
Else the is_null check will also be executed on the first load (before the form has been posted).
A: It's always good practice to check if the variable you're trying to retrieve from $_POST has actually been set, try this:
<?php
//My variables
if (isset($_POST['1stnumber'])) {
$number = $_POST['1stnumber'];
}
if (isset($_POST['2ndnumber'])) {
$numbero = $_POST['2ndnumber'];
}
if (isset($_POST['type'])) {
$mathtype = $_POST['type']; /* **<-line 33** */
}
//The calculation part of the form here, which is working
//Tell the user if he didn't pick a math type (+-)
if (is_null($mathtype)) {
echo "You forgot to pick mathtype!";
}
?>
| |
doc_4407
|
{
public HMACAuthenticationAttribute(IUser user)
{
.....
}
}
The above is my class attribute. I want to call this in below controller.Is there any way to call the above class.
[HMACAuthentication()]
public class WeatherForecastController : ControllerBase
{
}
| |
doc_4408
|
A: What value are you setting in ActionType? If you set PAY_PRIMARY then payment will reach primary only
A: Ensure that these 2 Fiedls are set as suggested
In PayRequest -> actionType = PAY_PRIMARY and also ensure that feesPayer is not set as "SENDER" as this is not a valid value for chained payment.
If this doesn't work paste the request here for us to look and suggest.
| |
doc_4409
|
My schema is:
const particularUser = new GraphQLObjectType({
name: "particularUser",
description: "particular user field for person",
fields: () => ({
"id": {type: GraphQLInt},
"first_name": {type: GraphQLString},
"last_name": {type: GraphQLString},
"avatar": {type: GraphQLString}
})
});
My main query schema is this:
specificUser:{
type:particularUser,
description:"fetching particular user for specific id",
args:{
id:{
type:new GraphQLNonNull(GraphQLString)
}
},
resolve:(_,{id}) => {
console.log({id})
const url = `https://reqres.in/api/users/${id}`;
console.log(url)
return axios.get(url).then((response) => {
console.log(response.data)
return response.data;
})
.catch((error) => {
return error;
})
}
}
when i run on graphql server it returns null values where am i doing wrong??
A: You have to return response.data.data !
const specificUser = {
type: ParticularUser,
args: { id: { type: new GraphQLNonNull(GraphQLString) } },
description: 'fetching particular user for specific id',
resolve: (_, { id }) =>
axios
.get(`https://reqres.in/api/users/${id}`)
.then(response => response.data.data)
.catch(error => error),
};
| |
doc_4410
|
Do you have some idea of how can I proceed ?
A: var x = 0;
$(".yourclass").click(function(event) {x++;
if(x==1){
X1 = event.clientX;
Y1 = event.clientY;
}
else{
X2 = event.clientX;
Y2 = event.clientY;
}
});
in this way you can get the x,y axis of both points.
Make a div and make its background image this with background positions as these values.. Hope that would help.
| |
doc_4411
|
It appears we can create a property on a Django model, and add an annotation with the exact same name to querysets for that model.
For example, our FooBarModel has foo = property(...), and on top of that we can do FooBarModel.objects.annotate(foo=...).
Note that the names are the same: If foo were a normal attribute, instead of a property, annotate(foo=...) would raise a ValueError. In this case, no such error.
Initial tests suggest this approach works, allowing us to create e.g. a quasi filterable-property.
What I would like to know: Is this a good approach, or could it lead to conflicts or unexpected surprises of some sort?
Background
We have an existing database with a FooBarModel with field bar, which is used in many places in our project code, mostly to filter FooBarModel querysets.
Now, for some reason, we need to add a new field, foo to our model, which should be used instead of the bar field. The bar field still serves a purpose, so we need to keep that as well. If foo has not been set (e.g. for existing database entries), we fall back to bar.
This has to work both on new (unsaved) model instances and on querysets.
Note: Although a simple data migration would be an alternative solution for the specific example provided below (fallback), there are more complicated scenarios in which data migration is not an option.
Implementation
Now, to make this work, we implement the model with a foo property, a _foo model field, a set_foo method and a get_foo method that provides the fallback logic (returns bar if _foo has not been set).
However, as far as I know, a property cannot be used in a queryset filter, because foo is not an actual database field (_foo is, but that does not have the fallback logic). The following SO questions seem to support this: Filter by property, Django empty field fallback, Do properties work on django model fields, Django models and python properties, Cannot resolve keyword
Thus, we add a customized manager which annotates the initial queryset using the Coalesce class. This duplicates the fallback logic from get_foo (except for empty strings) on the database level and can be used for filtering.
The final result is presented below (tested in Python 2.7/3.6 and Django 1.9/2.0):
from django.db import models
from django.db.models.functions import Coalesce
class FooManager(models.Manager):
def get_queryset(self):
# add a `foo` annotation (with fallback) to the initial queryset
return super(FooManager,self).get_queryset().annotate(foo=Coalesce('_foo', 'bar'))
class FooBarModel(models.Model):
objects = FooManager() # use the extended manager with 'foo' annotation
_foo = models.CharField(max_length=30, null=True, blank=True) # null=True for Coalesce
bar = models.CharField(max_length=30, default='something', blank=True)
def get_foo(self):
# fallback logic
if self._foo:
return self._foo
else:
return self.bar
def set_foo(self, value):
self._foo = value
foo = property(fget=get_foo, fset=set_foo, doc='foo with fallback to bar')
Now we can use the foo property on new (unsaved) FooBarModel instances, e.g. FooBarModel(bar='some old value').foo, and we can filter FooBarModel querysets using foo as well, e.g. FooBarModel.objects.filter(foo='what I'm looking for').
Note: Unfortunately the latter does not appear to work when filtering on related objects, e.g. SomeRelatedModel.objects.filter(foobar__foo='what I'm looking for'), because the manager is not used in that case.
A drawback of this approach is that the "fallback" logic from get_foo needs to be duplicated in the custom manager (in the form of Coalesce).
I suppose it would also be possible to apply this "property+annotation" pattern to more complicated property logic, using Django's conditional expressions in the annotation part.
The Question
The approach above emulates a filterable model property. However, the annotation named foo shadows the property named foo, and I am not sure if this will lead to conflicts or other surprises at some point. Does anyone know?
If we add a "normal" annotation to a queryset, i.e. one that does not match a property name, such as z, that z shows up as an attribute (when I call vars() on an instance from that queryset). However, if we use vars() on an instance from our FooBarModel.objects, it shows no attribute named foo. Does this mean that the get_foo method overrides the annotation?
| |
doc_4412
|
Running transformation: System.ArgumentException: URI formats are not
supported.
at System.IO.Path.NormalizePath(String path, Boolean
fullCheck, Int32 maxPathLength) at
System.IO.Path.GetFullPathInternal(String path) at
System.IO.FileInfo.Init(String fileName, Boolean checkHost) at
System.IO.FileInfo..ctor(String fileName) at
Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation.GetProjectPath()
at
Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation.GetConfigPath()
at
Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation.GetConnectionString(String&
connectionStringName, String& providerName) at
Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation.InitConnectionString()
at
Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation.LoadTables()
at
Microsoft.VisualStudio.TextTemplating.GeneratedTextTransformation.TransformText()
in Database.tt
I'm not sure what I'm doing wrong here.. the connection string is specified and has been set correctly in Database.tt. Are there some other requirements for using this T4 template other than a correct connection string?
My Database.tt settings look like this:
// Settings
ConnectionStringName = "ConnectionString";
Namespace = "TVPPData";
RepoName = "MyContext";
GenerateOperations = true;
GeneratePocos = true;
GenerateCommon = true;
ClassPrefix = "";
ClassSuffix = "";
TrackModifiedColumns = true;
Thanks!
A: I've figured it out myself:
It turns out the Petapoco T4 template doesn't work with website projects which have been added to the solution using their URL or IIS entry. I've now re-added the project as a filesystem project and now it works fine.
| |
doc_4413
|
Struct vs. Class
*
*Struct is by default preferred in swift.
*Struct is value type. Class is reference type
pic from : https://cocoacasts.com/value-types-and-reference-types-in-swift
Okay. That's all fine and dandy. Now What's the difference between static func and func within a class?
static just means that -> Static, but when it's within a class and used to declare a func? What does it mean?
static keyword is same like final class. final keyword makes the
variable or function final i.e. they can not be overridden by any
inheriting class. (link)
class TestStruct {
var count = Int()
func popeye(name: String) -> String {
count = count + 1
return "TestStruct - func popeye - name:\(name) Count:\(count)"
}
static func brutus(name: String) -> String {
var count = Int() // when declared within the static func
count = count + 1 // this never gets incremented
return "TestStruct - static func brutus - name:\(name) count:\(count)"
}
}
I tried this and found out that I can't do foo1.brutus as I can do foo1.popeye when it's assigned with a static func keyword.
But as just a func, I can have 2 variables referencing the same func and both will have it's own value (example below,count output is different). What's the benefit of using static then? When do I use static func
let foo1 = TestStruct()
let foo2 = TestStruct()
var bar1 = foo1.popeye(name: "popeye sailorman")
var bar2 = foo2.popeye(name: "popeye spinach ")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
bar1 = foo1.popeye(name: "popeye sailorman")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
bar1 = foo1.popeye(name: "popeye sailorman")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
bar1 = foo1.popeye(name: "popeye sailorman")
bar2 = foo2.popeye(name: "popeye spinach ")
print("foo1:\(bar1)")
print("foo2:\(bar2)")
var oliveOil1 = TestStruct.brutus(name: "Brutus Big ")
var oliveOil2 = TestStruct.brutus(name: "Brutus Mean")
print("oliveOil1:\(oliveOil1)")
print("oliveOil2:\(oliveOil2)")
oliveOil1 = TestStruct.brutus(name: "Brutus Big ")
oliveOil2 = TestStruct.brutus(name: "Brutus Mean")
print("oliveOil1:\(oliveOil1)")
print("oliveOil2:\(oliveOil2)")
which results in these printouts:
foo1:TestStruct - func popeye - name:popeye sailorman Count:1
foo2:TestStruct - func popeye - name:popeye spinach Count:1
foo1:TestStruct - func popeye - name:popeye sailorman Count:2
foo2:TestStruct - func popeye - name:popeye spinach Count:1
foo1:TestStruct - func popeye - name:popeye sailorman Count:3
foo2:TestStruct - func popeye - name:popeye spinach Count:1
foo1:TestStruct - func popeye - name:popeye sailorman Count:4
foo2:TestStruct - func popeye - name:popeye spinach Count:2
oliveOil1:TestStruct - static func brutus - name:Brutus Big count:1
oliveOil2:TestStruct - static func brutus - name:Brutus Mean count:1
oliveOil1:TestStruct - static func brutus - name:Brutus Big count:1
oliveOil2:TestStruct - static func brutus - name:Brutus Mean count:1
A:
var count = Int() // when declared within the static func
count = count + 1 // this never gets incremented
The above code you have declared inside the brutus(name function which is local var and has the same name with the class var. so the scope of the var is within the function. when the function end, count var inside the function also ends/release.
Each time function calls, you are creating a new count var so it always prints count 1.
You can not access class var inside the static function, because static function required static var too. so it's clear when you print inside the static function, it always used local var instead of class var.
What's the benefit of using static then? When do I use static func
By using static keyword also means, you no need to create an object for accessing var or function.
You can see some inbuilt function with static keyword for when you used.
Example:
Int have one static function
@inlinable public static func random(in range: ClosedRange<Int>) -> Int
this function returns a random int value within the specified range.
so you can use the static function where you no need to create an object and use the direct function.
here is one example of the static function. You can see how I used the static function for showing the alert controllers. You can create your own static function where you don't want to create an object and then use function or var.
| |
doc_4414
|
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
}
}
I am pretty sure that it ends at [2][1] but I am not 100% sure of it
A: Just tried this code:
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
System.out.print(numarray[j][i]+" ");
}
System.out.println("");
}
and got this result:
0 1
2 3
4 5
The 'cnt' is incremented by 1 for each iteration. That's why you have 0,1,2,3,4,5.
Also learn how to use debugger in an IDE, you can then explore the value of i, j, cnt by yourself.
A: why don't you try this?
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
System.out.println(String.format("array[%d[%d]=%d",j,i,numarray[j][i]));
cnt++;
}
}
A: you can iterate the array after code finish
for(int i = 0; i < 2; i++) {
for(int j = 0; j< 3; j++) {
System.out.print(numarray[i][j]+" ");
}
System.out.println();
}
A: summary: cnt is incremented by 1 for each iteration in the inner for loop.
cnt is being incremented by 1 i.e. cnt++ is same as cnt = cnt + 1;
so count values increment from 0 i.e. 0,1,2,3,4,5... Also note, the value of cnt is assigned to the array being created, where you have numarray[j][i] = cnt;
You can simply printout the value using System.out.println(cnt);
| |
doc_4415
|
<div class="media">
<img src="/img/sample.jpg">
<div class="caption">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip.
</div>
</div>
The size of the image will shrink/grow with the size change of the browser. The caption should be positioned over the image and within the boundary of the image. The width of the caption must change when the image size changes.
The image is large enough to hold the text. The image size is not known in advance. The image must retain original width when the browser's viewport width is larger than the image's actual width. I hope the caption is positioned at the bottom of the image.
If there is any css solution, that will be fantastic.
Thanks for any input!
A: Try this it should work perfectly.
http://jsfiddle.net/cornelas/ygL64/
img {
width: 100%;
height: 100%;
background: #ccc;
position: relative;
}
.caption {
position: absolute;
top: 25%;
left: 50%;
width: 200px;
background: rgba(255,255,255,0.2);
}
A: http://jsfiddle.net/P92Fs/7/
.media {
position: relative;
display: inline-block;
}
.media .caption {
position: absolute;
bottom: 0;
text-align: left;
}
img {
width: 100%;
}
| |
doc_4416
|
Here is my code -
import React, { useState } from "react";
import "../css/Destination.css";
function Destination(props) {
const [selectedPlanets, SetselectedPlanets] = useState([
null,
null,
null,
null,
]);
const OnSelectPlanet = async (e, key) => {
const clonedSelectedPlanets = JSON.parse(JSON.stringify(selectedPlanets));
clonedSelectedPlanets[key] = e.target.value;
SetselectedPlanets(clonedSelectedPlanets);
};
const CustomSelectComponents = ({ value, options, OnSelect}) => {
return (
<select value={value} onChange={OnSelect}>
<option> -- Select a Planet -- </option>
{options.map((option) => {
return <option key = {option.name} value={option.name} >{option.name}</option>;
})}
</select>
);
};
const OptionsToRender = (Alloptions, AllselectedOptions, index) => {
console.log(AllselectedOptions);
const optionstoRender =
AllselectedOptions[index] != null
? Alloptions.filter(
(option) =>
!AllselectedOptions.some(
(selectedOption) =>
option && selectedOption && option.name === selectedOption
)
)
: Alloptions;
return optionstoRender;
};
return (
<>
<div className="Parent_Card">
{selectedPlanets.map((planet, index) => {
const options = OptionsToRender(props.planets, selectedPlanets, index);
return (
<>
{console.log(index)}
<CustomSelectComponents
value={
selectedPlanets[index] != null ? selectedPlanets[index] : ""
}
options={options}
OnSelect={(e) => OnSelectPlanet(e, index)}
key={index}
/>
</>
);
})}
</div>
</>
);
}
export default Destination;
I tried debugging it and figured that its maybe because of how and when my component is rendering.But I dont know why and hence not able to find the solution.
My expected result is when I am choosing an option it shows in the input field.
A: Your code could benefit from a few different approaches to building your 4 different select components:
*
*the use of controlled components
(https://reactjs.org/docs/forms.html#controlled-components)
*separating the state for each of the different selects
*refactoring the <CustomSelectComponent /> to be a component that only accepts props
Here is an example of those approaches in practice that might provide some direction on getting these selects operating as expected!
import React, { useState } from 'react';
import '../css/Destination.css';
// custom select component
const CustomSelectComponent = ({ onChange, options, value }) => (
<select onChange={onChange} value={value}>
<option> -- Select a Planet -- </option>
{options.map(option => (
<option key={option.name} value={option.name}>
{option.name}
</option>
))}
</select>
);
const Destination = () => {
// mock props
const props = { planets: [{ name: 'Pluto' }, { name: 'Earth' }] };
// separated state
const [selectOneValue, setSelectOneValue] = useState('');
const [selectTwoValue, setSelectTwoValue] = useState('');
const [selectThreeValue, setSelectThreeValue] = useState('');
const [selectFourValue, setSelectFourValue] = useState('');
return (
<div className="Parent_Card">
{/* each custom select component is now controlled by it's own state */}
<CustomSelectComponent
onChange={e => setSelectOneValue(e.target.value)}
options={props.planets}
value={selectOneValue}
/>
<CustomSelectComponent
onChange={e => setSelectTwoValue(e.target.value)}
options={props.planets}
value={selectTwoValue}
/>
<CustomSelectComponent
onChange={e => setSelectThreeValue(e.target.value)}
options={props.planets}
value={selectThreeValue}
/>
<CustomSelectComponent
onChange={e => setSelectFourValue(e.target.value)}
options={props.planets}
value={selectFourValue}
/>
</div>
);
};
export default Destination;
| |
doc_4417
|
This is the example from:
https://www.typescriptlang.org/docs/handbook/functions.html#overloads
function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
function pickCard(x: any): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
export pickCard; // DOES NOT WORK
I can't use a function expression like: export const pickCard = () => {}; because overloads won't work on function expressions.
QUESTION
How can I do a named export on the pickCard function. Note: the name should be pickCard
A: This worked for me:
export function pickCard(x: { suit: string; card: number }[]): number;
export function pickCard(x: number): { suit: string; card: number };
export function pickCard(x: any): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
Use in other file:
import { pickCard } from ".";
pickCard([{ suit: 'test', card: 10 }]);
pickCard(21);
| |
doc_4418
|
lea rax, [f + rip]
call rax
Cool! That has a lot of potential. But I am getting an error in a test I did:
When I give my compiler this,
(define f (lambda (x) (+ x 1)))
(display_num (f 2))
it yields this.
.global _main
.text
_main:
call _begin_gc
and rsp, -16
jmp after_lambda_1
lambda_1:
push rbp
mov rbp, rsp
push 1 # push argument to +
push [rbp + 16] # push argument to +
call plus
add rsp, 16 # discard 2 local arguments
mov rbp, rsp
pop rbp
ret
after_lambda_1:
lea rax, [lambda_1 + rip]
mov [f + rip], rax
push 2 # push argument to f
call f
add rsp, 8 # discard 1 local argument
push rax # result of f
call display_num
add rsp, 8 # discard 1 local argument
and rsp, -16
call _end_gc
xor rdi, rdi
mov rax, 0x2000001
syscall
.data
f:
.quad 0
That seemed okay at first. I got a bus error when running it though:
$ make run
./out/test
make: *** [run] Bus error: 10
Hm! weird. I ran it through LLDB next:
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x100008050)
* frame #0: 0x0000000100008050 test`f
frame #1: 0x0000000100003d9c test`after_lambda_1 + 21
frame #2: 0x0000000100003d67 test`main + 5
frame #3: 0x00007fff72c13cc9 libdyld.dylib`start + 1
frame #4: 0x00007fff72c13cc9 libdyld.dylib`start + 1
It says that it failed here,
test`f:
-> 0x100008050 <+0>: jo 0x10000808f ; gc + 55
0x100008052 <+2>: add byte ptr [rax], al
0x100008054 <+4>: add dword ptr [rax], eax
0x100008056 <+6>: add byte ptr [rax], al
but I don't see a line that looks like that in my code. I am utterly confused.
Does anyone know what is happening here, why I am getting a bus error, and what I need to tweak to make my code functional?
I am assembling on MacOS with Clang.
| |
doc_4419
|
Some background:
I am using docker swarm stack services. One service (MAPS) creates a simple http server that lists xml files to port 8080 and another service (WAS) uses WebSphere Application Server that has a connector that uses these files, to be more precise it calls upon a file maps.xml that has the urls of the other files as http://localhost:8080/<file-name>.xml.
I know docker allows me to call on the service name and port within the services, thus I can use curl http://MAPS:8080/ from inside my WAS service and it outputs my list of xml files.
However, this will not always be true. The prod team may change the port number they want to publish or they might update the maps.xml file and forget to change localhost:8080 to MAPS:8080.
Is there a way to make it so any call to localhost:8080 gets redirected to another url, preferrably using a configuration file? I also need it to be lightweight since the WAS service is already quite heavy and I can't make it too large to deploy.
Solutions I tried:
*
*iptables: Installed it on the WAS service container but when I tried using it it said my kernel was outdated
*tinyproxy: Tried setting it up as a reverse proxy but I couldn't make it work
*ncat with inetd: Tried to use this solution but it also didn't work
I am NO expert so please excuse any noob mistakes I made. And thanks in advance!
A: It is generally not a good idea to redirect localhost to another location as it might disrupt your local environment in surprising ways. Many packages depend on localhost being localhost :-)
it is possible to add MAPS to your hosts file (/etc/hosts) giving it the address of maps.
| |
doc_4420
|
I would recreating something like that creating a "modal" rectangle that appear when the user taps on a UIButton. When the user taps on this button the app should move an UIView (actually inside an UITableViewCell) and move it within this rectangle, BUT the original UIView should stay in the same place. It needs to duplicate itself, something alike.
I've created a simple image explaining the concept.
How to implement something like this?
A: i might suggest you to create another UIView. Do not add it to the main view yet.
now on the view that you're currently working on,
[UIView transitionWithView: self.view duration: 0.5 options: UIViewAnimationOptionsCurveEaseOut animations:^{
[self.view addSubView:createdView]; } completion:nil];
Hope this works, if you haven't already implemented. I'm a beginner, excuse me if there's any mistake.
A: I assume we're looking for something similar :-)
How to display datepicker like that in iOS 7 calendar UIDatePicker , apologies if its not. @bobnoble has pointed to exact solution. I'm trying to achieve it but I'm new to iOS so bit stuck.
Found another link with sample code :-) iOS 7 - How to display a date picker in place in a table view?
| |
doc_4421
|
The following code is used to create the nodes:
func create_distance_marker():
var static_body = StaticBody2D.new()
static_body.name = "distance_location"
static_body.position = Global.mid_point
add_child(static_body)
var panel_container = PanelContainer.new()
panel_container.name = "panel_container"
static_body.add_child(panel_container)
var distance_label = Label.new()
distance_label.name = "distance_label"
distance_label.text = str(Global.distance)
panel_container.add_child(distance_label)
The following code is used to place the static body and update the label text:
func display_distance_marker():
var static_body = get_node("distance_location")
static_body.position = Global.mid_point
Global.distance = round(point_one.distance_to(point_two) / 35)
var distance_label = get_node("distance_location/panel_container/distance_label")
distance_label.text = str(Global.distance)
I've found similar questions already asked, but the answers were geared towards configuring the nodes via the inspector. I suspect that the align and valign controls to need to be set to 'center', but can't figure out how to do that via script.
A: So, the first step was to simplify things and eliminate the panel container. Then I used conditional logic to center both single-digit and double-digit distances within the distance marker circle.
func display_distance_marker():
var distance_label
var static_body = get_node("distance_location")
if Global.click_and_drag and Global.shift_pressed:
static_body.position = Global.mid_point
static_body.visible = true
Global.distance = round(point_one.distance_to(point_two) / 35)
distance_label = get_node("distance_location/distance_label")
distance_label.text = str(Global.distance)
var label_size = distance_label.size
var label_coord
if Global.distance < 10:
label_coord = Vector2(-.1 * label_size.x, -10)
else:
label_coord = Vector2(-.2 * label_size.x, -10)
distance_label.position = label_coord
else:
static_body.visible = false
| |
doc_4422
|
My question is: Can we add a custom kind: keyword to Spotlight plugins? If yes, will they work in the same manner as the default keywords?
A: It's not entirely clear what you're asking. I think by kind: you're referring to the kMDItemKind metadata attribute.
If so, then yes, you can definitely expose this in your Spotlight importer. You can expose any of the standard metadata keys or define new ones of your own.
| |
doc_4423
|
A: Yes it's possible, only you must ensure to set the credentials of the connection according to the remote machine to access, and then use the StdRegProv wmi class which allow you to access the registry in local and remote machines. A key point is the namespace where the class is located, that depends of the version of windows installed in the remote machine. so for Windows Server 2003, Windows XP, Windows 2000, Windows NT 4.0, and Windows Me/98/95 the StdRegProv class is available in the root\default namespace and for others versions like windows Vista/7 the namespace is root\CIMV2. check the accepted answer in this question to see a sample.
| |
doc_4424
|
$("#idOfUl").on('scroll', function() {
console.log('Event Fired');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="idOfUl">
<ul>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
</ul>
</div>
I am unable to show text in console.log when I scroll the page.
I am unable to show text in console.log when I scroll the page.
I am unable to show text in console.log when I scroll the page.
I am unable to show text in console.log when I scroll the page.
I am unable to show text in console.log when I scroll the page.
A: The element needs to be scrollable (fixed height with an overflow:scroll).
$("#idOfUl").scroll(function() {
console.log('Event Fired');
});
#idOfUl {
height: 100vh;
overflow: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="idOfUl">
<ul>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
<li>
You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow
property when you want to have better control of the layout. The default value is visible. You can use the overflow property when you want to have better control of the layout. The default value is visible. You can use the overflow property when
you want to have better control of the layout. The default value is visible.
</li>
</ul>
</div>
| |
doc_4425
|
The first post was confusamagin. My assignment is to create a password prompt program. The password needs to be checked to see if it does have at least one digit and one letter in it. Also the password length must be between 6 - 10.
My problem is trying to figure out how see if a digit and letter exist the password. In the check password area I am not sure where to begin really. I am not sure how to see if it has a Letter and a Digit in one. I know how to do either or by using a for statement to count and check but all it does is check to see rather it contains all letters or all digits.
Below is what I have so far...
import java.util.Scanner;
class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//------ENTER A USERNAME
System.out.println("Welcome please enter your username and password.");
System.out.print("Username >>");
input.nextLine();
//------PASSWORD AUTHENTICATION BEGIN
String password = enterPassword();
while ( !checkPassword(password) ) {
System.out.println("Password must be 6 - 10 characters long!");
password = enterPassword();
}
//------PASSWORD VERIFY
String passwordverify = enterPassword();
while (!password.equals(passwordverify)){
System.out.println("ERROR - Passwords DO NOT MATCH Re-Enter Passwords Again");
password = enterPassword();
}
//------ACCEPT PASSWORD
System.out.println("Username and Password Accepted!");
}
//--ENTER PASSWORD STATEMENT
public static String enterPassword(){
String password;
Scanner input = new Scanner(System.in);
System.out.print("Password >>");
password = input.nextLine();
return password;
}
//--BOOLEAN CHECK PW
public static boolean checkPassword(String password){
int length;
length = password.length();
if (length < 6 || length > 11){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(i)))
return false;
}
return true;
}
}
A: public static boolean checkPasswordLetter(String password){
for (int i = 0; i < password.length();){
if (!Character.isLetter(password.charAt(i))){
return false;
}
}
return true;
}
Here you didn't increment variable i , need in for i++ or your loop is going forever if is not letter, same and in checkPasswordDigit
A: checkPasswordLetter and checkPasswordDigit will only return true if ALL chars are letters/digits respectively. Is this what you meant?
A: First off... It's not that Java is not looping or checking Boolean. Java is doing what you are telling it to do.
Now, what you want to do is different than what you are doing.
What you need to do is something like:
public static void main(String[] args) {
// ...
String password = enterPassword();
while ( !isPasswordValid(password) ) {
password = enterPassword();
}
System.out.println("Username and Password Accepted!");
}
public static boolean isPasswordValid(String password) {
// return true if and only if password:
// 1. has 6-10 characters
// 2. contains at least one digit
// 3. contains at least one character
// print messages accordingly
}
A: There are two things wrong.
*
*Your letter checking is failing on the first non-letter. Same thing happening with your digit checking. You only want to reject if every character is a non-letter, for example. So logic error.
*You have three loops. Bad idea, because if you pass the length check once, it is never going to be checked again. Consider what would happen if someone entered: 12345678. Length ok, but no letter. Ok, now enter: a1. Length not checked again.
A: import java.util.Scanner;
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class CheckingPassword
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 9) {
return false;
}
else {
char c = 0 ;
int count=0;
System.out.println(password.length());
for (int i = 0;i<=password.length()-1; i++)
{
c = password.charAt(i);
System.out.println(c);
if (!Character.isLetterOrDigit(c))
{
return false;
}
else if (Character.isDigit(c))
{
count++;
if(count==3)
{
return false;
}
}
}
return true;
}
}
}
A: import java.util.Scanner;
public class password{
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a password ") ;
String s = input.nextLine();
if(isValid(s))
System.out.println(s + " is a valid password");
else
System.out.println(s + " is not a valid password");
}
public static boolean isValid(String s )
{
int i = 0,j=0;
if(s.length()>=8)
{
for(i=0;i<s.length();i++)
{
//if(Charcter.isLetter(s.charAt(i))||Digit.isLetter(s.charAt(i)))
if (Character.isLetterOrDigit(s.charAt(i)))
{
if(Character.isDigit(s.charAt(i)))
j++;
}
}
}
else
return false;
if(j>=2)
return true;
return false;
} }
| |
doc_4426
|
declare @sql nvarchar(4000) =
N';with cteColumnts (ORDINAL_POSITION, COLUMN_NAME) as
(
select ORDINAL_POSITION, COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = N'''+ @tableName + ''' and COLUMN_NAME like ''' + @columnLikeFilter + '''
),
cteValues (ColumnName, SumValue) as
(
SELECT ColumnName, SumValue
FROM
(SELECT ' + @sumColumns + '
FROM dbo.' + @tableName + ') p
UNPIVOT
(SumValue FOR ColumnName IN
(' + @columns + ')
)AS unpvt
)
select row_number() over(order by ORDINAL_POSITION) as ID, ColumnName, SumValue
from cteColumnts c inner join cteValues v on COLUMN_NAME = ColumnName
order by ORDINAL_POSITION'
exec sp_executesql @sql
--OR
exec (@sql)
Why did lobodava pick exec sp_executesql @sql and not exec(@sql)
So what is the difference here?
Is it better to use sp_executesql on recursive dynamic queries?
In other post they say sp_executesql is more likely to promote query plan reuse...
So it helps in these kind of queries?
A: Because EXEC sp_executesql will cache the query plan -- EXEC will not. For more info, and a very good read, see:
*
*The Curse and Blessings of Dynamic SQL
Caching a query means that the logistics to the query are temporarily stored, and make running the query later on faster for it.
| |
doc_4427
|
RewriteRule ^test.html default.php?page=10&language=en
I want:
test.html -> default.php?page=10&language=en
(this line is working fine)
And if test.html is called with extra url param then I want to add them, like this:
test.html?user_id=ABC¤cy=EUR -> default.php?page=10&language=en&user_id=ABC¤cy=EUR
(this line is not working, because I don't get user_id=ABC¤cy=EUR)
A: Use:
RewriteRule ^test.html default.php?page=10&language=en [QSA,L]
With [QSA|qsappend]:
When the replacement URI contains a query string, the default behavior
of RewriteRule is to discard the existing query string, and replace it
with the newly generated one. Using the [QSA] flag causes the query
strings to be combined.
http://httpd.apache.org/docs/current/rewrite/flags.html
| |
doc_4428
|
It looks like so:
$query = new Query($boolQuery);
$categoryAggregation = new Terms('category_ids');
$categoryAggregation->setField('category_ids');
$categoryAggregation->setSize(0);
$manufacturerAggregation = new Terms('manufacturer_ids');
$manufacturerAggregation->setField('manufacturer_id');
$manufacturerAggregation->setSize(0);
$globalAggregation = new GlobalAggregation('global');
$globalAggregation->addAggregation($categoryAggregation);
$globalAggregation->addAggregation($manufacturerAggregation);
$query->addAggregation($globalAggregation);
I would like to add some custom filters to manufacturer_ids and category_ids aggregations. At the moment they are aggregated from all documents. Is there any way to do it via Elastica API, so that it applies some filtering to it?
A: I found it myself through trial and error, it goes as following:
$categoryAggregation = new Terms('category_ids');
$categoryAggregation->setField('category_ids');
$categoryAggregation->setSize(0);
$filter = new Filter('category_ids', $merchantIdQuery);
$filter->addAggregation($categoryAggregation);
$globalAggregation = new GlobalAggregation('global');
$globalAggregation->addAggregation($filter);
| |
doc_4429
|
The command i'm using:
thin start -p 2048 -e production --ssl --ssl-key-file ./mykey.key --ssl-cert-file ./mycert.crt
So i looked inside my log:
-> production.log
ActionView::Template::Error (jquery-1.7.1.min.js isn't precompiled):
3: <head>
4: <title>MSDNAA</title>
5: <%= stylesheet_link_tag "application" %>
6: <%= javascript_include_tag "jquery-1.7.1.min.js" %>
7: <%= javascript_include_tag "application" %>
8: <%= csrf_meta_tags if false %>
9: </head>
Well i'm pretty new to Rails so i watched 2 Railscasts handling the assets-pipeline
(279 and 282) to make sure i understood everything.
When I'm understanding that correctly the things i have to do are the following:
Add the following lines to my application.js:
//= require jquery
//= require jquery_ujs
//= require_self
//= require_tree .
That will include all the needed JQuery files, itself and all the JS-files in my assets directory.
Then I have to make sure that the JQuery-Rails gem is installed and included inside my Gemfile. I hit bundle to make sure it is used and evrything went fine.
Then i added the stuff explained in Rails Cast 282.
After that i have to precompile my assets using the following command:
bundle exec rake assets:precompile
After that i still get that error.
There is no need to load the jquery-1.7.1.min.js, it's not even inside my application directory.
The second thing i'm worried abot is that when i'm connecting to my app via browser like this:
https://myapp:2048/assets/application.js
I should see every JScript related stuff wrapped together. Instead i get a "404 - Page not found" error and the log says: "No route matches /[AppDir]/assets/javascripts/application.js"
What am i doing wrong?
Did i miss something? (I guess!)
Versioninfo:
Rails 3.2.8
ruby 1.9.3p194 (2012-04-20 revision 35410) [i686-linux]
| |
doc_4430
|
I have an existing MySQL database I would like to use. It is build like this:
URL of the website is http://virtualtransavia.com/
$dbhost = "localhost"; //the host
$dbuser = "k116892_hv"; //the username
$dbpass = "******"; //the password
$dbname = "k116892_hv"; //the database name
$dbprefix = "IPS_"; //the table name prefix
The table it has to read is called IPS_Users (included the dbprefix) and the fields are "Email" and "Pass" (without the cuotation marks).
The password is encrypted for example like this: 0495769618c5515ef7d5d42c600cf66a14341b10.
So it just has to read out of the database and check if the username and password are correct. And it would be nice if it could remember someones login details.
A: First, create PHP on server to handle a web request that will contain the user login information and authenticate the user (you should be able to do the authentication part this using the answer from user3013545).
In iOS you are going to want to create an NSURLRequest and post the appropriate data to the PHP you created above. An easy way to post the data to the website is formatting it using JSON (Google, tons of info out there) and put it in your request.
This is an overview of course, but if I understand your question correctly NSURLRequest is where you want to start. Here is the documentation...
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html
A: Connect to DB:
$db_host = ""; //Hostname
$db_user = ""; //Database user
$db_pass = ""; //Databse password for user
$db = ""; //Database to be
try{
$db_pdo = new PDO("mysql:host=" . $db_host . ";dbname=" . $db, $db_user, $db_pass);}
catch (PDOException $e){
echo $e->getMessage();
}
Select table and fields:
$columnEmail = '';
$columnPass = '';
$Table = '';
$st = $db_pdo->prepare("SELECT " . $column . ", " . $columnPass . " FROM " . $Table );
$st->execute();
//check if username and password exist
if($st->rowCount() > 0 ){
echo 'User correct';
} else {
echo 'User incorrect';
}
Since the password is cripted(or hashed?) you'll have to perform some stuff before checking for password validity.
| |
doc_4431
|
collection.RemoveAll(collection.OfType<type>());
To remove all the elements of a given type from a collection?
A: Both of the already-submitted answers are correct, but omit an explanation why the poster's sample code doesn't work. A couple of interesting points:
First, RemoveAll() is not defined in the ICollection or ICollection<T> interface; it's defined on List<T>, for example, but the semantically equivalent method on HashSet<T> is called RemoveWhere(). If you want to be able to do this for any ICollection<T>, you should write an extension method.
Second, the question's sample code passes a sequence of items to be removed from the collection, but List<T>.RemoveAll() and HashSet<T>.RemoveWhere() take a predicate to identify the items to be removed (as shown in the other answers). You could write your extension method to take the other approach, and pass an IEnumerable<T> as in your example. You need to be careful, though, because you can't do this:
foreach (var item in collection)
if (ShouldRemove(item))
collection.Remove(item);
If you try to do that, you should get an InvalidOperationException with a message like "Collection was modified; enumeration operation may not execute."
A: As the first two code answers use a List specifically, and the third only has nonworking code:
ICollection collection = GetCollection();
foreach (object obj in collection.Where(obj => obj is type).ToList())
collection.Remove(obj);
You can end the enumeration by calling ToList, so that removal is allowed again. It's totally inefficient tho, as it requires one enumeration to get the objects and then removes them one by one, possibly requiring enumeration each time. If the collection type you're using has it's own methods, like List.RemoveAll, use those instead, but your use of "collection" implies you do not know its type.
Alternatively, if the importance is not on preserving the object, consider reassigning instead:
collection = collection.Where(obj => obj is type == false).ToList();
A: I would do something like this:
collection.RemoveAll(i => collection.OfType().Contains(i));
EDIT:
collection.RemoveAll(i => i is type);
A: If I understand it correctly, you have a single collection of any object type and you want to remove all items of a type from that collection. If so, it's simple:
objects.RemoveAll(q=>q.GetType()==typeof(YourType));
A: collection.Clear() removes all elements.
| |
doc_4432
|
Going through an Octave script is acceptable.
The file is created with the command:
save("-binary",fileName,myMatrix,"var1","var2");
A: If you program is licensed under the GPL you can use liboctave/libinterp and link your C++ program against it. See libinterp/corefcn/load-save.cc
http://wiki.octave.org/FAQ#I_wrote_a_program_that_links_with_Octave_libraries_and_I_don.27t_want_to_release_it_under_the_terms_of_the_GPL._Will_you_change_the_license_of_the_Octave_libraries_for_me.3F
See
https://www.gnu.org/software/octave/doc/interpreter/Standalone-Programs.html howto write standalone programs which use octave.
| |
doc_4433
|
Here is my script:
import pandas as pd
import nltk.corpus
nltk.download('stopwords')
from nltk.corpus import stopwords
df = pd.read_csv('keywords_to_cluster.csv')
stop_words = stopwords.words('english')
df['clean_keyword'] = df['keyword'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop_words)]))
The script runs without errors when I execute from my venv with the command,
python cleanup_keywords.py
Although there is no output in my CSV file.
I have simply been following this guide so please forgive me if I have missed something simple, but I am at a loss here.
| |
doc_4434
|
I have access through ssh. My hosting provider uses cPanel Accelerated.
Regards
Javi
A: What about just putting a .htaccess somewhere which alters some readily-observable settings and look whether they have been changed or not?
A: Try uploading a sample .htaccess file (e.g. with a single simple redirect rule) and check if it works.
| |
doc_4435
|
It's weird because I can't locate the file in the windows explorer, but it is visible with the "browse" thing, only at the exporting wizard!
Does anyone know why? How can I reach my file?
A: What IDE are you using ? If you use Eclipse, the .apk must be in the folder YourProjectFolder/bin
| |
doc_4436
|
In the navigation bar, there will be a button.
As I tap this button, the visibility of the 3 VCs will cycle. (no animations, just hiding/showing).
When I tap the button, I want the 3 childrens to respect events viewWillAppear, viewWillDisappear, etc... Does changing the hidden property call these?
How can I do this?
My theory is to create 3 containers and add them to RestaurantViewController.view, then set hidden for them as I tap the button. I'm not sure if this is the "right" way.
A: If you want each child to have it's own area of the screen then using 3 different containers with a different child in each will work fine.
No, viewWillAppear/viewWillDisappear will not be called each time the child's hidden flag switches from true to false. As Tj3n says, that will only be called if the child view controller's view is removed from the screen and then re-added.
EDIT:
If you have a single container view that you want to replace with a different child view controller each time you press a button then you want to use the parent/child view controller methods in UIViewController. See the section "Implementing a Container View Controller" in the Xcode docs on UIViewController.
You could add your starting child view controller to the container using an embed segue, and add the others using addChildViewController.
There are also methods that let you transition from one child to another, like transitionFromViewController:toViewController:duration:options:animations:completion:. That's a very powerful method that lets you swap child view controllers with a wide variety of transition effects. That's the method that you'd trigger when the user pressed the button to swap view controllers.
A: You can add 3 UIViewControllers to the main view controller, but none of them will call viewWillAppear.
Instead of playing with the property hidden you can add a tag value to each view do something like:
-(void)changeViews:(int) index {
if (lastDisplayedView == 1) {
// code you wanted in viewWillDisappear for view 1
} else if (lastDisplayedView == 2) {
// code you wanted in viewWillDisappear for view 2
} else if (lastDisplayedView == 3) {
// code you wanted in viewWillDisappear for view 3
}
UIView *viewToRemove = (UIView *)[self.view viewWithTag:lastDisplayedView];
[viewToRemove removeFromSuperview];
UIView *viewToShow = (UIView *)[self.view viewWithTag:index];
[self.view addSubview:viewToShow];
lastDisplayedView = index;
// code you need to do when view appears
}
| |
doc_4437
|
What direction should I look for setting the location on the device.
The scenario i have is a jailbroken Wi-Fi iPad tethered to a nexus one. The nexus one would host a background service that when a request is recieved, it would respond with gps data of its current location. The jailbroken ipad would have a background service that either updated the location on a time interval, or on a per request basis (depending on how i have to implement it) by submitting a request to the tethered nexus one service. That data would then be set on the ipad and an application requesting location would get the service data.
The goal is to recreate the location faker app's functionality with the exception of the spoofed location comes from the nexus ones gps via the service but i have not yet found out how to set the location data for the device. I can ofcourse implement this in a per app basis but it would be awesome to have any app be able to use it.
A: Core Location presents significant privacy and personal security concerns. For that reason, it will be very difficult to crack or spoof even for a jailbroken device. To my knowledge, the location is calculated every time a request for location is made (which is why it drains the battery.) There is no file or setting that can be easily set.
In order to spoof the location for all apps, you will have to patch the system code that Core Location calls. There is zero documentation for that system code as it is all Apple proprietary. You have to find someone who has reverse engineered the Apple Code for some reason.
Your best bet would see if there is a custom process running that manages locations and then replace that entire process with one of your own that returns nothing but the spoofed location.
No matter what, your basically going to have to recreate the entire interface that Core Location calls to ensure that every Core Location call in every app works. You're looking at a great deal of low level C coding in an API with no docs. The odds of getting it right are fairly low.
A: Well, the way to get the location on iPhone is via a CLLocationManager. If you want to get a custom location, then just subclass it and override the startUpdatingLocation method to not call super, and then just invoke the delegate method yourself. Something like:
@interface CustomLocationManager : CLLocationManager {
}
@end
@implementation CustomLocationManager
- (void) startUpdatingLocation {
[[self delegate] locationManager:self didUpdateToLocation:customLocation fromLocation:nil];
}
@end
Then you can do:
CLLocationManager * manager = [[CustomLocationManager alloc] init];
[manager setDelegate:self];
[manager startUpdatingToLocation];
A: hooking into core location or using the locationd caches seems to be the best way to do this. though i have yet implemented anything. that is the route to go.
| |
doc_4438
|
Also, I am quite new to Python so sorry if this is a stupid question but I just couldn't find the right answer to fit my needs.
I've tried to use different axis formatting options using yaxis.set_major_formatter (not sure if this doesn't work because I'm plotting from pandas, but yielding no results either way), pandas.set_option to customise display.
from pandas.plotting import scatter_matrix
scatter_matrix(df, alpha=0.3, figsize=(9,9), diagonal='kde')
df: Tesla Ret Ford Ret GM Ret
Date
2012-01-03 NaN NaN NaN
2012-01-04 -0.013177 0.015274 0.004751
2012-01-05 -0.021292 0.025664 0.048227
2012-01-06 -0.008481 0.010354 0.033829
2012-01-09 0.013388 0.007686 -0.003490
2012-01-10 0.013578 0.000000 0.017513
2012-01-11 0.022085 0.022881 0.052926
2012-01-12 0.000708 0.005800 0.008173
2012-01-13 -0.193274 -0.008237 -0.015403
2012-01-17 0.167179 -0.001661 -0.003705
...
I've tried to use:
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) and ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) after importing the respective modulesm, to no avail.
Figure is available here
Everything else in the figure is just as it should be, just the y-axis of the top left plot. I would like it to show one or two decimal point values like the rest of the figure.
I'd greatly appreciate any help that could fix my issue.
Thanks.
A: P.S: I have edited this answer based on the problem pointed out by @ImportanceOfBeingEarnest (thanks to him). Please read the comments below the answer to see what I mean.
The new solution is to get the displayed ticks for that particular axis and format them up to 2 decimal places.
new_labels = [round(float(i.get_text()), 2) for i in axes[0,0].get_yticklabels()]
axes[0,0].set_yticklabels(new_labels)
OLD ANSWER (Still kept as a history as you will see that the y-ticks in the figure generated below are not correct)
The problem is that you are using ax object to format the labels but ax returned from scatter_matrix is not a single axis object. It is an object containing 9 axis (3x3 subfigure). You can prove this if you plot the shape of the axes variable.
axes = scatter_matrix(df, alpha=0.3, figsize=(9,9), diagonal='kde')
print (axes.shape)
# (3, 3)
The solution is either to iterate through all the axis or to just change the formatting for the problematic case. P.S: The figure below don't match with your's because I just used the small DataFrame you posted.
Following is how you can do it for all the y-axis
from pandas.plotting import scatter_matrix
from matplotlib.ticker import FormatStrFormatter
axes = scatter_matrix(df, alpha=0.3, figsize=(9,9), diagonal='kde')
for ax in axes.flatten():
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
Alternatively you can just choose a particular axis. Here your top left subfigure can be accessed using axes[0,0]
axes[0,0].yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
A: pandas.scatter_matrix suffers from an unfortunate design choice. That is, it plots the kde or histogram on the diagonal to the axes that shows the ticks for the rest of the row. This then requires to fake the ticks and labels to be fitting for the data. In the course of this a FixedLocator and a FixedFormatter are used. The format of the ticklabels is hence directly taken over from the string representation of a number.
I would propose a completely different design here. That is, the diagonal axes should stay empty, and instead twin axes are used to show the histogram or kde curve. The problem from the question can hence not occur.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def scatter_matrix(df, axes=None, **kw):
n = df.columns.size
diagonal = kw.pop("diagonal", "hist")
if not axes:
fig, axes = plt.subplots(n,n, figsize=kw.pop("figsize", None),
squeeze=False, sharex="col", sharey="row")
else:
flax = axes.flatten()
fig = flax[0].figure
assert len(flax) == n*n
# no gaps between subplots
fig.subplots_adjust(wspace=0, hspace=0)
hist_kwds = kw.pop("hist_kwds", {})
density_kwds = kw.pop("density_kwds", {})
import itertools
p = itertools.permutations(df.columns, r=2)
n = itertools.permutations(np.arange(len(df.columns)), r=2)
for (i,j), (y,x) in zip(n,p):
axes[i,j].scatter(df[x].values, df[y].values, **kw)
axes[i,j].tick_params(left=False, labelleft=False,
bottom=False, labelbottom=False)
diagaxes = []
for i, c in enumerate(df.columns):
ax = axes[i,i].twinx()
diagaxes.append(ax)
if diagonal == 'hist':
ax.hist(df[c].values, **hist_kwds)
elif diagonal in ('kde', 'density'):
from scipy.stats import gaussian_kde
y = df[c].values
gkde = gaussian_kde(y)
ind = np.linspace(y.min(), y.max(), 1000)
ax.plot(ind, gkde.evaluate(ind), **density_kwds)
if i!= 0:
diagaxes[0].get_shared_y_axes().join(diagaxes[0], ax)
ax.axis("off")
for i,c in enumerate(df.columns):
axes[i,i].tick_params(left=False, labelleft=False,
bottom=False, labelbottom=False)
axes[i,0].set_ylabel(c)
axes[-1,i].set_xlabel(c)
axes[i,0].tick_params(left=True, labelleft=True)
axes[-1,i].tick_params(bottom=True, labelbottom=True)
return axes, diagaxes
df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
axes,diagaxes = scatter_matrix(df, diagonal='kde', alpha=0.5)
plt.show()
| |
doc_4439
|
static async getSnapshot(fc: FormControl){
let isPresent:boolean = false;
await firebase.database().ref().child("users").orderByChild("username")
.equalTo(fc.value)
.once("value", snapshot => {
}).then((data)=> {
if(data.exists())
isPresent = true;
else
isPresent = false;
});
console.log(isPresent);
return isPresent;
}
The problem is when I call this function in another where I want to do other operations based on the result:
static async validUsername(fc: FormControl){
try{
let bool:boolean =await this.getSnapshot(fc.value)
if(bool===true)
return ({validUsername: true});
else{
return (null);
}
}catch(e){
console.log(e)
}
}
The line :
let bool:boolean =await this.getSnapshot(fc.value)
returns the following error:
TypeError: Cannot read property 'getSnapshot' of undefined
How can I modify my function? Thanks in advance for response
A: this refers to an instance usually. Static methods don't belong to any instance so this doesn't make sense in them.
To fix your case, just use your class name instead of this. E.g.
class APIHandlers {
static async getSnapshot {...}
static async validUsername(fc: FormControl){
try{
let bool:boolean = await APIHandlers.getSnapshot(fc.value);
...
}
}
| |
doc_4440
|
<?php
//Count ap´s before import
$before = mysql_query("SELECT * FROM wifi");
$num_rows_before = mysql_num_rows($before);
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$linesCount ++;
mysql_query("INSERT INTO wifi (bssid, channel, privacy, ciper, auth, power, essid, latitude, longitude, first_seen, last_seen) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."',
'".addslashes($data[5])."',
'".addslashes($data[6])."',
'".addslashes($data[7])."',
'".addslashes($data[8])."',
'".addslashes($data[9])."',
'".addslashes($data[10])."'
)
");
}
} while ($data = fgetcsv($handle,1000,","));
//redirect
header('Location: index.php/ladda-upp?success=1&before=' . $num_rows_before); die;
}
//Catch argument from url
$arg_bef=$_GET['before'];
//Count ap´s after import
$after = mysql_query("SELECT * FROM wifi");
$num_rows_after = mysql_num_rows($after);
//Count new rows
$new_rows = $num_rows_after - $arg_bef;
//generic success notice
if (!empty($_GET[success])) { echo "<br><b>Resultat: Din fil har blivit importerad!</b><br><br>";
//echo stats
echo "Antal före import - ";
echo "$arg_bef";
echo "<br>";
echo "Antal efter import - ";
echo "$num_rows_after";
echo "<br>";
echo "Antal nya rader - ";
echo "$new_rows";
echo "<br>";
echo "Rader i CSV-fil - ";
}
//Close connection to databse
mysql_close($connect) ;
?>
A: You want mysql's on duplicate key feature
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Make sure you've got a key set on a field that appears in the CSV eg: bssid could probably work.
instead of addslashes() use mysql_real_escape_string() but as no doubt someone will point out mysql_ functions are deprecated and will be removed soon so you should be using at least mysqli.
A: Alternative: REPLACE INTO will behave exactly like INSERT INTO, except that it does an UPDATE when a duplicate unique value is encountered.
| |
doc_4441
|
[DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
static extern uint LoadLibraryEx(string fileName, uint notUsedMustBeZero, uint flags);
Below is the code that I tried to load the 64-bit assembly.
var hLib = LoadLibraryEx(filePath, 0, DONT_RESOLVE_DLL_REFERENCES | LOAD_IGNORE_CODE_AUTHZ_LEVEL);
How to fix this issue?
| |
doc_4442
|
{size:1, title:"Hello", space:0}
{size:21, title:"World", space:10}
{size:3, title:"Goodbye", space:20}
However, there is so much data that I cannot see it all in the terminal, and would like to write code that automatically writes a json file. I am having trouble getting the json to keep the separated lines. Right now, it is all one large line in the json file. I have attached some code that I have tried. I have also attached the code used to make the string that I want to convert to a json. Thank you so much!
for value in outputList:
newOutputString = json.dumps(value)
outputString += (newOutputString + "\n")
with open('data.json', 'w') as outfile:
for item in outputString.splitlines():
json.dump(item, outfile)
json.dump("\n",outfile)
A: If the input really is a string, you'll probably have to make sure it's some properly formated as json:
outputString = '''{"size":1, "title":"Hello", "space":0}
{"size":21, "title":"World", "space":10}
{"size":3, "title":"Goodbye", "space":20}'''
You could then use pandas to manipulate your data (so it's not a problem of screen size anymore).
import pandas as pd
import json
pd.DataFrame([json.loads(line) for line in outputString.split('\n')])
Which gives:
size title space
0 1 Hello 0
1 21 World 10
2 3 Goodbye 20
On the other hand, from what I understand outputString is not a string but a list of dictionaries, so you could write a simpler version of this:
outputString = [{'size':1, 'title':"Hello", 'space':0},
{'size':21, 'title':"World", 'space':10},
{'size':3, 'title':"Goodbye", 'space':20}]
pd.DataFrame(outputString)
Which gives the same DataFrame as before. Using this DataFrame will allow you to query your data and it will be much more confortable than a JSON. For example
>>> df = pd.DataFrame(outputString)
>>> df[df['size'] >= 3]
size title space
1 21 World 10
2 3 Goodbye 20
You could also to try ipython (or even jupyter/jupyterlab) as it will probably also make your life easier.
A: You can use below code:
json_data = json.loads(outputString)
with open('data.json', 'w') as outfile:
json.dump(json_data, outfile, indent= 5)
| |
doc_4443
|
A: You don't need a script. Use cp -R for recursive copy:
cp -R source_path dest_path
To do a recursive copy while preserving file attributes like last modified time etc., use the -p option as well:
cp -Rp source_path dest_path
From man cp:
-R
If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the
source_file ends in a /, the contents of the directory are copied
rather than the directory itself. This option also causes symbolic
links to be copied, rather than indirected through, and for cp to
create special files rather than copying them as normal files.
Created directories have the same mode as the corresponding source
directory, unmodified by the process' umask.
A: It sounds like you want to copy a single file into all the subdirectories under the target directory (and into the target directory itself). If that is correct, then:
find $targetdir -type d -exec cp $sourcefile {} \;
| |
doc_4444
|
I'm sure the answer is simple, but can anyone enlighten me?
A: %pylab is a magic function in ipython.
Magic functions in ipython always begin with the percent sign (%) followed without any spaces by a small text string; in essence, ipython magic functions define shortcuts particularly useful for interactive work, e.g., to give you an idea of how magic functions work in python, a few of my favorites:
*
*to view cwd directory contents:
%ls
*to run a script in ipython using an empty namespace, type space then a script name:
%run
*to execute a code snippet (particularly for multi-line snippets which would usually cause an _IndentationError_ to be thrown):
%paste
When the %pylab magic function is entered at the IPython prompt, it triggers
the import of various modules within Matplotlib.
Which modules? well, the ones subsumed under the pylab interface.
The awesome Matplotlib plotting library has two distinct interfaces: a pythonic one, and the original MATLAB-like one intended for plotting at the interactive prompt.
The former is usually imported like so:
from matplotlib import pyplot as PLT
Indeed, pyplot has its own magic python magic function
%pyplot
Why two different interfaces? Matplotlib's original interface was pylab; only
later was the pythonic interface added. Scripting and app development were not
the primary uses cases for Matplotlib when the project began, plotting in the
python shell was.
Apparently John Hunter (Matplotlib's creator) wanted to include interactive plotting in python so he submitted a patch to Fernando Perez's (FP) IPython project. FP was a Ph.D student at the time and informed JH that he would not able to review the path for some time. As a result, JH created Matplotlib. The significance is that Matplotlib began as a shell-based plotting scheme.
the pylab interface is indeed more suitable for interactive work:
from pylab import *
x, y = arange(10), cos(x/2)
plot(x, y)
show()
and using the pyplot interface:
from matplotlib import pyplot as PLT
import numpy as NP
x, y = NP.arange(10), NP.cos(x/2)
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y)
PLT.show()
A: More recent documentation about the IPython magics here.
Magics function are often present in the form of shell-like syntax,
but are under the hood python function. The syntax and assignment
possibility are similar to the one with the bang (!) syntax, but with
more flexibility and power. Magic function start with a percent sign
(%) or double percent (%%).
A little bit here and more specifically about the %pylab magic here.
%pylab [--no-import-all] [gui]
Load numpy and matplotlib to work interactively.
This function lets you activate pylab (matplotlib, numpy and
interactive support) at any point during an IPython session.
%pylab makes the following imports:
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.display import display
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *
A: %pylab is a shortcut for typing all of the below commands - in essence adding numpy and matplotlib into your session. This was incorporated in iPython as a transition tool and the current recommendation is that you should not use it. The core reason is that the below sets of commands import too much into the global namespace and also they don't allow you to change the mode for matplotlib from UI to QT or something else. You can see tje history and reasoning behind this at http://nbviewer.ipython.org/github/Carreau/posts/blob/master/10-No-PyLab-Thanks.ipynb?create=1.
This is what %pylab does:
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *
This is what I use instead at the start of my notebook:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
A: %pylab is a "magic function" that you can call within IPython, or Interactive Python. By invoking it, the IPython interpreter will import matplotlib and NumPy modules such that you'll have convenient access to their functions. As an example,
rich@rich-ubuntu:~/working/fb_recruit/working$ ipython
Python 2.7.6 |Anaconda 1.8.0 (64-bit)| (default, Nov 11 2013, 10:47:18)
Type "copyright", "credits" or "license" for more information.
IPython 1.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: arange(4)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-2e43d7eb1b3e> in <module>()
----> 1 arange(4)
NameError: name 'arange' is not defined
In [2]: %pylab
Using matplotlib backend: Qt4Agg
Populating the interactive namespace from numpy and matplotlib
In [3]: arange(4)
Out[3]: array([0, 1, 2, 3])
In [4]:
A: As its name implies, Pylab is a MATLAB-like front end for doing mathematics in Python. iPython has specific support for Pylab, which is invoked using the %pylab magic command.
| |
doc_4445
|
Multiple markers at this line
- Syntax error on token(s), misplaced construct(s)
- Syntax error on token "myLabel", VariableDeclaratorId expected after
this token
Is this because they depend on the context and string coming from the constructor?
These errors are way too vague.
Thanks for your help.
public class CustomSeekBar implements SeekBar.OnSeekBarChangeListener {
Context myContext;
CharSequence myLabel;
CustomSeekBar(Context context, CharSequence label){
myContext = context;
myLabel = label;
}
TextView myValue = new TextView(myContext);
SeekBar mySeekBar = new SeekBar(myContext);
myValue.setText(myLabel);
mySeekBar.setProgress(3);
//mySeekBar.setOnSeekBarChangeListener();
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
public void onStopTrackingTouch(SeekBar seekBar){
}
public void onStartTrackingTouch (SeekBar seekBar){
}
}
A: Did you want that code within your constructor?
CustomSeekBar(Context context, CharSequence label){
myContext = context;
myLabel = label;
TextView myValue = new TextView(myContext);
SeekBar mySeekBar = new SeekBar(myContext);
myValue.setText(myLabel);
mySeekBar.setProgress(3);
}
| |
doc_4446
|
*
*Are easy to work with with the
Windows SDK (particularly
DirectShow, which I plan to use
with C#)
*Have drivers for both
64-bit and 32-bit Windows Vista (and
Server 2008)
I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at. I suspect that any old web cam will do but I'd rather be safe than sorry.
A: If you only want images, many web cams support TWAIN -- you can use with .NET using this code
http://www.codeproject.com/KB/dotnet/twaindotnet.aspx
A: I'm doing something very similar with webcams and have found that logitech and Microsoft branded webcams work just fine with DirectShow.
I've also found that many NEW webcams don't support twain, and WIA support for doing live captures has been removed in Vista, and doesn't exist in 2000, so Directshow has been the only thing that seems to work reliably accross OS's.
| |
doc_4447
|
Here is the input:
Insert 10000 2
Insert 10000 2
Insert 10000 3
Insert 19444 9
Pop
Insert 10331 3
Pop
Pop
Pop
Pop
Pop
Here's what the output should be:
19444
10000
10331
10000
10000
-1
Here's the output which I get:
19444
10000
10000
10000
10331
-1
SOLVED !
A: I believe your priority checking logic is incorrect:
while (queue->next != NULL && queue->next->prior >= /* not <= */ priorty)
or better yet
while (queue->next != NULL && priorty <= queue->next->prior)
Not sure how you intend to handle the case where two elements have the same priority, but since your insert uses "greater than" to replace the head of the queue you probably want to keep the same logic.
A: You loop for inserting the node is incorrect, it should read:
while (queue->next != NULL && queue->next->prior >= priorty)
queue = queue->next;
| |
doc_4448
|
dictionary.timeslot_events.Add(t, new List<int>() { i });
but it is giving me exception that more an item with the same key has already added.
i have also tried to populate list with add function timeslot_events.Add(t, new List<int>() { i }); but it is giving me exception that the given key was not present in the dictionary.
kindly guide how can i populate it successfully.? In C++, i used to do it with
map<int, vector<int>>
for (int i = 0; i < data.noevents; i++)
{
int t = (int)(rg.Next(1, 45));
Console.WriteLine(t);
timeslot_events.Add(t, new List<int>() { i });
}
A: Check if key is already present then add against that key else insert new KeyValue pair like below:
for (int i = 0; i < data.noevents; i++)
{
int t = (int)(rg.Next(1, 45));
Console.WriteLine(t);
if (timeslot_events.ContainsKey(t))
{
if (timeslot_events[t] == null)
{
timeslot_events[t] = new List<int>();
}
timeslot_events[t].Add(i);
}
else
{
timeslot_events.Add(t, new List<int>() { i });
}
}
A: I would use a bit of LINQ.
var query =
from n in Enumerable.Range(0, data.noevents)
group n by rg.Next(1, 45);
foreach (var x in query)
{
timeslot_events.Add(x.Key, x.ToList());
}
| |
doc_4449
|
Error is following:
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/pyplot.py", line 2813, in plot
is not None else {}), **kwargs)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/__init__.py", line 1810, in inner
return func(ax, *args, **kwargs)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 1611, in plot
for line in self._get_lines(*args, **kwargs):
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 393, in _grab_next_args
yield from self._plot_args(this, kwargs)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 370, in _plot_args
x, y = self._xy_from_xy(x, y)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 204, in _xy_from_xy
bx = self.axes.xaxis.update_units(x)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1475, in update_units
self.set_units(default)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1548, in set_units
self._update_axisinfo()
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1490, in _update_axisinfo
info = self.converter.axisinfo(self.units, self)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 353, in axisinfo
majfmt = PandasAutoDateFormatter(majloc, tz=tz)
File "/opt/anaconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_converter.py", line 367, in __init__
self._tz._utcoffset = self._tz.utcoffset(None)
AttributeError: 'datetime.timezone' object has no attribute '_utcoffset'
Is it possible to upgrade without loosing capabilities in Python?
A: I think a viable workaround is indicated by this question. Basically, if you convert the pandas timestamps to str and then back to datetime, it magically works.
| |
doc_4450
|
here is my html
<div class="profile">
<div class="tabbable-line tabbable-full-width">
<ul id="tabs" class="nav nav-tabs">
<li class="active">
<a href="#tab_1_1" data-toggle="tab"> Overview </a>
</li>
<li>
<a href="#tab_1_2" data-toggle="tab"> Loan Details </a>
</li>
<li>
<a href="#tab_1_3" data-toggle="tab"> Edit Details </a>
</li>
<li>
<a href="#tab_1_6" data-toggle="tab"> Delete Account </a>
</li>
after searching on this site for some time
I tried doing :
var data = $("#tabs li.active").prop("href");
alert(data);
also :
var data = $(".profile li.active").prop("href");
alert(data);
but both of them give me output as undefined
What am I doing wrong here?
A: You're not targeting the <a> element in your selector.
Try
var data = $(".profile li.active a").prop("href");
alert(data);
or
var data = $("#tabs li.active a").prop("href");
alert(data);
A: href is not the property of li element, so you will be getting udefined in your data variable. You should point to tag in your selector as shown below :
var data = $("#tabs li.active a").prop("href");
alert(data);
A: I think use attr() is better,Bind with a event is better.
var data = $(".profile li.active a").attr("href");
alert(data);
A: Try this with attr() rather than prop().
var href= $($('ul#tabs>li.active').find('a')[0]).attr("href");
alert(href);
A: Well, you are not locating to the anchor tag try this.
$(document).ready(function(){
$('.active').click(function(){
var href = $('a').attr('href');
alert(href);
});
});
| |
doc_4451
|
Does anyone have any experience with this? Can I use the newer Win32 API with mingw? How?
A: You can always download the very latest platform SDK and have all you need. Use the header and lib files from the SDK.
Having said that, it may be that all you need to do is to define _WIN32_WINNT and/or WINVER to 0x0600 or higher to gain access to more recent APIs. Off the top of my head, I'm not sure what Windows header file mingw ships with.
| |
doc_4452
|
Everything works fine, with one simple itch...
Every single request made to the service stays in TIME_WAIT.
Am I missing something, I've looked around and most samples I've seen on HTTPListeners and Windows Services are doing it in a similar fashion?!
private HttpListener _listener;
protected override void OnStart(string[] args)
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:8080/");
_listener.Start();
_listener.BeginGetContext(new AsyncCallback(OnRequestReceive), _listener);
}
protected override void OnStop()
{
_listener.Stop();
}
private void OnRequestReceive(IAsyncResult result)
{
if (!_listener.IsListening)
return;
//Get context for a request.
HttpListenerContext context = _listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
//Obtain a response object.
HttpListenerResponse response = context.Response;
response.ContentType = "application/json";
response.KeepAlive = false;
//Our return message...
string responseString = "OK";
//Construct the response.
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
Stream output = response.OutputStream;
response.ContentLength64 = buffer.Length;
output.Write(buffer, 0, buffer.Length);
//Close and send response
try
{
output.Flush();
output.Close();
response.Close();
}
finally
{
//Wait for another request
_listener.BeginGetContext(new AsyncCallback(OnRequestReceive), _listener);
}
}
Edit: Fixed Local declaration of _listener.
A: Thanks to rene for pointing out the correct direction...
TIME-WAIT
(either server or client) represents waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request. [According to RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes known as a MSL (maximum segment lifetime).]
For anyone else who wants to change this behavior:
The TIME_WAIT period is configurable by modifying the following DWORD registry setting that represents the TIME_WAIT period in seconds.
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters\TcpTimedWaitDelay
| |
doc_4453
|
I suppose when the matrix is singular there are multiple solutions possible. Is there a way in Jama API to get one of these solutions or is there any other API that can help me here.
Below is a code snippet I am using:
Matrix A = new Matrix(input);
Matrix B = new Matrix(startState);
Matrix X = A.solve(B);
answer = X.getArray();
return answer;
A: check the determinant of the matrix - if zero, it means that the matrix does not have an inverse (rows making up the matrix are not independent). In that case, you can look into SVD, Gauss-Siedel, Jacobi iteration etc. Also, as an alternate library, you could look into apache commons math if it helps.
| |
doc_4454
|
Thx.
A: If you are new to graphs and new to Titan, start here:
http://s3.thinkaurelius.com/docs/titan/0.5.4/getting-started.html
If you don't follow that then recognize that Titan implements the Blueprints interfaces (i.e. TinkerPop) and thus is accessible via the Gremlin graph traversal language:
https://github.com/tinkerpop/gremlin/wiki/Getting-Started
There are plenty of resources available that explain how these things work. Consider looking at GremlinDocs as well as Sql2Gremlin as well.
| |
doc_4455
|
What I want to do:
*
*Perform background subtraction to obtain a mask isolating the peoples' motion.
*Perform grid based optical flow on those areas -
What would be my best bet?
I am struggling to implement. I have tried blob detection and also some optical flow based examples (sparse), sparse didn't really do it for me as I wasn't getting enough feature points from goodfeaturestotrack() - I would like to end up with at least 20 track able points per person so that's why I think a grid based method would be better for me, I will use the motion vectors obtained to classify different people ( clustering on magnitude and direction possibly? )
I am using opencv3 with Python 3.5 - but am still quite noobish in this field.
Would appreciate some guidance immensely!
A: For a sparse optical flow ( in OpenCV the pyramidal Lucas Kanade method) you don't need good features-to-track mandatory to get the positions.
The calcOpticalFlowPyrLK function allows you to estimate the motion at predefined positions and these can be given by you too.
So just initialized a grid of cv::Point2f by your self, e.g. create a list of points and set the positions to the grid points located at your blobs, and run calcOpticalFlowPyrLK().
The idea of the good features-to-track method is that it gives you the points where the calcOpticalFlowPyrLK() result is more likely to be accurate and this is on image locations with edge-like structures. But in my experiences this gives not always the optimal feature point set. I prefer to use regular grids as feature point sets.
| |
doc_4456
|
The array data has about 800 posts which are from API.
Initially, I want to display 20 posts and every single time the page is scrolled, it will display 20 more posts.
Currently, I can see the console log message (scrolled!) whenever I scroll down.
But I can't figure out how to append 20 posts into the table when it's scrolled.
This is the codes that I am trying.
onScrollDown function
onScrollDown(){
this.dataService.getPosts().subscribe((posts)=>{
for (let post of posts){
let data = '<tr><td>'+ post.title +'</td><td>'+ post.geo +'</td><td>'+ post.Telephone +'</td><td>'+ post.category +'</td><td>Detail</td></tr>';
$('table.feed tbody').append(data);
}
});
.
This is the component codes.
posts.component.html
<div *ngIf="posts?.length > 0;else noPosts" class="search-results" infinite-scroll [infiniteScrollDistance]="2" [infiniteScrollUpDistance]="2" [infiniteScrollThrottle]="50" (scrolled)="onScrollDown()" [scrollWindow]="false">
<table class="responsive-table feed striped">
<thead>
<tr>
<th>Name</th>
<th>State/City</th>
<th>Phone</th>
<th>Category</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let post of posts | filter:term">
<td>{{post.title}}</td>
<td>{{post.geo}}</td>
<td>{{post.Telephone}}</td>
<td>{{post.category}}</td>
<td>Detail</td>
</tr>
</tbody>
</table>
</div>
posts.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
import { FilterPipe } from '../../filter.pipe';
declare var jquery:any;
declare var $ :any;
@Component({
selector: 'feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {
term : '';
posts: Post[];
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getPosts().subscribe((posts)=>{
this.posts = posts.slice(0,10);
});
}
onScrollDown(){
console.log("scrolled!");
}
interface Post{
id:number,
title:string,
contact:string,
Address:string,
Telephone:number,
Email:string,
Website:string,
Establishment:string,
sector:string,
category:string,
}
A: first, save your original array like this
this.dataService.getPosts().subscribe((response)=>{
this.originalPosts = response;
this.posts = response.slice(0,20);
});
onScrollDown(){
if(this.posts.length < this.originalPosts.length){
let len = this.posts.length;
for(i = len; i <= len+20; i++){
this.posts.push(this.originalPosts[i]);
}
}
}
just push it on the same array you don't need to append it to the table directly, angular will manage itself, its too easy when using angular.
| |
doc_4457
|
SampleId1 SampleId2
1 2
1 2
2 2
3 2
1 4
2 4
2 4
3 5
I want to find duplicate combination
Eg. SampleId2 has duplicate value of SampleId1 on first two rows
Expected Result :-
SampleId1 SampleId2
1 2
2 4
I tried :-
SELECT
SampleId1 , SampleId2, COUNT(*)
FROM
tablename
GROUP BY
SampleId1 , SampleId2
HAVING
COUNT(*) > 1
But this query is not giving me results as expected.
A: You just want to remove the count in your query, so you can try with below one.
SELECT
SampleId1 , SampleId2
FROM
Test_group
GROUP BY
SampleId1 , SampleId2
HAVING
COUNT(1) > 1;
A: I think you just don't want to project count result in your selection other wise your expected result and your query all the things 100% correct just remove count(*) from select
SELECT
SampleId1 , SampleId2
FROM
t
GROUP BY
SampleId1 , SampleId2
HAVING
COUNT(*) > 1
SampleId1 SampleId2
1 2
2 4
A: you want to get duplicated rows and this is the solution
SELECT a.*
FROM docs a
JOIN (
SELECT SampleId1, SampleId2, COUNT(*)
FROM docs
GROUP BY SampleId1, SampleId2
HAVING count(*) > 1
) b
ON a.SampleId1 = b.SampleId1
AND a.SampleId2 = b.SampleId2
Group BY SampleId1
ORDER BY a.SampleId2
see the result here
| |
doc_4458
|
What did I do:
sudo pip install virtualenv
with this response:
The directory '/Users/ricardogonzales/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/ricardogonzales/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting virtualenv
/Library/Python/2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Downloading virtualenv-13.1.0-py2.py3-none-any.whl (1.7MB)
100% |████████████████████████████████| 1.7MB 59kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-13.1.0
After that I've run virtualenv venv and I'm getting this response: command not found
I've execute this command (brew info python) like other persons around here with the same problem but their responses from the terminal is not the same as my.
brew info response:
python: stable 2.7.10 (bottled), HEAD
Interpreted, interactive, object-oriented programming language
https://www.python.org
Not installed
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/python.rb
==> Dependencies
Build: pkg-config ✘
Required: openssl ✘
Recommended: readline ✘, sqlite ✘, gdbm ✘
Optional: homebrew/dupes/tcl-tk ✘, berkeley-db4 ✘
==> Options
--universal
Build a universal binary
--with-berkeley-db4
Build with berkeley-db4 support
--with-poll
Enable select.poll, which is not fully implemented on OS X (https://bugs.python.org/issue5154)
--with-quicktest
Run `make quicktest` after the build (for devs; may fail)
--with-tcl-tk
Use Homebrew's Tk instead of OS X Tk (has optional Cocoa and threads support)
--without-gdbm
Build without gdbm support
--without-readline
Build without readline support
--without-sqlite
Build without sqlite support
--HEAD
Install HEAD version
==> Caveats
Pip and setuptools have been installed. To update them
pip install --upgrade pip setuptools
You can install Python packages with
pip install <package>
They will install into the site-package directory
/usr/local/lib/python2.7/site-packages
See: https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Homebrew-and-Python.md
I don't know how it says "Not installed" but when I run python --version I'm getting Python 2.7.6 but if I go to usr/local/bin I can not see any python 2.7 or something what I see is a lot of python3.
Any help? or suggestion to try to resolve this will be very aprecciated.
ANSWER:
I've resolved this issue uninstalling the virtualenv and installing again without any extra configuration or something.
sudo pip uninstall virtualenv
sudo pip install virtualenv
A: You've installed Python 2.7.10 according to brew info. python --version returns 2.7.6, so you're probably using the Python that's bundled with OS X. To fix that, run: brew link python, confirm that it is linked correctly by running which python. It should return /usr/local/bin/python (unless you've installed Homebrew in another directory than /usr/local).
After that, you probably need to reinstall virtualenv using the command you've used before, because brew link python will also update the path to pip (the version of pip which is linked to your Python install in /usr/local).
| |
doc_4459
|
My question relates to this one but none of the suggested solutions outputs a method with the required signature: someMethod(...params)
Instead, the produced method is: someMethod(params:*=null)
This won't compile in AS3 projects using the library and the used code is beyond my reach. Is there a way to do this, perhaps macros?
A: Well, that's a great question. And, it turns out there is a way to do it!
Basically, __arguments__ is a special identifier on the Flash target, mostly used to access the special local variable arguments. But it can also be used in the method signature, in which case it changes the output from test(args: *) to test(...__arguments__).
A quick example (live on Try Haxe):
class Test {
static function test(__arguments__:Array<Int>)
{
return 'arguments were: ${__arguments__.join(", ")}';
}
static function main():Void
{
// the haxe typed way
trace(test([1]));
trace(test([1,2]));
trace(test([1,2,3]));
// using varargs within haxe code as well
// actually, just `var testm:Dynamic = test` would have worked, but let's not add more hacks here
var testm = Reflect.makeVarArgs(cast test); // cast needed because Array<Int> != Array<Dynamic>
trace(testm([1]));
trace(testm([1,2]));
trace(testm([1,2,3]));
}
}
Most importantly, this generates the following:
static protected function test(...__arguments__) : String {
return "arguments were: " + __arguments__.join(", ");
}
| |
doc_4460
|
I downloaded and built the wxWidgets libraries successfully and I can run the minimal_vc14 solution just fine. Now it comes time to create my Hello World app. I've created a new, empty C++ project and using NuGet added the wxWidgets template. Then I use class wizard to add a new class (Test3) with a base class of wxApp.
I immediately get 45 errors. The first of which is
Severity Code Description Project File Line Suppression State
Error (active) cannot open source file "../../../lib/vc_dll/mswud/wx/setup.h" Test3 c:\wxWidgets-3.1.0\include\msvc\wx\setup.h 121
digging into that file I find the following bit. The last include statement is the problem line identified above, but the problem I think is in the wxConcat6 statement. All of those ../ lead nowhere. Shouldn't that point to $(WXWIN)?
// the real setup.h header file we need is in the build-specific directory,
// construct the path to it
#ifdef wxSUFFIX
#define wxSETUPH_PATH \
wxCONCAT6(../../../lib/, wxLIB_SUBDIR, /, wxTOOLKIT_PREFIX, wxSUFFIX, /wx/setup.h)
#else // suffix is empty
#define wxSETUPH_PATH \
wxCONCAT5(../../../lib/, wxLIB_SUBDIR, /, wxTOOLKIT_PREFIX, /wx/setup.h)
#endif
#define wxSETUPH_PATH_STR wxSTRINGIZE(wxSETUPH_PATH)
#include wxSETUPH_PATH_STR
Also, smaller problem but further up the setup.h file I see that WXUSINGDLL has been defined, but I want to use libs. I can't figure out where that is being set either.
Obviously there is a configuration step I missed somewhere. Please advise.
A: As usual the answer can be found by reading EVERYTHING.
There are 2 things that need to be configured for this process to work correctly.
*
*After creating the project go to the project properties and set the character set to Unicode. The default is Multi-Byte. My next quest will be to find where to change the default!
*After installing the package template (or is it a template package?) go to the project properties and set shared to "statically linked build".
*Presto changeo, you are ready to go. Add the following for the absolute minimum to make a compilable application. This is based on the tutorial here:creating-wxwidgets-programs-with-visual-studio-2015
bool MyProjectApp::OnInit()
{
wxFrame* mainFrame = new wxFrame(nullptr, wxID_ANY, L"MyProject");
mainFrame->Show(true);
return true;
}
wxIMPLEMENT_APP(MyProjectApp);
A: I suggest you make a copy of minimal sample (or widgets, as it uses more controls and links more libs), in the same location, and modify the source file as you need.
When you have played enough with it, for sure you'll find it quite easy to change the project file so that it'll use $(WXWIN) or any other custom settings.
p.s. I don't know what "wxWidgets template" from NuGet contains, but I strongly doubt it is provided by wxWidgets maintainers.
| |
doc_4461
|
Dim x As Double
Do
x = x + 0.1
Range("A" & Rows.count).End(xlUp).Offset(1).Value = x
Loop Until x = Range("b1").Value
A: Try converting the numbers during the comparison.
Private Sub this()
Dim i As Long, y As Double, x As Double
x = CDbl(ThisWorkbook.Sheets("Sheet1").Range("b1").Value)
Debug.Print ; x
y = 0
i = 1
For i = 1 To 999
ThisWorkbook.Sheets("Sheet1").Range("a" & i).Value = y
y = y + 0.01
Debug.Print ; y
If CLng(y) = CLng(x) Then
Exit For
End If
Next i
End Sub
OR
Private Sub this()
Dim i As Long, y As Double, x As Double
x = CDbl(ThisWorkbook.Sheets("Sheet1").Range("b1").Value)
Debug.Print ; x
y = 0
i = 1
For i = 1 To 999
ThisWorkbook.Sheets("Sheet1").Range("a" & i).Value = y
y = y + 0.01
Debug.Print ; y
If CStr(y) = CStr(x) Then
Exit For
End If
Next i
End Sub
A: Using as double can be problematic for EQUALS (long decimal) numbers. If you change your loop to be Loop Until x >= Range("b1").Value you should get desirable results.
A: you could "transpose" the whole problem to integer numbers and then divide them by 10 to get back decimals
Option Explicit
Sub main()
Dim iLoop As Long
For iLoop = 1 To Range("b1").Value * 10 + 1
Range("A" & iLoop).Value = (iLoop - 1) * 0.1
Next
End Sub
| |
doc_4462
|
this is my code i want to get input from user using "textbox" but this code dosent work.
please tell me how to get input from user in an int value.(c# gui)
A: TryPase first this method is called TryParse, then it returns bool. So what your code should look like:
int value;
if (!Convert.Int32.TryPase(textbox2.text, out value))
//Show error
A: Yes Andrey is correct. There are some other ways to do this as well, that don't use a boolean
int value = Convert.ToInt32(textbox2.Text);
int value = Int32.Parse(textBox2.Text);
A: int value;
if (Int32.TryParse(textbox2.Text), value)
{
// display error
}
See also:
How to: Convert a string to an int (C# Programming Guide)
| |
doc_4463
|
After 4 days importing this schema in a new cluster, I have just 10.000 tables imported. It´s normal? How Can I import this schema faster? Any suggestion?
Regards,
A: First off: seriously consider changing your data model. 40k tables is far beyond what Cassandra is designed to handle. Usually people get told to consider changing things at around 1000. Each table has a serious amount of overhead that must remain in memory and there are operations that fire off per-table tasks.
While you should test it something that could work as a hack is to turn a fresh new cluster completely off after starting it. Every node down. Then copy the system_schema tables from any one of your current nodes to all the new clusters nodes. You might need to create the folder structure as well for the keyspaces and tables. Then bring new cluster up. Test it out before trying it though but I believe that will work with 3.x.
| |
doc_4464
|
df['duration'] = df['start'] - df['end']
However, now the duration column is formatted as numpy.timedelta64, instead of datetime.timedelta as I would expect.
>>> df['duration'][0]
>>> numpy.timedelta64(0,'ns')
While
>>> df['start'][0] - df['end'][0]
>>> datetime.timedelta(0)
Can someone explain to me why the array subtraction change the timedelta type? Is there a way that I keep the datetime.timedelta as it is easier to work with?
A: This was one of the motivations for implementing a Timedelta scalar in pandas 0.15.0. See full docs here
In >= 0.15.0 the implementation of a timedelta64[ns] Series is still np.timedelta64[ns] under the hood, but all is completely hidden from the user in a datetime.timedelta sub-classed scalar, Timedelta (which is basically a useful superset of timedelta and the numpy version).
In [1]: df = DataFrame([[pd.Timestamp('20130102'),
pd.Timestamp('20130101')]],
columns=list('AB'))
In [2]: df['diff'] = df['A'] - df['B']
In [3]: df.dtypes
Out[3]:
A datetime64[ns]
B datetime64[ns]
diff timedelta64[ns]
dtype: object
# this will return a Timedelta in 0.15.2
In [4]: df['A'][0] - df['B'][0]
Out[4]: datetime.timedelta(1)
In [5]: (df['A'] - df['B'])[0]
Out[5]: Timedelta('1 days 00:00:00')
| |
doc_4465
|
import collections
students = collections.defaultdict(list)
while True:
student = input("Enter a name: ").replace(" ","")
if student == "0":
print ("A zero has been entered(0)")
break
if not student.isalpha():
print ("You've entered an invalid name. Try again.")
continue
while True:
grade = input("Enter a grade: ").replace(" ","")
if grade == "0":
print ("A zero has been entered(0)")
break
if not grade.isdigit():
print ("You've entered an invalid name. Try again.")
continue
grade = int(grade)
if 1 <= grade <= 10:
students[student].append(grade)
break
for i, j in students.items():
print ("NAME: ", i)
print ("LIST OF GRADES: ", j)
print ("AVERAGE: ", round(sum(j)/len(j),1))
I figured out a way how to make the program stop and post results after a 0 is entered in the "Enter a name: " part. This is what is printed out:
Enter a name: Stacy
Enter a grade: 8
Enter a name: 0
A zero has been entered(0)
NAME: Stacy
LIST OF GRADES: [8]
AVERAGE: 8.0
I need to do the same with the "Enter a grade: " part but if I try to make the program like it is now, this is what it prints out:
Enter a name: Stacy
Enter a grade: 0
A zero has been entered(0)
Enter a name:
How do I make the program show results like it does when a 0 is entered in the name input?
A: In one of your inputs, check to see if the input is 0. If it is, make a call to sys.exit. This can be done anywhere, even when checking for the grade. Just make sure that you include both options then (a string 0 and an int 0). Also, the reason for why it was still saying A zero has been entered(0) is because you are only quitting out of one loop, and then continuing from the beginning basically.
# Be sure to import sys!
random_place = input("Whatever is here ")
if random_place == '0' or random_pace == 0:
sys.exit(0)
Your program will exit then.
A: You should look into functions as they would save you a lot of hassle here, however here is a commented version of your code that will exit on either input being 0 and display the end message.
import collections
students = collections.defaultdict(list)
while True: #combined while loops
print ("Enter 0 for name or grade to exit") #you don't say how to exit
student = input("Enter a name: ").replace(" ","")
if student == "0":
print ("A zero has been entered(0)")
break
grade = input("Enter a grade: ").replace(" ","")
if grade == "0":
print ("A zero has been entered(0)")
break
#can combined if student == 0 or grade == 0, but then both inputs must display
if not student.isalpha() or not grade.isdigit():
print ("You've entered an invalid name or grade. Try again.")
#since these were the same message just combine them
#can switch to too if statements if you want seperate messages
#Also you might want to add a enter only alpha or digits for... message
break
grade = int(grade)
if 1 <= grade <= 10:
students[student].append(grade)
for i, j in students.items():
print ("NAME: ", i)
print ("LIST OF GRADES: ", j)
print ("AVERAGE: ", round(sum(j)/len(j),1))
| |
doc_4466
|
for (int x = 0; x < data.game.Length; x++)
for (int y = 0; y < data.game[x].LayerList.Length; y++)
{
int posX = data.game[x].LayerList[y].PositionOnMapX;
int posY = data.game[x].LayerList[y].PositionOnMapY;
InsertWord(data.game[x].LayerList[y].Word, data.game[x].LayerList[y].Direction, posX, posY, boardHeight);
}
}
and
private void InsertWord(string word, int direction, int positionX, int positionY, int boardHeight)
{
int x = positionX;
int y = boardHeight - positionY;
for (int i = 0; i < word.Length; i++)
{
string letter = word.Substring(i, 1);
tileText.text = letter;
Vector2 tempPosition = new Vector2(x, y);
/// Instantiate Background Tile
GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity, this.transform) as GameObject;
backgroundTile.name = letter + " ( " + x + "," + y + ")";
allTiles[x, y] = backgroundTile;
if (direction == 0)
x += 1;
else
y -= 1;
}
}
The objects are instantiated correctly. The problem is that they are instantiated in Screen View coordinates but I need to convert them to World Point because they are off the screen.
I tried to convert tempPosition to WorldCoordinates:
Vector3 screenVector = camera.ScreenToWorldPoint(new Vector3(x,y,10))
but all of the instantiated GameObjects get the same X,Y,Z (2.3 , 5, 0).
A: It is because you are passing world coordinates from here:
int posX = data.game[x].LayerList[y].PositionOnMapX;
You should scale the parent GameObject preferably to be in the center of the camera view.
You should do this based on the max tiles in X and max tiles in Y so its centered.
Like this, you parent object needs to be moved and scaled.
| |
doc_4467
|
I've tried to run the "Consuming Web Services" tutorial from Xamarin ( http://android.xamarin.com/index.php?title=Documentation/Guides/Consuming_Web_Services&file=58 ) but it doesn't work, neither on my 2.2 simulator, nor on my HTC Legend device.
When i click on the button, the application freeze for 3-4 seconds, I don't see any network activity on the status bar and then it crashes and close application.
Here's the console trace :
I/MonoDroid( 1358): UNHANDLED EXCEPTION: System.InvalidOperationException: A Binding must be configured for this channel factory
I/MonoDroid( 1358): at System.ServiceModel.ChannelFactory.EnsureOpened () <0x000f0>
I/MonoDroid( 1358): at System.ServiceModel.ChannelFactory`1<TestWS.soatest.parasoft.com.ICalculator>.CreateChannel () <0x00013>
I/MonoDroid( 1358): at System.ServiceModel.ClientBase`1<TestWS.soatest.parasoft.com.ICalculator>.CreateChannel () <0x0001f>
I/MonoDroid( 1358): at System.ServiceModel.ClientBase`1<TestWS.soatest.parasoft.com.ICalculator>.get_InnerChannel () <0x00033>
I/MonoDroid( 1358): at System.ServiceModel.ClientBase`1<TestWS.soatest.parasoft.com.ICalculator>.get_Channel () <0x00013>
I/MonoDroid( 1358): at TestWS.soatest.parasoft.com.CalculatorClient.add (single,single) <0x0001b>
I/MonoDroid( 1358): at TestWS.ThreadDemo.button_Click (object,System.EventArgs) <0x0007f>
I/MonoDroid( 1358): at Android.Views.View/IOnClickListenerImplementor.OnClick (Android.Views.View) <0x0005f>
I/MonoDroid( 1358): at Android.Views.View/IOnClickListenerAdapter.n_OnClick_Landroid_view_View_ (intptr,intptr,intptr) <0x00063>
I/MonoDroid( 1358): at (wrapper dynamic-method) object.191f2c9a-a458-4c04-ae08-d2241fd3ff65 (intptr,intptr,intptr) <0x00033>
E/mono ( 1358):
E/mono ( 1358): Unhandled Exception: System.InvalidOperationException: A Binding must be configured for this channel factory
E/mono ( 1358): at System.ServiceModel.ChannelFactory.EnsureOpened () [0x00000] in <filename unknown>:0
E/mono ( 1358): at System.ServiceModel.ChannelFactory`1[TestWS.soatest.parasoft.com.ICalculator].CreateChannel () [0x00000] in <filename unknown>:0
E/mono ( 1358): at System.ServiceModel.ClientBase`1[TestWS.soatest.parasoft.com.ICalculator].CreateChannel () [0x00000] in <filename unknown>:0
E/mono ( 1358): at System.ServiceModel.ClientBase`1[TestWS.soatest.parasoft.com.ICalculator].get_InnerChannel () [0x00000] in <filename unknown>:0
E/mono ( 1358): at System.ServiceModel.ClientBase`1[TestWS.soatest.parasoft.com.ICalculator].get_Channel () [0x00000] in <filename unknown>:0
E/mono ( 1358): at TestWS.soatest.parasoft.com.CalculatorClient.add (Single x, Single y) [0x00000] in <filename unknown>:0
E/mono ( 1358): at TestWS.ThreadDemo.button_Click (System.Object sender, System.EventArgs e) [0x00000] in <filename unknown>:0
E/mono ( 1358): at Android.Views.View+IOnClickListenerImplementor.OnClick (Android.
( yes it ends with Android. , i didn't cut it )
Could anyone help me on that ?
Regards,
C.Hamel
A: Apparently it was coming from the fact that I was using WCF implementation of web services when i had to use .NET 2.0.
| |
doc_4468
|
This is for a chat window and I want all the current users messages to display on one side and I want all other messages to display on the other side with a different color, etc.
I have a file.js.coffee that basically reads in some user input and apends it to an ordered list and adds some elements and classes along the way
projectRef.on "child_added", (snapshot) ->
message = snapshot.val()
$("<li class='self'>").append($("<div class='message'>").append($("<p>").text(message.text))).prepend($("<b/>").text(message.name + ": ")).appendTo $("#messagesDiv")
$("#messagesDiv")[0].scrollTop = $("#messagesDiv")[0].scrollHeight
$("#messageInput").keypress (e) ->
if e.keyCode is 13
text = $("#messageInput").val()
projectRef.push
name: userName
text: text
$("#messageInput").val ""
The above would yield something like this in the browser
<li class="self">
<b>User : </b>
<div class="message">
<p>My chatt message from file.js.coffee!!</p>
</div>
</li>
That 'self' class in the li is what I have been trying to dynamically set based on the current_user. So I have 2 issues - 1. I'm trying to figure out who posted the li and 2. I'm trying to dynamically set the class of that li based on the user that chatted/posted it.
My thinking was something along the lines of in the file.js.coffee use JQuery to grab that li and add the <%= current_user.name %> as a class then I could have a file.js.erb where I would do something like
<% unless $('li').hasClass('<%= current_user.name %>'); %>
<%= $('li').toggleClass('others') %>
<% end %>
This way it checks if the class of the target li is from the current user and if it is keep the css class as self if not toggle it to others. Then I could style the classes appropriately (left, right, background-color:blue;, etc).
Is there a more correct way to approach this problem given what I am trying to accomplish? I think so..
A: It seems like you are saying you're trying to assign a class as the current user's name.
I'm wondering if going that far is necessary.
Assigning the list element with a class named "current_user" might be enough, then have separate CSS to control anything with class named "current_user".
Here's an example fiddle.
CSS
li {
list-style:none;
clear:both;
float:right;
text-align:right;
background-color:#A7A2A0;
border:1px solid #EEE;
width:200px;
margin:10px;
padding:5px;
}
li.current_user {
float:left;
text-align:left;
background-color:#24887F;
}
HTML
<li class="current_user">
<b>Current User:</b>
<div class="message">
<p>My message!</p>
</div>
</li>
<li>
<b>All Other Users:</b>
<div class="message">
<p>Other person's smessage.</p>
</div>
</li>
UPDATE:
Looking at the firebase example I altered it to add a class "current_user" if the username matched the the name of the user that wrote the message. Below is the part of the code that I altered in the "displayChatMessage" function, I also added CSS to the head section for the "current_user" class.
Here's a link to the working example, view it in to different web browsers using different usernames at the same time to see.
function displayChatMessage(name, text) {
if(name == $('#nameInput').val()){
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv')).addClass('current_user');
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
}
else{
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
}
};
This is the CSS I added to the head.
<style type="text/css">
.current_user {
background-color:#24887F;
}
</style>
A: There are many users using the app concurrently. But for every user, there is only one current_user in session. Don't mix it up.
Since the message is to be processed by server, you can easily add a new attribute of message.klass in server side by judging the message comes from current_user. If it is, the class may be current, else blank or others.
Then, in JS
$('li').addClass('<%= message.klass %>')
| |
doc_4469
|
for example:
dev account: const config = require("config-dev.json")
prod account: const config = require("config-prod.json")
At first I tried passing it using build --container-env-var-file but after getting undefined when using process.env.myVar, I think that env file is used at the build stage and has nothing to do with my function, but I could use it in the template creation stage..
So I'm looking now at deploy and there are a few different things that seem relevant, but it's quite confusing to chose which one is relevant for my use case.
There is the config file, in which case, I have no idea how to configure it since I'm in a pipeline context, so where would I instruct my process to use the correct json?
There is also parameters, and mapping.
My json is not just a few vars. its a bit of a complex object. nothing crazy not simple enough to pass the vars 1 by 1.
So I thought a single one containing the filename that I want to use could do the job
But I have no idea how to tell which stage of deployment I currently am in, or how to pass that value to access it from the lambda function.
A: I also faced this issue while exectuing aws lambda function locally.By this command my issue was solved.
try to configure your file using the sam build command
| |
doc_4470
|
import { Common } from './CameraPlugin.common';
import { android } from 'tns-core-modules/application';
export class CameraPlugin extends Common {
constructor() {
super();
}
public takePicture() {
const cameraManager = new android.hardware.camera2.CameraManager();
cameraManager.openCamera();
}
}
A: NativeScript has native access to the Java/Kotlin (on Android) and ObjC/Swift (on iOS) devices with some minor limitations. (1)(2)
First you don't want/need to import "android" from anything; it is a valid global on all Android devices. So all you have to do is do android. (or java., or whatever namespace you need access too.) The import you did actually just hid the android global and replaced it with a different object which for sure doesn't have it.
One word of caution; unless you have installed the platform typescript typings, your editor will NOT know what android., android.hardware., etc are. When you go to actually run it; NativeScript will know what it is and use it just fine.
If you want your editor to know what it is, you need to install the platform typings:
npm i --save-dev tns-platform-declarations and you can read how to set them up here: https://github.com/NativeScript/NativeScript/tree/master/tns-platform-declarations
NativeScript documentation related to how the engine accesses the native code.
(1) - https://docs.nativescript.org/core-concepts/android-runtime/overview
(2) - https://docs.nativescript.org/core-concepts/ios-runtime/Overview
| |
doc_4471
|
Now I want to copy this password to my Open LDAP server. I have already copied SHA-256 password in the LDAP by using {SHA-256}+"Encrypted Password" and it worked fine.
Could anyone please help me out how can I import this SSHA-256 password to my LDAP server. Any help will be highly appreciated and thanks in advance.
A: What LDAP server is this? If it supports SSHA-256, then the same style i.e. {SSHA-256}+"Encrypted Password" should work.
| |
doc_4472
|
int main()
{
map<int,int> a;
for (int i = 0; i < 6; i++)
{
a.insert(make_pair(i, i+1));
}
map<int,int>::iterator it;
#pragma omp parallel for default(none) shared(a)
for (it = a.begin(); it != a.end(); it++)
{
printf("the first is %d\n", it->first);
}
return 0;
}
the code compilation fails. But I can use vector iterator, the code is as follows:
int main()
{
vector<int> vec(23,1);
vector<int>::iterator it;
// map<int,int>::iterator it;
#pragma omp parallel for default(none) shared(vec)
for (it = vec.begin(); it < vec.end(); it++)
{
printf("the number is %d\n", *it);
}
return 0;
}
the vector iterator can work correctly.How can I parallelize for loop with map iterator directly as the same way of using vector iterator? The newest OpenMP version (5.2) has been published, OpenMP website. Can I do this by the newest OpenMP API?
A: The iterator for a std::map is not a random-access-iterator, so it cannot be used as the control variable in an OpenMP parallel for loop. The iterator for a std::vector is a random access iterator, so it can be used.
The random access is necessary so that the OpenMP runtime can quickly advance the loop counter for each thread to its proper initial value (and the later iteration values it will compute for that thread).
| |
doc_4473
|
I want to validate the form however, prior to it launching the new window. I could use window.open instead, but then it can be blocked by popup blockers.
The problem I'm having is the validation uses ajax and the time it takes to get the response for return false, is too long and it opens the new window.
$('.submit').click(function(){
$.post("/ajax/save/", { state: $('.state_field').val() },
function(data) {
if(data == 'false'){
alert('invalid state');
return false;
}else{
return true;
}
}
);
});
Would anyone have suggestions as how I can workaround this?
Thank you!
A: (You should probably use $("form").submit(function() {}) because that also catches when somebody presses Enter in a textfield.)
What you could do is
*
*Don't include the target="_blank" in the form
*catch the submission and block it (preferably using event.preventDefault();)
*do the ajax call for validation
*from within the callback: add the target="_blank" and submit the form again (you could use a check like $("form[target]").length == 1 to see if the form is being submitted for the second time.
While this all can make it work, you should think about validating the form right after the user enters data in each field, this will also improve the user experience a lot.
A: Use the preventDefault method of the event at the beginning of your click.
$('.submit').click(function(event){
event.preventDefault();
[...]
This will stop your form from submitting and is a better solution than using return false;.
If you need to do a redirect after the ajax call you can do that the standard way:
window.location.replace([url to redirect to]);
A: Popup blockers block the new window if they are opened in script execution context. If the window is opened through user action then it is allowed. You can try to use jQuery ajax in synchronous mode this will solve your other part of the question because the function will not wait untill ajax response comes and you return true/false conditionally.
$('.submit').click(function(){
$.ajax({
url: "/ajax/save/",
type: "POST",
async: false,
data: { state: $('.state_field').val() },
success: function(data) {
if(data == 'false'){
alert('invalid state');
return false;
}else{
return true;
}
}
);
});
| |
doc_4474
|
Is it possible to turn it on by default?
I know that it's possible to use this.someMethod = this.ticksomeMethod.bind(this); trick do manually do this, but is it possible to do it for all methods? Or am I forced to write bind for all methods?
Example of code I have now:
import MessageStore from '../stores/MessageStore.js';
export default class Feed extends React.Component {
constructor() {
this.state = {messages: MessageStore.getAll()}
//can I avoid writing this for every single method?
this._onChange = this._onChange.bind(this);
}
_onChange() {
this.setState({messages: MessageStore.getAll()});
};
// componentDidMount, componentWillUnmount and render methods ommited
}
A: There is no feature to activate that does this in React currently. It's simply not an option.
You could post-process a class and automatically bind every function, but that's likely unnecessary in many classes, and adds overhead to every call (as your code will probably have a mixture of functions needing binding and some that don't).
You'll need to decide whether automatic adjustment is worth it or just using the bind syntax in the context of event callbacks, the typical place it's required in JavaScript, is acceptable.
A: There is a new solution using the elegant @decorator syntax.
You have to enable the JavaScript ES2015 stage-0 features for Babel, but after that it's a breeze!
You can then just write:
import autobind from 'autobind-decorator'
// (...)
<li onClick={ this.closeFeedback }>Close</li>
// (...)
@autobind
closeFeedback() {
this.setState( { closed: true } );
}
To get that to work, you need to install some build libraries. Here's how:
npm install --save-dev babel-preset-stage-0
npm install --save-dev babel-plugin-react-transform
npm install --save-dev babel-plugin-transform-decorators-legacy
npm install --save-dev autobind-decorator
Or wrap them all together in one command:
npm install --save-dev babel-preset-stage-0 babel-plugin-react-transform babel-plugin-transform-decorators-legacy autobind-decorator
After that change your .babelrc or webpack.config.js depending on where you specify your babel settings:
query: {
presets: ['es2015', 'react', 'stage-0'],
plugins: [['transform-decorators-legacy']]
}
(Note that in a .babelrc file the root node start at the query object.)
Good luck and don't forget the import statement!
A: If you don't want to or can't use the babel decorator syntax yet. You can define an autobind function and add a line of boiler-plate to your class to handle auto-binding.
function autobind(target) { // <-- Define your autobind helper
for (let prop of Object.getOwnPropertyNames(Object.getPrototypeOf(target))) {
if (typeof target[prop] !== 'function') {
continue;
}
if (~target[prop].toString().replace(/\s/g, '').search(`^${prop}[(][^)]*[)][{;][\'\"]autobind[\'\"];`)) {
target[prop] = target[prop].bind(target);
}
}
}
class Test {
constructor() {
autobind(this); // <- single line of boilerplate
this.message = 'message';
}
method1(){ return this.method2(); }
method2(){ console.log(this.message);}
_handleClick() { 'autobind'; // <-- autobind searches for functions with 'autobind' as their first expression.
console.log(this.message);
}
}
let test = new Test();
let _handleClick = test._handleClick;
_handleClick();
| |
doc_4475
|
Thank u
Code play exoplayer me :
try {
emVideoView.setOnPreparedListener(ExoActivity.this);
emVideoView.setVideoURI(Uri.parse("" + stream));
emVideoView.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError() {
return false;
}
});
} catch (Exception e) {
}
| |
doc_4476
|
I have an url that looks like article.php?id=1&replycomment=1 and what it does it that it shows the article from the databse with ID 1 and let you comment the comment in the database with the ID 1. What I want it to do when I go to that link is that it would add <blockquotes> around the comment you want to reply to, inside of the tinymce wysiwyg. I shouldn't have to tell people to add blockquotes manually... it doesn't seem right.
| |
doc_4477
|
Here is my Ant build file:
<project name="Main" basedir="." default="main">
<property name="src.dir" value="src"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.dir" value="lib"/>
<property name="main-class" value="myProject.Main"/>
<target name="clean">
<delete dir="${classes.dir}"/>
</target>
<target name="compile" depends="clean">
<mkdir dir="${classes.dir}"/>
<javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
<classpath>
<path location="${jar.dir}/dropbox-core-sdk-1.7.7.jar"/>
<path location="${jar.dir}/jackson-core-2.2.4.jar"/>
</classpath>
</javac>
</target>
<target name="jar" depends="compile">
<mkdir dir="${jar.dir}"/>
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
<manifest>
<attribute name="Main-Class" value="${main-class}"/>
</manifest>
</jar>
</target>
<target name="run" depends="jar">
<java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
</target>
<target name="clean-build" depends="clean,jar"/>
<target name="main" depends="clean,run"/>
this generates the following errors:
Buildfile: /Users/Phil/Documents/Java workspace/DropBoxProgram/build.xml
clean:
[delete] Deleting directory /Users/Phil/Documents/Java workspace/DropBoxProgram/build/classes
compile:
[mkdir] Created dir: /Users/Phil/Documents/Java workspace/DropBoxProgram/build/classes
[javac] Compiling 7 source files to /Users/Phil/Documents/Java workspace/DropBoxProgram/build/classes
jar:
[jar] Building jar: /Users/Phil/Documents/Java workspace/DropBoxProgram/lib/Main.jar
run:
[java] Error: A JNI error has occurred, please check your installation and try again
[java] Exception in thread "main" java.lang.NoClassDefFoundError: com/dropbox/core/DbxException
[java] at java.lang.Class.getDeclaredMethods0(Native Method)
[java] at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
[java] at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
[java] at java.lang.Class.getMethod0(Class.java:3018)
[java] at java.lang.Class.getMethod(Class.java:1784)
[java] at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
[java] at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
[java] Caused by: java.lang.ClassNotFoundException: com.dropbox.core.DbxException
[java] at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[java] ... 7 more
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 1 second
I really appreciate any help!
A: I had the same error. Turns out that Eclipse was using a symlink in the Eclipse setup for Ant Home (external ant installation).
I solved it by changing Eclipse's Ant Home to a definitive location.
In Eclipse Window->Preferences then Ant->Runtime then click on the Ant Home... button on the right and choose the correct Ant install directory.
A: You compiled with the classpath set to the dropbox-core-sdk-1.7.7.jar jar, but you didn't run the code with that classpath. You need to do the same for the java task, otherwise the JVM won't find the third-party classes.
<java jar="${jar.dir}/${ant.project.name}.jar" fork="true">
<classpath>
<path location="${jar.dir}/dropbox-core-sdk-1.7.7.jar"/>
<path location="${jar.dir}/jackson-core-2.2.4.jar"/>
</classpath>
</java>
| |
doc_4478
|
Running Gradle task 'assembleDebug'...
Exception: Gradle task assembleDebug failed with exit code -1
this is the error showing in the run log when im trying to run the demo flutter codes.
| |
doc_4479
|
1- When I try with Filezilla, I connect.
2- I did tracert in cmd and I got the error 'Destination host unreachable'. And I opened Telnet Client in windows features. But this time I got error 'Rewuest timed out.'
3- I closed Windows firewall but still the same.
By the way, Ftp server name is starting with sftp. Could it be related to this?
Why is this happening?
A: SFTP and FTP are totally different protocols. Filezilla supports both, that's why it connects. SFTP is a protocol that is run over SSH usually on port 22.
FTPWebRequest doesn't support SFTP protocol. There exist many third-party components for SFTP, including our SecureBlackbox (free license for SFTP is available), SSH.NET on codeplex etc..
| |
doc_4480
|
I tried using the fetch() when I console.log, I see the array of products. My problem is how to output these products from the API.
Please help me debug, I've tried different approaches but I've always been stocked at this point. Thank you.
Product.js file
import React, { useEffect, useState } from "react";
const Products = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(false);
const { title, image, price, category } = products;
useEffect(() => {
getProducts();
// eslint-disable-next-line
}, []);
const getProducts = async () => {
setLoading(true);
const res = await fetch("https://fakestoreapi.com/products");
const data = await res.json();
setProducts(data);
setLoading(false);
console.log(data);
};
if (loading) {
return <h4>Loading.....</h4>;
}
return (
<div>
{!loading && products.length === 0 ? (
<p className='center'>No logs to show....</p>
) : (
products.map((product) => (
<div class='card' style={{ width: "18rem" }} key={products.id}>
<img src={image} class='card-img-top' alt='...' />
<div class='card-body'>
<h5 class='card-title'>Card title</h5>
<p class='card-text'>
Some quick example text to build on the card title and make up
the bulk of the card's content.
</p>
</div>
<ul class='list-group list-group-flush'>
<li class='list-group-item'>{title}</li>
<li class='list-group-item'>$ {price}</li>
<li class='list-group-item'>{category}</li>
</ul>
<div class='card-body'>
<a href='#' class='card-link'>
Card link
</a>
<a href='#' class='card-link'>
Another link
</a>
</div>
</div>
))
)}
</div>
);
};
export default Products;
A: You have to first destructure the properties that you are trying to use in you JSX (title, price, category), then you can show them.
products.map((product) => {
const { title, price, category } = product;
return (****your JSX goes here***)})
A: I don't know too. But this worked for me.
products.map(({ title, image, price, category }, index) => (
<div key={index} class='card' style={{ width: "18rem" }} key={products.id}>
<img src={image} class='card-img-top' alt='...' />
<div class='card-body'>
<h5 class='card-title'>Card title</h5>
<p class='card-text'>
Some quick example text to build on the card title and make up
the bulk of the card's content.
</p>
</div>
<ul class='list-group list-group-flush'>
<li class='list-group-item'>{title}</li>
<li class='list-group-item'>$ {price}</li>
<li class='list-group-item'>{category}</li>
</ul>
<div class='card-body'>
<a href='#' class='card-link'>
Card link
</a>
<a href='#' class='card-link'>
Another link
</a>
</div>
</div>
))
)}
You need to add { title, image, price, category } in the map function. I think it is because the map function doesn't know what is { title, image, price, category } variables and you need to add a key every time you use the map function and don't forget to change class= to className.
A: You can simply use product?.title ,product?.price,product?.category to access individual fields.
This approach is better than the other as you will not get an error for the field that is not in the API.
| |
doc_4481
|
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("input.txt"));
}
catch(Exception e){
System.out.println("Oh noes, the file has not been founddd!");
}
}
public void readFile(){
int n = 0;
n = Integer.parseInt(x.next()); //n is the integer on the first line that creates boundaries n x n in an array.
System.out.println("Your array is size ["+ n + "] by [" + n +"]");
//Create n by n array.
int[][] array = new int[n][n];
//While there is an element, assign array[i][j] = the next element.
while(x.hasNext()){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
array[i][j] = Integer.parseInt(x.next());
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}
}
public void closeFile(){
x.close();
}
}
I'm reading a text file that contains an adjacency matrix, where the first line indicates how large the matrix will be. ie) line 1 reads 5. Therefore I create a 2d array that is 5x5. The problem I'm having is after I read the file and print it, I get a NoSuchElement Exception. Thanks ahead of time!
Note: I am curious, I've seen that I need to user x.hasNext() when in a loop, so I do not assume there is input when there isn't. However, I've done this. Not sure what the problem is.
Output:
Your array is size [7] by [7]
0110011
1000000
1001000
0010001
0000001
1000001
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at readfile.readFile(readfile.java:32)
at verticies.main(verticies.java:8)
A: It looks like your code is reading a whole line as an int, is each of those numbers:
0110011 1000000 1001000 0010001 0000001 1000001
meant to be the 7 digits forming each row?
If that is the case, you need to split each value into the its component parts for its corresponding sub array.
In which case, use this section of code instead:
while(x.hasNext()){
for(int i = 0; i < n; i++){
String line = x.next();
for(int j = 0; j < n; j++){
array[i][j] = line.charAt(j) - '0';
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}
| |
doc_4482
|
Here is a link to a sample page:
http://merkd.com/community
Here is the relevant function:
// searchInput is a jQuery reference to the <input> field
// searchTextColor is the original font color of the unfocused form
// searchText is the original search text
$('#header form').on('blur', 'input', function() {
searchInput.css('color', searchTextColor);
// When I comment these lines out, it doesn't move
if ( searchInput.val() == '' ) {
searchInput.val(searchText);
}
});
To see the glitch, type some text into the search field, then delete it and blur the search form, the input field will move to the left.
Any idea why this would be happening? Like I said, if I don't change the text then it doesn't move. I don't know how this would be affecting the position of the element within the page.
A: Problem
this is happen that's why the problem is occur
see in firebug
<input type="text" value="Search Teams, Players, Etc." name="search">
<img title="Search" alt="Search" src="/engine/themes/img/search.white.focus.png">
<input type="submit" value="Search Teams, Players, Etc.">
solution
$('#header form').on('blur', 'input[name=search]', function() {// not use input other wise valuse also set in submit input box
searchInput.css('color', searchTextColor);
// When I comment these lines out, it doesn't move
if ( $(this).val() == '' ) {
$(this).val(searchText);
}
});
| |
doc_4483
|
I'm trying to send this object through a REST service, but it just sends the empty string instead of the correct value.
What is going on here? I've used these kind of strings before and it worked fine, but now it looks like I'm missing something important.
To make it clear, this gets the above output:
console.log(myObject);
This prints an empty string:
console.log(myObject.Value);
EDIT:
This is how the Value is assigned:
for (var i = 0; i < vm.data.profileSettings.length; i++) {
(function (i) {
var setting = vm.data.settings.filter(function(setting) { return setting.Id == vm.data.profileSettings[i].Id });
if (setting[0].Type == 2 && vm.data.profileSettings[i].copiedValue && typeof(vm.data.profileSettings[i].copiedValue) == 'object') {
Upload.base64DataUrl(vm.data.profileSettings[i].copiedValue)
.then(function(response) {
var splitted = response.split(",");
vm.data.profileSettings[i].Value = splitted[1];
});
}
})(i);
}
profileDataService.saveProfileSettings(vm.data.selectedProfile.Id, vm.data.profileSettings)
.then(function(response) {
vm.success = true;
});
A: Upload() is asynchronous so you need all the Upload to complete before you send your final data since that data is dependent on responses from uploads.
You can create array of upload promises and use $q.all() to run code when all of those promises have resolved
Create empty array before the loop and push each upload promise into that array
var uploadPromises = []
Then change
Upload.base64DataUrl(vm.data.profileSettings[i].copiedValue)
.then(function(response) {
// do stuff with response
});
To
var req = Upload.base64DataUrl(vm.data.profileSettings[i].copiedValue)
.then(function(response) {
// do stuff with response
});
uploadPromises.push(req);
Now wrap your final request
$q.all(uploadPromises ).then(function(){
profileDataService.saveProfileSettings(...)
}).catch(function(err){
// do something when any upload promise is rejected
});
Note you will need to determine strategy if any upload promise gets rejected. You can use a catch on upload promises themselves to also resolve that promise if that's what you want to do so final request will always be made
A: Im guessing that your long String is a file encoded to base64.
Then you can use btoa() and atob() to convert to and from base64 encoding.
You can have a look at this answer:
https://stackoverflow.com/a/247261/2886514
| |
doc_4484
|
import numpy as np
import matplotlib.pyplot as plt
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Just print x and y for fun
print(x)
print(y)
# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)
# Without the line below, the figure won't show
plt.interactive(False)
plt.show()
i addded some comments for more readability..
however when i run the script, nothing is showing in the SciView window in pycharm. Why would that be? I looked into other resources, that set the plt.interactive(False) might help, but i have tried both options without any luck, can anybody help?
| |
doc_4485
|
accounts = me.get_ad_accounts(fields=['name', 'account_status'])
accounts_list = list(accounts)
for accounti in accounts_list:
campaign = accounti.get_ad_campaigns(fields=[facebookads.objects.AdCampaign.Field.name])
campaign_list = list(campaign)
for campaigni in campaign_list:
adset = campaigni.get_ad_sets(fields=["name"])
adset_list = list(adset)
for adseti in adset_list:
adgroups = adseti.get_ad_groups()
adgroups_list = list(adgroups)
for adgroupi in adgroups_list:
adgroup = AdGroup(str(adgroupi["id"]))
adgroup.remote_read(fields=[AdGroup.Field.name, AdGroup.Field.campaign_id])
adgroup_conv = accounti.get_ad_group_conversion_stats()
print accounti["name"]+", "+campaigni["name"]+", "+adseti["name"]+", "+str(adgroupi["id"])
I get the following Error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python27\lib\site-packages\facebookads\objects.py", line 1283, in get_conversion_stats
return self.edge_object(ConversionStats, fields, params)
File "C:\Python27\lib\site-packages\facebookads\objects.py", line 708, in edge_object
params=params
File "C:\Python27\lib\site-packages\facebookads\objects.py", line 96, in __next__
if not self._queue and not self.load_next_page():
File "C:\Python27\lib\site-packages\facebookads\objects.py", line 125, in load_next_page
for json_obj in response['data']:
KeyError: 'data'
The documentation for this object and method can be found here:
https://github.com/facebook/facebook-python-ads-sdk/blob/master/facebookads/objects.py
I can't figure out what's wrong, and I'd appreciate any help you can give me.
Thanks!
| |
doc_4486
|
i get the images from a server, then convert to byte array and then to base64 string to send to index in
data:image/webp;base64,{0}
i use this:
Html.Raw(String.Format("data:image/webp;base64,{0}", Convert.ToBase64String(File.ReadAllBytes("\\\\ImageServer\\ImagePathFolder\\Image.JPG".Replace("\\", "\\\\")))))
so far the index takes to load about 24 seconds.
I ask for help to compress the images and get at least the half size now i get.
NOTE: all this code in in ASP.NET MVC with C#
A: You should return binary-large-objects ("BLOBs", generally anything larger than a kilobyte or so) in a separate request - this has numerous advantages, but the main reasons are
*
*Browsers can cache individual responses and images.
*They can be transferred directly without encoding them using an inefficient format like Base64 (which effectively uses 1 byte to transfer 6 bits of data).
Whereas using data: URIs to include images inline in the page is wasteful because the image data needs to be loaded and encoded to Base64 on every request. Avoid disk IO when you can (additionally your code isn't using Async IO, so it's particularly inefficient).
In ASP.NET MVC and ASP.NET Core, define a new Action to handle requests for images:
[HttpGet("images/{imageName}")]
public ActionResult GetImage( String imageName )
{
String imagefileName = GetImageFileName( imageName ); // don't forget to sanitize input to prevent directory traversal attacks
// Use `FileResult` to have ASP.NET MVC efficiently load and transmit the file rather than doing it yourself:
return new FilePathResult( imagefileName, "image/jpeg" ); // assuming all images are JPEGs.
}
In your page, use an <img /> element like so:
<img src="@( this.Url.Action("GetImage", new { imageName = "foo" } ) )" />
In ASP.NET WebForms you'll need to use an *.ashx instead, but the principle is the same.
| |
doc_4487
|
I thought about using UseEffect with UseRef and it worked for the initial rendering but doesn't update when any property of the reference changes e.g. due to scrolling.
How can I watch for changes of my reference? Thx!
Here is my code:
const triggerRef = useRef(null)
const [popupStyles, setPopupStyles] = useState({})
useEffect(() => {
if (triggerRef.current) {
setPopupStyles({
width: `${triggerRef.current.offsetWidth}px`,
left: `${triggerRef.current.offsetLeft}px`,
top: `${triggerRef.current.offsetTop + triggerRef.current.offsetHeight}px`
})
}
}, [triggerRef])
return (
<>
<button ref={triggerRef} onClick={() => setState(!state)}>
Open Popup
</button>
<div className="z-50 fixed" ref={popupRef}>
{state && (
<div style={popupStyles} className="form-input opacity-75">
Popup content
</div>
)}
</div>
</>
)
A: Watch the ref element via scroll on page, set the state of the current value and watch the state
Example:
Init state & ref
const [offset, setOffset] = useState(null);
const myRef = useRef(null);
Watch ref element on scroll
useEffect(() => {
window.onscroll = () => {
const refHtmlElement = myRef?.current;
if (refHtmlElement) {
setOffset(refHtmlElement.getBoundingClientRect().top);
}
};
}, [myRef]);
Watch updated state
useEffect(() => {
console.log('!!! offset: ', offset);
}, [offset]);
HTML
<div ref={myRef}>MyRef</div>
| |
doc_4488
|
I'm going to delete my numerous comments and limit myself to a few questions on it.
1. Is FILE a keyword in Obj-C? What is its function? Why all caps?
2. What does "r" do?
3. The text file already has strings containing empty spaces, each ending with \n; why not make them NSStrings instead of c-strings?
4. Why, when I try to change the launch parameter of the file (using executables, clicking on arguments and plus, and typing in the parameter) to anything other than /tmp (such as /Desktop), do I get errors? After all, /tmp is a volatile, vulnerable place. This is the error I got for /Desktop: The Debugger has exited due to signal 10 (SIGBUS).
Here's the code:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
if (argc == 1)
{
NSLog(@"You need to provide a file name");
return 1;
}
FILE *wordFile = fopen(argv[1], "r");
char word[100];
while (fgets (word, 100, wordFile))
{
word[strlen(word) - 1] = '\0';
NSLog(@"%s is %d characs long", word, strlen(word));
}
fclose (wordFile);
[pool drain];
return 0;
}
A: Most of this is standard C stuff, it happens to be compiled as objective-c but FILE and fopen() and fgets() are plain old fashioned C.
FILE is presumbably a #define'd somewhere to refer to a structure definition. It is not a keyword, just a regular symbol defined (I think) in stdio.h.
"r" means "readable". Look up fopen for all the values that argument can have, but "r", "r+", "b", "a", "w" etc are some of the options.
Are you sure /Desktop is a valid directory? Change to that directory in a console window and type "pwd" to make sure youve got the right path. You might want to have an error message if wordFile is null (i.e. couldn't find the file or open it for some reason) before trying to use fgets on it.
| |
doc_4489
|
1) R text mining toolbox: Meant for local (client side) text processing and it uses the XML library
2) Hive: Hadoop interative, provides the framework to call map/reduce and also provides the DFS interface for storing files on the DFS.
3) RHIPE: R Hadoop integrated environment
4) Elastic MapReduce with R: a MapReduce framework for those who do not have their own clusters
5) Distributed Text Mining with R: An attempt to make seamless move form local to server side processing, from R-tm to R-distributed-tm
I have the following questions and confusions about the above packages
1) Hive and RHIPE and the distributed text mining toolbox need you to have your own clusters. Right?
2) If I have just one computer how would DFS work in case of HIVE
3) Are we facing with the problem of duplication of effort with the above packages?
I am hoping to get insights on the above questions in the next few days
A: (1) Well Hive and Rhipe dont need cluster, you can run them on single node cluster.
RHipe basically is a framework (in R language a package) which integrates R and Hadoop and you can leverage the power of R on Hadoop. For using Rhipe you don't need to have a cluster, you can run in either way i.e. either in cluster mode or pseudo mode. Even if you have Hadoop cluster of more than 2 nodes you can still use Rhipe in local mode by specifying the property mapered.job.tracker='local'.
You can go to my site (search for) "Bangalore R user groups" and you can see how i have tried solving the problems using Rhipe, i hope you can get a fair idea
(2)Well by Hive means do you mean hive package in R? since this package is somewhat misleading with Hive (hadoop data ware house).
The hive package in R is similar to Rhipe only with some additional functionalites( i have not gone through fully)..The hive package when i saw i thought they have integrated R with Hive, but after seeing the functionality it was not like dat.
Well Hadoop data ware house which is HIVE, is basically if you are interested in some subset of results which should run through subset of data, which you normally do using SQL queries. The queries in HIVE also are very much similar to SQL queries.
TO give you a very simple example: lets say you have 1TB of stock data for various stocks for last 10 years. Now the first thing you will do is, you will store on HDFS and then you create a HIVE table on top of it. Thats it...Now fire whatever query you wish. You also might want to do some complex calculatiion also like finding simple moving average (SMA), in this case you can write your UDF (userr defined function). Besides this you can also use UDTF( User defined table generating function)
(3) If you have one system that means you are running Hadoop in pseudo mode. Moreover you need not worry whether Hadoop is running on pseudo mode or cluster mode,, since Hive needs to be installed only on NameNode, not on the data nodes. Once proper configuration is done,hive will take care of submitting the job on cluster.
Unlike Hive, you need to install R and Rhipe on all the data nodes including NameNode. But then at any point of time if you want to run the job only in NameNode you can do as i mentioned above.
(4) One more thing Rhipe is meant for only batch jobs, that means the MR job will run on the whole data set while Hive you can run on subset of data.
(5)I would like to understand what exactly you are doing in text mining, are you trying to do some king of NLP stuff like Name Entity Recognition using HMM (Hidden Markov Models), CRF(Condition Random fields), feature vectors or SVM (Support Vector machines).
Or you simple trying to to do document clustering, indexing etc
Well there are packages like tm,openNLP,HMM,SVM etc
A: I'm not familiar with the distributed text mining with R application, but Hive can run on a local cluster or on a single-node cluster. This can be done for experimenting or in practice, but does defeat the purpose of having a distributed file system for serious work. As far as duplication of effort, Hive is meant to be a complete SQL implementation on top of Hadoop, so there is duplication in as much as both SQL and R can both work with text data, but not in as much as both are specific tools with different strengths.
| |
doc_4490
|
Folder
- .htaccess
- Subfolder
- Otherfolder
- file1.html
- file2.html
- filea.html
- fileb.html
I can have many folders at the place of 'otherfolder' and I don't want to add code for each subfolder of 'Subfolder'.
i want to remove all other subfolders names except folder.
I just want to get URL like - mywebsite.com/folder/file.html
Edit
currently I am using this code snippet in .htaccess
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^subfolder/([^.]+)\.html$ /folder/$1 [L,R]
RewriteCond %{REQUEST_URI} !/folder/subfolder/
RewriteCond %{REQUEST_URI} !\.(css|js|jpg|gif|png|jpeg)$
RewriteRule ^(.+)/?$ /folder/subfolder/$1.html [L]
A:
I can have many folders at the place of 'otherfolder' and I don't want to add code for each subfolder of 'Subfolder'.
This isn't possible in .htaccess alone. The problem is not in removing the subfolder from the URL (although this should already have been done in the internal link), the problem is internally rewriting the request back to the appropriate subfolder. There is no built-in mechanism to "search" for arbitrary files in .htaccess.
If you have a limited number of known subfolders then you can do this, but you need to add a rule (in the root .htaccess file) for every subfolder. However, this is not particularly efficient since you need to manually test for the existence of that file in each subfolder. You also have a potential problem of name collision. Obviously, if you effectively "flatten" the filesystem the file file1.html can only exist once on the filesystem, amongst all subfolders. If there is more than one file1.html then the first match wins.
In principle, you would need to do something like the following to rewrite a request for /folder/<file>.html back to /folder/subfolder/otherfolderN/<file>.html.
# Test "subfolder/otherfolder1"
RewriteCond %{DOCUMENT_ROOT}/folder/subfolder/otherfolder1/$0 -f
RewriteRule ^[^/.]\.html$ subfolder/otherfolder1/$0 [L]
# Test "subfolder/otherfolder2"
RewriteCond %{DOCUMENT_ROOT}/folder/subfolder/otherfolder2/$0 -f
RewriteRule ^[^/.]\.html$ subfolder/otherfolder2/$0 [L]
# Test "subfolder/otherfolder3"
RewriteCond %{DOCUMENT_ROOT}/folder/subfolder/otherfolder3/$0 -f
RewriteRule ^[^/.]\.html$ subfolder/otherfolder3/$0 [L]
The parent /folder/ could be abstracted out of the RewriteCond TestString if you wish, but the subfolder and otherfolderN would need to be hardcoded. (Although subfolder could be manually assigned to an environment variable to save repetition.)
Aside:
RewriteCond %{REQUEST_URI} !/folder/subfolder/
RewriteCond %{REQUEST_URI} !\.(css|js|jpg|gif|png|jpeg)$
RewriteRule ^(.+)/?$ /folder/subfolder/$1.html [L]
A "problem" with this code is that it rewrites the request regardless of whether the target file exists or not. This is OK if you are rewriting all requests to a single subfolder, but if you have multiple subfolders then you must check for the target file's existence before rewriting.
This also rewrites the request even if it already maps to an existing file. So any legitimate files in the /folder/ directory (eg. filea.html and fileb.html in your file structure) would not be accessible.
This also rewrites every file type (except for the few file extensions listed in the preceding condition). It would, for instance rewrite a request for foo/bar/file.webp to /folder/subfolder/foo/bar/file.webp.html. If you are only wanting to rewrite .html files then include this in the RewriteRule pattern and the preceding condition is not required.
| |
doc_4491
|
UserID Purchased
A Laptop
A Food
A Car
B Laptop
B Food
C Food
D Car
Now I want to find all the unique combinations of purchased products and number of unique users against each combination. My data set has around 8 different products so doing it manually is very time consuming. I want end result to be something like:
Number of products Products Unique count of Users
1 Food 1
2 Car 1
2 Laptop,Food 1
3 Car,Laptop,Food 1
A: # updated sample data
d = {'UserID': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B', 5: 'C', 6: 'D', 7: 'C'},
'Purchased': {0: 'Laptop',
1: 'Food',
2: 'Car',
3: 'Laptop',
4: 'Food',
5: 'Food',
6: 'Car',
7: 'Laptop'}}
df = pd.DataFrame(d)
# groupby user id and combine the purchases to a tuple
new_df = df.groupby('UserID').agg(tuple)
# list comprehension to sort your grouped purchases
new_df['Purchased'] = [tuple(sorted(x)) for x in new_df['Purchased']]
# groupby purchases and get then count, which is the number of users for each purchases
final_df = new_df.reset_index().groupby('Purchased').agg('count').reset_index()
# get the len of purchased, which is the number of products in the tuple
final_df['num_of_prod'] = final_df['Purchased'].agg(len)
# rename the columns
final_df = final_df.rename(columns={'UserID': 'user_count'})
Purchased user_count num_of_prod
0 (Car,) 1 1
1 (Car, Food, Laptop) 1 3
2 (Food, Laptop) 2 2
| |
doc_4492
|
I want to swap 2 images when I move the mouse over and out an object on my webpage.
I would like to know for both cases:
- css-background images assigned to , , elements (image url is in css file)
- elements (image url is in html code)
I'm currently using jQuery for it. But the problem is that the second image is always showed with a bit of delay the first time a roll-over event occurs, because it needs to be loaded.
NB. I need a solution compatible with all browsers! (IE 6-7 not required. IE 8, Firefox, Safari, Chrome...)
thanks
A: Use CSS sprites.
Because "both" images are downloads at once - they will appear instantly for the user.
A: You can use CSS sprite in this situation.
You can also read What are the advantages of using CSS sprites?
A: Define two class like (clsImg1,clsImg2) and define images to their backgrounds.
You should change the classNames while mouseover-mouseout events called
A: You can try to load the image with jQuery before showing this way:
$('img').attr('src', 'YOUR_IMAGE_PATH').hide().appendTo('html');
| |
doc_4493
|
Here I reproduced a snippet with a working example (which when clicking on a section brings you to the following one); Problem is this works only on versions below v6.0.0.
As you can notice on index.js, I added a commented line with a component which contains the exact same logic but converted to v9.1.2 (which doesn't work).
So question is, what part did I convert wrongly? I am probably missing some bits from breaking changes on v6 and I tried looking into the documentation, but they reference to breaking changes for v8 and v9 only, so I'm a bit confused on what I'm missing?
Any answer with a working solution it's perfectly fine, doesn't need to be based on my example - big thank you in advance!
A: The version 9.1.2 seems to have some bugs which might be causing this. I found an issue which also states the same problems. (Also, the original issue that found this)
So, according to their releases, version 9.2.0 or upwards would have this issue fixed. I tried 9.2.1 (latest at the time of this answer) in the sandbox provided in the question and it works:
Forked Sandbox (working)
| |
doc_4494
|
Possible Duplicate:
How to run a terminal inside of vim?
I can setup my workspace nicely with split and vsplit and open... but I would
like to simply use one of the splits as a terminal window. I know opening an
additional xterm and placing it strategically might be able to accomplish this
but many times I am telneted into a single window and my hands are beginning to hurt
from alt tabbing between terminals.
Update: The best thing I came up with based on the suggestions below was to use screen and actually have vim occupy one of its windows.
A: The vimshell patch sounds like what you're looking for.
A: If you're in vim, you can exit to a sub-shell with the ":sh" command, and then get back to vim with "exit". Or you can just suspend vim and go back to the original shell you started it from with control-Z, then go back to vim with "fg" (foreground).
Or there is an "vim-shell" add-on you can install.
A: Expanding on Brian Carper's answer, you could throw this into your
~/.screenrc:
startup_message off
# Launch 2 screens on startup
split
# Have bash login so $PATH will be updated
screen -t Vim bash -l -c 'vim' 0
focus
screen -t canvas bash -l
# switch focus back to vim
focus up
Then when you type screen, you'll have a Vim window on top and
a bash window on the bottom. You can switch between screen windows with
<C-a><Tab>.
A: conque shell for vim does this too.
http://www.vim.org/scripts/script.php?script_id=2771
http://code.google.com/p/conque/
A: I use : http://code.google.com/p/conque/wiki/Usage
You can type :split new and the :ConqueTerm bash. And you have a working terminal window. :)
A: Consider running Vim and a shell together in GNU Screen. The Vim wiki has info on integrating Vim and Screen. Screen supports splitting into "windows" similar to Vim's. See here for an example of even tighter Vim+Screen integration.
Having a Vim buffer tied directly to an external interactive commandline app is a feature that many have wanted for a long time, but apparently it's a bit difficult to do, due to how Vim is implemented, and the Vim devs are reluctant to change this (for arguably good reasons).
But there have been a few success stories. The Lisp community in particular has tried to reproduce Emacs' SLIME (an interactive Lisp prompt) in Vim. See VimClojure and Limp for examples. One of those could probably be altered to run a shell, but it'd take some work.
A: You will have to forgo this I'm afraid - no way to do it in vim.
| |
doc_4495
|
mvn clean install -PBrandADev
you get Brand A's Dev profile, with the corresponding application.properties and other config files, and if you build it with
mvn clean install -PBrandBProd
you get Brand B's production profile. This is important to me because it controls which CMS I'm connecting to, and thus I'm able by building as Brand B Prod to run an instance of the Prod environment in debug & see what's going wrong when there's a bug, or otherwise to build the Dev profile for the development work I'm doing, to plug into the Dev CMS.
As it's a Spring Boot app, in the resources directory for each profile we have a banner.txt file that says "Brand A - Dev" or "Brand A - QA" or whatever the brand & CMS is for that profile.
Just lately though, I'm building for a particular profile, e.g. I want Brand B's Preview-Prod environment, and I see when it starts up for its integration tests "Brand B - Preview-Prod", which is as should be expected, but then when I start it up using the Application config item in the Run/Debug configurations widget at the top of the screen, it starts up saying "Brand A - Dev"
I've tried cleaning & reinstalling the app. I've tried re-importing the maven dependencies. I've tried invalidating the cache and restarting the IDE. I've tried deselecting all the profiles and reselecting the one I need. No joy. Except, just earlier today, it worked, and then I tried to swap back to the Dev environment & it got stuck on Prod. Does anyone know what I can do to force it to use the profile it's built with? Is this a bug in IntelliJ or what?
A: A possible reason of such behaviour could be the Run Configuration used to start the application which builds it using default profile before starting the application. Verify Before Launch section of the configuration.
As a workaround, create a Run Configuration per profile you'd like to start, and specify -Dspring.profiles.active=<PROFILE-NAME> in the VM Options of the run configuration. Additionally, you could build the application using the same profile before starting it, adjust the Before Launch section accordingly.
A: You can use the spring-boot maven plugin instead.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
This allows you to use mvn spring-boot:run -PBrandADev and start the spring boot application with the correct maven profile.
| |
doc_4496
|
I need to do this in R since this step is part of a longer pipeline for machine learning, and I am trying to implement the whole pipeline within a single environment to minimize headache.
I have found an answered questions slightly related to the present one here. However, in that case, the number of clusters was known beforehand, while in my case the number of clusters could be anything from 1 to the number of instances equal to 1 (provided that no instance is neighbour with another one).
I could write a function to this aim, but it would be time consuming and probably not very efficient, as I cannot think to any other strategy than looking for non-zero instances, check every neighbour instances, if any of these is non-zero, than check its neighbours and so on.
Since the clustering step is included in a nested-cross validation loop you can see for yourself that I would need something more efficient (or maybe just the same thing written in C, in order to be faster).
Is any of you aware of any function or package that could help me ?
Update
To answer to a comment, my "sparse" array is sparse in the sense that most of the elements are zero, not in the sense that it is saved in a sparse format.
Here a toy example (that is indeed a crop around the non-zero elements of my original array, that have dim (91,109,91)).
sparse_array = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0), .Dim = c(13L, 3L, 6L))
Update 2
I am working on a Windows x64 machine, with RStudio 1.0.153 and R version 3.4.2 (Short Summer)
Update 3
I have tried the answer given by @gdkrmr, and while it works fine for the example given, it fails to generalize to bigger and more complex images. Specifically, it over-segregates the clusters in my image, meaning that voxels that do indeed touch each other are sometimes split in different clusters.
You can visualize it yourself downloading this image and running the following code
read 3d images
library(oro.nifti)
roi <- readNIfTI("image_to_cluster.nii")
roi_img <- cal_img(roi)
read data as array
array_img <- roi@.Data
transform in sparse format
sparse_format <- (array_img > 0) %>%
which(., arr.ind = TRUE)
find neighbouring voxels
neighborhoods <- sparse_format %>%
dist %>%
as.matrix %>%
{. < 2}
assign clusters labels
cluster <- 1:nrow(sparse_format)
for (i in 1:nrow(sparse_format)) {
cl_idx <- cluster[i]
cluster[neighborhoods[, i]] <- cl_idx
}
sparse_format <- sparse_format %>%
as_data_frame(.) %>%
mutate(cluster_id = cluster)
write the clusters to a new 3d image
new_img <- roi
new_img@.Data <- array(0,c(74,92,78))
for (cl in cluster) {
new_img@.Data[sparse_format %>% filter(., cluster_id == cl) %>% select(dim1,dim2,dim3) %>% as.matrix] <- cl
}
writeNIfTI(new_img, "test", verbose=TRUE)
Now if you open the file test.nii.gz (you can do it with e.g. mricron) you will see that there is one big cluster at roughly coordinates 37 23 15which has been splitted in 3 different clusters, even if all voxels are connected.
A:
You could use the spatstat package to do this. You need the newly
created branch connected.pp3 from github which can be installed if you
have either devtools or remotes package loaded (here I use
remotes):
library(remotes)
install_github("spatstat/spatstat")
library(spatstat)
Grid and bounding box
grid <- expand.grid(0:4,0:4,0:4)
bb <- box3(range(grid[,1]), range(grid[,2]), range(grid[,3]))
Sparse array of data (and the id of the sparse rows)
grid$id <- 1:nrow(grid)
set.seed(42)
a <- grid[sample(nrow(grid), 20),]
a
#> Var1 Var2 Var3 id
#> 115 4 2 4 115
#> 117 1 3 4 117
#> 36 0 2 1 36
#> 102 1 0 4 102
#> 78 2 0 3 78
#> 63 2 2 2 63
#> 88 2 2 3 88
#> 16 0 3 0 16
#> 77 1 0 3 77
#> 82 1 1 3 82
#> 53 2 0 2 53
#> 116 0 3 4 116
#> 106 0 1 4 106
#> 29 3 0 1 29
#> 52 1 0 2 52
#> 104 3 0 4 104
#> 107 1 1 4 107
#> 13 2 2 0 13
#> 51 0 0 2 51
#> 60 4 1 2 60
Convert to 3D point pattern and find connected components (returned as
so-called marks to the points). As pointed out by @gdkrmr any point with
distance less than 2 is a neighbour (here we use 1.8, but anything
between sqrt(3) and 2 should work).
x <- pp3(a[,1], a[,2], a[,3], bb)
x_labelled <- connected.pp3(x, R = 1.8)
df <- data.frame(cluster_id = marks(x_labelled), point_id = a$id)
For nicer printing we sort according to cluster id
df[order(df$cluster_id, df$point_id),]
#> cluster_id point_id
#> 1 1 115
#> 14 2 29
#> 19 2 51
#> 15 2 52
#> 11 2 53
#> 20 2 60
#> 6 2 63
#> 9 2 77
#> 5 2 78
#> 10 2 82
#> 7 2 88
#> 4 2 102
#> 16 2 104
#> 13 2 106
#> 17 2 107
#> 12 2 116
#> 2 2 117
#> 8 3 16
#> 3 3 36
#> 18 4 13
A: Here is a pure R solution, it takes advantage that the maximum distance of neighboring voxels is sqrt(d) < 2 if d <= 3:
library(rgl)
library(magrittr)
sparse_format <- (sparse_array > 0) %>%
which(., arr.ind = TRUE)
neighborhoods <- sparse_format %>%
dist %>%
as.matrix %>%
{. < 2}
n <- nrow(sparse_format)
perm <- 1:n
for (i in 1:n) {
perm[i:n] <- perm[i:n][
order(neighborhoods[perm[i], perm][i:n],
decreasing = TRUE)
]
}
neighborhoods <- neighborhoods[perm, perm]
sparse_format <- sparse_format[perm, ]
cluster <- 1:n
for (i in 1:n) {
cl_idx <- cluster[i]
cluster[neighborhoods[, i]] <- cl_idx
}
plot3d(sparse_format, col = cluster)
UPDATE: Added sorting of the neighborhoods matrix to find the connected clusters. This has become very slow (~30s for your example image), but I think that there is still a lot of room for optimization. If you want a really fast solution look at the Julia language, especially at Images.jl.
UPDATE: Made the first loop fast.
| |
doc_4497
|
git log \
--pretty=format:'{%n "commit": "%H",%n "author": "%an <%ae>",%n "date": "%ad",%n "message": "%f"%n},' \
$@ | \
perl -pe 'BEGIN{print "["}; END{print "]\n"}' | \
perl -pe 's/},]/}]/'
Example above parses author, commit, date, message values. How can we parse the value of Approved-by which is available when a pull-request is approved.
Even the official documentation does not mention that
A: Approved-by is not a builtin field so Git doesn't have a placeholder for it. We could use other methods to get the fields and format the output.
Suppose the Approved-by line looks like:
Approved-by: Someone Nice
Here is a bash sample:
for commit in $(git log --pretty=%H);do
echo -e "{\n\
\"commit\": \"$commit\",\n\
\"author\": \"$(git log -1 $commit --pretty=%an)\",\n\
\"date\": \"$(git log -1 $commit --pretty=%cd)\",\n\
\"message\": \"$(git log -1 $commit --pretty=%f)\",\n\
\"approved-by\": \"$(git log -1 $commit --pretty=%b | grep Approved-by | awk -F ': ' '{print $NF","}' | xargs echo | sed -e 's/,$//')\"\n\
},"
done | \
perl -pe 'BEGIN{print "["}' | \
sed -e '$s/},/}]/'
It needs improvement to meet your real needs, especially the \"approved-by\" line. Basically it gets all the commit sha1 values first and then parse them to get the fields of each commit and then format the output.
| |
doc_4498
|
A = np.array([[1, 2, 3, 4],
[2, float('inf'), 3, 4],
[5, 6, 7, 8]])
I would like to remove the lines that contain an infinite value in them so that the results would be
np.array([[1,2,3,4],
[5,6,7,8]])
I tried to do A = A[float('inf') not in A], but the result is array([], shape=(0, 3, 4), dtype=float64).
I could do
B = []
for line in A:
if float('inf') not in line:
B.append(line)
A = np.array(B)
but is there a better way to do this?
A: Given that you have a NumPy array, a NumPy based solution will perform much better than using python lists.You can use np.isinf with any here:
A[~np.isinf(A).any(1)]
array([[1., 2., 3., 4.],
[5., 6., 7., 8.]])
is_inf = np.isinf(A) # returns True when there is an Inf
print(is_inf)
array([[False, False, False, False],
[False, True, False, False],
[False, False, False, False]])
is_inf_any = is_inf.any(1) # Checks is there are any Trues along axis 1
# (hence reduces along that axis)
print(is_inf_any)
# array([False, True, False])
~is_inf_any # applies a bitwise logical not
# array([ True, False, True])
A: You could use a list comprehension for this.
A = np.array([line for line in A if float('inf') not in line])
| |
doc_4499
|
<?php
$quotes = array(
'quote 1',
'quote 2',
'quote 3',
'quote 4',
'quote 5',
);
$i = array_rand($quotes);
header('Content-Type: text/plain; charset=utf-8');
print($quotes[$i]);
?>
How could I call it every minute to display a new quote (Russian text in UTF8 encoding) at my web page (which itself is an iframe app at Facebook)?
Do I need to use jQuery here or is there a lighter solution, working in the usual browsers?
I don't have any AJAX experience yet.
UPDATE:
As suggested by Uku Loskit below, I've added the following snippet and it works well. Can anybody please show me how to fade the new quote in with fadeIn()?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
setTimeout( function() {
$.get("/hint.php", function(data) {
$("#hint").html(data);
});
}, 5*60*1000 );
});
</script>
Thank you!
Alex
A: use the setTimeout() method.
I'd say there's nothing heavy about using jQuery (especially the minified version) "just for AJAX", because it provides a cross-browser compatible solution and is much easier to program.
example:
function getNewQuotes() {
$.get("random_quotes.php", function(data) {
// set the response from random_quotes.php to this div
$("#quotesDiv").html(data);
});
}
// 60000 milliseconds = 60 seconds = 1 minute
var t=setTimeout("getNewQuotes()", 60000);
As for your question of mixing "non-JQuery and Javascript", there's no jQuery function for this that I know of, all-in-all jQuery is still Javascript and relying on jQuery specific code all the time isn't necessary, but would be only be useful for consistency.
Edit:
$(function() {
setTimeout( function() {
$.get("/hint.php", function(data) {
// first hide, then insert contents
$("#hint").hide();
$("#hint").html(data);
// you can probably chain this together into one command as well
$("#hint").fadeIn("slow");
});
}, 5*60*1000 );
});
A: You don't need jquery, but its easier like that. Just pick up from the manual
Basic example of how to get it once:
$.ajax({
url: "yourFileName.php",
context: document.body,
success: function(result){
$('#someDiv').html('result');
}
});
then add the javascript code to do this periodically. I'm sure you could find something nifty from the jquery thingymabob too :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.