id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_5100
|
While creating the new image canvas there are multiple options to choose the mode of the image (Ex: P, PA, RGB, RGBA etc).
When I use the P mode, the rendered text is not anti-aliased.
Size of the result image is considerably smaller when used P mode compared to other modes like RGB, RGBA so, this would be my preference.
I would like to know why the font rendering is dependent on the color pallet? Is P mode (8-bit pixels ) with 256 colors are not sufficient to render the font?
When I use several of these png images as frames and generate a GIF image out of it, the quality of the image is reduced drastically.
As discussed on this thread, I do not want to resize the image which is a time consuming operation.
Below is the code which I have used:
fnt = ImageFont.truetype('Assets/somefont.ttf',82)
b = Image.new('P',(680,120),color=255)
#b = Image.new('RGB',(680,120),color=255)
draw = ImageDraw.Draw(b)
#draw.fontmode = "0"
draw.text((b.width/2, (b.height-50)/2), "88", fill=0, font=fnt)
f = BytesIO()
b.save(f, format='PNG')
A: 2 things:
*
*use mode 'PA' for your Image
*convert to 'RGB' prior to saving
So your code becomes something like:
fnt = ImageFont.truetype('Assets/somefont.ttf',82)
b = Image.new('PA',(680,120),color=255)
draw = ImageDraw.Draw(b)
draw.text((b.width/2, (b.height-50)/2), "88", fill=0, font=fnt)
b = b.convert('RGB')
f = BytesIO()
b.save(f, format='PNG')
I got reasonable-looking results with this approach (different font, obviously, but you can see that it's anti-aliased):
| |
doc_5101
|
Column Data :
{"Department":"Mens
Wear","Departmentid":"10.1;20.1","customername":"john4","class":"tops wear","subclass":"sweat shirts","product":"North & Face 2 Bangle","style":"Sweat shirt hoodie - Large - Black"}
Is there any other way to load the data in to single column.
A: The best solution would be use a different delimiter instead of comma in your CSV file. If it's not possible, then you can ingest the data using a non-existing delimiter to get the whole line as one column, and then parse it. Of course it won't be as effective as native loading:
cat test.csv
1,2020-10-12,Gokhan,{"Department":"Mens Wear","Departmentid":"10.1;20.1","customername":"john4","class":"tops wear","subclass":"sweat shirts","product":"North & Face 2 Bangle","style":"Sweat shirt hoodie - Large - Black"}
create file format csvfile type=csv FIELD_DELIMITER='NONEXISTENT';
select $1 from @my_stage (file_format => csvfile );
create table testtable( id number, d1 date, name varchar, v variant );
copy into testtable from (
select
split( split($1,',{')[0], ',' )[0],
split( split($1,',{')[0], ',' )[1],
split( split($1,',{')[0], ',' )[2],
parse_json( '{' || split($1,',{')[1] )
from @my_stage (file_format => csvfile )
);
select * from testtable;
+----+------------+--------+-----------------------------------------------------------------+
| ID | D1 | NAME | V |
+----+------------+--------+-----------------------------------------------------------------+
| 1 | 2020-10-12 | Gokhan | { "Department": "Mens Wear", "Departmentid": "10.1;20.1", ... } |
+----+------------+--------+-----------------------------------------------------------------+
| |
doc_5102
|
package com;
public class Hi {
public static void main(String args[]) {
String[] myFirstStringArray = new String[] { "String 1", "String 2",
"String 3" };
if (myFirstStringArray[3] != null) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
}
}
A: Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?
if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
A: In arrays, they are measured differently than numbers. The first object inside an array is considered 0. So, in your if statement, instead of a 3, you just put a 2.
if (myFirstStringArray[3] != null) {
System.out.println("Present");
to
if (myFirstStringArray[2] != null) {
System.out.println("Present");
Hope this helps! :)
A: Your String array contains 3 elements and you are accessing array[3] i.e. 4th element as index in 0 based and so you get this error (Exception, anyway).
To avoid the ArrayIndexOutOfBoundsException use an index within specified index range. And always check whether your index is >= array.length.
| |
doc_5103
|
class _TeachersState extends State<TeachersList> {
final _biggerFont = const TextStyle(fontSize: 18.0);
List tests = List();
Widget _buildSuggestions(BuildContext context) {
initTests();
return ListView.builder(
itemCount: tests.length,
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
return _buildRow(tests[i]);
});
}
void gotoTest(String title) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => TestList(title)));
}
Widget _buildRow(String pair) {
return ListTile(
onTap: () => gotoTest(pair),
title: Text(
pair,
style: _biggerFont,
),
);
}
void initTests() async {
List t = List();
String baseDir = await ExtStorage.getExternalStorageDirectory();
String waDir = "$baseDir/mandarin";
Directory dir = new Directory(waDir);
dir.list().forEach((element) {
t.add(element.path);
});
setState(() {
tests.addAll(t);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("请选择老师")),
body: _buildSuggestions(context),
);
}
}
A: Have you tried using the FutureBuilder widget ?
Check the code below:
Pass a snapshot to your buildSuggestion method
Widget _buildSuggestions(BuildContext context, AsyncSnapShot snapshot) {
initTests();
return ListView.builder(
itemCount: snapshot.data.length,
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
return _buildRow(snapshot.data[i]);
});
}
Change the function return type
Future initTests() async {
List t = List();
String baseDir = await ExtStorage.getExternalStorageDirectory();
String waDir = "$baseDir/mandarin";
Directory dir = new Directory(waDir);
dir.list().forEach((element) {
t.add(element.path);
});
setState(() {
tests.addAll(t);
});
return tests;
}
Use a future builder widget in your body:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("请选择老师")),
body: FutureBuilder(
future: initTests(),
builder: (context, snapshot){
if (snapshot.hasData){
return _buildSuggestions(context, snapshot);
} else {
return CircularProgressIndicator();
}
},
);
);
}
It will show a Circle Progress Indicator until all the files have been read and then display them when done.
| |
doc_5104
|
Something like this:
l = [1,2,3]
def f(passed_in_list):
different_list = [4,5,6]
passed_in_list = different_list[:]
print(l) # Prints [1,2,3]. How to make it [4,5,6] ?
How can I achieve this?
A: This strikes me as a dangerous design pattern, creating a function with intentional side effects on global scope. I would be careful doing things like this. That being said it doesn't look like you've called your function which may be why you aren't seeing what you expect.
A: You need to modify the list, not the variable that points to it. And as mentioned by others, you need to call that function:
l = [1,2,3]
def f(passed_in_list):
different_list = [4,5,6]
passed_in_list[:] = different_list[:]
f(l)
print(l)
A: You need to actually call your function:
l = [1,2,3]
def f(passed_in_list):
passed_in_list[:] = [4,5,6]
f(l)
print(l)
Yields:
[4, 5, 6]
| |
doc_5105
|
This is my snippet code:
@FXML
private void initialize() {
tf_code.textProperty().addListener((observable, oldValue, newValue) -> {
System.out.println(newValue.substring(2, 6));
tf_newCode.setText(newValue.substring(2, 6));
});
}
Should I add another listener to my second TextField ?
A: Works for me. Note that the below code does not require a .fxml file. Perhaps the call to method substring() in the code you posted is throwing an Exception that you are unaware of because you are catching it in an empty catch block? Of-course I'm only guessing since you only posted part of your code.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class JfxTst00 extends Application {
public void start(Stage mainStage) throws Exception {
mainStage.setTitle("JfxTst00");
BorderPane root = new BorderPane();
TextField tf_NewCode = new TextField();
TextField tf_Code = new TextField();
tf_Code.textProperty().addListener((observable, oldVal, newVal) -> tf_NewCode.setText(newVal));
root.setTop(tf_Code);
root.setBottom(tf_NewCode);
Scene scene = new Scene(root, 220, 70);
mainStage.setScene(scene);
mainStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
A: Your questions does not actually explain the problem you're facing, though I see a few that you should be having.
First of all, you only need one listener for the first TextField because that is the one we are watching for changes.
Then you need to account for input into the TextField that is less than 2 characters and more than 6. Since you have set hard limits in your subString(2, 6) call, we only want our listener to work within those constraints.
Here is a simple text application that demonstrates:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextFieldBinding extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
TextField txt1 = new TextField();
TextField txt2 = new TextField();
txt1.textProperty().addListener((observable, oldValue, newValue) -> {
// First, only update txt2 if the new value entered in txt1 is greater than 2, otherwise
// our substring() method will throw an exception
if (newValue.length() > 2) {
// We also need to prevent trying to get a substring that exceeds the remaining length
// of the txt1 input
int maxIndex;
if (newValue.length() < 6) {
maxIndex = newValue.length();
} else {
maxIndex = 6;
}
// Now set the text for txt2
txt2.setText(newValue.substring(2, maxIndex));
}
});
root.getChildren().addAll(txt1, txt2);
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
| |
doc_5106
|
If there's no way to do this via the API, is it possible to intercept the shift click and transform it into a standard click before it gets processed by the Shield UI JS?
Thanks,
Chris
A: By default, the selection mechanism of the chart is single. This is demonstrated in the following example:
https://demos.shieldui.com/web/pie-chart/sliced-offset
Another option would be to disable the default selection and simply allow clicking and then try to set the .selected property of a the corresponding datapoint.
A: Seems there is no easy way to force selection of 0 or 1 slices at a time. Currently selecting while pressing the Shift / Ctrl keys will not unselect the other slices.
You might want to contact their support and ask their opinion/solution on your request.
A: After contacting the dev team, they have made changes to the Javascript and the Wicket API code to allow this to happen.
chart.getOptions().getSeriesSettings().getPie().setAllowMultiPointSelection(false);
| |
doc_5107
|
df = pd.DataFrame(index=np.arange(10))
df["address"] = "Iso Omena 8 a 2"
need to split it to different column so that resulting dataframe would be like:
address street_name building_number door_number_letter appartment_numner
Iso Omena 8 a 2 Iso Omena 8 a 2
what makes it tricky is that:
1.names may have or have not space between them like above example.
2.door_number_letter might be sometimes number not letter. (eg. "Iso Omena 8 5 2" )
address most complete form is :[address,street_name, building_number,door_number_letter,appartment_numner]
A: Supposed address is letters and spaces only and rest is space separated while building number always starts with a number, this could be achieved the following way:
import re
s = ['Iso Omena 8 a 2', 'Xstreet 2', 'Isö Ømenå 8 a 2']
for addr in s:
street = re.findall('[^\d]*', addr)[0].strip()
rest = addr[len(street):].strip().split(' ')
print(street, rest)
# Iso Omena ['8', 'a', '2']
# Xstreet ['2']
# Isö Ømenå ['8', 'a', '2']
Or if you want to have everything in one dataframe:
df = pd.DataFrame()
df['address'] = ['Iso Omena 8 a 2', 'Xstreet 2', 'Asdf 7 c', 'Isö Ømenå 8 a 2']
df['street'] = None; df['building'] = None; df['door'] = None; df['appartment'] = None
import re
for i, s in enumerate(df['address']):
street = re.findall('[^\d]*', s)[0].strip()
df.loc[i,('street')] = street
for col, val in zip(['building', 'door', 'appartment'], s[len(street):].strip().split(' ')):
df.loc[i,(col)] = val
# address street building door appartment
# 0 Iso Omena 8 a 2 Iso Omena 8 a 2
# 1 Xstreet 2 Xstreet 2 None None
# 2 Asdf 7 c Asdf 7 c None
# 3 Isö Ømenå 8 a 2 Isö Ømenå 8 a 2
EDIT: Building number only left of '-'sign:
you could just replace df.loc[i,(col)] = val by
df.loc[i,(col)] = re.findall('[^-]*', val)[0]
if this suits also door and appartment. Otherwise you'd have to if-test against col=='building' to only then use this version.
A: You can use:
In [116]: s1 = df.address.str.findall(r'([\w ]+?) +(\d+) +([\d\w]+) +(\d+)').map(lambda s: s[0])
In [117]: s1
Out[117]:
0 (Iso Omena, 8, a, 2)
1 (Iso Omena, 8, a, 2)
2 (Iso Omena, 8, a, 2)
3 (Iso Omena, 8, a, 2)
4 (Iso Omena, 8, a, 2)
5 (Iso Omena, 8, a, 2)
6 (Iso Omena, 8, a, 2)
7 (Iso Omena, 8, a, 2)
8 (Iso Omena, 8, a, 2)
9 (Iso Omena, 8, a, 2)
Name: address, dtype: object
Then construct a dataframe based on these columns:
In [118]: pd.DataFrame(s1.values.tolist(), index=s1.index, columns=['street_name', 'building_number', 'door_number_letter', 'appartment_numner'])
Out[118]:
street_name building_number door_number_letter appartment_numner
0 Iso Omena 8 a 2
1 Iso Omena 8 a 2
2 Iso Omena 8 a 2
3 Iso Omena 8 a 2
4 Iso Omena 8 a 2
5 Iso Omena 8 a 2
6 Iso Omena 8 a 2
7 Iso Omena 8 a 2
8 Iso Omena 8 a 2
9 Iso Omena 8 a 2
A: Taking some inspiration from this answer I came up with this regex+extract solution:
In [77]: df.address.iloc[1] = 'Big Apple 19 21 7'
In [78]: df.address.str.extract('(?P<street>^[^0-9]*) (?P<building>.+?) (?P<door>.+?) (?P<apartment>.+?$)')
Out[78]:
street building door apartment
0 Iso Omena 8 a 2
1 Big Apple 19 21 7
2 Iso Omena 8 a 2
3 Iso Omena 8 a 2
4 Iso Omena 8 a 2
5 Iso Omena 8 a 2
6 Iso Omena 8 a 2
7 Iso Omena 8 a 2
8 Iso Omena 8 a 2
9 Iso Omena 8 a 2
A: Something like this?
import re
addr = "Iso Omena 8 a 2"
pattern = r'[a-öA-Ö]{3,100} *[a-öA-Ö]{3,100}'
street = re.findall(pattern, addr)[0]
bda = addr[len(street):].split()
print(street, bda,addr[len(street):])
| |
doc_5108
|
Code I have:
string = str(
"hello \n"+
"foo %f \n" % (-1) +
for i in range(5):
n = i + 1
"bar %f \n" % (n) +
"END"
)
print(str(string))
however this gives me a syntax error but the output I was looking for was something like this:
hello
foo -1
bar 0
bar 2
bar 3
bar 4
bar 5
bar 6
END
A: you do not need str as your value is already a string.
The syntax error is the closing brace at the end before your print.
You could try this code:
s = """hello
foo -1
"""
for i in range(5):
s += """bar {value}
""".format(value=i+1)
s += "END"
print(s)
| |
doc_5109
|
I'm using app engine with cloud endpoints to deploy APIs. All service in the following description is about APIs.
I know in app engine flex env, I could deploy several independent service which talk to each other only through REST.
It's a great idea to make services as independent as possible, but there are some opportunities for code reuse I don't know how to achieve.
For example, there are same procedures I will need to use regardless which API under which service. Usually I'll write a helper library so all these small helper functions would be in one place and I could reuse them across various APIs.
The purpose is to write once and use at many places.
So my questions:
*
*Is this shared library still good idea under the context of app engine? If not, wouldn't it has too much overhead to make all those small function as api?
*If shared helper library still make sense, how to achieve it in app engine flex environment? I know in standard env you could use includes directive to include files, I don't see how in flex environment.
*I know we could use 3rd party library by declaring them in the requirement and pip support install from github repo, but my helper library would be a private repo, how to allow app engine to pip install private repo?
Thanks in advance.
A: You can specify private dependencies in requirements.txt files. You would do this in the same way you would handle private dependencies for any other python package. You might directly specify a github url, or you might use a private repository such as an instance of devpi.
| |
doc_5110
|
I added
I try to use the following code:
return new PagedList<Dto.DrugConsortium.CollectionSiteWithCoordinatesDto>(query.Select(p =>
new Dto.DrugConsortium.CollectionSiteWithCoordinatesDto { CollectionSite = p, Distance = p.Location.ProjectTo(2855).Distance(myLocation) }).ToList(), pageIndex, pageSize);
where is my extension:
public static class GeometryExtensions
{
static readonly IGeometryServices _geometryServices = NtsGeometryServices.Instance;
static readonly ICoordinateSystemServices _coordinateSystemServices
= new CoordinateSystemServices(
new CoordinateSystemFactory(),
new CoordinateTransformationFactory(),
new Dictionary<int, string>
{
// Coordinate systems:
// (3857 and 4326 included automatically)
// This coordinate system covers the area of our data.
// Different data requires a different coordinate system.
[2855] =
@"
PROJCS[""NAD83(HARN) / Washington North"",
GEOGCS[""NAD83(HARN)"",
DATUM[""NAD83_High_Accuracy_Regional_Network"",
SPHEROID[""GRS 1980"",6378137,298.257222101,
AUTHORITY[""EPSG"",""7019""]],
AUTHORITY[""EPSG"",""6152""]],
PRIMEM[""Greenwich"",0,
AUTHORITY[""EPSG"",""8901""]],
UNIT[""degree"",0.01745329251994328,
AUTHORITY[""EPSG"",""9122""]],
AUTHORITY[""EPSG"",""4152""]],
PROJECTION[""Lambert_Conformal_Conic_2SP""],
PARAMETER[""standard_parallel_1"",48.73333333333333],
PARAMETER[""standard_parallel_2"",47.5],
PARAMETER[""latitude_of_origin"",47],
PARAMETER[""central_meridian"",-120.8333333333333],
PARAMETER[""false_easting"",500000],
PARAMETER[""false_northing"",0],
UNIT[""metre"",1,
AUTHORITY[""EPSG"",""9001""]],
AUTHORITY[""EPSG"",""2855""]]
"
});
public static IGeometry ProjectTo(this IGeometry geometry, int srid)
{
var geometryFactory = _geometryServices.CreateGeometryFactory(srid);
var transformation = _coordinateSystemServices.CreateTransformation(geometry.SRID, srid);
return GeometryTransform.TransformGeometry(
geometryFactory,
geometry,
transformation.MathTransform);
}
}
ProjNet4GeoAPI nuget package is added (v 1.4.1)
But I can't resolve GeometryTransform class, it's not found.
How to resolve it?
A: First GeometryTransform.TransformGeometry() is a method that is under NetTopologySuite.CoordinateSystems.Transformations namespace. Do you have
"using NetTopologySuite.CoordinateSystems.Transformations;"
at the top of your extension method?
Second I would add that 2855 is a coordinate system for NorthWest Washington state. I would check to see if your coordinates that you are using are within that area.
Also, each coordinate system has its own units of measurement. For example, SRID:4326 is in degrees for geometry(Cartesian coordinates) and meters for geography types.
SRID:2855 is in feet
You can check out this site to get a list of the coordinate systems available.
https://epsg.io/
I am new to geography types and transforms but in my search this is what I found.
| |
doc_5111
|
I kwnow how to do it with Winforms but I need a full online solution, so that:
*
*The user open an standard browser and types in a start url.
*In this url the menus and bars of the standard browser are hidden and
the user can see a "simulated browser", with standard buttons
(back, reload, ...).
*From the Asp (c#) code behind this page I can start collecting click
data.
Thanks in advance, and keep the good work.
A: What you want to collect (a heat map of clicks essentially) is doable, but I don't think the way you want to go about it is very feasible.
Try this out.
I think that using this kind of solution with frames, etc. is much more feasible than embedding a browser (this amounts to writing a browser that can be served up by some kind of java/silverlight technology, not trivial).
Another idea would be that since, I assume, you have the permission of your users to track their clicks, write a greasemonkey (firefox plugin) based on the javascript in the link I provided above. You could then have all users use this plugin script combination to give you their clicks.
A: Web browsers are normally designed to prevent this kind of cross-site scripting vulnerability. This would only be feasible if you had the complete cooperation of all sites involved.
A: I don't think browsers will allow you to do this, for the simple reason that it opens up a whole bunch of security holes. If you think about it, an attack site designed like this would be able to follow people around the net tracking their actions, stealing passwords, etc. without them even knowing it was there.
A: This is not so simple for a web app.
Your options are:
*
*Create a plugin (or Greasemonkey script) for your favorite browser to collect click data.
*JavaScript that tracks the user's cursor position. Keep in mind that this won't be reliable if your users go to other sites from within your site thanks to the fact that JavaScript doesn't work well if scripts come from different origins.
You won't be able to make a "browser" control like you can on a desktop app because browsers intentionally don't allow web sites to be that powerful.
For the "browser in a browser" effect, you can use the tag. Remember, you'll only be able to track user actions in this iframe if the source is from the the same domain as the page it's included on.
A: Cross domain scripting is impossible by client-side. For obvios security reasons, you can't even read from a frame or iframe pointing to somewhere not from your own site.
Maybe the solution here is to to build something similar to the famous PHPProxy, or PHPBrowser, in this case a "ASP.NET Proxy". Its not that hard to build, you can Google for many exemples of those little codes.
A: While I doubt you can hide the original browsers toolbars etc, you could set up a single page that does this (it certainly wouldn't handle everything though).
This page would contain a the buttons and textbox required (to make up the inner browser UI) and a placeholder that would contain the page that the user requested. Of course the page contained in the placeholder will need to have all the links replaced so that they can be tracked (I would use linkbuttons). I'm not sure how well form submits would work.
Personally I'd use a proxy if I had control of the computer.
| |
doc_5112
|
But what is the advantage of such feature, cause after all we are hitting db either through SELECT or through UPDATE.
| |
doc_5113
|
import pyglet
import numpy as np
from pyglet.gl import *
from ctypes import pointer, sizeof
vbo_id = GLuint()
glGenBuffers(1, pointer(vbo_id))
window = pyglet.window.Window(width=800, height=800)
glClearColor(0.2, 0.4, 0.5, 1.0)
glEnableClientState(GL_VERTEX_ARRAY)
c = 0
def update(dt):
global c
c+=1
data = (GLfloat*4)(*[500+c, 100+c,300+c,200+c])
glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
glBufferData(GL_ARRAY_BUFFER, sizeof(data), 0, GL_DYNAMIC_DRAW)
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data)
pyglet.clock.schedule(update)
glPointSize(10)
@window.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(0, 0, 0)
glVertexPointer(2, GL_FLOAT, 0, 0)
glDrawArrays(GL_POINTS, 0, 2)
pyglet.app.run()
A: You don't need to call glBufferData every single time in update - create and fill the VBO once (see setup_initial_points) and only update it with glBufferSubData. In case you are only working with a single VBO, you can also comment out the glBindBuffer call in update() (see code below).
GL_DYNAMIC_DRAW vs GL_STATIC_DRAW won't make a big difference in this example since you are pushing very few data onto the GPU.
import pyglet
from pyglet.gl import *
from ctypes import pointer, sizeof
window = pyglet.window.Window(width=800, height=800)
''' update function '''
c = 0
def update(dt):
global c
c+=1
data = calc_point(c)
# if there's only on VBO, you can comment out the 'glBindBuffer' call
glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data)
pyglet.clock.schedule(update)
''' draw function '''
@window.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(0, 0, 0)
glVertexPointer(2, GL_FLOAT, 0, 0)
glDrawArrays(GL_POINTS, 0, 2)
''' calculate coordinates given counter 'c' '''
def calc_point(c):
data = (GLfloat*4)(*[500+c, 100+c, 300+c, 200+c])
return data
''' setup points '''
def setup_initial_points(c):
vbo_id = GLuint()
glGenBuffers(1, pointer(vbo_id))
data = calc_point(c)
glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
glBufferData(GL_ARRAY_BUFFER, sizeof(data), 0, GL_DYNAMIC_DRAW)
return vbo_id
############################################
vbo_id = setup_initial_points(c)
glClearColor(0.2, 0.4, 0.5, 1.0)
glEnableClientState(GL_VERTEX_ARRAY)
glPointSize(10)
pyglet.app.run()
| |
doc_5114
|
<?php
include "connection.php";
$selectedpatient = $_POST['patient_dropdown'];
$myquery = "SELECT * FROM `patient_info` patient_info.Name = '$selectedpatient' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
<script> data_arrival($_tempdata); </script>
And I defined the source for the javascript file in the HTML header. It displays two errors:
1) Parse error in the javascript file - that's understandable as I included the javascript file in header and the file gets executed before the php actually retrieves any data.
2) data_arrival method is undefined
How can I fix this ?? I want to pass the $tempdata (after its populated by php) to data_arrival method as an argument.
Thanks in advance !
A: *
*First of all: it's PHP that's executed first, not JavaScript. It can't be the other way round in your example.
*data_arrival is undefined... because either you haven't defined it at all, or because it is defined after it's called.
To pass the value from PHP to JavaScript in your case, you can use:
data_arrival(<?php echo $_tempdata; ?>);
It will generate something like:
data_arrival([a, b, c, d, ...]);
Of course, data_arrival function need to be defined prior to its execution.
Edit
And maybe it's good to use the same variable name: $_tempdata vs $tempdata.
| |
doc_5115
|
Student Grade Name : String Id :
String math grade : double english grade :
double science grade : double Average () :
double printInfo () : void
The Instructions are:
1)Create Student Grade Class
2)Create an Array of 10 Student
3) Enter Grade info using Keyboard
4) Print list of students (name and average)
My problem is every time I run the public class StudentGradeApp2 it always gives me this error
Exception in thread "main" java.lang.NullPointerException
at javaDay3.StudentGradeApp2.main(StudentGradeApp2.java:15)
Now i do not know what to put on this portion:
public static void printTheStudentDetails (StudentGrade info) {
please oh please help me
My codes are:
StudentGrade Class:
package javaDay3;
public class StudentGrade {
String name;
String id;
double mathgrade;
double enggrade;
double scigrade;
public void printInfo() {
System.out.println("Math = " + mathgrade);
System.out.println("English = " + enggrade);
System.out.println("Science = " + scigrade);
System.out.println( "Average = " + average());
}
public double average () {
return ((mathgrade + enggrade + scigrade) / 3);
}
public void printCompleteInformation() {
System.out.println("Name = " + name);
System.out.println("ID = " + id);
System.out.println("Math = " + mathgrade);
System.out.println("English = " + enggrade);
System.out.println("Science = " + scigrade);
System.out.println( "Average = " + average());
}
public void printNeed () {
System.out.println("Name = " + name);
System.out.println( "Average = " + average());
}
}
StudentGradeApp Class:
package javaDay3;
import java.util.Scanner;
public class StudentGradeApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentGrade stud1 = new StudentGrade ();
stud1.name = "SpongeBop SquarePants";
stud1.id = ("Student 1");
stud1.mathgrade = 72;
stud1.enggrade = 80;
stud1.scigrade = 90;
stud1.average();
StudentGrade stud2 = new StudentGrade ();
stud2.name = "Patrick Star";
stud2.id = ("Student 2 ");
stud2.mathgrade = 72;
stud2.enggrade = 85;
stud2.scigrade = 91;
stud2.average();
StudentGrade stud3 = new StudentGrade ();
stud3.name = "Squidward Tentacles";
stud3.id = ("Student 3" );
stud3.mathgrade = 90;
stud3.enggrade = 85;
stud3.scigrade = 95;
stud2.average();
StudentGrade stud4 = new StudentGrade ();
stud4.name = "Eugene H. Krabs";
stud4.id = ("Student 4");
stud4.mathgrade = 95;
stud4.enggrade = 85;
stud4.scigrade = 95;
stud4.average();
StudentGrade stud5 = new StudentGrade ();
stud5.name = "Sandy Cheeks";
stud5.id = ("Student 5");
stud5.mathgrade = 75;
stud5.enggrade = 75;
stud5.scigrade = 95;
stud5.average();
StudentGrade stud6 = new StudentGrade ();
stud6.name = "Gary the Snail";
stud6.id = ("Student 6");
stud6.mathgrade = 75;
stud6.enggrade = 74;
stud6.scigrade = 95;
stud6.average();
StudentGrade stud7 = new StudentGrade ();
stud7.name = "Sheldon J Plankton";
stud7.id = ("Student 7 ");
stud7.mathgrade = 79;
stud7.enggrade = 76;
stud7.scigrade = 75;
stud7.average();
StudentGrade stud8 = new StudentGrade ();
stud8.name = "Larry The Lobster";
stud8.id = ("Student 8");
stud8.mathgrade = 79;
stud8.enggrade = 76;
stud8.scigrade = 75;
stud8.average();
StudentGrade stud9 = new StudentGrade ();
stud9.name = "King Neptune";
stud9.id = ("Student 9 ");
stud9.mathgrade = 79;
stud9.enggrade = 96;
stud9.scigrade = 75;
stud9.average();
StudentGrade stud10 = new StudentGrade ();
stud10.name = "Pearl Krabs";
stud10.id = ("Student 10 ");
stud10.mathgrade = 79;
stud10.enggrade = 76;
stud10.scigrade = 75;
stud10.average();
/*stud1.printInfo();
System.out.println(" ");
stud2.printInfo();
System.out.println(" ");
stud3.printInfo();
System.out.println(" ");
stud4.printInfo();
System.out.println(" ");
stud5.printInfo();
System.out.println(" ");
stud3.printInfo();
System.out.println(" ");
stud6.printInfo();
System.out.println(" ");
stud7.printInfo();
System.out.println(" ");
stud8.printInfo();
System.out.println(" ");
stud9.printInfo();
System.out.println(" ");
stud10.printInfo(); */
}
public static void printTheStudentDetails (StudentGrade info) {
}
}
StudentGradeApp2 Class:
import java.util.Scanner;
public class StudentGradeApp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentGrade studgrad [] = new StudentGrade [10];
Scanner scanner = new Scanner (System.in);
for(int i = 0; i <= studgrad.length; i++) {
System.out.print("Enter Math Grade = ");
studgrad[i].mathgrade = scanner.nextInt();
System.out.print("Enter English Grade = ");
studgrad[i].enggrade = scanner.nextInt();
System.out.print("Enter Science Grade = ");
studgrad[i].scigrade = scanner.nextInt();
}
for(StudentGrade info:studgrad)
info.printInfo();
scanner.close();
}
}
A: You have below issues with posted code for StudentGradeApp2 :
*
*You got java.lang.NullPointerException at studgrad[i].mathgrade. It is equivalent to invoking null.mathgrade.
*mathgrade, enggrade, scigrade in StudentGrade are double and you are using scanner.nextInt()
*For loop condition is incorrect
PFB corrected implementation:
package javaDay3;
import java.util.Scanner;
public class StudentGradeApp2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentGrade studgrad[] = new StudentGrade[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < studgrad.length; i++) {
StudentGrade sg = new StudentGrade();
System.out.print("Enter Math Grade = ");
sg.mathgrade = Double.parseDouble(scanner.nextLine());
System.out.print("Enter English Grade = ");
sg.enggrade = Double.parseDouble(scanner.nextLine());
System.out.print("Enter Science Grade = ");
sg.scigrade = Double.parseDouble(scanner.nextLine());
studgrad[i] = sg;
}
for (StudentGrade info : studgrad)
info.printInfo();
scanner.close();
}
}
A:
Now i do not know what to put on this portion:
public static void printTheStudentDetails (StudentGrade info) {
You need a list to add all the Student grades
List<> studentList = new ArrayList<StudentGrade>();
studentList.add(stud1);
studentList.add(stud2);
Everytime you create a new StudentGrade object add it to the list.
In your StudentGrade class override the toString() method
Now in your method printTheStudentDetails pass the student's list studentList
public static void printTheStudentDetails (List<StudentGrade> list) {
System.out.println(list);
}
A: Debug the code around where you are getting your issue. You'll find that your object is null. Don't forget to add your data to a list so you can use them.
| |
doc_5116
|
This command to build the container and its build successfully.
sudo docker build -t getting-started .
After that I ran the docker container using bellow command
sudo docker run -dp 3000:3000 getting-started
After running the docker container everything is running fine and I am able to see my container when I ran bellow command
sudo docker ps
But the problem is I am not able to see my container that I just built and ran in my Docker Desktop.
Note: If I build and run the docker container without sudo privilege then I am able to see the container in Docker Desktop.
So now what should I do to manage my containers using Docker Desktop those are build and running using sudo privilege.
A: i am facing the same problems for a while and didn't get anything that worked for me as of yet but maybe in your case if you can enable docker to run in rootless mode or add your user to docker group enable privileges to enable the user to use docker with out sudo it may also work for the docker desktop to access those images in the sudo mode.
try
https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo
https://docs.docker.com/engine/install/linux-postinstall/
the other solution i thought up is to make the docker desktop use the context you are using for the docker engine which is the default not the desktop-linux it will create when its starting up maybe that will enable it to read the past containers you were using
or another solution is to run the docker desktop in sudo mode i dont know how to do that as of yet but its worth a shot if you can find out how
A: if your build successed you can run
docker ps -a
to see all the working and stoped containers
and you can run
docker logs --tail=50 container-name
so you can see the container logs and start fixing the issue
| |
doc_5117
|
const form = document.getElementById("form");
const carDatas = [];
class Car {
constructor(plate, carMaker, carModel, carOwner, carPrice, carColor) {
(this.plate = plate),
(this.carMaker = carMaker),
(this.carModel = carModel),
(this.carOwner = carOwner),
(this.carPrice = carPrice),
(this.carColor = carColor);
}
}
form.addEventListener("submit", (e) => {
const plate = document.getElementById("plate").value;
const carMaker = document.getElementById("carMaker").value;
const carModel = document.getElementById("carModel").value;
const carOwner = document.getElementById("carOwner").value;
const carPrice = document.getElementById("carPrice").value;
const carColor = document.getElementById("carColor").value;
const carDetails = new Car(
plate,
carMaker,
carModel,
carOwner,
carPrice,
carColor
);
carDatas.push(carDetails);
console.log(carDetails);
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
"data"
).innerHTML = ` <td>${carDatas[i].plate} </td>
<td>${carDatas[i].carMaker} </td>
<td>${carDatas[i].carModel} </td>
<td>${carDatas[i].carOwner} </td>
<td>${carDatas[i].carPrice} </td>
<td>${carDatas[i].carColor} </td>`;
}
e.preventDefault();
});
and here is my HTML for the table
<div class="database">
<h1>Cars Database</h1>
<table>
<tr>
<th>LICENCE</th>
<th>MAKER</th>
<th>MODEL</th>
<th>OWNER</th>
<th>PRICE</th>
<th>COLOR</th>
</tr>
<tr id="data"></tr>
</table>
</div>
A: <pre>This is what I recommend I changed your code to add <tr></tr> to each line that's to be created and wrap your <tr> inbetween and tbody tag and use the first line has a head.</pre>
<pre>For the code:</pre>
<code>
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
"data"
).innerHTML = `<tr><td>${carDatas[i].plate} </td>
<td>${carDatas[i].carMaker} </td>
<td>${carDatas[i].carModel} </td>
<td>${carDatas[i].carOwner} </td>
<td>${carDatas[i].carPrice} </td>
<td>${carDatas[i].carColor} </td> </tr>`;
}
e.preventDefault();
<body>
<div class="database">
<h1>Cars Database</h1>
<table>
<thead>
<tr>
<th>LICENCE</th>
<th>MAKER</th>
<th>MODEL</th>
<th>OWNER</th>
<th>PRICE</th>
<th>COLOR</th>
</tr>
</thead>
<tbody id="data"> <tbody>
</table>
</div>
</body>
</code>
| |
doc_5118
|
% height and width are dimensions of black and white image
[hh,ww] = meshgrid( 1:height , 1:width );
% change to polar coordinates relative to the centroid
[theta, r] = cart2pol(hh - centroid(1), ww - centroid(2));
% make divisions of image into Sectors each of 36 degree
E = 0:36:360;
[~, sectorid] = histc(theta * (180/pi), E);
% count for each sector the number of black pixels
N = zeros(size(E));
N = arrayfun(@(k) nnz(bw(sectorid==k)==0), 1:max(sectorid));
N gives me the number of black pixels in each sector. I am not understanding how to find the co-ordinates of all pixels and then store them in a matrix.
Any help would be great!
Thank you.
| |
doc_5119
|
A: This is not supported as yet and I've registered an issue under codeplex's nuget project.
| |
doc_5120
|
thanks
here is my jsf code in xhtml file
i tried with @form / @this also. but same result
error is my inputtext not submitted to controller
<a4j:region id="panel-region">
<f:facet name="header">
<h:outputText value="SAM Selector"/>
</f:facet>
<rich:panel style="clear:both;" header="Search SAM" styleClass="col" id="panelSamSearch">
<ui:decorate template="/jsf/templates/two_columns.xhtml">
<ui:define name="left_label">*Search By</ui:define>
<ui:define name="left_field">
<h:selectOneMenu value="#{pOSController.samType}" id="samType">
<f:selectItem itemValue="a" itemLabel=""/>
<f:selectItem itemValue="samUid" itemLabel="SAM UID"/>
<f:selectItem itemValue="samDid" itemLabel="SAM DID"/>
<f:selectItem itemValue="status" itemLabel="Status"/>
</h:selectOneMenu>
</ui:define>
<ui:define name="right_label">
<h:inputText value="#{pOSController.samValue}" id="samValue"/>
</ui:define>
<ui:define name="right_field">
<a4j:commandButton id="samBtnSearch" value="Search" execute="lp"
action="#{pOSController.loadSamPosTagging(rich:element('samType').value,rich:element('samValue').value)}"
render="#{rich:clientId('dataTableSamView')}"/>
</ui:define>
</ui:decorate>
</rich:panel>
here shows my error
May 05, 2014 1:13:41 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/cms-web] threw exception [/jsf/popups/samPosTagginPopup.xhtml @29,230 action="#{pOSController.loadSamPosTagging({rich:element('samType')}.value,{rich:element('samValue')}.value)}" Failed to parse the expression [#{pOSController.loadSamPosTagging({rich:element('samType')}.value,{rich:element('samValue')}.value)}]] with root cause
org.apache.el.parser.ParseException: Encountered " <ILLEGAL_CHARACTER> "{ "" at line 1, column 35.
Was expecting one of:
<INTEGER_LITERAL> ...
<FLOATING_POINT_LITERAL> ...
<STRING_LITERAL> ...
"true" ...
"false" ...
"null" ...
"(" ...
")" ...
"!" ...
"not" ...
"empty" ...
"-" ...
<IDENTIFIER> ...
at org.apache.el.parser.ELParser.generateParseException(ELParser.java:2217)
at org.apache.el.parser.ELParser.jj_consume_token(ELParser.java:2099)
at org.apache.el.parser.ELParser.MethodParameters(ELParser.java:1153)
at org.apache.el.parser.ELParser.ValueSuffix(ELParser.java:1047)
at org.apache.el.parser.ELParser.Value(ELParser.java:980)
EDITED
i added
<a4j:commandButton id="samBtnSearch" value="Search" execute="lp" action="#{pOSController.loadSamPosTagging(rich:component('samType'),rich:component('samValue'))}" render="#{rich:clientId('dataTableSamView')}" />
then string come as like below.its not pass value of field.just name which i passes returns :-)
document.getElementById('frmMasPosTagging:dataTablePosView:0:samType')
A: change the line:
action="{pOSController.loadSamPosTagging(rich:element('samType').value,rich:element('samValue').value)}"
to action="{pOSController.loadSamPosTagging()}
the value 'samType' and 'samValue'can be accessed in the controller as these are mapped to a backing bean, and backing bean would be updated.so no need to send the values from UI
i assume pOSController have getters and setters for 'samType' and 'samValue'
| |
doc_5121
|
*
*Command to compile the test.c file-
gcc test.c -lm
Results:
[root@XXXXXXX95549 test]# gcc test.c -lm
test.c:28:24: error: libxls/xls.h: No such file or directory
test.c: In function ‘main’:
test.c:33: error: ‘xlsWorkBook’ undeclared (first use in this function)
test.c:33: error: (Each undeclared identifier is reported only once
test.c:33: error: for each function it appears in.)
test.c:33: error: ‘pWB’ undeclared (first use in this function)
test.c:34: error: ‘xlsWorkSheet’ undeclared (first use in this function)
test.c:34: error: ‘pWS’ undeclared (first use in this function)
test.c:39: error: ‘WORD’ undeclared (first use in this function)
test.c:39: error: expected ‘;’ before ‘t’
test.c:53: error: ‘t’ undeclared (first use in this function)
test.c:58: error: ‘tt’ undeclared (first use in this function)
test.c:60: error: dereferencing pointer to incomplete type
test.c:63: error: dereferencing pointer to incomplete type
test.c:64: error: dereferencing pointer to incomplete type
test.c:66: error: dereferencing pointer to incomplete type
test.c:67: error: dereferencing pointer to incomplete type
test.c:68: error: dereferencing pointer to incomplete type
test.c:70: error: dereferencing pointer to incomplete type
test.c:70: error: dereferencing pointer to incomplete type
test.c:71: error: dereferencing pointer to incomplete type
*To solve this problem, I copied the library files at the '/user/include' location
After which the results for same compilation commands were:
[root@XXXXXX95549 test]# gcc test.c -lm
/tmp/cc8DJETV.o: In function `main':
test.c:(.text+0x14): undefined reference to `xls_open'
test.c:(.text+0xd4): undefined reference to `xls_getWorkSheet'
test.c:(.text+0xe4): undefined reference to `xls_parseWorkSheet'
test.c:(.text+0xf0): undefined reference to `xls_getCSS'
test.c:(.text+0x49c): undefined reference to `xls_showBookInfo'
collect2: ld returned 1 exit status
Please, explain how can I rectify this problem.
The code test.c is given below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <libxls/xls.h>
int main()
{
xlsWorkBook* pWB;
xlsWorkSheet* pWS;
FILE *f;
int i;
struct st_row_data* row;
WORD t,tt;
pWB=xls_open("files/test2.xls", "ASCII"); // "KOI8-R"
if (pWB!=NULL)
{
f=fopen ("test.htm", "w");
for (i=0;i<pWB->sheets.count;i++)
printf("Sheet N%i (%s) pos %i\n",i,pWB->sheets.sheet[i].name,pWB->sheets.sheet[i].filepos);
pWS=xls_getWorkSheet(pWB,0);
xls_parseWorkSheet(pWS);
fprintf(f,"<style type=\"text/css\">\n%s</style>\n",xls_getCSS(pWB));
fprintf(f,"<table border=0 cellspacing=0 cellpadding=2>");
for (t=0;t<=pWS->rows.lastrow;t++)
{
row=&pWS->rows.row[t];
// xls_showROW(row->row);
fprintf(f,"<tr>");
for (tt=0;tt<=pWS->rows.lastcol;tt++)
{
if (!row->cells.cell[tt].ishiden)
{
fprintf(f,"<td");
if (row->cells.cell[tt].colspan)
fprintf(f," colspan=%i",row->cells.cell[tt].colspan);
// if (t==0) fprintf(f," width=%i",row->cells.cell[tt].width/35);
if (row->cells.cell[tt].rowspan)
fprintf(f," rowspan=%i",row->cells.cell[tt].rowspan);
fprintf(f," class=xf%i",row->cells.cell[tt].xf);
fprintf(f,">");
if (row->cells.cell[tt].str!=NULL && row->cells.cell[tt].str[0]!='\0')
fprintf(f,"%s",row->cells.cell[tt].str);
else
fprintf(f,"%s"," ");
fprintf(f,"</td>");
}
}
fprintf(f,"</tr>\n");
}
fprintf(f,"</table>");
printf("Count of rows: %i\n",pWS->rows.lastrow);
printf("Max col: %i\n",pWS->rows.lastcol);
printf("Count of sheets: %i\n",pWB->sheets.count);
fclose(f);
xls_showBookInfo(pWB);
}
return 0;
}
Thanks in advance,
A: Got the answer to this question on the following location:
http://www.cprogramdevelop.com/2018568/
Those who might be facing the problem with libxls library can refer the above mentioned website.
cheers
| |
doc_5122
|
package main
import (
"fmt"
"html/template"
"net/http"
"local-pkg/pages"
"local-pkg/structs"
)
var tmpl *template.Template
var htmlTags map[string]structs.Tags
func main() {
router := mux.NewRouter()
router.HandleFunc("/", indexHandler).Methods("GET") //works fine
data := pages.GetHTMLTags()
http.HandleFunc("/", testHandler(data)) //-> {{define "index"}}{{template "header" . }}Index{{template "footer"}}{{end}}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := pages.GetHTMLTags()
page2Handler(w, r, data) //-> {{define "index"}}{{template "header" . }}Index{{template "footer"}}{{end}}
})
}
func indexHandler(w http.ResponseWriter, req *http.Request) {
fmt.Println(fmt.Printf("%T", tmpl)) //-> *template.Template
data := pages.GetHTMLTags()
err := tmpl.ExecuteTemplate(w, "index", data["index"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func testHandler(page map[string]structs.Tags) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println(fmt.Printf("%T", tmpl)) //-> prints nothing
err := tmpl.ExecuteTemplate(w, "index", page["index"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func page2Handler(w http.ResponseWriter, r *http.Request, data map[string]structs.Tags) {
fmt.Println(fmt.Printf("%T", tmpl)) //-> prints nothing
err := tmpl.ExecuteTemplate(w, "index", data["index"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Can anyone spot my mistake?
| |
doc_5123
|
struct Token {
int type;
char value[64];
};
and I want put objects of Token to a stream, and functions like get(), peek() all returns an object(or a reference/pointer)?
something like this:
Token token = stream.get(); or
Token* token = stream.get();
A: Here is a recipe for a way to create a custom stream object which can be done by inheriting std::stringbuf
class MyStreamBuf : public std::stringbuf {
//... override some functions from stringbuf (eg. sync) to change behavior
};
class MyInputStream : public std::istream {
MyStreamBuf buf_;
public:
MyInputStream : std::istream(&buf_){
}
//... add more interface here, etc.
}
Continueing from that you should be able to acomplish what you asking for.
| |
doc_5124
|
Say, I have a string I am batman
How can I capture bat in one group and whole of batman in another group?
The word can be anything..
Example:
I am batman
I am superman
I am ironman
Output
bat and batman
sup and superman
iro and ironman
I tried I am (\w{3}|\w*) but it is capturing only one group (1st).
Is it even possible what I am trying?
A: Try this
I am ((\w{3})\w+)
it captures whole word first and first three characters in the second group
Demo
A: Here is the PHP code:
<?php
$string = 'I am Ironman';
preg_match('/I am (\w{3}).*(man)/', $string, $matches);
var_dump($matches);
The output is:
array(3) {
[0]=>
string(12) "I am Ironman"
[1]=>
string(3) "Iro"
[2]=>
string(3) "man"
}
What you want will always be in the first and second ([1] and [2]) indexes of $matches.
| |
doc_5125
|
Till now, I was using mysqli_query($conn, $sql) to send a query to the MySQL server.
Recently I read another technique which use $conn - > query($sql).
I know that $conn->query($sql) is the OOP way of sending query and mysqli_query($conn, $sql) is the procedural method.
I haven't learned Object Oriented PHP yet However, I am going to learn it soon before moving onto a framework.
Could someone tell me the advantages of using $conn->query($sql) over the mysqli_query($conn, $sql)?
Is it more secure? Is there something else to it?
I know OOP is better than Procedural, but I'd like to know the main advantages, from the point of Security(mainly)!
A: Neither.
Three points to get it straight:
*
*There is noting much to "learn". The object syntax is as silly as it seems: just an arrow to access a method or a property. Surely you already go it.
*Second option just gets you less typing:
mysqli_query($mysqli, $query);
vs.
$mysqli->query($query);
*Either way you should be using PDO, not mysqli
I know OOP is better than Procedural
This is just irrelevant here. Do not confuse Object Oriented Programming with object syntax. The former is a very complex topic, which takes years to learn and you are not nearly going to get it soon. While object syntax is just a syntax - no more no less. Nothing too complicated to worry about, nor any dramatical benefits either
A: "OOP is better than Procedural Programming" - I'd say it depends. If we're talking about performance then yes OOP is efficient and more organized than Procedural Programming. If you're building a large complex project then OOP is the way to go. However if we're talking about security then Procedural Programming method is as secure as OOP method. Especially if you're using PDO. When you use PDO, you use named placeholders instead of passing variables directly into the Query which helps prevent attacks such as SQL Injection. And if you use PDO, you don't need to sanitize your inputs by yourself (eliminating extra coding) because PDO takes care of that.
I'd recommend you start learning with PDO because it follows Obejct Oriented Programming styles so if you start with it, you'll already be one step ahead when you start writing code in OOPHP. Hope that helps.
| |
doc_5126
|
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css/common|robots\.txt|sitemap\.xml|test\.html|sitemap\.xml)
RewriteRule ^(.*)$ /index.php/$1 [L]
A: Try to improve you question-asking skills. It would be nice to see that you tried something of even checked you original configuration wihtout calling for help with a copy-paste (duplicate entry...).
Automated tools can at best try to apply pre-cooked recipes or 1 -> 1 relations between Apache and nginx rules.
They will fail at understanding what you wish to do and will most probably won't give you the best/cleanest/leanest/most recommended solution.
Here, for example, @Cheery tool even ignored the condition... -_-'
Try the following:
location /index.php {
}
location /images {
}
location /css/common {
}
location /robots.txt {
}
location /sitemap.xml {
}
location /test.html {
}
location / {
# Use 301 instead of 302 for permanent redirect
return 302 $scheme://$host/index.php$request_uri;
}
| |
doc_5127
|
If I write an MQL5 code, it will work in MetaTrader Terminal 4;but if I write an MQL4 code, will this work in MetaTrader Terminal 5?
A: No, it will not.
MQL4 started it's "secret transition" towards MQL5 syntax / concept foundations very surprisingly & painfully somewhere around Build-6xx+
There is zero motivation for MetaQuotes, Inc., to reverse & block this marketing driven shift by re-engineering of the MetaTrader Terminal 5 code-execution environment so as to become "backward compatible".
Epilogue
If interested in more details, one may like other posts on impacts on code-base in these posts on how painfull was anMQL4 shift towards MQL5-syntax since it had started and was creeping forward.
| |
doc_5128
|
So i have
namespace ultragrep
{
class File {
public:
int lineNumber;
std::string contents;
std::string fileName;
File(int ln, std::string lc, std::string fn) : lineNumber(ln), contents(lc), fileName(fn) {};
File() {};
~File(){};
string ln_toString() {
return "[" + std::to_string(lineNumber) + "]";
}
string contents_toString() {
return " \"" + contents + "\" ";
}
};
std::ostream& operator<<(std::ostream& out, const File& f) {
return out << "[" << f.fileName << "]...";
}
//operator < so sort works
bool operator < (File& lhs, File& rhs)
{
return lhs.fileName < rhs.fileName;
}
}
and when all my threads are done in my main() i have
sort(files.begin(), files.end());
for (ultragrep::File file : files)
{
cout << file << file.ln_toString() << file.contents_toString() << endl;
}
and this seemingly returns the results i am expecting but there is no guarantee that the line numbers are also sorted within' a grouping of results.
example results:
[file1.txt]...[1] "clock hello"
[file4.txt]...[1] "hello hello "
[file4.txt]...[2] "hello"
[file4.txt]...[3] "hello hello hello hello "
[file4.txt]...[5] "hello"
[file6.txt]...[3] "hello"
is there a snippet of code i could add into the < overload to account for a secondary sort param?
A: //operator < so sort works
bool operator < (File& lhs, File& rhs)
{
if (lhs.fileName == rhs.fileName)
{
return lhs.lineNumber < rhs.lineNumber;
}
return lhs.fileName < rhs.fileName;
}
| |
doc_5129
|
A: Overriding a function or method requires a signature match. You can, however, create a function overload with a different signature, and call the original function from it.
| |
doc_5130
|
"i_field": {
"$or": [{
query_1
}, {
query_2
}
]
}
However mongo throws exception "Can't canonicalize query: BadValue unknown operator: $or" since I must use $or in top level (or that's my understanding so far).
Working OR in top level query: (but that's not what I need)
"$or": [{
"i_field": query_1
}, {
"i_field": query_2
}
]
Does anyone have any suggestions how could I make this query work?
Edit (real exmple):
"i_field": {
"$or": [{
"$gte": 3.5,
"$lt": 88.5
}, {
"$eq": null
}
]
}
A: Putting $or in the top level is the way to go:
"$or":[
{ "i_field":{"$gte": 3.5, "$lt": 88.5}},
{ "i_field": null}
]
Playground
A: Use $in instead:
{ "i_field": { "$in": [query_1, query_2] } }
| |
doc_5131
|
server {
server_name foo.com;
set $s3_bucket 'foo.com.s3.amazonaws.com';
proxy_http_version 1.1;
proxy_set_header Host $s3_bucket;
proxy_set_header Authorization '';
proxy_hide_header x-amz-id-2;
proxy_hide_header x-amz-request-id;
proxy_hide_header Set-Cookie;
proxy_ignore_headers "Set-Cookie";
proxy_buffering off;
proxy_intercept_errors on;
resolver 172.16.0.23 valid=300s;
resolver_timeout 10s;
location ~* ^/(assets|styles)/(.*) {
set $url_full '$1/$2';
proxy_pass http://$s3_bucket/live/$url_full;
}
location / {
rewrite ^ /live/index.html break;
proxy_pass http://$s3_bucket;
}
}
I don't assume anything with this config. It could all be completely wrong.
It does "work". I can go to foo.com and the site serves and I can navigate and it all work wonders. But it won't load any URL that is not /. All other redirect to / and that is a problem.
What am I doing wrong? All help appreciated.
| |
doc_5132
|
Person personEntity=personArrayList.get(0);
personEntity.setCardType("add");
personArrayList.add(1,personEntity);
A: Write a copy constructor for Person and do this:
Person personEntity = new Person(personArrayList.get(0));
Your copy constructor will depend on the structure of your Person class. The copy constructor will use the values of properties in personArrayList.get(0) to initialize a new instance of Person.
A: What if you try to clone it?
Person personEntity=personArrayList.get(0).clone();
personEntity.setCardType("add");
personArrayList.add(1,personEntity);
Or even better define a constructor in Person that you create using a Person as parameter then you can do
Person personEntity= Person.from(personArrayList.get(0));
personEntity.setCardType("add");
personArrayList.add(1,personEntity);
A: You should implement Cloneable interface.
https://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html
Object.clone() supports only shallow copying but we will need to override it if we need deep cloning.
Then, you just need to create this method:
@Override
public Test clone(){
try {
return (Test)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
That's because Object.clone() is protected.
You can get more info at
https://www.javatpoint.com/object-cloning
| |
doc_5133
|
I'm using a Backbone view to control jPlayer, and here's the initialize function:
initialize: function() {
_.bindAll(this, 'render', 'get_media_url', 'on_player_error',
'play', 'scrub', 'move_playhead', 'on_media_progress',
'on_player_ready', 'on_player_timeupdate', 'on_player_ended',
'set_progress_bar', 'set_current_time', 'time_from_percent');
// set up jplayer and bind essential events to view methods, bound to the current object
$(this.player).jPlayer(this.player_defaults);
$(this.player).bind($.jPlayer.event.ready, _.bind(this.on_player_ready, this));
$(this.player).bind($.jPlayer.event.timeupdate, _.bind(this.on_player_timeupdate, this));
$(this.player).bind($.jPlayer.event.ended, _.bind(this.on_player_ended, this));
$(this.player).bind($.jPlayer.event.progress, _.bind(this.on_media_progress, this));
$(this.player).bind($.jPlayer.event.error, _.bind(this.on_player_error, this));
this.current_state = this.PAUSED;
},
on_media_progress: function(event){
$('time#total').html($.jPlayer.convertTime(event.jPlayer.status.duration));
},
on_player_error: function(event){
alert(event);
},
(cut off the rest of the methods due to brevity, but you'll see the methods are defined the same; on_media_progress fires without fail. on_player_error however, NADA!)
on_player_ready, on_player_timeupdate, on_player_ended and on_media_progress all fire correctly.
on_player_error, however, never gets called.
I've got only an MP3 being passed into setMedia, and I do not have Flash installed and I'm loading the page on Firefox 9.0.1, but
If I set errorsAlert: true in the this.player_defaults object, jPlayer presents it's own error dialog, but my error handler still never fires.
A: Could be because there are specific error events:
http://jplayer.org/latest/developer-guide/#jPlayer-event-error-codes
A: The answer, thanks to the jPlayer Google Group, the answer is that you need to do all your binding prior to instantiating the jPlayer object -- once it's been instantiated the error event has already fired, so you can't capture it anymore!
So you need to do this:
$(this.player).bind($.jPlayer.event.ready, _.bind(this.on_player_ready, this));
$(this.player).bind($.jPlayer.event.timeupdate, _.bind(this.on_player_timeupdate, this));
$(this.player).bind($.jPlayer.event.ended, _.bind(this.on_player_ended, this));
$(this.player).bind($.jPlayer.event.progress, _.bind(this.on_media_progress, this));
$(this.player).bind($.jPlayer.event.error, _.bind(this.on_player_error, this));
$(this.player).jPlayer(this.player_defaults);
| |
doc_5134
|
How I can prevent their existence?
The only thing I can find in these files is EF stuff:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxx requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.OData.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.12.0.0" newVersion="6.12.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.OData.Core" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.12.0.0" newVersion="6.12.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.12.0.0" newVersion="6.12.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
| |
doc_5135
|
date.html
Start Date (mm/yyyy): <input type="date" id="start_date" min="" max="">
End Date (mm/yyyy): <input type="date" id="end_date" min="" max=""/>
date.js
//Last Valid/Year = 2014-06-01
//First Month/Year = 2012-11-01
//Max does not work even if I hard code it.
jQuery('#start_date').attr({ "max": lastValidYear.toString() + "-" + lastValidmonth.toString() + "-" + "01", "min": FirstYear.toString() + "-" + FirstMonth.toString() + "-" + "01"});
jQuery('#end_date').attr({ "max": lastValidYear.toString() + "-" + lastValidmonth.toString() + "-" + "01", "min": FirstYear.toString() + "-" + FirstMonth.toString() + "-" + "01" });
A: Oh my gosh, a really easy fix that took me literally all day. My last Valid year was 2014-6-30. But the max needs to be read in as a yyyy/mm/dd format. The fix was to add a 0 before the month if it is not october, december or november and to make sure that the day you are picking is a valid day in the month. I.E, I was reading in 2014-6-31, and there are not 31 days in June. So the final string needed to be read in as 2014-06-30 instead of 2014-6-31
jQuery('#end_date').attr({
"min": v.FirstYear.toString() + "-" + v.FirstMonth.toString() + "-" + "01",
"max": v.LastYear.toString() + "-" + "0" + v.LastMonth.toString() + "-" + "30",
"value": v.LastYear.toString() + "-" + "0" + v.LastMonth.toString() + "-" + "01"
});
A: use Firstmonth instead of FirstMonth "unknown variable used.this is problem."
jQuery('#start_date').attr({ "max": lastValidYear.toString() + "-" + lastValidmonth.toString() + "-" + "01", "min": FirstYear.toString() + "-" + Firstmonth.toString() + "-" + "01"});
jQuery('#end_date').attr({ "max": lastValidYear.toString() + "-" + lastValidmonth.toString() + "-" + "01", "min": FirstYear.toString() + "-" + Firstmonth.toString() + "-" + "01" });
| |
doc_5136
|
Firefox behaves like I want, IE doesn't.
So I tried to trap the event in the onclick handler:
function my_onclick_handler(evt){
if (!evt) evt = window.event;
// ... handle the click
if (evt.stopPropagation) evt.stopPropagation();
evt.cancelBubble = true;
}
That didn't work so then I thought maybe it's actually the onmouseup or onmousedown events that trigger the anchor tag so I added a clickSwallow method to onmouseup and onmousedown methods:
function clickSwallow(evt){
if (!evt) evt = window.event;
if (evt.stopPropagation) evt.stopPropagation();
evt.cancelBubble = true;
}
That didn't work either. Any ideas how to keep the enclosing anchor from reacting to the click in this case?
A: I would just use a <span>, but I think returning false from the event handler should also do the trick.
A: This post has a few items yours doesn't (like e.returnValue and e.preventDefault) but from the text it appears those are FF specific functions. Might be worth a shot though.
A: Try to change your anchor to:
<a href="javascript:void(0)"> <img src="..." onclick=".."> </a>
| |
doc_5137
|
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Headers["Accept-Encoding"] = "gzip, deflate";
httpWebRequest.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);
httpWebRequest.Timeout = this.Timeout;
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Method = method;
httpWebRequest.KeepAlive = this.KeepAlive;
httpWebRequest.ContentType = this.ContentType;
httpWebRequest.Accept = this.Accept;
httpWebRequest.UserAgent = this.UserAgent;
httpWebRequest.Referer = this.Referer;
httpWebRequest.ProtocolVersion = HttpVersion.Version11;
httpWebRequest.AllowAutoRedirect = true;
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.AllowWriteStreamBuffering = false;
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
httpWebRequest.Proxy = WebRequest.DefaultWebProxy;
The url is: somewhere.com/index?1yyezksvrgzkelork□=rgu{z5iihy5zvreiihy&1iutlomLork=gjsot5otjk~
Referer: somewhere.com/index?1yyezksvrgzkelork□=rgu{z5iihy5zvreiihy&1iutlomLork=gjsot5otjk~
If use only url it's running normally.
A: Try encoding your referer with HttpUtility.UrlEncode(...)
| |
doc_5138
|
This is my .NET Core API code:
public async Task<IActionResult> Rotate([FromBody] PhotoRotateViewModel model)
{
var photo = await _photoRepository.Get(model.PhotoId);
if (photo != null)
{
byte[] imageBytes;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(photo.imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
var rotatedImage = RotateImage(imageBytes);
}
return Ok();
}
private byte[] RotateImage(byte[] imageInBytes)
{
using (var image = Image.Load(imageInBytes, out var imageFormat))
{
image.Mutate(x => x.Rotate(90));
return ImageToByteArray(image, imageFormat);
}
}
private byte[] ImageToByteArray(Image<Rgba32> image, IImageFormat imageFormat)
{
using (var ms = new MemoryStream())
{
image.Save(ms, imageFormat);
return ms.ToArray();
}
}
It looks like the new image gets cut off.
I've attached my original image, and the result that I get
Original:
Rotated:
This appears to be happening to all the images I've tried
A: I have had a look at the api docs. of ImageSharp and it seems there is no problem either in the library or your code(the part you rotate the image). But what seems interesting to me is that when you read the bytes, you set a number for the bytes to be read. Instead of reading like this imageBytes = br.ReadBytes(500000);, try read the bytes until the end of the stream. To do that try below code.
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(int.MaxValue);
br.Close();
}
Edit:
To deal with out of memory exception and to read the file with the help of this answer or simply setting br.ReadBytes(stream.Length);.
| |
doc_5139
|
I'm developing a map application in which the users will select the
origin and destination points from a list of available points in
drop-down. All I want is that the map generated should take the values
of latitude and longitude instead of string values as I mentioned in
below code. How can I achieve this?
I also wonder if I could draw my custom map with my own routes instead of google generated routes.
Any help is appreciated!
<b>Start: </b>
<select id="start" onchange="calcRoute();">
<option value="chicago, il">Chicago</option>
<option value="st louis, mo">St Louis</option>
<option value="joplin, mo">Joplin, MO</option>
<option value="oklahoma city, ok">Oklahoma City</option>
<option value="amarillo, tx">Amarillo</option>
<option value="gallup, nm">Gallup, NM</option>
<option value="flagstaff, az">Flagstaff, AZ</option>
<option value="winona, az">Winona</option>
<option value="kingman, az">Kingman</option>
<option value="barstow, ca">Barstow</option>
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select>
<b>End: </b>
<select id="end" onchange="calcRoute();">
<option value="chicago, il">Chicago</option>
<option value="st louis, mo">St Louis</option>
<option value="joplin, mo">Joplin, MO</option>
<option value="oklahoma city, ok">Oklahoma City</option>
<option value="amarillo, tx">Amarillo</option>
<option value="gallup, nm">Gallup, NM</option>
<option value="flagstaff, az">Flagstaff, AZ</option>
<option value="winona, az">Winona</option>
<option value="kingman, az">Kingman</option>
<option value="barstow, ca">Barstow</option>
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select>
</div>
The JS part is :
<script>
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 41.85,
lng: -87.65
}
});
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
A: You may use waypoints for this, you will have to put location which is the address of the waypoint. You can have an array of waypoints to add to your route. Please see this documentation to know how to use this.
| |
doc_5140
|
Hi I have a problem where my black horizontal lines between menu items is also appearing in the dropdown menu which looks messy. An example is in the above image. Any ideas how I might remove it/exclude the drop down menu from my code which is below
.site-nav li {
border-left: 1px solid #000000;
margin: 0px 0;
}
.site-nav li:first-child {
border-left: none;
}
.site-nav li > a {
line-height: 20px;
height: 20px;
}
Thanks for your help
Francis
A: If .site-nav is your class for your ul element, try this.
.site-nav > li {
border-left: 1px solid #000000;
margin: 0px 0;
}
Or, if .site-nav is not defined class for ul element, try this.
.site-nav ul > li {
border-left: 1px solid #000000;
margin: 0px 0;
}
A: Change the line .site-nav li { to .site-nav > ul > li {
(Or: .site-nav > li { if your site-nav class is on the ul element.)
You can also add this to your css instead:
site-nav li li {
border-left: none;
}
Another option is to add this class to the elements that you wish to remove the borders on:
.no-border {
border-left: none;
}
A: You can simply remove the border from your nested li the same way you've removed it from the first-child
.site-nav > [dropdown element name] li {
border-left: none;
}
| |
doc_5141
|
Should I scan the array for each string ?
thanks
A: You could do this by creating a new set from the array. The set will only contain unique entries so if the number of elements in the set is 1 then all items in the array was equal.
NSSet *uniqueItems = [NSSet setWithArray:yourArray];
if ([uniqueItems count] < 2) {
// All items in "yourArray" are the same (no matter how many they are)
}
In the above example I'm considering an empty set (meaning an empty array) as a being unique as well. If you don't then you can change the if-statement to if ([uniqueItems count] == 1) { ... }
This will also work for any object, not just strings.
A: The NSArray class is general-purpose so it won't contain functionality to perform this, so yes, you'll have to check each string yourself.
A: trojanfoe is right. You can enhance NSArray with category and do something like this ...
NSArray *array = @[ @"A", @"B", @"C" ];
__block BOOL allObjectsAreEqual = YES;
if ( array.count > 1 ) {
NSString *firstObject = array[0];
[array enumerateObjectsUsingBlock:^void(id obj, NSUInteger idx, BOOL *stop) {
if ( idx == 0 ) {
return;
}
if ( ( allObjectsAreEqual = [firstObject isEqualToString:obj] ) == NO ) {
*stop = YES;
}
}];
// And here check for allObjectsAreEqual ...
... there're many ways how to do this.
A: Are you wanting to check whether all the strings are equal to each other?
@interface NSArray (MyAdditions)
- (BOOL) isFilledWithEqualObjects {
if (!self.count) return YES;
id firstObject = [self objectAtIndex:0];
for (id obj in self) {
// Avoid comparing firstObject to itself (and any other pointers to
// firstObject)
if (firstObject == obj) continue;
if (![firstObject isEqual:obj]) return NO;
}
return YES;
}
@end
That example uses -isEqual:, to work with any kind of object. If you know the contents are strings, you can use -isEqualToString: instead:
if (![firstObject isEqualToString:obj]) return NO;
| |
doc_5142
|
My code points at a directory that contains 60 or so subfolders. Within these subfolders are multiple files .PDF/.XLS etc. The following code works fine if the files are not embedded in the subfolders but what I need to do is be able to loop through the subfolders and pull the files themselves to move. Also, is there a way to eventually pull files by wildcard name? Thanks in advance for any help.
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim Fdate As Date
Dim FileInFromFolder As Object
FromPath = "H:\testfrom\"
ToPath = "H:\testto\"
Set FSO = CreateObject("scripting.filesystemobject")
For Each FileInFromFolder In FSO.getfolder(FromPath).Files
Fdate = Int(FileInFromFolder.DateLastModified)
If Fdate >= Date - 1 Then
FileInFromFolder.Copy ToPath
End If
Next FileInFromFolder
End Sub
A: You can also use recursion. Your folder can have subfolders having subfolders having ...
Public Sub PerformCopy()
CopyFiles "H:\testfrom\", "H:\testto\"
End Sub
Public Sub CopyFiles(ByVal strPath As String, ByVal strTarget As String)
Set FSO = CreateObject("scripting.filesystemobject")
'First loop through files
For Each FileInFromFolder In FSO.getfolder(strPath).Files
Fdate = Int(FileInFromFolder.DateLastModified)
If Fdate >= Date - 1 Then
FileInFromFolder.Copy strTarget
End If
Next FileInFromFolder
'Next loop throug folders
For Each FolderInFromFolder In FSO.getfolder(strPath).SubFolders
CopyFiles FolderInFromFolder.Path, strTarget
Next FolderInFromFolder
End Sub
A: I managed to get this code to work. It copies all folders / files and sub folders and their files to the new destination (strTarget).
I have not added checks and balances like 1) if the files and folders exist already. 2) if the source files are open etc. So those additions could be useful.
I got this code from Barry's post but needed to change it to make it work for me, so thought i'd share it again anyway.
Hope this is useful though. . .
strPath is the source path and strTarget is the destination path. both paths should end in '\'
Note: one needs to add "Microsoft Scripting Runtime" under "Tools / References" for FSO to work.
==================== call ================================
MkDir "DestinationPath"
CopyFiles "SourcePath" & "\", "DestinationPath" & "\"
==================== Copy sub ===========================
Public Sub CopyFiles(ByVal strPath As String, ByVal strTarget As String)
Dim FSO As Object
Dim FileInFromFolder As Object
Dim FolderInFromFolder As Object
Dim Fdate As Long
Dim intSubFolderStartPos As Long
Dim strFolderName As String
Set FSO = CreateObject("scripting.filesystemobject")
'First loop through files
For Each FileInFromFolder In FSO.GetFolder(strPath).Files
Fdate = Int(FileInFromFolder.DateLastModified)
'If Fdate >= Date - 1 Then
FileInFromFolder.Copy strTarget
'end if
Next
'Next loop throug folders
For Each FolderInFromFolder In FSO.GetFolder(strPath).SubFolders
'intSubFolderStartPos = InStr(1, FolderInFromFolder.Path, strPath)
'If intSubFolderStartPos = 1 Then
strFolderName = Right(FolderInFromFolder.Path, Len(FolderInFromFolder.Path) - Len(strPath))
MkDir strTarget & "\" & strFolderName
CopyFiles FolderInFromFolder.Path & "\", strTarget & "\" & strFolderName & "\"
Next 'Folder
End Sub
A: I found the solution here:
Private Sub Command3_Click()
Dim objFSO As Object 'FileSystemObject
Dim objFile As Object 'File
Dim objFolder As Object 'Folder
Const strFolder As String = "H:\testfrom2\"
Const strNewFolder As String = "H:\testto\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFolder In objFSO.GetFolder(strFolder & "\").SubFolders
'If Right(objFolder.Name, 2) = "tb" Then
For Each objFile In objFolder.Files
'If InStr(1, objFile.Type, "Excel", vbTextCompare) Then
On Error Resume Next
Kill strNewFolder & "\" & objFile.Name
Err.Clear: On Error GoTo 0
Name objFile.Path As strNewFolder & "\" & objFile.Name
'End If
Next objFile
'End If
Next objFolder
End Sub
| |
doc_5143
|
$_SERVER['REMOTE_ADDR'];
But I see it can not give the correct IP address using this. I get my IP address and see it is different from my IP address and I can also see my IP address in some website like:
http://whatismyipaddress.com/
I paste the IP address which give my PHP function but this website shows no result about this. How does this problem come about and how can I get IP address of the client?
A: The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
A: In PHP 5.3 or greater, you can get it like this:
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
A: $ipaddress = '';
if ($_SERVER['HTTP_CLIENT_IP'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if ($_SERVER['HTTP_X_FORWARDED_FOR'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if ($_SERVER['HTTP_X_FORWARDED'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if ($_SERVER['HTTP_FORWARDED_FOR'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if ($_SERVER['HTTP_FORWARDED'] != '127.0.0.1')
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1')
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
A: Here is a function to get the IP address using a filter for local and LAN IP addresses:
function get_IP_address()
{
foreach (array('HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $IPaddress){
$IPaddress = trim($IPaddress); // Just to be safe
if (filter_var($IPaddress,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
!== false) {
return $IPaddress;
}
}
}
}
}
| |
doc_5144
|
suppose there is no name for the device default it was displaying the Bluetooth address.
Now my doubt is want to display only Bluetooth name for every time. Sometime Bluetooth name is displaying and sometimes Bluetooth address is displaying.
can any one please help me want to show every time Bluetooth name.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final DeviceListViewHolder viewHolder = (DeviceListViewHolder) holder;
if (mDevices != null) {
BluetoothDevice bluetoothDevice = mDevices.get(position);
if (bluetoothDevice != null) {
String deviceName = bluetoothDevice.getName();
if (!TextUtils.isEmpty(deviceName)) {
viewHolder.mDeviceName.setText(deviceName);
} else {
viewHolder.mDeviceName.setText(bluetoothDevice.getAddress());
}
}
}
}
A: Every Bluetooth device will not have a name. But yes address will always be there. So, make sure first whether your Bluetooth device is having a name if not then you can display some default name instead displaying address.
| |
doc_5145
|
*
*When starting the interactive Python interpreter with default
settings, is there any module implicitly imported/loaded into the
interpreter, without explicitly running import <modulename>?
I thought that modules like sys or builtins would be, but when I
type their module names,
>>> sys
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
>>> builtins
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'builtins' is not defined
So is it correct that by default, there is no module imported/loaded implicitly?
*When executing a python script, is there any module implicitly
imported/loaded into the script, without explicitly specifying
import <modulename> in the script?
Thanks.
A: One module that is usually imported automatically is site.py. And it imports a lot of other modules. But even if you prevent it from importing using option -S Python still imports many modules. Try the following script:
#! /usr/bin/python2.7 -ESs
import sys
print(sys.modules)
and see how many modules are there. Change shebang to
#! /usr/bin/python3 -EISs
and say "Wow!" :-)
A: Only __builtins__:
#! /usr/bin/python2.7 -ESs
print(dir())
=> ['__builtins__', '__doc__', '__file__', '__name__', '__package__']
| |
doc_5146
|
root@beaglebone:/tmp# cat env.output
HOME=/root
LOGNAME=root
PATH=/usr/bin:/bin
LANG=en_US.UTF-8
SHELL=/bin/sh
PWD=/root
I have given my crontab like this
SHELL=/bin/sh
PATH=/usr/bin:/bin
24 20 09 11 * python3 /bin/remote_iomodified.py
What will be the path for my corntab
A: Always use absolute paths when adding cronjobs:
24 20 09 11 * /usr/bin/python3 /bin/remote_iomodified.py
A: If you're asking for the location of a crontab file than it's under
/var/spool/cron/crontabs/username
But you really shouldn't edit them directly
| |
doc_5147
|
The <classpath> or <modulepath> for <junit> must include junit.jar if not in Ant's own classpath
I could probably hack the build script to include junit.jar, but I want to know: what's the right way to fix this?
Shouldn't NetBeans come with a version of JUnit already accessible? Should I configure my project differently? How do I add a path to the library?
How can I find the classpath for Ant (and what version/binary NetBeans is using)?
The project Test Libraries shows that JUnit 5.3.1 is present, I have three Jar files listed there: junit-jipiter-api, junit-jupiter-params, junit-jupiter-engine. But it seems to be not actually found.
The project is a standard Java Library (no main class). I didn't add any "extras" or mess with the default project setup that NetBeans uses. Just used the basic setup wizard thing.
Re. a reply from the NetBeans mailing list by Geertjan Wielenga, he pointed me at this thread and reply:
Yep...
We never got around to implementing JUnit 5 support for Ant based projects in NB 10.
John McDonnell
http://mail-archives.apache.org/mod_mbox/netbeans-users/201901.mbox/%3cCAAuDyk6WcgLaUDz0dp=4Arr7QGnwWcYey3VOeGojRRMRqVZrFA@mail.gmail.com%3e
So I think it's just not going to work. I'll try the suggested reversion to JUnit 4 below.
A: I'm running netbeans 10 as well, in xubuntu if that helps. I have no idea what is going on, so I had to revert to junit4.
EDIT: To be perfectly clear, ant needs junit.jar which is nowhere to be found in the default netbeans 10 installation.
Until someone brings a better solution, revert to junit4:
1) in your test libraries, right click and import the junit 4.1.2 ones.
2) remove the junit 5.3 ones.
3) scrap all the imports in your test file and use the junit4 ones. ie your imports will look like:
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
import org.junit.*;
/*import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;*/
4) scrap the beforeAll and other test tags. Only leave the @Test one.
5) save all, close and re-open the project. It will complain that the hamcrest libraries for junit4 are not imported. Allow netbeans to fix it for you.
With that done, I was able to test successful and failing tests. I guess when you generate the junit tests with the template generator, it will generate the junit5 ones, so, a bit annoying. But you'll have tests!
A: I had the same error but it was not a configuration issue, it was only a typo.
The main method of the class I was testing was written like this:
public static void main(String agrs) {
///
}
The only thing I had to do was to write it properly, like this:
public static void main(String[] args) {
///
}
Once I changed it, the problem was gone.
I suppose this is not a global solution, but may help some.
A: I found a better solution to the accepted answer is to select JUnit 4 from Create/Update tests. Then you don't have to reconfigure your tests every time.
From Netbeans: https://netbeans.apache.org//kb/docs/java/junit-intro.html#_writing_junit_3_unit_tests
A: I faced the same problem. I removed the existing Junit 5 files and added the files here instead.
https://github.com/junit-team/junit4/wiki/Download-and-Install
| |
doc_5148
|
self.calc_tax_button.clicked.connect(self.CalculateTax)
AttributeError: 'AppWindow' object has no attribute 'calc_tax_button'
I am using python on eclipse.
My main code till now.
**gu1.py**
import sys
# from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QMainWindow, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
from design import Ui_MainWindow
class AppWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
self.calc_tax_button.clicked.connect(self.CalculateTax)
def CalculateTax(self):
price = int(self.price_box.toPlainText())
tax = (self.tax_rate.value())
total_price = price + ((tax / 100) * price)
total_price_string = "The total price with tax is: " + str(total_price)
self.results_window.setText(total_price_string)
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())
My design code.
**design.py**
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'design.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.price_box = QtWidgets.QTextEdit(self.centralwidget)
self.price_box.setGeometry(QtCore.QRect(240, 100, 104, 71))
self.price_box.setObjectName("price_box")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(140, 130, 51, 21))
font = QtGui.QFont()
font.setFamily("Georgia")
font.setPointSize(14)
self.label.setFont(font)
self.label.setObjectName("label")
self.tax_rate = QtWidgets.QSpinBox(self.centralwidget)
self.tax_rate.setGeometry(QtCore.QRect(240, 220, 101, 31))
self.tax_rate.setProperty("value", 0)
self.tax_rate.setObjectName("tax_rate")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(130, 230, 71, 21))
font = QtGui.QFont()
font.setFamily("Georgia")
font.setPointSize(12)
font.setBold(False)
font.setWeight(50)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.calc_tax_button = QtWidgets.QPushButton(self.centralwidget)
self.calc_tax_button.setGeometry(QtCore.QRect(240, 310, 101, 31))
self.calc_tax_button.setObjectName("calc_tax_button")
self.results_window = QtWidgets.QTextEdit(self.centralwidget)
self.results_window.setGeometry(QtCore.QRect(240, 390, 104, 71))
self.results_window.setObjectName("results_window")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(160, 20, 301, 41))
font = QtGui.QFont()
font.setFamily("Georgia")
font.setPointSize(20)
font.setBold(True)
font.setItalic(True)
font.setUnderline(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Price"))
self.label_2.setText(_translate("MainWindow", "Tax Rate"))
self.calc_tax_button.setText(_translate("MainWindow", "Calculate Tax"))
self.label_3.setText(_translate("MainWindow", "Sales Tax Calculator"))
A: The classes generated by pyuic are intended to be used as a mixin, e.g:
import sys
# from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QMainWindow, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
from design import Ui_MainWindow
class AppWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.show()
self.calc_tax_button.clicked.connect(self.CalculateTax)
@pyqtSlot()
def CalculateTax(self):
price = int(self.price_box.toPlainText())
tax = (self.tax_rate.value())
total_price = price + ((tax / 100) * price)
total_price_string = "The total price with tax is: " + str(total_price)
self.results_window.setText(total_price_string)
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())
You tried to use it by creating a dedicated ui object which then holds all ui elements. That can also work, but then you need to access everything through the ui attribute:
class AppWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
self.ui.calc_tax_button.clicked.connect(self.CalculateTax)
@pyqtSlot()
def CalculateTax(self):
price = int(self.ui.price_box.toPlainText())
tax = (self.ui.tax_rate.value())
total_price = price + ((tax / 100) * price)
total_price_string = "The total price with tax is: " + str(total_price)
self.ui.results_window.setText(total_price_string)
A: You are creating an object self.ui which is the constructor class for your GUI. You will have to address your GUI and all widgets in it through that object.
import sys
# from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QMainWindow, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
from design import Ui_MainWindow
class AppWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
@pyqtSlot()
def CalculateTax(self):
price = int(self.ui.price_box.toPlainText())
tax = (self.ui.tax_rate.value())
total_price = price + ((tax / 100) * price)
total_price_string = "The total price with tax is: " + str(total_price)
self.ui.results_window.setText(total_price_string)
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())
| |
doc_5149
|
For example, I have 1TB of text data, and lets assume that 300GB of it is
the word
"Hello".
After each map operation, i will have a collection of key-value pairs of <"Hello",1>.
But as I said, this is a huge collection, 300GB and as I understand , the reducer gets all of it and will crush.
What is the solution for this? Lets assume that the combiner won't help me here(the WordCount example is just for simplicity) and the data will still be too big for the reducer.
A: The intermediate (Mapper) output is stored in the Local File System of the nodes running the mapper task and is cleaned afterwards. Note that this mapper output is NOT stored in HDFS. The reducer indeed gets all the the intermediate key-value pairs for any particular key (i.e.. all 300 GB output for the key 'Hello' will be processed by the same Reducer task). This data is brought to memory only when required.
Hope this helps.
A: The reducer does get all of that data, but that data is actually written to disk and is only brought into memory as you iterate through the Iteratable of values. In fact, the object that is returned by that iteration is reused for each value: the fields and other state are simply replaced before the object is handed to you. That means you have to explicitly copy the value object in order to have all value objects in memory at the same time.
| |
doc_5150
|
arr[2, 3]
This means element at intersection of 3nd row and 4th column. What confuses me separation of different indices by comma inside square brackets (like in function arguments). Doing so with python lists is not valid:
l = [[1, 2], [3, 4]]
l[1, 1]
Traceback (most recent call last):
File "", line 1, in
TypeError: list indices must be integers or slices, not tuple
So, if this not a valid python syntax, how numpy arrays work?
A: Use Colon ':' instead of commas ','.
In slicing or indexing is done using colon ':'
In your above example,
l = [[1, 2], [3, 4]]
->l[0] is [1,2] and -> l[1] is [3,4]
Read further documentation for better understanding.
Thank You
A: In your given example, you're comparing a numpy array to a list of lists. The main difference between the two is that a numpy array is predictable in terms of shape, data type of its elements, and so on, while a list can contain an arbitrary combination of any other python objects (lists, tuples, strings, etc.)
Take this as an example, say you create a numpy array like so:
arr = np.array([[0, 1], [2, 3], [4, 5]])
Here, the shape of arr is known right after instantiation "arr.shape returns (3,2)", so you can easily index the array with only a comma separated square bracket. On the other hand, take the list example:
l = [[0, 1], [2, 3], [4, 5]]
l[0] # This returns the list [0, 1]
l[0].append("HELLO")
l[0] # This returns the list [0, 1, "HELLO"]
A list is very unpredictable, as there's no way to know what each list element will return to you. So, the way we index a specific element in a list of lists is by using 2 square brackets "e.g. l[0][0]"
What if we created a non-uniform numpy array? Well, you get a similar behaviour to a list of lists:
arr = np.array([[0, 1], [2, 3], [4]]) # Here, you get a Warning!
print(arr) # Returns: array([list([0, 1]), list([2, 3]), list([4])], dtype=object)
In this case, you can't index the numpy array using [0, 0]. Instead, you have to use two square brackets, just like a list of lists
You can also check the documentation of ndarray for more info.
| |
doc_5151
|
Whenever I call the method, which is called GetNamespaces, I get a MissingMethodException.
The full exception is as follows: "MissingMethodException: Method not found: 'k8s.Models.V1NamespaceList k8s.KubernetesExtensions.ListNamespace(k8s.IKubernetes, System.String, System.String, System.String, System.Nullable1<Int32>, System.String, System.Nullable1, System.Nullable`1, System.String)'."
This is my code:
NamespacesController
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Administration.Libary;
using Administration.Model;
using k8s.Models;
namespace Administration.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class NamespacesController : ControllerBase
{
private readonly IK8sClient _k8sClient;
public NamespacesController(IK8sClient client)
{
_k8sClient = client;
}
//GET: api/namespaces
[HttpGet]
public async Task<IEnumerable<NameSpace>> GetNamespaces()
{
var result = await _k8sClient.nsService.GetNamespaces();
return result;
}
}
}
K8sClient.cs
using k8s;
using System;
namespace Administration.Libary
{
public class K8sClient : IK8sClient
{
private readonly Kubernetes _k8sClient = null;
public NamespaceService nsService { get; private set; }
public Kubernetes Client
{
get
{
return _k8sClient;
}
}
public K8sClient()
{
string kubeConfigFile = System.IO.Path.Combine(Environment.CurrentDirectory, "kubeconfig");
if (!System.IO.File.Exists(kubeConfigFile)) throw new System.IO.FileNotFoundException("Kube config file not found");
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeConfigFile);
_k8sClient = new Kubernetes(config);
InitiateServices(this);
}
public void InitiateServices(K8sClient client)
{
if (client == null)
throw new ArgumentNullException("Client was null.");
nsService = new NamespaceService(client);
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_k8sClient.Dispose();
}
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
public interface IK8sClient : IDisposable
{
Kubernetes Client { get; }
NamespaceService nsService { get; }
void InitiateServices(K8sClient client);
}
NamespaceService.cs
using Administration.Model;
using k8s;
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
namespace Administration.Libary
{
public class NamespaceService
{
private IK8sClient _k8sClient;
private CreateNsService createNsService;
public NamespaceService(K8sClient client)
{
_k8sClient = client;
createNsService = new CreateNsService(client);
}
public NameSpace selectedNamespace;
private List<string> namespacesToIgnore = new List<string> { "default", "kube-node-lease", "kube-public", "kube-system"};
public Task<List<NameSpace>> GetNamespaces()
{
var namespaceList = new Task<List<NameSpace>>(() => new List<NameSpace>());
var namespaces = _k8sClient.Client.ListNamespace();
foreach (var ns in namespaces.Items)
{
string nsName = ns.Metadata.Name;
if (String.IsNullOrEmpty(nsName))
throw new Exception("Failed to retrieve namespace ID.");
if (!namespacesToIgnore.Contains(nsName) && ns.Status.Phase != "Terminating")
{
namespaceList.Result.Add(new NameSpace()
{
Id = ns.Metadata.Name
});
}
}
return namespaceList;
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Administration.Libary;
namespaceAdministration.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddScoped<IK8sClient, K8sClient>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
The line which should throw the error is: "var namespaces = _k8sClient.Client.ListNamespace();" in the NamespaceService class. It's also notable that I can't enter my NamespaceService class while debugging, when I set a breakpoint in the class it never stops there, even tho it appears that my program enters the class.
| |
doc_5152
|
I'm currently using the 'ode' command in package deSolve (version 1.20). I'm running R version 3.4.2 in RStudio (version 1.1.419) on Windows 10 with 4 GB of RAM. The code reproduced below takes about 16 seconds to run. While that doesn't sound so bad, for tens of thousands of run over a larger dataset, the time is prohibitive. I have performed the code on a super cluster computer across 28 cores; however, it is still time consuming.
start <- Sys.time()
library(deSolve)
##CONTROL PANEL##
state <- c(4,1)
time <- seq(0,9,1)
parms <- c(alpha_star = 4.577,
theta_a = 2.334,
beta_star = 4.560,
theta_b = 0.085,
delta_star = 2.836,
theta_d = 2.496,
gamma_star = 1.254,
theta_g = 0.031)
extVar <- c(154.35, 150.8, 150.85, 152, 152.15, 153.3, 155.1, 154.65, 156.35, 152.5)
data <- data.frame(x = c(4,5,2,5,4,7,8,3,7,10),
y = c(1,3,3,4,9,9,2,2,6,4))
##LOTKA-VOLTERRA##
LotVmod <- function (Time, State, pars) {
with(as.list(c(State, pars)), {
alpha <- alpha_star + theta_a*sigimp(Time)
beta <- beta_star + theta_b*sigimp(Time)
gamma <- gamma_star + theta_g*sigimp(Time)
delta <- delta_star + theta_d*sigimp(Time)
dx = alpha*State[1]-(beta*State[1]*State[2])
dy = (-delta*State[2]) + (gamma*State[1]*State[2])
return(list(c(dx, dy)))
})
}
sigimp <- approxfun(time, extVar, rule=2)
out <- ode(state, time, LotVmod, parms, rtol = 1e-15, maxsteps = 500000)
print(Sys.time() - start)
I would like to shorten the time running the above code by as much as possible. I'm open to any type of solution. Also, if this is a question best suited for another place or another discipline, I'd greatly appreciate you pointing me in the right direction!
Thank you so much!
| |
doc_5153
|
So when user with ID=1 want to send a message to user with ID = 2,
Server search for Socket with UserID = 2 in ClientList to find the right Socket and send user 1's message to the found Socket (user 2's socket).
I'm trying to accomplish this without using socket.io! That's what my employer made me to do! :))
Now my question is: am I doing this right? Is this efficient to check ClientList array (every time a connection send Data) to see if this UserID exists in ClientList? if not, then what is the right and efficient way? there is no problem with my code and it works. but what if there are thousands of connections?
Any Sample code , example or link would be appreciated. Thank you.
here is a pseudo code :
var net = require('net');
var Server = net.createServer();
var myAuth = require('./myAuth');
var ClientList = [];
Server.on('connection', function(Socket){
Socket.UserData = {}; // I want to add user data as a property to Socket
Socket.on('data', function (Data) {
var userID = myAuth.Authenticate_and_getUserID(Data);
if(userID != undefined){
var found = false;
ClientList.filter(function(item){
// check if Socket is in ClientList
if(item.UserData.ID == userID){
// client was connected before
found = true;
}
});
if(!found){
// this is a new connection, Add it to ClientList
Socket.UserData.ID = userID;
ClientList.push(Socket);
}
}
Socket.once('close', function(has_error){
var index = ClientList.indexOf(Socket);
if (index != -1){
ClientList.splice(index, 1);
console.log('Client closed (port=' + Socket.remotePort + ').');
}
});
});
UPDATE for clarification:
is this efficient to look into ClientList every time Data is coming to Server, to check for receiverID (presence of receiver) and to Update ClientList with current connection UserID if not exists?
how should I manage new connections(users) and store them in server for later use when number of users are thousands or millions! NOT 10 or 100. How socket.io is doing this?
later usages could be:
*
*check to see if one specific user is online (have an object in ClientList)
*send realtime message to a user if he/she is online
*etc . . .
A: Actually I am doing this wrong!
Arrays in JavaScript are passed by reference! So there is no need to update ClientList every time a Socket send data.
Therefor the Code changes like Following:
var net = require('net');
var Server = net.createServer();
var myAuth = require('./myAuth');
var ClientList = [];
Server.on('connection', function(Socket){
ClientList.push(Socket);
Socket._isAuthorized = false;
// when socket send data for the first time
// it gets authenticated and next time it send data
// server does not authenticate it
Socket.on('data', function (Data) {
var userID = getUserID(Data);
if(Socket._isAuthorized != true){
if(authenticate(Socket)){
Socket._isAuthorized = true;
Socket._userID = userID;
return;
}
}
// do something with data...
}
Socket.once('close', function(has_error){
var index = ClientList.indexOf(Socket);
if (index != -1){
ClientList.splice(index, 1);
console.log('Client closed (port=' + Socket.remotePort + ').');
}
});
});
And its efficient!
| |
doc_5154
|
Sub OpenFileAsText()
Dim FilePath As String
FilePath = "C:\Users\Default\Desktop\test.csv"
Open FilePath For Input As #1
row_number = 0
Loop Until EOF(1)
Line Input #1, LineFromFile
'cant work out the code to do the check
row_number = row_number + 1
Loop
Close #1
End Sub
A: Thank You for head start. This code does what I need.
Sub Sample()
Dim filename As String
filename = "C:\Users\Default\Desktop\339734.csv"
Dim file As Integer
file = FreeFile
Open filename For Input As #file
Dim rowNumber As Long
rowNumber = 0
Dim match As String
Do Until EOF(file)
rowNumber = rowNumber + 1
Dim line As String
Line Input #file, line
If Len(line) > 15 Then
match = line
Exit Do
End If
Loop
Close #file
If match <> vbNullString Then
MsgBox "Found"
Else
MsgBox "Did not find"
End If
End Sub
A: @Edvardas:
If you are interested in being informed about all lines that are too long, you can use this:
Sub Sample()
Const MAX_LINE_LENGTH As Integer = 15
Dim filename As String
filename = "C:\Users\Default\Desktop\339734.csv"
Dim file As Integer
file = FreeFile
Open filename For Input As #file
Dim lineNumber As Long
lineNumber = 0
Dim matchingLines As String
Do Until EOF(file)
lineNumber = lineNumber + 1
Dim line As String
Line Input #file, line
If Len(line) > MAX_LINE_LENGTH Then
' Concatenate every found line number to a string
matchingLines = matchingLines & CStr(lineNumber) & ", "
End If
Loop
Close #file
' Check if any line has been found
If Len(matchingLines) > 0 Then
' Remove the last ", ".
matchingLines = Left(matchingLines, Len(matchingLines) - 2)
MsgBox "Found those lines: " & matchingLines
Else
MsgBox "Did not find any"
End If
End Sub
A: How About this?
Sub Sample()
Const SEARCH_STRING As String = "SearchThis"
Dim filename As String
filename = "C:\Users\Default\Desktop\test.csv"
Dim file As Integer
file = FreeFile
Open filename For Input As #file
Dim rowNumber As Long
rowNumber = 0
Dim match As String
Do Until EOF(file)
rowNumber = rowNumber + 1
Dim line As String
Line Input #file, line
If InStr(line, SEARCH_STRING) > 0 Then
match = line
Exit Do
End If
Loop
Close #file
If match <> vbNullString Then
MsgBox "Found '" & SEARCH_STRING & "' in line #" & rowNumber & ": " & match, vbInformation, "Result"
Else
MsgBox "Did not find '" & SEARCH_STRING & "'", vbInformation, "Result"
End If
End Sub
Explanation:
In the top of the procedure I defined a constant SEARCH_STRING with the string you may want to search for in the file.
Then in the Do Until loop If InStr(line, SEARCH_STRING) > 0 checks if the read line contains the searched string.
Instr returns the position of a substring in a string. If it is not found it returns 0.
If the string has been found, it is stored in the string variable match and the loop is exited by Exit Do
Afterwards match will be checked, if it contains a value, and regarding to this some information will be posted by a message box.
| |
doc_5155
|
<?php
echo ("Thank you.")
$msg = "Some email message for testing. Please disregard if you receive this in your email.";
$msg = wordwrap($msg,70);
mail("email1@internet.com","Subject Verbiage",$msg);
mail("email2@internet.com","Subject Verbiage",$msg);
?>
Any help would be very appreciated.
| |
doc_5156
|
I have created a new route/action/view:
Controller action:
func (c Ctrl1) Action3() revel.Result {
variable1 := "test1"
variable2 := "test2"
c.Flash.Error("Message")
return c.Render(variable1,variable2)
}
Action3.html:
{{set . "title" "Test"}}
{{template "header.html" .}}
{{template "flash.html" .}}
Hello: {{.variable1}}
{{template "footer.html" .}}
The first time i have runned my webapp, i saw the flash message.
But next times, if i refresh the page, it disapears !
I have restarted revel
Thanks
A: I'm not familiar with revel, but message "flashing" is typically used when you need some user communication to carry over through a redirect. The godoc seems to describe it as exactly for that use case as well.
If you're rendering a template directly in this request handler, you probably shouldn't be using c.Flash. My guess of what is happening is that revel will only show the flash message received with the request. Calling c.Flash.Error sets the field in the cookie, which means it will be sent back to the caller, not to the template. On the next render, it will read from the cookie that the caller sends back to the server, which would include this flash message. Apparently, though, setting a new flash message replaces the old one, causing it to (yet again) send it to the caller not the template.
The good news is that there's really only one way for your message to get on the page, and you can almost definitely shoehorn your message there: the template data! Instead of calling c.Flash.Error, send the message using the usual mechanisms. In this case, assuming your flash.html template contains something like:
{{ if .flash.error }}
<div class="error">{{ .flash.error }}</div>
{{ end }}
you should be able to pass that data by replacing the c.Flash.Error("Message") line with:
c.ViewArgs["flash"] = map[string]string{"error": "Message"}
A: This seems to be a known issue/expected behaviour. As the discussion on github seems to suggest, to use the flash message for errors, you either need to redirect:
c.Flash.Error("Message")
return c.Redirect("App/ShowError")
Or using the field template function if you need to add the error message next to a specific input element.
Seeing as you're not rendering a form in your template, I'm guessing a redirect is what you need to add.
Incidentally: revel is, by many, considered harmful. I'd urge you to not use a framework that attempts to force you to use go following a classical MVC structure. Nowadays, most web applications are single page apps using react on the client side, and an API based backend. It might make your life easier to go down this route, too?
| |
doc_5157
|
http://jsfiddle.net/rRKU3/25/
Here is the essence of the layout:
<ul>
<li>
<div class="rel">
<div class="abs">1</div>
</div>
</li>
<li>
<div class="rel">
<div class="abs">2</div>
</div>
</li>
...etc
</ul>
The divs help place text in relative and absolute containers for type positioning and transitions.
This Nav Bav currently looks like the following:
1 / 2 / 3 / 4 / 5 /
I would like it to drop the last "/" separator character to look like the following:
1 / 2 / 3 / 4 / 5
When I create a Nav Bar, that is made of only ul and li items, using the "li:last-child:after" selector works correctly and eliminates the last separator. When I create it using the above technique, with 2 div containers inside the li, I cannot figure out the selector I need, to overwrite the :after selector that creates the separator in the first place.
Here is what I have tried:
Selector that creates the separator;
ul > li > .rel > .abs:after {
position: absolute;
bottom: 0;
left: 55px;
content: "/";
font-size: 12px;
color: black;
}
Selector to overwrite the above selector (I tried all of versions below and none work):
/* .rel > .abs ~ .rel > .abs { */
/* li > .rel > .abs ~ li > .rel > .abs { */
/* ul > li > .rel > .abs ~ ul > li > .rel > .abs { */
/* .rel .abs:last-child { */
/* .rel > .abs:last-child { */
/* li > .rel > .abs:last-child { */
ul > li > .rel > .abs:last-child {
position: absolute;
bottom: 0;
/*left: 55px; */
content: "+";
font-size: 12px;
color: black;
}
Instead of overwriting the separator, this last selector somehow eliminates the hover (not mentioned, but you can see it in the jsfiddle). These last several lines are commented out in the jsfiddle so you can see the effect I am going for on hover.
Thank you for your esteemed knowledge of CSS selectors!
A: Add the following class in your CSS. It will remove the "/" from last child.
ul > li:last-child > .rel > .abs:after {
content: " ";
}
DEMO
| |
doc_5158
|
Then on the same view, below the Sandwich Edit form, we have a drop down list of ingredients with an Add button next to it. How do I make the Add Ingredient form post to a different Action, but then reload the Edit view?
RedirectToAction("Edit") puts a lot of junk up in the URL.
Here is one way I have tried that works, but puts junk in the URL:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LoginRemoveAssociation(FormCollection values)
{
int webUserKey = Int32.Parse(values["WebUserKey"]);
int associationKey = Int32.Parse(values["AssociationKey"]);
db.DeleteWebUserAssociation(webUserKey, associationKey);
return RedirectToAction("LoginEdit", new LoginEditViewModel(webUserKey, true));
}
Here is the junk in the URL after the RedirectToAction:
https://localhost/mvc/Admin/Login/382?WebUser=Web.Data.Entities.WebUser&Associations=System.Data.Objects.ObjectQuery`1[Web.Data.Entities.Association]&WebUserAssociations=System.Data.Objects.DataClasses.EntityCollection`1[Web.Data.Entities.WebUserAssociation]&ManagementCompanies=System.Collections.Generic.List`1[Web.Data.Entities.ManagementCompany]&ManagementCompanyList=System.Web.Mvc.SelectList&AccessLevels=System.Collections.Generic.List`1[Web.Data.Entities.AccessLevel]&AccessLevelList=System.Web.Mvc.SelectList&PostMessage=Changes%20saved.
A: The reason why your getting "junk" in your url is because your passing a LoginEditViewModel to the edit action. .Net is using trying to convert the object to a name so it can pass it in a parameter. Which is why your seeing Web.Data.Entities.......
What does your Edit controller look like?
If its something like:
public ActionResult Edit(int id)
Then your redirect to action should be something like:
return RedirectToAction("Edit", new { id = 1 });
Rather than passing your view model.
| |
doc_5159
|
cursor.execute("INSERT INTO api.mytable(id) VALUES (:id);", {"id": 1})
and error:
ERROR in connection: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near ':id)' at line 1")
code you please tell me what's the wrong with my code?
A: I am assuming id is given as some kind if input! Hence you can always check for the required format and allow only required ones! This is to avoid SQL injection!. Hence the natural formatting as shown below should do the job! And this is very basic level checking!
id_in = input("Here is the id taken " ) ## can be through any source . It is just an example
if isinstance(id_in,int): ##Please mention the required format here I am assuming it as integer
cursor.execute("INSERT INTO api.mytable(id) VALUES (%s);", (id_in))
else:
##do some stuff here
| |
doc_5160
|
@media screen and (max-width: 639.98px){
#menuPanel{
display: none !important;
}
}
I'm getting unresolved method on ready in the JQuery so I must be using the library wrong.
I'm new to JQuery and Javascript and was wondering is there a way to convert this Jquery to javascript?
(document).ready(function() {
$('#myCheck').change(function() {
$('#menuPanel').toggle();
});
});
With some html
<div class="hamburger">
<label class="toggle" id="menuDisplay">
<input type="checkbox" id="myCheck">
<header class="masthead mb-auto" id="menuPanel">
Current code in this js file is working.
function displayWindowSize() {
var w = document.documentElement.clientWidth;
var toggle = document.querySelector(".toggle input");
if (w > 640) {
toggle.checked = false;
}
}
Any help is much appreciated!
A: First, that jQuery ' script ' will not work because you should have $(document).ready(function(){ })
Second, you do not need to load jQuery to achieve what you want.
You can apply an onclick event on the checkbox, then check if it is checked or not and show/hide your menu.
var menu = document.getElementById('menuPanel');
function checkboxChanged(event) {
event.target.checked ? menu.style.display = 'block' : menu.style.display = 'none'
}
#menuPanel {
display: none;
}
<header class="masthead mb-auto" id="menuPanel">HEADER</header>
<div class="hamburger">
<label class="toggle" id="menuDisplay">
<input type="checkbox" id="myCheck" onclick="checkboxChanged(event)" />
</label>
</div>
OR if you cannot change HTML and apply a function inline, you can do everything inside the script tags
var menu = document.getElementById('menuPanel');
var checkbox = document.getElementById('myCheck');
checkbox.onclick = function() {
this.checked ?
menu.style.cssText += ';display:block !important;': menu.style.cssText += ';display:none !important;'
}
#menuPanel {
display: none!important;
}
<header class="masthead mb-auto" id="menuPanel">HEADER</header>
<div class="hamburger">
<label class="toggle" id="menuDisplay">
<input type="checkbox" id="myCheck" />
</label>
</div>
A: It seems that you want to use the jQuery version of document.ready. For that you have to prepend a $ symbol, like so:
$(document).ready( ... )
| |
doc_5161
|
My try:
boolean validIntegers = (Arrays.asList(A)).stream().allMatch(i -> (i >= -1000 && i <= 1000) );
Error:
A: Arrays.asList accepts T... but T as generic type can represent only Objects like int[], not primitive int. So T... represents {int[]} array, which contains internally array object, not array elements. So your stream contains array and you can't use any comparison operators on array.
To solve this problem and get stream of elements stored in array of ints you can use
*
*IntStream.of(int...),
*or Arrays.stream(yourArray) which supports double[] int[] long[] and T[].
So your code could be
boolean validIntegers = IntStream.of(A).allMatch(i -> (i >= -1000 && i <= 1000) );
| |
doc_5162
|
Example:
proxy: {
type: 'rest',
url: 'ajustes.getUrl()'
}
A: Unfortunately not. The above is treated as string.
| |
doc_5163
|
In Child 1 I'm setting an object data using setState
this.setState({data:{someobect}})
In Child 2 I want to access this data and modify
In my parent class I have code like this
import Child1 from .src/child1.jsx
import Child2 from .src/child2.jsx
<div>
<child1>
<child2>
</div>
What is the process of accessing any object between two different children?
A: With this.setState({data:{someobect}}) You set local state for your component.
If you want to use this object for both children you should set it with props from parent.
A: You need to hoist the state up to the parent and have the children delegate to the parent component to receive that information.
import Child1 from .src/child1.jsx
import Child2 from .src/child2.jsx
class Parent Extends React.Component {
constructor() {
super()
this.state = {
data: {}
}
}
_updateData = (newData) => {
this.setState({
data: newData
})
}
render() {
return (
<div>
<child1 data={this.state.data} updateData={this._updateData}>
<child2 data={this.state.data} >
</div>
)
}
}
and in your child1 component where you need to update data just called this.props.updateData with the new data object you want to update too and then both components will be updated simultaneously and state is managed in one spot.
| |
doc_5164
|
Thank you for your help.
const body = <html><head></head><body><p>This is SignUp Email with confirmation link</p><p><a href = "http://www.company.com/ls/click?upn=tokenid-11111-22222-333333-444444-555555-xxxxxx"></a></p></body></html>
const activation_link = ???
console.log(activation_link)
/*
The expected result to be printed on Console:
"http://www.company.com/ls/click?upn=tokenid-11111-22222-333333-444444-555555-xxxxxx"
*/
A:
const body = `<html><head></head><body><p>This is SignUp Email with confirmation link</p><p><a href = "http://www.company.com/ls/click?upn=tokenid-11111-22222-333333-444444-555555-xxxxxx"></a></p></body></html>`
const matched_links = body.match(/(?<=")http.+(?=")/);
console.log(matched_links);
| |
doc_5165
|
embed["description"] = "Username: {username}"
And here is what it's sending instead
Any help would be greatly appreciated.
A: You must make it an f string
username = 'Alex'
embed["description"] = f'Username: {username}'
Now, the {username} will be replaced with Alex.
| |
doc_5166
|
#include <boost/circular_buffer.hpp>
int main() {
// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(3);
// Insert some elements into the buffer.
cb.push_back(1);
cb.push_back(2);
cb.push_back(3);
// Here I want some function to be called (for example one that would cout all buffer contents)
int a = cb[0]; // a == 1
int b = cb[1]; // b == 2
int c = cb[2]; // c == 3
return 0;
}
So how to listen for such event in boost::circular_buffer and for example cout all buffer contents?
A: You can wrap the circular_buffer instance into its own class and implement event handling on top of it.
class MyCircularBuffer
{
public:
MyCircularBuffer() : buffer(3) {}
void PushBack(int i)
{
buffer.push_back(i);
if(buffer.size() == 3)
{
// buffer is full!
}
}
private:
boost::circular_buffer<int> buffer;
};
If code outside of MyCircularBuffer needs to be notified of the event, you can implement some variant of the Observer pattern, use Boost.Function or use some other callback mechanism.
A: It doesn't fire an event. You must manually check to see if it is full each time you add to it, and if it is, then you execute some process.
This would typically be done by wrapping the container in a user-created object, so that you can monitor additions to the buffer.
Or, to put it another way, you don't need a generic solution; just write an object that uses the container and flushes it automatically.
| |
doc_5167
|
CSS:
#kidsage40, #kidsage41, #kidsage42
{
display:none;
}
HTML:
<select name="kids4" onChange="showroom4kidsage(this.value);">
<option value="0">Kids</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="kidsage40" id="kidsage40">
<option value="0">Kids Age</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
</select>
<select name="kidsage41" id="kidsage41">
<option value="0">Kids Age</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
</select>
<select name="kidsage42" id="kidsage42">
<option value="0">Kids Age</option>
<option value="1">1</option>
<option value="3">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
</select>
JAVASCRIPT:
function showroom4kidsage(value)
{
for(i=0;i<value;i++)
{
kidsage = 'kidsage1'+i;
document.getElementById(kidsage).style.display = "block";
}
}
A: Simply add a class onto the selectboxes, say "kidsageselect" and then have your javascript do this:
function showroom4kidsage(value) {
var elems = document.getElementsByClassName('kidsageselect');
for (var i = 0; i < elems.length; i++) {
elems[i].style.display = 'none';
}
for(var i = 0; i < value; i++) {
kidsage = 'kidsage4'+i;
document.getElementById(kidsage).style.display = "block";
}
}
A: The easiest way is to just hide them all first, then your loop will show the correct number of drowns after.
function showroom4kidsage(value){
for(i=0;i<3;i++){
document.getElementById('kidsage4' + i).style.display = "none";
}
for(i=0;i<value;i++){
kidsage = 'kidsage4'+i;
document.getElementById(kidsage).style.display = "block";
}
}
Or adding a classname to make accessing these inputs easier:
<select class="foo" id="kidsage41>...</select>
<select class="foo" id="kidsage42>...</select>
and then you can:
function showroom4kidsage(value){
document.getElementByClassName('foo').style.display = "none";
for(i=0;i<value;i++){
kidsage = 'kidsage4'+i;
document.getElementById(kidsage).style.display = "block";
}
}
A: you have to set all SELECTS to display:none before
Give all those select ONE class="randomclass" and set all elements in that class display:none
or set em one by one via loop or ony by one to display:none like
document.getElementById('kidsage42').style.display = "none";
that would hide the last select f.E.
| |
doc_5168
|
My service/notification is started in the onCreate() method for my BackgroundService class...
Notification notification = new Notification();
startForeground(1, notification);
registerReceiver(receiver, filter);
and this service is launched from my main activity's button click:
final Intent service = new Intent(Main.this, BackgroundService.class);
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((counter % 2) == 0){
bStart.setText("STOP");
startService(service);
}else {
bStart.setText("BEGIN");
stopService(service);
}
counter++;
}
any advice is appreciated
A: You'll have to use a BroadcastReceiver for that. Take a look at the following code. Put it in your Service
private MyBroadcastReceiver mBroadcastReceiver;
@Override
onCreate() {
super.onCreate();
mBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("do_something");
registerReceiver(mBroadcastReceiver, intentFilter);
}
// While making notification
Intent i = new Intent("do_something");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);
notification.contentIntent = pendingIntent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch(action) {
case "do_something":
doSomething();
break;
}
}
}
public void doSomething() {
//Whatever you wanna do on notification click
}
This way the doSomething() method will be called when your Notification is clicked.
| |
doc_5169
|
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like @City+'%' and EmpID =@EmpId";
SqlCommand cmd = new SqlCommand(CmdText, con);
cmd.Parameters.AddWithValue("@City", prefixText);
cmd.Parameters.AddWithValue("@EmpId", contextKey);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][0].ToString());
}
return CityNames;
}
aspx code
<asp:UpdatePanel ID="UpdatePanel7" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCity" runat="server" UseContextKey="true" onkeyup="SetContextKey()" CssClass="input-1" Width="200px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCity" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCity" UseContextKey="true" CompletionListCssClass="autocomplete_completionListElement">
</ajaxToolkit:AutoCompleteExtender>
</ContentTemplate>
</asp:UpdatePanel>
A: You cannot call a webmethod through a user control because it will be automatically rendered inside the page. Move your webmethod to your aspx page.
If you want the logic inside the controller then you can call it from aspx page but your webmethod needs to be in aspx page.
Example:
In aspx page:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{
return mycontrol.GetCity(prefixText, contextKey);
}
In your user control :
public static List<string> GetCity(string prefixText, string contextKey)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like @City+'%' and EmpID =@EmpId";
SqlCommand cmd = new SqlCommand(CmdText, con);
cmd.Parameters.AddWithValue("@City", prefixText);
cmd.Parameters.AddWithValue("@EmpId", contextKey);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][0].ToString());
}
return CityNames;
}
| |
doc_5170
|
*
*Take Just 'a', so the value in context of type Maybe in this case is 'a'
*Take [3], so value in context of type [a] in this case is 3
*And if you apply the monad for [3] like this: [3] >>= \x -> [x+3], it means you assign x with value 3. It's ok.
But now, take [3,2], so what is the value in the context of type [a]?. And it's so strange that if you apply monad for it like this:
[3,4] >>= \x -> x+3
It got the correct answer [6,7], but actually we don't understand what is x in this case. You can answer, ah x is 3 and then 4, and x feeds the function 2 times and concat as Monad does: concat (map f xs) like this:
[3,4] >>= concat (map f x)
So in this case, [3,4] will be assigned to the x. It means wrong, because [3,4] is not a value. Monad is wrong.
A: I think your problem is focusing too much on the values. A monad is a type constructor, and as such not concerned with how many and what kinds of values there are, but only the context.
A Maybe a can be an a, or nothing. Easy, and you correctly observed that.
An Either String a is either some a, or alternatively some information in form of a String (e.g. why the calculation of a failed).
Finally, [a] is an unknown number of as (or none at all), that may have resulted from an ambiguous computation, or one giving multiple results (like a quadratic equation).
Now, for the interpretation of (>>=), it is helpful to know that the essential property of a monad (how it is defined by category theorists) is
join :: m (m a) -> m a.
Together with fmap, (>>=) can be written in terms of join.
What join means is the following: A context, put in the same context again, still has the same resulting behavior (for this monad).
This is quite obvious for Maybe (Maybe a): Something can essentially be Just (Just x), or Nothing, or Just Nothing, which provides the same information as Nothing. So, instead of using Maybe (Maybe a), you could just have Maybe a and you wouldn't lose any information. That's what join does: it converts to the "easier" context.
[[a]] is somehow more difficult, but not much. You essentially have multiple/ambiguous results out of multiple/ambiguous results. A good example are the roots of a fourth-degree polynomial, found by solving a quadratic equation. You first get two solutions, and out of each you can find two others, resulting in four roots.
But the point is, it doesn't matter if you speak of an ambiguous ambiguous result, or just an ambiguous result. You could just always use the context "ambiguous", and transform multiple levels with join.
And here comes what (>>=) does for lists: it applies ambiguous functions to ambiguous values:
squareRoots :: Complex -> [Complex]
fourthRoots num = squareRoots num >>= squareRoots
can be rewritten as
fourthRoots num = join $ squareRoots `fmap` (squareRoots num)
-- [1,-1,i,-i] <- [[1,-1],[i,-i]] <- [1,-1] <- 1
since all you have to do is to find all possible results for each possible value.
This is why join is concat for lists, and in fact
m >>= f == join (fmap f) m
must hold in any monad.
A similar interpretation can be given to IO. A computation with side-effects, which can also have side-effects (IO (IO a)), is in essence just something with side-effects.
A: You have to take the word "context" quite broadly.
A common way of interpreting a list of values is that it represents an indeterminate value, so [3,4] represents a value which is three or four, but we don't know which (perhaps we just know it's a solution of x^2 - 7x + 12 = 0).
If we then apply f to that, we know it's 6 or 7 but we still don't know which.
Another example of an indeterminate value that you're more used to is 3. It could mean 3::Int or 3::Integer or even sometimes 3.0::Double. It feels easier because there's only one symbol representing the indeterminate value, whereas in a list, all the possibilities are listed (!).
If you write
asum = do
x <- [10,20]
y <- [1,2]
return (x+y)
You'll get a list with four possible answers: [11,12,21,22]
That's one for each of the possible ways you could add x and y.
A: It is not the values that are in the context, it's the types.
Just 'a' :: Maybe Char --- Char is in a Maybe context.
[3, 2] :: [Int] --- Int is in a [] context.
Whether there is one, none or many of the a in the m a is beside the point.
Edit: Consider the type of (>>=) :: Monad m => m a -> (a -> m b) -> m b.
You give the example Just 3 >>= (\x->Just(4+x)). But consider Nothing >>= (\x->Just(4+x)). There is no value in the context. But the type is in the context all the same.
It doesn't make sense to think of x as necessarily being a single value. x has a single type. If we are dealing with the Identity monad, then x will be a single value, yes. If we are in the Maybe monad, x may be a single value, or it may never be a value at all. If we are in the list monad, x may be a single value, or not be a value at all, or be various different values... but what it is not is the list of all those different values.
Your other example --- [2, 3] >>= (\x -> x + 3) --- [2, 3] is not passed to the function. [2, 3] + 3 would have a type error. 2 is passed to the function. And so is 3. The function is invoked twice, gives results for both those inputs, and the results are combined by the >>= operator. [2, 3] is not passed to the function.
A: "context" is one of my favorite ways to think about monads. But you've got a slight misconception.
Take Just 'a', so the value in context of type Maybe in this case is 'a'
Not quite. You keep saying the value in context, but there is not always a value "inside" a context, or if there is, then it is not necessarily the only value. It all depends on which context we are talking about.
The Maybe context is the context of "nullability", or potential absence. There might be something there, or there might be Nothing. There is no value "inside" of Nothing. So the maybe context might have a value inside, or it might not. If I give you a Maybe Foo, then you cannot assume that there is a Foo. Rather, you must assume that it is a Foo inside the context where there might actually be Nothing instead. You might say that something of type Maybe Foo is a nullable Foo.
Take [3], so value in context of type [a] in this case is 3
Again, not quite right. A list represents a nondeterministic context. We're not quite sure what "the value" is supposed to be, or if there is one at all. In the case of a singleton list, such as [3], then yes, there is just one. But one way to think about the list [3,4] is as some unobservable value which we are not quite sure what it is, but we are certain that it 3 or that it is 4. You might say that something of type [Foo] is a nondeterministic Foo.
[3,4] >>= \x -> x+3
This is a type error; not quite sure what you meant by this.
So in this case, [3,4] will be assigned to the x. It means wrong, because [3,4] is not a value. Monad is wrong.
You totally lost me here. Each instance of Monad has its own implementation of >>= which defines the context that it represents. For lists, the definition is
(xs >>= f) = (concat (map f xs))
You may want to learn about Functor and Applicative operations, which are related to the idea of Monad, and might help clear some confusion.
| |
doc_5171
|
Installed node js using :
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash
. ~/.nvm/nvm.sh
nvm install 9.3.0
[root@ip ~]# node -v
v9.3.0
[root@ip ~]# npm -v
5.6.0
While trying to install angular-cli :
[root@ip ~]# npm install @angular/cli
> node-sass@4.7.2 install /root/node_modules/node-sass
> node scripts/install.js
sh: node: command not found
> uglifyjs-webpack-plugin@0.4.6 postinstall /root/node_modules/@angular/cli/node _modules/webpack/node_modules/uglifyjs-webpack-plugin
> node lib/post_install.js
sh: node: command not found
npm WARN enoent ENOENT: no such file or directory, open '/root/package.json'
npm WARN license-webpack-plugin@1.1.1 requires a peer of webpack-sources@>=1.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN root No description
npm WARN root No repository field.
npm WARN root No README data
npm WARN root No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fse vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@ 1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"} )
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: node-sass@4.7.2 (node_modules/no de-sass):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: node-sass@4.7.2 install: `node s cripts/install.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: spawn ENOENT
npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! uglifyjs-webpack-plugin@0.4.6 postinstall: `node lib/post_install.js`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the uglifyjs-webpack-plugin@0.4.6 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional log ging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2018-02-11T05_17_45_238Z-debug.log
Tried , -f option :
[root@ip ~]# npm install -g -f angular-cli
npm WARN using --force I sure hope you know what you are doing.
npm WARN deprecated angular-cli@1.0.0-beta.28.3: angular-cli has been renamed to @angular/cli. Please update your dependencies.
npm WARN deprecated gulp-util@3.0.7: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
/root/.nvm/versions/node/v9.3.0/bin/ng -> /root/.nvm/versions/node/v9.3.0/lib/node_modules/angular-cli/bin/ng
> fsevents@1.1.3 install /root/.nvm/versions/node/v9.3.0/lib/node_modules/angular-cli/node_modules/fsevents
> node install
sh: node: command not found
> node-sass@4.7.2 install /root/.nvm/versions/node/v9.3.0/lib/node_modules/angular-cli/node_modules/node-sass
> node scripts/install.js
sh: node: command not found
> node-sass@4.7.2 postinstall /root/.nvm/versions/node/v9.3.0/lib/node_modules/angular-cli/node_modules/node-sass
> node scripts/build.js
sh: node: command not found
npm WARN @angular/core@2.4.10 requires a peer of rxjs@^5.0.1 but none is installed. You must install peer dependencies yourself.
+ angular-cli@1.0.0-beta.28.3
added 917 packages in 21.658s
After installing the beta version , executing ng serve command inside the angular project code shows :
As a forewarning, we are moving the CLI npm package to "@angular/cli" with the next release,
which will only support Node 6.9 and greater. This package will be officially deprecated
shortly after.
To disable this warning use "ng set --global warnings.packageDeprecation=false".
You have to be inside an angular-cli project in order to use the serve command.
Any ideas on the above ?
OS : CentOS 7
Arch : 64bit
Host : AWS
A: Try the following suggestions:
*
*Clear caches: npm cache clean.
*Reinstall: npm uninstall @angular/cli && npm install @angular/cli.
*Install with -f/--force.
For other suggestions, read: Can't install angular-cli globally.
| |
doc_5172
|
<?php
if (isset($_GET['id'])) {
$c = $_GET['id'];
}
mysql_connect("localhost","root","");
mysql_select_db("blog");
?>
<html>
<head>
<body background="u.jpg">
<center>
<a href="register.php"><img src="1.jpg" width="100" height="50"/></a>
<a href="login.php"><img src="2.jpg" width="100" height="50"/></a>
<a href="index.php"><img src="3.jpg" width="100" height="50"/></a>
</center>
<center>
<title>Pinoy Blog</title>
</head>
<?php
if(isset($_POST['submit']))
{
$content = $_POST['content'];
mysql_query("INSERT INTO comment (comment,p_id) VALUE('$content','$c')");
echo '<a href="index.php">span style="font-size:26px;"><strong><span style="font-family: verdana, geneva, sans-serif; ">Success! Tignan ang post. </span></strong></span>.</a>
|| <a href="post.php">Magpost ulit? Click mo to.</a>';
}else{
?>
<form action='post.php' method='post'>
<span style="font-size:26px;"><strong><span style="font-family: verdana, geneva, sans-serif; ">Comment: </span></strong></span>
<textarea name='content' ></textarea><br />
<input type='submit' name='submit' value='POST!'/>
</form>
<?php
}
?>
<center>
</body>
</html>
A: 1) When you are coming from first page to second page with link then it's called query string & you will get it in $_GET['id']
2) But now you are on second page & click on submit button it means it is new http request which doesn't carry $_GET values from previous http request. so you need store $_GET['id'] into second page as hidden form field.
Change your php code as below
if (isset($_REQUEST['id'])) {
$c = $_REQUEST['id'];
}
Now take one hidden field in your form.
<form action='post.php' method='post'>
<span style="font-size:26px;"><strong><span style="font-family: verdana, geneva, sans-serif; ">Comment: </span></strong></span>
<input type="hidden" value="<?php echo $_REQUEST['id'] ?>" name="id">
<textarea name='content' ></textarea><br />
<input type='submit' name='submit' value='POST!'/>
</form>
Note: $_REQUEST default contains the contents of $_GET, $_POST and $_COOKIE
A: You're submitting a POST form and then searching for GET variables???
To be honest I'm struggling to understand the question, you're saying that when you first land on the page the $_GET['id'] is printing out, but then when you submit the form on that page the ID isn't there??
A: First of all, where/when are you echoing the query string value such that it displays?
More to the point, I'm going to assume that the code we're seeing is for post.php and that the page is essentially submitting to itself. I'm also going to assume that when you first load the page, you do so with a query string argument. Something like this:
/path/to/post.php?id=123
However, when you submit the form, you change that URL:
<form action='post.php' method='post'>
Now you're loading something like this:
/path/to/post.php
There's no more query string value on the URL, so when the PHP code responds to this request it won't have anything in $_GET['id']. You need to include the query string value when submitting the request to the server. Something like this might work:
<form action="post.php?id=<?php echo htmlspecialchars($_GET['id']); ?>" method="post">
Conversely, instead of mixing POST and GET values, you could set a hidden field in the form. Something like this:
<input type="hidden" name="id" value="<?php echo htmlspecialchars($_REQUEST['id']); ?>" />
Then your form's action won't have to change, but you would have to change how to access the value in the PHP code. $_REQUEST['id'] will pull the value from either the GET values or the POST values, so it need only be present in one of them. That way the same array can be used both when first loading the page and when submitting the page back to itself.
Note the use of htmlspecialchars() here. I'm not a PHP expert, but what I'm explicitly attempting to do is prevent some cross-site scripting attack whereby the code would blindly echo to the page (on your behalf) user-submitted input, which could be malicious. url encode() may also do the trick. It's worth further research for your needs.
A: <form action='post.php?id=<?php echo $id;?>' method='post'>
<span style="font-size:26px;"><strong><span style="font-family: verdana, geneva, sans-serif; ">Comment: </span></strong></span>
<textarea name='content' ></textarea><br />
<input type='submit' name='submit' value='POST!'/>
</form>
It Will Post Form To post.php?id=1 or any other
And You Will get Values Of $_GET['id']
Replace action='post.php' with action='post.php?id=<?php echo $id;?>'
| |
doc_5173
|
This is a part of my gridview adapter:
public View getView(int position, View view, ViewGroup parent) {
Date date = getItem(position);
int day = date.getDate();
int month = date.getMonth();
int year = date.getYear();
}
and the int day = date.getDate(); int month = date.getMonth(); int year = date.getYear();
are deprecated. I am trying to use the Calendar class instead of Date but unable to do the same. I know that for retrieve the day, month or year I can use this:
Calendar calendar = Calendar.getInstance();
calendar.get(Calendar.DAY_OF_MONTH);
but I don't know how to convert this line:
Date date = getItem(position);
for using with Calendar.
A: You can use this line of code:
Just replace this line
Date date = getItem(position);
with this line:
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Here is a full example for you:
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
A: Here is how you convert a Date object to a Calendar object:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Then (like you said) you can do:
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH)
int year = cal.get(Calendar.YEAR);
A: First you're gonna want to reference Calendar. Once you've done that, you can say Date date = calendar.getTime
public View getView(int position, View view, ViewGroup parent) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH)
int year = calendar.get(Calendar.YEAR);
}
A:
Looking for an answer drawing from credible and/or official sources.
Ok
To major sources:
*
*https://docs.oracle.com/javase/7/docs/api/java/util/Date.html
*https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Date is not deprecated. Only some methods.
So,
public View getView(int position, View view, ViewGroup parent) {
Date date = getItem(position);
long ms = date.getTime();https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime()
Calendar calendar = Calendar.getInstance();//allowed
calendar.setTimeInMillis(ms);//allowed https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long)
//calendar.setTime(date); is also allowed https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime(java.util.Date)
int day = calendar.get(Calendar.DAY_OF_MONTH);//allowed
int month = calendar.get(Calendar.MONTH);//allowed
int year = calendar.get(Calendar.YEAR);//allowed
}
A: Here is the sample code to convert from Date to Calendar.
public View getView(int position, View view, ViewGroup parent) {
Date date = getItem(position);
// convert a Date object to a Calendar object
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
}
| |
doc_5174
|
But when I do on activity onCreate
Intent serviceIntent = new Intent(context, SyncService.class);
context.startService(serviceIntent);
I see the logs.
Please suggests.
Cheers,
Raj
A: Sync adapter starts explicitly by calling:
ContentResolver.requestSync(ACCOUNT, AUTHORITY, null);
or similar method:
ContentResolver.addPeriodicSync(
ACCOUNT,
AUTHORITY,
Bundle.EMPTY,
SYNC_INTERVAL);
https://developer.android.com/training/sync-adapters/running-sync-adapter.html
I strongly recommend this book, especially first 200 pages http://www.wrox.com/WileyCDA/WroxTitle/Enterprise-Android-Programming-Android-Database-Applications-for-the-Enterprise.productCd-1118183495.html .
| |
doc_5175
|
I have some simple SQL to highlight where the issue is coming from;
SELECT TOP 1 'Surname' AS 'name.family'
,'Forename, Middle Name' AS 'name.given'
,'Title' AS 'name.prefix'
,getDATE() AS 'birthdate'
,'F' AS 'gender'
,'Yes' AS 'active'
,'work' AS 'telecom.use'
,'phone' AS 'telecom.system'
,'12344556' AS 'telecom.value'
FROM tblCustomer
FOR json path
Which will return JSON as;
[
{
"name": {
"family": "Surname",
"given": "Forename, Middle Name",
"prefix": "Title"
},
"birthdate": "2019-02-13T12:06:45.490",
"gender": "F",
"active": "Yes",
"telecom": {
"use": "work",
"system": "phone",
"value": "12344556"
}
}
]
What I need to is to add extra objects into the "telecome" array so it would appear as;
[
{
"name": {
"family": "Surname",
"given": "Forename, Middle Name",
"prefix": "Title"
},
"birthdate": "2019-02-13T12:06:45.490",
"gender": "F",
"active": "Yes",
"telecom": {
"use": "work",
"system": "phone",
"value": "12344556"
},
{
"use": "work",
"system": "home",
"value": "12344556"
},
}
]
I have incorrectly assume I could keep adding to my SQL as follows;
SELECT TOP 1 'Surname' AS 'name.family'
,'Forename, Middle Name' AS 'name.given'
,'Title' AS 'name.prefix'
,getDATE() AS 'birthdate'
,'F' AS 'gender'
,'Yes' AS 'active'
,'work' AS 'telecom.use'
,'phone' AS 'telecom.system'
,'12344556' AS 'telecom.value'
,'home' AS 'telecom.use'
FROM tblCustomer
FOR json path
And it would nest the items as per my naming indents however;
Property 'telecom.use' cannot be generated in JSON output due to a
conflict with another column name or alias. Use different names and
aliases for each column in SELECT list.
Is there a way to handle this nesting with SQL or will I need to create separate for JSON queries and merge them?
Thanks
Using @@Version Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64)
Aug 22 2017 17:04:49 Copyright (C) 2017 Microsoft Corporation
Express Edition (64-bit) on Windows Server 2012 R2 Datacenter 6.3
(Build 9600: ) (Hypervisor)
Small edit to the question to use dynamic values rather than forced static members.
SELECT TOP 1 'Surname' AS 'name.family'
,'Forename, Middle Name' AS 'name.given'
,'Title' AS 'name.prefix'
,getDATE() AS 'birthdate'
,'F' AS 'gender'
,'Yes' AS 'active'
,'work' AS 'telecom.use'
,'phone' AS 'telecom.system'
,customerWorkTelephone AS 'telecom.value'
,'home' AS 'telecom.use'
,'phone' AS 'telecom.system'
,customerHomeTelephone AS 'telecom.value'
FROM tblCustomer
FOR json path
The "value" items will be taken from columns within the tblCustomer table. I've tried to make good on the responses below but cant get the logic quite correct in the sub query.
Thanks again
FURTHER EDIT
I have some SQL that is giving me the output I expect however I am not sure its the best that it could be, is my approach less than optimal?
SELECT TOP 1 [name.family] = 'Surname'
,[name.given] = 'Forename, Middle Name'
,[name.prefix] = 'Title'
,[birthdate] = GETDATE()
,[gender] = 'F'
,[active] = 'Yes'
,[telecom] = (
SELECT [use] = V.used
,[system] = 'phone'
,[value] = CASE V.used
WHEN 'work'
THEN cu.customerWorkTelephone
WHEN 'home'
THEN cu.customerHomeTelephone
when 'mobile'
then cu.customerMobileTelephone
END
FROM (
VALUES ('work')
,('home')
,('mobile')
) AS V(used)
FOR json path
)
FROM tblCustomer cu
FOR JSON PATH
A: Using a subselect with a few hard-coded rows:
SELECT TOP 1
'Surname' AS 'name.family'
,'Forename, Middle Name' AS 'name.given'
,'Title' AS 'name.prefix'
,getDATE() AS 'birthdate'
,'F' AS 'gender'
,'Yes' AS 'active'
,'telecom' = (
SELECT
'work' AS 'use'
,V.system AS 'system'
,'12344556' AS 'value'
FROM
(VALUES
('phone'),
('home')) AS V(system)
FOR JSON PATH)
FROM tblCustomer
FOR JSON PATH
Note the lack of the telecom. prefix inside the subquery.
Results (without the table reference):
[
{
"name": {
"family": "Surname",
"given": "Forename, Middle Name",
"prefix": "Title"
},
"birthdate": "2019-02-13T12:53:08.400",
"gender": "F",
"active": "Yes",
"telecom": [
{
"use": "work",
"system": "phone",
"value": "12344556"
},
{
"use": "work",
"system": "home",
"value": "12344556"
}
]
}
]
PD: Particularly for SQL Server I find using the alias on the left side more readable:
SELECT TOP 1
[name.family] = 'Surname',
[name.given] = 'Forename, Middle Name',
[name.prefix] = 'Title',
[birthdate] = GETDATE(),
[gender] = 'F',
[active] = 'Yes',
[telecom] = (
SELECT
[use] = 'work',
[system] = V.system,
[value] = '12344556'
FROM
(VALUES ('phone'), ('home')) AS V(system)
FOR JSON
PATH)
FROM tblCustomer
FOR JSON
PATH
A: SELECT
EMP.ID,
EMP.NAME,
DEP.NAME
FROM EMPLOYEE EMP INNER JOIN DEPARTMENT DEP ON EMP.DEPID=DEP.DEPID
WHERE EMP.SALARY>1000
FOR JSON PATH
| |
doc_5176
|
Thanks in advance!
A: In games the menus are usually part of the game not a windows-form. You normally have the menu scene with buttons like Options, Exit, Credits, and Play.
My friends and I built this game in a 24 hour hackathon; you can see an example of what the menu looks like at the start of this YouTube video: ClockWork.
I remember having a lot of fun making that 3D menu. You have options, you could make a simple 2D menu with textures or use 3D. You can start by reading the GUI.Button API. You can also add a song to your menu. I also suggest you look at examples of menus for other games.
| |
doc_5177
|
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = e.source.getActiveSheet();
var r = e.source.getActiveRange();
if (s.getName() == "Sheet1" && r.getColumn() == 6 && r.getValue() == "APPROVED") {
var row = r.getRow();
var numColumns = s.getLastColumn();
var namedRange = ss.getRangeByName('APPROVED');
s.getRange(row, 1, 1,numColumns).moveTo(namedRange);
s.deleteRow(row)
}
}
The script currently overwrites the first row in the named range. I've tried the following
var row = r.getRow();
var numColumns = s.getLastColumn();
var namedRange = ss.getRangeByName('APPROVED');
var target = (namedRange.getLastRow() +1, 1));
s.getRange(row, 1, 1,numColumns).moveTo(target);
s.deleteRow(row)
I'm certainly a novice with GAS so any elaborations on fixes would be appreciated.
A: Try this:
function setLastRowOfANamedRange(row,s,nr) {
var nr=nr || SpreadsheetApp.getActive().getRangeByName('APPROVED');//debug
var s=s || SpreadsheetApp.getActive().getActiveSheet();//debug
var row=row || 5;//debug
var vA=nr.getValues();
vA[vA.length-1]=s.getRange(row,1,1,vA[0].length).getValues();
nr.setValues(vA);
}
A: *
*You want to move a row to the last row of namedRange.
If my understanding is correct, as another solution, how about this modification? I think that the approach of your 2nd script is close to the goal. So in this answer, I used moveTo(). Because I thought that this approach might be also useful for other users, I posted this. I think that there are several answers for your situation. So please think of this as just one of them.
From:
s.getRange(row, 1, 1,numColumns).moveTo(namedRange);
To:
s.getRange(row, 1, 1,numColumns).moveTo(namedRange.offset(namedRange.getLastRow() - namedRange.getRow(), 0));
*
*In this modification, put a row to the last row of namedRange using offset().
*If you want to put the row to the next row of the last row of namedRange, please modify as follows.
*
*s.getRange(row, 1, 1,numColumns).moveTo(namedRange.offset(namedRange.getLastRow() - namedRange.getRow() + 1, 0))
Note:
*
*In your script, moveTo() is used. So this line of s.deleteRow(row) might be able to be deleted. About this, please do this for your situation.
References:
*
*offset()
*moveTo()
If this was not the result you want, I apologize.
Edit:
*
*You want to put a row to the last row in the named range.
*In this case, the last row is the last row in the named range.
*
*For example, the named range has 40 rows and some values are put in the first 5 rows, you want to put the row from 6 row.
If my understanding is correct, how about this modification?
From:
s.getRange(row, 1, 1,numColumns).moveTo(namedRange);
To:
var values = namedRange.getValues();
for (var i = values.length - 1; i >= 0; i--) {
var r = values[i].some(function(e) {return e});
if (r) {
s.getRange(row, 1, 1,numColumns).moveTo(namedRange.offset(i + 1, 0));
break;
}
}
*
*namedRange.getLastRow() retrieves the maximum row number of the named range. So I prepared the script for retrieving the last row in the named range.
| |
doc_5178
|
where deque also provides a function push_front to insert the element at the beginning, which is bit costly in case of vector.
My question is when we can achieve the same functionality (push_back) of vector by using deque, then why vector is required?
A: std::deque is a double-ended queue. It provides efficient insertion and deletion of elements at the beginning also, not just at the end, as std::vector does. Vectors are guaranteed to store the elements in a contiguous storage, therefore you can access its elements by index/offset. std::deque does not offer this guarantee.
A: One main difference between vectors and deques is that the latter allows efficient insertion at the front of the structure as well as the back.
Deques also do not guarantee that their elements are contiguous in memory so the at-style operator (indexing) may not be as efficient.
Note that the difference is unlikely to matter in practice for smaller collections but would generally become more important if, for example, the collection size increases or you're modifying it many times per second.
A: Performance, mainly. An std::deque has all of the
functionality of std::vector, at least for normal use, but
indexing and iterating over it will typically be somewhat
slower; the same may hold for appending at the end, if you've
used reserve. And of course, std::vector is the default
container, using anything else will suggest to the reader that
you have special requirements.
std::vector also guarantees contiguity, so it (and only it)
can be used to interface legacy functions which require a T*
or a T const*.
I might add that the one time I actually had a performance
issue, and measured, std::vector was faster than std::deque,
despite the fact that I was regularly removing elements from
the front (using the container as a queue, pushing at the back,
and popping at the front). I don't know if that generalizes,
however; in my case, the queue was relatively short (never more
than about 15 elements, and usually many less), and the contents
were char, which is extremely cheap to copy. But in general,
I'd use std::vector even if I needed to remove elements from
the front, if only because of its better locality. I'd probably
only consider std::deque if I expected thousands of elements,
which were expensive to copy.
| |
doc_5179
|
data.json::
[ {
"name": "Anam",
"age": 20,
"id": 100,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Moroni",
"age": 50,
"id": 101,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Tiancum",
"age": 43,
"id": 102,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Jacob",
"age": 27,
"id": 103,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Nephi",
"age": 29,
"id": 104,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
},
{
"name": "Anam",
"age": 20,
"id": 100,
"commentline": "Yes Good !!!",
"like":5,
"dislike":1
}
]
HTML ::
<!DOCTYPE html>
<html ng-app="FundooDirectiveTutorial">
<head>
<title>Rating Directive Demo</title>
<link rel="stylesheet" href="rating.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<style>
.sideheading
{
display: inline-block
}
</style>
</head>
<body ng-controller="FundooCtrl">
<h2>Listing All Comments </h2>
<br/><!--
<div class="commentbox" ng-repeat="comment in comments" >
<h4 class="sideheading">comment By:</h4>{{comment.name}}<br/>
<h4 class="sideheading">Comment ::</h4>{{comment.commentline}} <br/>
<h4 class="sideheading">Likes ::</h4> {{comment.like}} <br/>
<h4 class="sideheading">Dislike::</h4> {{comment.dislike}} <br/>
</div>
-->
<div class="panel panel-default" ng-repeat="comment in comments">
<div class="panel-heading">
<h3 class="panel-title">{{comment.name}}</h3>
</div>
<div class="panel-body">
Comment ::{{comment.commentline}} <br/>
Likes :: {{comment.like}}
<button type="button" class="btn btn-default btn-xs" ng-click="incrlikes(comment)">
<span class="glyphicon glyphicon-star"></span> Like
</button>
<button type="button" class="btn btn-default btn-xs" ng-click="decrlikes(comment)">
<span class="glyphicon glyphicon-star"></span> DisLike
</button><br/>
Dislike:: {{comment.dislike}}
<br/>
likeflag::
<br/>
</div>
</div>
<!-- <div fundoo-rating rating-value="rating" max="10" on-rating-selected="saveRatingToServer(rating)"></div>
<br/>
Readonly rating <br/>
<div fundoo-rating rating-value="rating" max="10" readonly="true"></div>
-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script type="text/javascript" src="comment.js"></script>
</body>
</html>
JS ::
var app=angular.module('FundooDirectiveTutorial', []);
app.controller('FundooCtrl', function ($scope, $http) {
$http.get('comment.json').success(function(data) {
$scope.comments = data;
$scope.incrlikes=function(a)
{
var selectedIndex=$scope.comments.indexOf( a );
console.log('Likes increment'+a.name);
console.log($scope.comments.indexOf( a ) +'with index of name is '+$scope.comments[selectedIndex].name );
$scope.comments[selectedIndex].like=$scope.comments[selectedIndex].like+1;
$scope.likeflag=1;
if($scope.likeflag==1)
{
}else
{
console.log('Already like');
}
}
});
});
Fiddle::
http://jsfiddle.net/simmi_simmi987/DeKP4/
A: I solved my this problem using ng-show and ng-hide,
when likeClicked is false then i show like button , and when user click it on it i change variable to false . so automaticaly , dislike button is shown
var app=angular.module('FundooDirectiveTutorial', []);
app.controller('FundooCtrl', function ($scope, $http) {
$http.get('comment.json').success(function(data) {
$scope.comments = data;
$scope.likeClicked=[];
$scope.incrlikes=function(a)
{
var selectedIndex=$scope.comments.indexOf( a );
if(! $scope.likeClicked[selectedIndex])
{
console.log('Likes increment'+a.name);
console.log($scope.comments.indexOf( a ) +'with index of name is '+$scope.comments[selectedIndex].name );
$scope.comments[selectedIndex].like=$scope.comments[selectedIndex].like+1;
$scope.likeClicked[selectedIndex]=true;
}
else
{
console.log('Already like');
}
}
$scope.decrlikes=function(a)
{
var selectedIndex=$scope.comments.indexOf( a );
if($scope.likeClicked[selectedIndex])
{
console.log('Likes increment'+a.name);
console.log($scope.comments.indexOf( a ) +'with index of name is '+$scope.comments[selectedIndex].name );
$scope.comments[selectedIndex].like=$scope.comments[selectedIndex].like-1;
$scope.likeClicked[selectedIndex]=false;
}
else
{
console.log('Already Dislike');
}
}
});
});
| |
doc_5180
|
"This is the main text <footnote>and this is the footnote</footnote> where
we speak of main-text things"
What I want to do is extract the footnotes from the body text and then have access to both the main text AND the footnotes as variables in the layout.
I've made some progress with this by creating a filter but it doesn't work very well because filters always output directly on return and I need to format the footnotes.
Would a generator be more appropriate? A converter? Should I not be using liquid tags at all in this case?
Filters make the most sense to me. Is there a way to get the return value of a filter without it printing to the screen? I currently use this:
{{ content | footnotes }}
But that just dumps the array as one big, unformatted array. If it isn't blindingly obvious already, I'm just getting started with Liquid and I'm a little confused.
A: Depending on your markdown parser you could just write the footnotes normally in the markdown. This is what I'm using on my blog. This is my config in the _config.yml file:
markdown: rdiscount
rdiscount:
extensions:
- autolink
- footnotes
- smart
Then I just use footnotes by using [^1] to specify the footnote and
[^1]: My footnote
To show it at the bottom of the screen.
Or are you trying to show footnotes at some other part of the screen and not at the bottom of the post?
| |
doc_5181
|
It appears that any content after the video is displayed, renders above the video on full-screen.
The blackberry developer tools were no help when trying to find the issue, or change z-indexes on various elements.
Is there a hook for html5 in blackberry that I can get to display above the content?
Is this a Blackberry bug or a VideoJS bug?
| |
doc_5182
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://www.ibm.com/webservices
/xsd/j2ee_web_services_1_1.xsd" version="1.1">
<webservice-description>
<webservice-description-name>CAPPLANService</webservice-description-name>
<wsdl-file>/wsdls/capplan.wsdl</wsdl-file>
<jaxrpc-mapping-file>WEB-INF/CAPPLANService.xml</jaxrpc-mapping-file>
<port-component>
<port-component-name>CAPPLANEndpointPort</port-component-name>
<wsdl-port>CAPPLANEndpointPort</wsdl-port>
<service-endpoint-interface>
com.eds.www.AirlineSOASchema.CAPPLAN.CAPPLANPortTypeImplPortType
</service-endpoint-interface>
<service-impl-bean>
<servlet-link>CAPPLANServiceServlet</servlet-link>
</service-impl-bean>
</port-component>
</webservice-description>
</webservices>
I am using this xml file.
But while compiling I am getting the below error,
16:17:22,837 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."capplan.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."capplan.war".PARSE: JBAS018733: Failed to process phase PARSE of deployment "capplan.war"
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:127) [jboss-as-server-7.2.0.Final-redhat-8.jar:7.2.0.Final-redhat-8]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_25]
at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_25]
Caused by: javax.xml.ws.WebServiceException: JBWS021004: Failed to unmarshall vfs:/C:/jboss-eap-6.1/standalone/deployments/capplan.war/WEB-INF/jboss-webservices.xml
at org.jboss.wsf.spi.metadata.webservices.JBossWebservicesFactory.load(JBossWebservicesFactory.java:111)
at org.jboss.as.webservices.deployers.JBossWebservicesDescriptorDeploymentProcessor.deploy(JBossWebservicesDescriptorDeploymentProcessor.java:53)
at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:120) [jboss-as-server-7.2.0.Final-redhat-8.jar:7.2.0.Final-redhat-8]
... 5 more
Caused by: java.lang.IllegalStateException: JBWS021001: Unexpected element parsing vfs:/C:/jboss-eap-6.1/standalone/deployments/capplan.war/WEB-INF/jboss-webservices.xml: webservices
at org.jboss.wsf.spi.metadata.webservices.JBossWebservicesFactory.parse(JBossWebservicesFactory.java:160)
at org.jboss.wsf.spi.metadata.webservices.JBossWebservicesFactory.load(JBossWebservicesFactory.java:109)
... 7 more
Can anyone help me to solve this problem?
A: You have the wrong xmlns.
<webservices xmlns="http://www.jboss.com/xml/ns/javaee">
<!-- Rest of your file here -->
</webservices>
| |
doc_5183
|
How to switch Playback->Program in VLC via command line.
A: The option is --program <service_id>. For full usage information you can do vlc -H.
| |
doc_5184
|
Is this possible, any link or code might help??
Thanks in advance
A: I got the tabs without the rest of the ActionBar by removing the home button and the title, like this:
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
and not overriding:
onCreateOptionsMenu
That way the ActionBar would be empty and Android won't display it.
A: It depends what kind of tabs you want to use. In my app I'm using ViewPager together with indicator and it works great, so maybe it will suite you. I hope I've understood your question.
A: You can use the tabWidget. In a part of my application, I have a TabActivity where the inner activity uses fragments. So, it is possible. It may not be the best solution, but I had to do what the customer wanted.
| |
doc_5185
|
{
some: {
complex: {
unknown: {
structure: {
fields: [
{ name: "group1", other: "data", currentValue: "" },
{ name: "group2", other: "another data", currentValue: "" },
]
}
}
}
}
}
We must inject, in this structure, proper value. We receive for example
{
group1: 'the proper value'
}
And we must replace the value in the proper group to obtain:
{
some: {
complex: {
unknown: {
structure: {
fields: [
{ name: "group1", other: "data", currentValue: "the proper value" },
{ name: "group2", other: "another data", currentValue: "" },
]
}
}
}
}
}
We tried to use lodash mergeWith but since we cannot know where exactly is the value we must inject and we only know the value of of of the key of the object we must inject the value in, we didn't manage to get this working.
A: A solution could be to use a recursive function like this:
object={
some: {
complex: {
unknown: {
structure: {
fields: [
{ name: "group1", other: "data", currentValue: "" },
{ name: "group2", other: "another data", currentValue: "" },
]
}
}
}
}
};
newValue={
group1: 'the proper value'
};
var inserted=false;
function search(data, newData){
if(inserted) return;
for(key in data){
if(data[key]==Object.keys(newData)[0]){
data["currentValue"]=newData[Object.keys(newData)[0]];
inserted=true;
return;
}else
search(data[key], newData);
}
}
search(object, newValue);
console.log(object);
A: You could do a recursive search and replace...
let theObj = {
some: {
complex: {
unknown: {
structure: {
fields: [
{ name: "group1", other: "data", currentValue: "" },
{ name: "group2", other: "another data", currentValue: "" },
]
}
}
}
}
}
function updateObj(obj, replacement) {
if(Array.isArray(obj)) {
let key = Object.keys(replacement)[0]
let itm = obj.find(i => i.name == key)
itm.data = replacement[key]
} else if(typeof obj == 'object') {
for(let i in obj) {
updateObj(obj[i], replacement)
}
}
}
updateObj(theObj, { group1: 'the proper value' })
console.log(theObj)
A: Have a recursive function going through the object and mutating it depending on the value of what you seek.
const obj = {
some: {
complex: {
unknown: {
structure: {
fields: [{
name: 'group1',
other: 'data',
currentValue: '',
},
{
name: 'group2',
other: 'another data',
currentValue: '',
},
],
},
},
},
},
};
const toChange = {
group1: 'the proper value',
group2: 'the proper value 2',
};
// Recursive function that go replace
function lookAndReplace(config, ptr) {
// If we deal with an object look at it's keys
if (typeof ptr === 'object') {
Object.keys(ptr).forEach((x) => {
// If the keys is the one we was looking for check the value behind
if (x === config.keyToCheck) {
// We have found one occurence of what we wanted to replace
// replace the value and leave
if (ptr[x] === config.key) {
ptr[config.keyToReplace] = config.value;
}
return;
}
// Go see into the value behind the key for our data
lookAndReplace(config, ptr[x]);
});
}
// If we are dealing with an array, look for the keys
// inside each of the elements
if (ptr instanceof Array) {
ptr.forEach(x => lookAndReplace(config, x));
}
}
// For each group we look for, go and replace
Object.keys(toChange).forEach(x => lookAndReplace({
key: x,
value: toChange[x],
keyToCheck: 'name',
keyToReplace: 'currentValue',
}, obj));
console.log(obj);
/!\ Important this soluce also work with nested arrays
const obj = {
some: {
complex: {
unknown: {
structure: {
// fields is an array of array
fields: [
[{
name: 'group1',
other: 'data',
currentValue: '',
}],
[{
name: 'group2',
other: 'another data',
currentValue: '',
}],
],
},
},
},
},
};
const toChange = {
group1: 'the proper value',
group2: 'the proper value 2',
};
// Recursive function that go replace
function lookAndReplace(config, ptr) {
// If we deal with an object look at it's keys
if (typeof ptr === 'object') {
Object.keys(ptr).forEach((x) => {
// If the keys is the one we was looking for check the value behind
if (x === config.keyToCheck) {
// We have found one occurence of what we wanted to replace
// replace the value and leave
if (ptr[x] === config.key) {
ptr[config.keyToReplace] = config.value;
}
return;
}
// Go see into the value behind the key for our data
lookAndReplace(config, ptr[x]);
});
}
// If we are dealing with an array, look for the keys
// inside each of the elements
if (ptr instanceof Array) {
ptr.forEach(x => lookAndReplace(config, x));
}
}
// For each group we look for, go and replace
Object.keys(toChange).forEach(x => lookAndReplace({
key: x,
value: toChange[x],
keyToCheck: 'name',
keyToReplace: 'currentValue',
}, obj));
console.log(obj);
const obj = {
some: {
complex: {
unknown: {
structure: {
fields: [{
name: "group1",
other: "data",
currentValue: ""
},
{
name: "group2",
other: "another data",
currentValue: ""
},
]
}
}
}
}
};
const toChange = {
group1: 'the proper value',
group2: 'the proper value 2',
};
// Recursive function that go replace
function lookAndReplace({
key,
value,
keyToCheck,
keyToReplace,
}, ptr) {
// If we deal with an object
if (typeof ptr === 'object') {
Object.keys(ptr).forEach((x) => {
if (x === keyToCheck) {
// We have found one
if (ptr[x] === key) {
ptr[keyToReplace] = value;
}
} else {
lookAndReplace({
key,
value,
keyToCheck,
keyToReplace,
}, ptr[x]);
}
});
}
if (ptr instanceof Array) {
ptr.forEach(x => lookAndReplace({
key,
value,
keyToCheck,
keyToReplace,
}, x));
}
}
// For each group we look for, go and replace
Object.keys(toChange).forEach(x => lookAndReplace({
key: x,
value: toChange[x],
keyToCheck: 'name',
keyToReplace: 'currentValue',
}, obj));
console.log(obj);
| |
doc_5186
|
Possible Duplicate:
how to update the textview variable for every 5 seconds
i have two tasks to do simultaneously using the same data file.One is to read the txt file and plot it in the chartview. The other task is to do calculations with the plotted data. My android app layout should have these calculated results in textview above the chartview and it should get updated constantly for 5 sec while the ploting is going on dynamically in the chart.
I have problem with the second task - updating the values in textview which runs in a while loop. I have used Handler,Asynctask,Thread, Wait. It works perfectly as java app.But, it dint work as an android app. My app either force closes or takes the delay before startup (i.e.) the app opens only after the delay given and shows the last value of while loop execution. I also did this in background, but it affects the plotting.
while(p[y1]!=0)
{
rr = ((p[y1]-p[y1-1]));
double x = rr/500;
HR = (int) (60/x);
final Handler handler=new Handler();
handler.post(runnable);
final Runnable runnable=new Runnable()
{
@Override
public void run()
{
hr.setText(String.valueOf(HR));
handler.postDelayed(runnable, 5000);
}
};
y1++;
}
I want the hr value to be updated every 5 sec, without affecting the chart. anyone pls help. Thanks in advance for the help.
A: have you tried something like, create a inner thread class, in its run method do what you need. you can also try sleep for 5 sec in its run. make sure your while loop is inside the run method.
i below code you have thread inside a while loop, but you should have loop inside a thread.let me know if u face any issue doing this.
boolean isAlive = true; //change it to falst whenever u want to stop the thread
class localT extends Thread {
@Override
public void run() {
while(isAlive) {
try {
sleep(5000);
textView.setText("yourChanging text");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
super.run();
};
}
use something like localThread.start(); , kill// stop this thread on on pause, on destroy.
| |
doc_5187
|
testCompile 'junit:junit:4.12'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
We are using the latest version of the support library (24.0.0), but the current version of the test runner (JUnit runner) and Espresso use version 23.1.0. To resolve the version conflict, I force the runner (and Espresso) to use the newer version (I understand the implications, but we can't use the older version):
androidTestCompile 'com.android.support:support-v4:24.0.0'
androidTestCompile 'com.android.support:appcompat-v7:24.0.0'
androidTestCompile 'com.android.support:support-v13:24.0.0'
androidTestCompile 'com.android.support:recyclerview-v7:24.0.0'
androidTestCompile 'com.android.support:design:24.0.0'
androidTestCompile 'com.android.support:support-annotations:24.0.0'
and:
configurations.all {
resolutionStrategy {
force 'com.android.support:support-annotations:24.0.0'
}
}
However, for some reason, Gradle doesn't add the runner package (under android.support.test). So
import android.support.test.runner.AndroidJUnit4;
throws an error: cannot resolve symbol 'runner'. Have cleared Android Studio's cache, restarted the IDE, cleared Gradle's cache (both project and global), all with no luck. Does anyone know what's going on?
A: try adding:
androidTestCompile 'com.android.support.test:rules:0.5'
A: This is my old question but thought it might help to explain the issue and the solution. The issue was with the name of the debug build variant: if you name your debug build variant anything but debug, make sure to notify Android's Gradle plugin by adding testBuildType "yourDebugBuildVariantName" to your build.gradle script (your app module's build.gradle not the project global) in the android{} section, or rename your debug build variant to just debug. If you have multiple debug build variants, you need to specify one of them on which you'd like to run your tests, like: testBuildType armDebug:
apply plugin: 'com.android.application'
...
android {
testBuildType "myDebug" <-
compileOptions { ... }
sourceSets { ... }
signingConfigs { ... }
}
Even with this explicit config, Gradle occasionally seems to have issues with running instrumentation tests. The best way to workaround this is to rename your debug build variant (the one you run your tests on) to debug if this is a feasible option for you.
| |
doc_5188
|
So can anyone tell me how to hide this Family Sharing option ?
Please see the screen shot here
Thanks!
| |
doc_5189
|
$number = new Zend_Form_Element_Text('number', array(
'size' => 32,
'description' => 'Please the the following website: <a href="foo/bar">lorem ipsum</a>',
'max_length' => 100,
'label' => 'Number'));
The link is not shown in the description, the brackets are converted into their special-char counterparts.
Is there another way to show a link (or use HTML at all...)?
A: It is possible, you just have to tell the Description decorator not to escape output.
Try:
$number = new Zend_Form_Element_Text('number', array(
'size' => 32,
'description' => 'Please the the following website: <a href="foo/bar">lorem ipsum</a>',
'max_length' => 100,
'label' => 'Number')
);
$number->getDecorator('Description')->setOption('escape', false);
If you create your own set of decorators for elements, you can also specify this option when configuring decorators like this:
$elementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('class' => 'description', 'escape' => false)),
array('HtmlTag', array('class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
The relevant part being:
array('Description', array('class' => 'description', 'escape' =>
false)),
| |
doc_5190
|
I have done some research before asking here but I was still unable to find an answer. I am writing an application that connects to twitter's streaming api and receives some tweets. I intend to run the program for a few hours and then I need to interrupt it.
There is no multi-threading so far in my project and I am trying to avoid that. If I make the function that gets the tweet synchronized, would it complete even if I closed the program while it's executing?
A: If there is no multi-threading in your application, why do you need synchronized? Never mind, your application will complete. Hitting Ctrl+C will just interrupt all threads and shutdown nicely.
A: No, it wouldn't complete. Synchronization doesn't prevent System.exit() to exit.
That said, unless you use Ctrl-C to kill your program, you have some multi-threading in the project. Else you wouldn't be able to call System.exit() while another method is executing.
| |
doc_5191
|
*
*A given process's CPU/RAM usage
*The process which is using the most CPU/RAM
Is there a way to access that information via Python or C++ (basically, via the Windows API)?
Here's what I'm essentially trying to do (in pseudo code):
app x = winapi.most_intensive_process
app y = winapi.most_RAM_usage
print x.name
print y.name
A: You can retrieve information about RAM usage with the PSAPI functions, especially EnumProcesses to find all the processes in the system, and GetProcessMemoryInfo to get information about each process' memory usage.
You can retrieve CPU usage for each process with GetProcessTimes. This isn't always perfectly accurate, but I believe the Task Manager produces results that are inaccurate in the same way under the same circumstances.
In case you want it, information about memory usage by the system as a whole is available via GetPerformanceInfo.
A: Instead of calling the windows API directly you can use the psutil library which is a cross-platform library that provides a lot of information about processes.
It works on Windows, Linux, Mac OS, BSD and Sun Solaris and works with python from 2.4 to 3.4 in both 32 and 64 bit fashion.
In particular it's Process class has the following interesting methods:
*
*cpu_times: user and system timings spent by the process from its start.
*cpu_percent: percentage of cpu utilization since last call or in the given interval
*memory_info: info about Ram and virtual memory usage. NOTE: the documentation explicitly states that these are the one shown by taskmgr.exe so it looks like exactly what you want.
*memory_info_ex: extended memory information.
*memory_percent: percentage of used memory by the process.
To iterate over all processes (in order to find the most CPU/memory hungry for example), you can just iterate over process_iter.
Here's a simple implementation of what you wanted to achieve:
import psutil
def most_intensive_process():
return max(psutil.process_iter(), key=lambda x: x.cpu_percent(0))
def most_RAM_usage():
return max(psutil.process_iter(), key=lambda x: x.memory_info()[0])
x = most_intensive_process()
y = most_RAM_usage()
print(x.name)
print(y.name)
Sample run on my system:
In [23]: def most_intensive_process():
...: # psutil < 2.x has get_something style methods...
...: return max(psutil.process_iter(), key=lambda x: x.get_cpu_percent(0))
...:
...: def most_RAM_usage():
...: return max(psutil.process_iter(), key=lambda x: x.get_memory_info()[0])
In [24]: x = most_intensive_process()
...: y = most_RAM_usage()
...:
In [25]: print(x.name, y.name)
firefox firefox
A: You can use the following Windows API to retrieve various process counters in C/C++ program.
It retrieves information about the memory usage of the specified process.
BOOL WINAPI GetProcessMemoryInfo(
_In_ HANDLE Process,
_Out_ PPROCESS_MEMORY_COUNTERS ppsmemCounters,
_In_ DWORD cb
);
There is complete example on MSDN, which explains how it can be used to retrieve such information for your process.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682050%28v=vs.85%29.aspx
You have mentioned that you would like to fetch the information on continuous basis(with some time interval as task manager do). To achieve this you may want to write the complete logic(mentioned in MSDN) inside a function and call it after some time delay(Sleep(1second)).This way you should be able to fetch all these information of your program till it executes.
| |
doc_5192
|
I have a page that I set to $('body').hide() until it finishes loading a AJAX request, after that the page is set to $('body').show(). In the meantime (about 2 seconds) the page stays blank and the browser icon stops loading, then it shows the content or redirect to another page (according to the returned AJAX variables).
There's any way to make the browser stay on a loading state even it isn't loading anything? Just to seems like it's still loading stuff.
I've already tried to create something like:
while(page_loading())
var l = 1;
But then the browser crashes. How can I force this "fake" state?
EDIT:
Sorry, I forgot to mention before: I want to keep the page blank as usual without any loading gif or anything like that but forcing the browser to be on a loading state. When the browser is loading a page there's an loading icon that keeps appearing on the browser tab or a message on statusbar. I know these particular states can't be change on directly with javascript so I thought that there's a way to keep the browser on this loading state using some infinite looping HTML request, or something like that. If I set "cursor: wait" the browser tab still changes to a "finish state".
A: The standard way to handle this is to create a loading gif that appears and disappears. You can create your own gif and download it. Then when the page starts loading: $("#mygif").show(); and when it's done, $("#mygif").hide();
A: Using a loading animation as yourdeveloperfriend suggests is probably the way to go. However, you can approximate a page loading using cursor: wait:
html,
body {
cursor: wait;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background: #555;
color: white;
text-align: center;
}
setTimeout(function unwait() {
document.body.style.cursor = 'default';
document.body.innerHTML = 'Loaded.';
}, 3000);
http://jsfiddle.net/8cxA7/
Obviously, this is just a demo. The tab favicon should be left alone, in my opinion, since some browsers will cache what they first see and hold onto that favicon for dear life.
| |
doc_5193
|
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
{
NSLog(@"TEST");
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:location];
if (indexPath) {
UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
NSDictionary *dict = [self.array objectAtIndex:indexPath.row];
cell.textLabel.text = [dict objectForKey:@"name"];
DetailViewController *previewController = [[DetailViewController alloc] init];
// previewController.content = content;
previewingContext.sourceRect = cell.frame;
return previewController;
}
return nil;
}
A: I'm currently implementing this in our app and that looks mostly right. A problem I encountered is that the coordinates given to you in location are for the UIViewController's view, not the UITableView. Depending on your setup, they may be the same, but in my case, I needed to convert the location to the UITableView's coordinates.
CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
Of course, your mileage may vary.
A: You should not need to correct the location if you registered the previewDelegate with the correct sourceView. So instead of
[self registerForPreviewingWithDelegate:self sourceView:self.view];
you should register it this way:
[self registerForPreviewingWithDelegate:self sourceView:self.tableView];
Then location you get from the delegate call takes scrolling / contentOffset into account.
A: The only problem with your code is the way to get convertedLocation is not right.
Below code will get correct location even after you scroll the table view.
CGPoint convertedLocation = [self.tableView convertPoint:location fromView:self.view];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
| |
doc_5194
|
set -e
LINE="$( ssh server1 cat 1.log | tail -1 )"
I want to break execution of the script on the ssh connection failure or if 1.log does not exists on the remote side.
How to stop the execution of the script if any of the participants of the pipe returns non-zero exit code?
A: Add set -o pipefail and it will manage errors between pipes.
| |
doc_5195
|
initialize: function(container, application) {
var globals = container.lookup("route:application").get('globals');
application.deferReadiness();
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
var startAppJob = setTimeout(function(){application.advanceReadiness();}, 10000),
pushNotification = window.plugins.pushNotification;
if ( device.platform == 'android' || device.platform == 'Android' ){
pushNotification.register(
successHandler,
errorHandler,
{
"senderID":"xxx",
"ecb":"onNotificationGCM"
});
}
}
So far so good. Except the ecb now expects the "onNotificationGCM" function to be in the global scope. So, where should the following go?
onNotificationGCM = function(e) {
switch( e.event ){
case 'registered':
clearTimeout(startAppJob)
application.advanceReadiness();
if ( e.regid.length > 0 ){
globals.set('push_registration_id', e.regid)
globals.set('push_device_type', 'iandroidos')
console.log('registered')
}
break;
Declaring it with window.onNotificationGCM or this.onNotificationGCM inside the intializer doesn't work:
processMessage failed: Error: ReferenceError: onNotificationGCM is not
defined
This question Cordova Pushplugin: ecb not called suggests altering the callback which in their example becomes:
"ecb":"window.GambifyApp.NotificationHandler.onNotificationGCM"
Except in Ember CLI what would this be inside an initializer? Is it even possible to access or is there a better way to implement all this in Ember CLI?
Thanks in advance for any help!
A: At my company we have developed a set of shims/interfaces to make working with Cordova plugins in Ember apps easier.
https://github.com/Skalar/ember-cli-cordova-shims
It hides all the handling of callbacks that PushPlugin requires, and exposes events emitted by a service in your application.
import NotificationsService from 'ember-cli-cordova-shims/services/notifications';
export function initialize(container, application) {
let service = NotificationsService.create({
gcmSenderId: '{INSERT-KEY-FROM-GCM-HERE}',
gcmTimeout: 10000 // Timeout for GCM in ms. Default: 15000
});
application.register('service:notifications', service, {
instantiate: false
});
application.inject('route', 'notifications', 'service:notifications');
}
export default {
name: 'notifications-service',
initialize: initialize
};
// In your route
export default Ember.Route.extend({
init: function(){
this._super();
this.notifications.on('alert', function(){...});
},
actions: {
subscribeForNotifications: function(){
this.notifications.register().then(function(){...});
}
}
});
| |
doc_5196
|
I have written a simple code where I am asking for a string from maas360 mdm.
Following is my Android manifest code snippet:
<receiver android:name=".GetRestrictionReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.APPLICATION_RESTRICTIONS_CHANGED"></action>
</intent-filter>
</receiver>
And following is my broadcast receiver:
public void onReceive(Context context, Intent intent) {
Log.d("Get Restriction", "on receive");
RestrictionsManager restrictionsManager = (RestrictionsManager) context.getSystemService(Context.RESTRICTIONS_SERVICE);
Bundle b = restrictionsManager.getApplicationRestrictions();
if(b.containsKey("siteName")) {
Log.d("Get Restriction", "Site name= "+b.getString("siteName"));
}
//String value = intent.getStringExtra("siteName");
}
Following is my app_restriction xml:
<restrictions xmlns:android="http://schemas.android.com/apk/res/android">
<restriction
android:key="siteName"
android:title="SiteName"
android:restrictionType="string"
android:defaultValue="English">
</restriction>
</restrictions>
Unfortunately my broadcast is not receiving my policy from maas360 mdm.
Would you help me understand what am I missing from my code that will get me the policy?
A: If you check out this page:
https://developer.android.com/work/managed-configurations.html#listen-configuration
You'll see the following -
Note: The ACTION_APPLICATION_RESTRICTIONS_CHANGED intent is sent only to listeners that are dynamically registered, not to listeners that are declared in the app manifest.
I see that you are delaring the listener in the app manifest. It needs to be dynamically registered.
| |
doc_5197
|
Here is what I have so far:
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from craigslist_sample.items import CraigslistSampleItem
class MySpider(CrawlSpider):
name = "craigs"
allowed_domains = ["craigslist.org"]
start_urls = ["http://sfbay.craigslist.org/npo/"]
rules = (
Rule(SgmlLinkExtractor(allow=('.*?s=.*',), restrict_xpaths('a[@class="button next"]',)), callback='parse', follow=True),)
def parse(self, response):
for sel in response.xpath('//span[@class="pl"]'):
item = CraigslistSampleItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
yield item`
I get this error
SyntaxError: non-keyword arg after keyword arg
UPDATE:
Thanks to the answer below. There is no syntax error, but my crawler just stays in the same page and doesn't crawl.
Updated code
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from craigslist_sample.items import CraigslistSampleItem
from scrapy.contrib.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
name = "craigs"
allowed_domains = ["craigslist.org"]
start_urls = ["http://sfbay.craigslist.org/npo/"]
rules = (Rule(SgmlLinkExtractor(allow=['.*?s=.*'], restrict_xpaths=('a[@class="button next"]')),
callback='parse', follow=True, ),
)
def parse(self, response):
for sel in response.xpath('//span[@class="pl"]'):
item = CraigslistSampleItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
yield item
A: Your problem is similar to this (Python 3)
>>> print("hello")
hello
>>> print("hello", end=",,")
hello,,
>>> print(end=",,", "hello")
SyntaxError: non-keyword arg after keyword arg
The line:
Rule(SgmlLinkExtractor(allow=('.*?s=.*',), restrict_xpaths('a[@class="button next"]',)), callback='parse', follow=True),)
must be called as:
Rule(SgmlLinkExtractor(restrict_xpaths('a[@class="button next"]'),allow=('.*?s=.*',)), callback='parse', follow=True),)
A: ok so i found whats the problem i was using the method parse:
def parse(self, response):
for sel in response.xpath('//span[@class="pl"]'):
item = CraigslistSampleItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
yield item
after reading this i found out my problem.
http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.contrib.spiders.CrawlSpider
CrawlSpider uses parse as a method, so i had to rename my function to this:
def parse_item(self, response):
for sel in response.xpath('//span[@class="pl"]'):
item = CraigslistSampleItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
yield item
| |
doc_5198
|
This question concerns socket.io versions < 0.9.x.
Newer versions have different transports and methods of setting transports.
I test node js and socket.io in two week. when I began I get the problem from socket.send(message) function in client. I can't send any message to the server. But I still can receive messages from the server. I solved this problem when I found the configure transport of server side:
socket.set('transports',[
'xhr-polling'
, 'jsonp-polling'
]);
Everything good. Now I can send messages to the server as well. But I still have a question why I have to configure transport. Default socket.io use websocket transport setting like this:
socket.set('transports', [
'websocket'
, 'flashsocket'
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
so it uses websocket at first, not xhr-polling. But the server cannot receive any messages sent from the client when using socket.send(msg) even socket.emit(...).
So the problem is: what is not supporting websocket here? browser or node.js ... I'm sorry but I searched so many pages from google and I haven't found an answer for this.
I use node.js version 0.8.16, socket.io version 0.9.13 and newest browsers: chrome, firefox, opera
I want to use websocket not xhr-polling.
A: That's odd because even if websockets are not supported by your server configuration, socket.io will select the next best available method (in your case xhr-polling). Actually, you shouldn't even need to set those transports as socket.io will try to use 'websocket' as a primary method by default. This may indicate some other problem, possibly with your code?
What is not supporting websockets is definitely not the browsers you're using nor node.js of course. This will depend on your server setup.
First check:
*
*The port you're listening to is open in your firewall
*Your webserver supports websockets. If you're using Apache and proxing your request to an internal IP:PORT, websocket will not work unless you install something like apache-websocket or pywebsocket
What finally solved my issue was to disable Apache listening on port 80 and having node.js listening on that port. Here's the answer on SO that helped me: https://stackoverflow.com/a/7640966/2347777
| |
doc_5199
|
Someone told me I could use RFID, but I am only aware of that being used in short-distance applications, like a card on a hotel door. I am not sure about Bluetooth either, because the phone would have to connect to the pi first, right? Maybe there is something I don't know about. So please offer any suggestions. Thanks
A:
I think bluetooth does good work for tracking user. Since it's the best to handle large distances than NFC and RFID these two technologies are used for low range scenarios, check this link.
In addition, you can check distance(using Proximity and RSSI) and membership status as well. but you need to know how to handle bluetooth connectivity with raspberry pi check this link. as well create an app on that mobile phone to use Bluetooth (depending which OS you're using for Android, iOS).
Regards,
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.