_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 21
37k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d673
|
train
|
urls = root.xpath('//div[1]/header/div[3]/nav/ul/li/a/@href')
These HREFs aren't full URLs; they're essentially just pathnames (i.e. /foo/bar/thing.html).
When you click on one of these links in a browser, the browser is smart enough to prepend the current page's scheme and hostname (i.e. https://host.something.com) to these paths, making a full URL.
But your code isn't doing that; you're trying to use the raw HREF value.
Later on in your program you use urljoin() which solves this issue, but you aren't doing that in the for l in l1: loop. Why not?
|
unknown
| |
d677
|
train
|
You can use the DataFrame.explode method, followed by groupby and size:
I am going to just use a simple .str.split instead of your function, as I don't know where word_tokenize comes from.
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'title': ['Hello World', 'Foo Bar'], 'date': ['2021-01-12T20:00', '2021-02-10T22:00']})
In [3]: df['words'] = df['title'].apply(lambda s: process_title(str(s)))
In [4]: df
Out[4]:
title date words
0 Hello World 2021-01-12T20:00 [Hello, World]
1 Foo Bar 2021-02-10T22:00 [Foo, Bar]
In [5]: exploded = df.explode('words')
In [6]: exploded
Out[6]:
title date words
0 Hello World 2021-01-12T20:00 Hello
0 Hello World 2021-01-12T20:00 World
1 Foo Bar 2021-02-10T22:00 Foo
1 Foo Bar 2021-02-10T22:00 Bar
In [7]: exploded.groupby(['date', 'words']).size()
Out[7]:
date words
2021-01-12T20:00 Hello 1
World 1
2021-02-10T22:00 Bar 1
Foo 1
dtype: int64
|
unknown
| |
d679
|
train
|
This is a common problem when setting up SSL for a web site. This issue is that your web pages are being requested using HTTPS but the page itself is requesting resources using HTTP.
Start Google Chrome (or similar). Load your web site page. Press F-12 to open the debugger. Press F-5 to refresh the page. Note any lines that look like the following:
Mixed Content: The page at 'https://mywebsite.com/' was loaded over
HTTPS, but requested an insecure image
'http://mywebsite.com/images/homepage_top.png'. This content should
also be served over HTTPS.
You will then need to edit the HTML content (or page generator such as PHP) to correctly use HTTPS instead of HTTP.
|
unknown
| |
d683
|
train
|
It depends on your DB2 platform and version. Timestamps in DB2 used to all have 6 digit precision for the fractional seconds portion. In string form, "YYYY-MM-DD-HH:MM:SS.000000"
However, DB2 LUW 10.5 and DB2 for IBM i 7.2 support from 0 to 12 digits of precision for the fraction seconds portion. In string form, you could have from "YYYY-MM-DD-HH:MM:SS" to "YYYY-MM-DD-HH:MM:SS.000000000000".
The default precision is 6, so if you specify a timestamp without a precision (length), you get the six digit precision. Otherwise you may specify a precision from o to 12.
create table mytable (
ts0 timestamp(0)
, ts6 timestamp
, ts6_also timestamp(6)
, ts12 timestamp(12)
);
Note however, that while the external (not exactly a string) format the DBMS surfaces could vary from 19 to 32 bytes. The internal format the TS is stored in may not. On DB2 for IBM i at least the internal storage format of TS field takes between 7 and 13 bytes depending on precision.
*
*timestamp(0) -> 7 bytes
*timestamp(6) -> 10 bytes (default)
*timestamp(12) -> 13 bytes
A: Since you refer to 10 as the length, I'm going to assume you're looking in SYSIBM.SYSCOLUMNS (or another equivalent table in the catalog.
The LENGTH column in the catalog refers to the internal length of the field. You can calculate this using the following formula:
FLOOR( ((p+1)/2) + x )
*
*p is the precision of the timestamp (the number of places after the decimal [the microseconds])
*x is 7 for a timestamp without a timezone, or 9 if it has a timezone (if supported by your platform)
If you are comparing the to a field in the SQLCA, that field will be the length of a character representation of the timestamp. See this Information Center article for an explanation between the two fields.
If you truly want to change the scale of your timestamp field, then you can use the following statement. x should be an integer for the number of places after the decimal in the seconds position.
The number of allowed decimals varies by platform and version. If you're on an older version, you can likely not change the scale, which is set at 6. However, some of the newer platforms (like z/OS 10+, LUW 9.7+), will allow you to set the scale to a number between 0 and 12 (inclusive).
ALTER TABLE SESSION.TSTAMP_TEST
ALTER COLUMN tstamp
SET DATA TYPE TIMESTAMP(x);
|
unknown
| |
d685
|
train
|
Shamelessly copying from a user note on the documentation page:
$buffer = fopen('php://temp', 'r+');
fputcsv($buffer, $data);
rewind($buffer);
$csv = fgets($buffer);
fclose($buffer);
// Perform any data massaging you want here
echo $csv;
All of this should look familiar, except maybe php://temp.
A: $output = fopen('php://output', 'w');
fputcsv($output, $line);
fclose($output);
Or try one of the other supported wrappers, like php://memory if you don't want to output directly.
|
unknown
| |
d687
|
train
|
You can implement a class inherited from EventHandler. For this class you can implement any additional behavior you want. For instance, you can create a collection which will hold object-event maps and you can implement a method which searches for a given pair or pattern.
A: you can do this assuming you have access to source of class. Beware this way you are giving away the control of when to call all delegates to client of your class which is not a good idea. If you are not looking for the list of eventhandler but just want to know if event is subscribed.Probably you can use the other method which only tells whether click event is subscribed by anyone.
class MyButton
{
delegate void ClickHandler(object o ,EventArgs e);
public event ClickHandler Click;
......
public List<ClickHandler> ClickHandlerList
{
get
{
return ClickHandler.GetInovationList().Cast<ClickHandler>().ToList();
}
}
public bool IsClickEventSubcribed
{
get
{
return ClickHandler.GetInovationList().Cast<ClickHandler>().Any();
}
}
}
A: If the purpose of this is to stop sending signals to event listeners, wouldn't it be easier just wrap the sending by the check?
if (NotifyingEnabled)
{
SomeEvent.Raise(this);
}
|
unknown
| |
d691
|
train
|
Move your deslectRowAtIndexPath message call below the assignment of your row variable:
NSInteger row = [[self tableView].indexPathForSelectedRow row];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
|
unknown
| |
d693
|
train
|
As of Riverpod 0.14.0, the way we work with StateNotifier is a bit different.
Now, state is the default property exposed, so to listen to the state, simply:
final counterModel = useProvider(provider);
To access any functions, etc. on your StateNotifier, access the notifier:
final counterModel = useProvider(provider.notifier);
And now when we create StateNotifierProviders, we include the type of the state of the StateNotifier:
final provider = StateNotifierProvider<CounterNotifier, CounterModel>((ref) => CounterNotifier());
See more on the changes from 0.13.0 -> 0.14.0 here.
|
unknown
| |
d697
|
train
|
There are a lot of ways to do this:
*
*Write a string into .txt file and upload the file to a storage container on Azure Portal.
*Generate a long lifetime SAS token on Azure Portal:
and use blob rest API to upload it to a blob, you can do it directly in postman:
Result:
*Use Azure Logic App to do this. Let me know if you have any more questions.
Let me know if you have any more questions.
|
unknown
| |
d699
|
train
|
Have you tried using the offset*classes?
http://twitter.github.io/bootstrap/scaffolding.html
|
unknown
| |
d701
|
train
|
You can just use a list for the sake of having a sorted - well - list. If you want to associate additional data, you could either use a tuple to store the data, or even create a custom object for it that stores the id in an additional field.
You shouldn’t need to extend the list for that, you can just put any object into a list. For example this would be easily possible:
>>> lst = [ ( 132, 'foobar' ), ( 58, 'other value' ) ]
>>> lst.append( ( 70, 'some data value' ) )
>>> lst
[(132, 'foobar'), (58, 'other value'), (70, 'some data value')]
>>> lst.sort( key=lambda x: x[0] )
>>> lst
[(58, 'other value'), (70, 'some data value'), (132, 'foobar')]
>>> lst.sort( key=lambda x: x[1] )
>>> lst
[(132, 'foobar'), (58, 'other value'), (70, 'some data value')]
edit:
In case you are using Python 3.1+, you could also use the collections.OrderedDict type. It is an extension to the normal dict which maintains the order just like list does.
A: Using lists or arrays is problematic when you need to do insertions or deletions -- these are O(n) operations which can be devastatingly slow with large datasets.
Consider using blist which has a list-like API but affords O(lg N) insertion and deletion.
A: why not using a dictionary, with the key as the item of original array, and value is the id related to the key.
of course you could access it in sorted order, like this:
a = {'key':'id'}
keys = a.keys()
keys.sort()
for k in keys:
print a[key]
A: Similar to poke's answer, you can use a 2d array -- but if the arrays are big, NumPy is generally a good bet for any kind of numerical data in Python. Just make a 2D array that looks like
[ [1 614.124]
[2 621236.139]
[3 1243.612] ]
and then you can sort with .sort().
|
unknown
| |
d705
|
train
|
The answer I needed is based upon Levon's reply at:
How to delete a table in SQLAlchemy?
Basically, this did the trick:
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
from [code location] import db
Base = declarative_base()
metadata = MetaData(db.engine, reflect=True)
table = metadata.tables.get(table_name)
table_to_delete = metadata.tables.get('table_name_for_table_to_delete')
Base.metadata.drop_all(db.engine, [table_to_delete])
|
unknown
| |
d709
|
train
|
If you want the Dialog Border to appear in any colour you wish you have to use layout style and a theme. There is an excellent article about it here: http://blog.androgames.net/10/custom-android-dialog/
|
unknown
| |
d711
|
train
|
Though it may be more complicated, why not just have an onmousedown event on the <p> element, and thet event will then attach an onmousemove event and onmouseout event, so that if there is a mouse movement, while the button is down, then remove the class on the span elements, and once the user exits, the element then you can put them back.
It may be a bit tricky, and you may want to also look for key presses, or determine other times you want to know when to put back the css classes, but this would be one option, I believe.
A: It sounds like you need to go one step further and on highlight, remove the <span> and save a reference to it. Once the highlight is finished, re-insert the reference to the object.
// copy start detected
var savedTooltip = $('.tooltip').remove();
// later that day when copy finished
$('p').append(savedTooltip);
If position of the <span> in your markup is important, you'd have to create a temporary reference element so you'd know where to re-insert it in the DOM.
|
unknown
| |
d713
|
train
|
I've had this problem before, and if I recall correctly it had something to do with iOS not knowing the actual size until after the view has been drawn the first time. We were able to get it to update by refreshing after viewDidAppear (like you mentioned it's the appropriate size after refreshing), but that's not exactly the nicest solution.
Something else you could try is adding constraint outlets to the cell that you manipulate wherever you do your cell setup. For example, if you needed a UI element to be a certain width in some cases but not others, you could add a width constraint that you change the value of. This lets your other elements resize themselves based on the other constraints in the view. The limitation here is that you need to know the width of one of your elements beforehand.
|
unknown
| |
d715
|
train
|
You can do this by enabling two-phase rendering: https://www.ibm.com/support/knowledgecenter/en/SSHRKX_8.5.0/mp/dev-portlet/jsr2phase_overview.html.
Enable two-phase rendering in the portlet.xml like this:
<portlet>
...
<container-runtime-option>
<name>javax.portlet.renderHeaders</name>
<value>true</value>
</container-runtime-option>
</portlet>
Then you can set the headers within the doHeaders method by using the setProperty or addProperty response methods:
@Override
protected void doHeaders(RenderRequest request, RenderResponse response) {
response.addProperty("MyHeader", "MyHeaderValue");
}
|
unknown
| |
d719
|
train
|
I found a way. Just add httpServletRequest.getSession().setMaxInactiveInterval(intervalInSeconds)
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String login(HttpServletRequest request, HttpServletResponse servletresponse){
//Your logic to validate the login
request.getSession().setMaxInactiveInterval(intervalInSeconds);
}
This worked for me.
EDIT 1
Found another way to do this. This would be the correct way of doing this,
@EnableJdbcHttpSession(maxInactiveIntervalInSeconds = intervalInSeconds)
|
unknown
| |
d733
|
train
|
It looks like the function you're trying to call is compiled as a C++ function and hence has it's name mangled. PInvoke does not support mangled name. You need to add an extern "C" block around the function definition to prevent name mangling
extern "C" {
void* aaeonAPIOpen(uint reserved);
}
A: Using the undname.exe utility, that symbol demangles to
void * __cdecl aaeonAPIOpen(unsigned long)
Which makes the proper declaration:
[DllImport("aonAPI.dll", EntryPoint="?aaeonAPIOpen@@YAPAXK@Z",
ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr aaeonAPIOpen(uint reserved);
|
unknown
| |
d735
|
train
|
It's feasible, at least, using PyQt + QWebKit (an example here and here).
|
unknown
| |
d737
|
train
|
Web-handler should return a response object, not None.
The fixed code is:
async def index(request):
async with aiohttp.ClientSession() as client:
data=await(email_verification(client))
await client.post('http://127.0.0.1:8000/acc/signup',data=data)
return web.Response(text="OK")
async def email_verification(client):
async with client.get('http://www.mocky.io/v2/5c18dfb62f00005b00af1241') as resp:
return await(resp.json())
|
unknown
| |
d739
|
train
|
use jQuery $(window).scrollTop()
|
unknown
| |
d741
|
train
|
You can create a text node and append it to the parent of img, and optionally remove img if needed. This code goes inside the error handler for img
$('img').on('error', function(){
$(this).parent().append($('<div>Broken image</div>'));
$(this).remove();
})
A: Ok, I think I have found a solution for you. I tried to use jQuery error function. This one helped me:
To replace all the missing images with another, you can update the src attribute inside the callback passed to .error(). Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.
In your example this would be the best:
$('img').each(function() {
var img = $(this);
img.error(function() {
img.replaceWith('<div class="error404">Image not found (error 404)</div>');
}).attr('src', img.attr('src'));
});
I also made a jsFiddle example for you, which is working great for me.
A: If you really need to use javascript for this try
$(document).ready(function() {
$('img').attr('alt', 'Alternative text');
});
But the same is achievable by barebone HTML
<img src="path/to/image.jpg" alt="Alternative text">
A: You can change the alt if an error is thrown just like you're doing with the image.
function imgMissing(image) {
image.onerror = "";
image.alt = "Image not Found";
return true;
}
The HTML:
<img src="image.jpg" onerror="imgMissing(this);" >
A: EDIT: OK, I have found this solution working fine:
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>');
});
});
</script>
Anyway one more think, I need to add CSS class "error404" for this "div", how to do that in JS? Thank you very much!
CSS will be:
.error404 {
display: block;
color: #667d99;
font-weight: bold;
font-size: 11px;
border: 1px dotted;
border-radius: 3px;
padding: 5px;
margin: 10px;
background: #e7edf3;
}
|
unknown
| |
d743
|
train
|
Your code has undefined behavior.
You cannot validly access the memory pointed at by an uninitialized pointer, like you do.
The memset() function writes to memory, it does not magically allocate new memory (it takes as input the pointer to the memory to be written), you cannot in anyway use it "instead of" malloc().
You can try with an on-stack buffer:
char log[128] = "";
of course you need to take care not to use more than 128 characters; your unbounded strcat() usage is dangerous.
If your fringe compiler supports C99 you can of course do:
const size_t flen = strlen(func);
const size_t mlen = strlen(msg);
char log[flen + 2 + mlen + 1]; // Space for func, msg, colon, space, terminator.
A: Declare an array of chars with the size of func + size of msg instead of an uninitialized char pointer.
|
unknown
| |
d745
|
train
|
Next to your question there are some other things to take into account:
a. Always use Parameters when creating Sql:
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord = @Password", conn);
cmd.Parameters.Add("@Password", password)
b. Put your database methods in a separate class (Encapsulation, etc.) --> example: ReserverationsDataAccess
c. To answer your main question we'll need some more info (see comments).
A: i have made some changes to the code now.
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord =" + textBox1.Text + "", conn);
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if (count ==1)
{
SqlCommand cmd1 = new SqlCommand("select afdeling from personeel where wachtwoord =" + textBox1.Text + "", conn);
SqlDataReader dr1 = cmd1.ExecuteReader();
MessageBox.Show("OK");
if (dr1.Rows[0][0].ToString() == "keuken")
{
this.Hide();
keukenoverzicht keukenoverzicht = new keukenoverzicht();
keukenoverzicht.Show();
}
else if (dr1.Rows[0][0].ToString() == "bar")
{
this.Hide();
baroverzicht baroverzicht = new baroverzicht();
baroverzicht.Show();
}
else
{
this.Hide();
tafeloverzicht tafeloverzicht = new tafeloverzicht();
tafeloverzicht.Show();
}
}
else
{
MessageBox.Show("wachtwoord niet corect");
}
textBox1.Clear();
conn.Close();
}
}
it have now 2 errors on dr1.rows
-a-
what needs to be changed to fix the error (rows)
-b-
cmd.Parameters.Add("@Password", password) is for ****** in the textbox ride?
error rows
|
unknown
| |
d747
|
train
|
You should consider using DS.ActiveModelAdapter instead of DS.RESTAdapter. See also https://stackoverflow.com/a/19209194/1345947
|
unknown
| |
d749
|
train
|
There were breaking changes in redux-forms from v5 to v6. Previously you could do something similar to what you have to access the touched field. If you want to do something similar to see if there are errors on a field, you need to create your own component to pass to redux-form's Field component.
Your custom component
const CustomComponent = function(field) {
return (
<div>
<input
type={field.type}
{...field.input}
/>
{field.meta.touched && field.meta.error && <div className='error'>{field.meta.error}</div>}
</div>
)
}
Then using it with the Field component
<Field name="my-prop" component={CustomComponent} />
Also take a look at the migration guide, hope this helps!
A: You are confusing v5 syntax with v6 syntax. In v6, your decorated form component is no longer passed this.props.fields. Re-read the migration guide, like @tyler-iguchi said.
|
unknown
| |
d751
|
train
|
External table feature is publicly available feature as per documentation
https://docs.snowflake.com/en/user-guide/tables-external-intro.html
|
unknown
| |
d753
|
train
|
You need a range value for every one of your ordinal values:
var x = d3.scale.ordinal()
.domain(["A", "B", "C", "D", "E"])
.range([0, 1/4 * width, 2/4 * width, 3/4 * width, width]);
https://jsfiddle.net/39xy8nwd/
|
unknown
| |
d755
|
train
|
property: value pairs must go inside a ruleset.
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
… is not a valid stylesheet.
foo {
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
}
… is.
Re edit:
The errors you are seeing are a side effect of the IE7 hacks at the beginning of the ruleset.
Remove the IE7 hacks. The browser is a decade out of date and doesn't even get security updates now.
|
unknown
| |
d757
|
train
|
You have installed SQLAlchemy, but you are trying to use the Flask extension, Flask-SQLAlchemy. While the two are related, they are separate libraries. In order to use
from flask.ext.sqlalchemy import SQLAlchemy
you need to install it first.
pip install Flask-SQLAlchemy
(You installed SQLAlchemy directly from source. You can also do that for Flask-SQLAlchemy.)
|
unknown
| |
d759
|
train
|
This is bit tricky to perform in crystal reports as record selection is compulsory applied. However you can overcome this by using sub report.
Calculate the report footer using report.
This will surely work
|
unknown
| |
d765
|
train
|
In JavaScript, variables and functions can't have the same name. (More confusingly: functions are variables!)
So that means that this line:
let hour = hour();
Is not allowed, because you're trying to reassign the hour variable from being a function to being a value. (This is a side effect of using let. If you had used var then this would have silently did the wrong thing.)
To fix the problem, just rename your variable to something that's not already a function.
let myHour = hour();
|
unknown
| |
d767
|
train
|
I have developed a sample application. I have used string as record item, you can do it using your own entity. Backspace also works properly.
public class FilterViewModel
{
public IEnumerable<string> DataSource { get; set; }
public FilterViewModel()
{
DataSource = new[] { "india", "usa", "uk", "indonesia" };
}
}
public partial class WinFilter : Window
{
public WinFilter()
{
InitializeComponent();
FilterViewModel vm = new FilterViewModel();
this.DataContext = vm;
}
private void Cmb_KeyUp(object sender, KeyEventArgs e)
{
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(Cmb.ItemsSource);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(Cmb.Text)) return true;
else
{
if (((string)o).Contains(Cmb.Text)) return true;
else return false;
}
});
itemsViewOriginal.Refresh();
// if datasource is a DataView, then apply RowFilter as below and replace above logic with below one
/*
DataView view = (DataView) Cmb.ItemsSource;
view.RowFilter = ("Name like '*" + Cmb.Text + "*'");
*/
}
}
XAML
<ComboBox x:Name="Cmb"
IsTextSearchEnabled="False"
IsEditable="True"
ItemsSource="{Binding DataSource}"
Width="120"
IsDropDownOpen="True"
StaysOpenOnEdit="True"
KeyUp="Cmb_KeyUp" />
A: I think the CollectionView is what you are looking for.
public ObservableCollection<NdfClassViewModel> Classes
{
get { return _classes; }
}
public ICollectionView ClassesCollectionView
{
get
{
if (_classesCollectionView == null)
{
BuildClassesCollectionView();
}
return _classesCollectionView;
}
}
private void BuildClassesCollectionView()
{
_classesCollectionView = CollectionViewSource.GetDefaultView(Classes);
_classesCollectionView.Filter = FilterClasses;
OnPropertyChanged(() => ClassesCollectionView);
}
public bool FilterClasses(object o)
{
var clas = o as NdfClassViewModel;
// return true if object should be in list with applied filter, return flase if not
}
You wanna use the "ClassesCollectionView" as your ItemsSource for your Combobox
|
unknown
| |
d771
|
train
|
I think you want to group the first "word" with the hyphen
^(\w+\-)*\w+$
This assumes that you want to match things like
XX-XX
XXX-X
XX-XX-XX-XX-XX-XX-XX-XX
XXX
But not
XX-
XX--XX
If there has to be a hyphen then this would work
^(\w+\-)+\w+$
|
unknown
| |
d773
|
train
|
The problem is most likely that request is not a valid json request. If that is the case then content will be equal to None which means it is not subscriptable.
|
unknown
| |
d775
|
train
|
I take no credit for this since I got every bit of it from going through multiple StackOverflow threads, but I got this working with:
@interface MyViewController ()
- (IBAction) toggleSettingsInPopover: (id) sender;
@property (nonatomic, strong) UIStoryboardPopoverSegue *settingsPopoverSegue;
@end
@implementation MyViewController
@synthesize settingsPopoverSegue = _settingsPopoverSegue;
- (IBAction) toggleSettingsInPopover: (id) sender {
if( [self.settingsPopoverSegue.popoverController isPopoverVisible] ) {
[self.settingsPopoverSegue.popoverController dismissPopoverAnimated: YES];
self.settingsPopoverSegue = nil;
} else {
[self performSegueWithIdentifier: @"Settings" sender: sender];
}
}
- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender {
if( [segue.identifier isEqualToString: @"Settings"] ) {
if( [segue isKindOfClass: [UIStoryboardPopoverSegue class]] )
self.settingsPopoverSegue = (UIStoryboardPopoverSegue *) segue;
MySettingsViewController *msvc = segue.destinationViewController;
msvc.delegate = self;
}
}
@end
In my storyboard I control-dragged from my settings bar button item to MyViewController and connected it to the toggleSettingsInPopover action. Then I control-dragged from MyViewController to the view for the settings to create the segue, set its type to popover, set its identifier to Settings, set its directions to up and left (the toolbar is at the bottom of the screen and the button is at the right end), then dragged from its Anchor to the bar button item I connected to the action.
A: You have to anchor the segue to the UIBarButton by Ctrl-Dragging the Anchor Field from the segue Attribute Inspector to the UIBarButton.
If you do it the opposite way, Ctrl-Dragging from the Button to the Window to be shown you won't have a possibility to control the behaviour from the Popoverwindow.
(The important part is also in the last sentence of LavaSlider's Reply)
|
unknown
| |
d777
|
train
|
Simple way: You could call the CMD version of php from inside node and return the value via node.
Hard way
|
unknown
| |
d779
|
train
|
When your working set (the amount of data read by all your processes) exceeds your available RAM, your throughput will tend towards the I/O capacity of your underlying disk.
From your description of the workload, seek times will be more of a problem than data transfer rates.
When your working set size stays below the amount of RAM you have, the OS will keep all data cached and won't need to go to the disk after having its caches filled.
|
unknown
| |
d781
|
train
|
Not in a "standards-based" way, no.
The X-Windows system is independent of specific window managers, as such, there is no standard way to "maximize" a window. It ultimately depends on the features of the window manager in use...
|
unknown
| |
d783
|
train
|
You can copy above code snippet as a service configuration to your services.yaml, which probably roughly looks like this:
# app/config/services.yaml
services:
app.memcached_client:
class: Memcached
factory: 'Symfony\Component\Cache\Adapter\MemcachedAdapter::createConnection'
arguments: [['memcached://my.server.com:11211', 'memcached://rmf:abcdef@localhost']]
app.memcached_adapter:
class: Symfony\Component\Cache\Adapter\MemcachedAdapter
arguments:
- '@app.memcached_client'
Then in your configuration you should be able to reference the adapter using the client created by the factory, e.g. something like:
# app/config/config.yaml
framework:
cache:
app: app.memcached_adapter
You might also be able to overwrite the default alias cache.adapter.memcached instead of having your own adapter.
Your approach using Memcached::addServer might work as well, but just like with MemcachedAdapter::createConnection this will return the Client, which needs to be passed to the cache adapter. That's why there is a second service app.memcached_adapter, which is used in the cache configuration.
Please be aware that I have not tested this, so this is rather a rough outline than a fully working solution,
A: For one of my projects running Symfony 3.4 the configuration was simpler:
Create a service that will be used as a client:
app.memcached_client:
class: Memcached
factory: ['AppBundle\Services\Memcached', 'createConnection']
arguments: ['memcached://%memcache_ip%:%memcache_port%']
The AppBundle\Services\Memcached can have all the custom logic I need like so:
class Memcached
{
public static function createConnection($dns)
{
$options = [
'persistent_id' => 'some id'
];
// Some more custom logic. Maybe adding some custom options
// For example for AWS Elasticache
if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
$options['CLIENT_MODE'] = \Memcached::DYNAMIC_CLIENT_MODE;
}
return \Symfony\Component\Cache\Adapter\MemcachedAdapter::createConnection($dns, $options);
}
}
And then I used that service in my config.yml:
framework:
cache:
default_memcached_provider: app.memcached_client
|
unknown
| |
d785
|
train
|
getDomain() needs to be added to the scope in the controller...
$scope.getDomain = function(url) {
// ...
return domain;
};
Then you can use it in your view...
<td colspan="3" class="linkCol">
<a ng-href="{{ad.url}}" target="_blank" title="{{ad.url}}">{{ getDomain(ad.url) }}</a>
</td>
|
unknown
| |
d797
|
train
|
I would recommend to design your API as a service loadable with ServiceLoader, similar to DOM API. Thus, your API will be loadable as:
Entry entry = ServiceLoader.load(Entry.class).next();
And it will be easy to have many implementations of the same API.
|
unknown
| |
d801
|
train
|
My team set it up so that a hub operation actually "returns" twice, and maybe this is what you're looking for.
When a hub operation is invoked, we have synchronous code do whatever it needs to do and return a result object, which is usually a model from a backend service we're calling. That is pushed to the client via client.SendAsync where client is IClientProxy. That's going to ultimately invoke a JS handler on your front end.
However, should something break, we may not get that callback to the JS handler. In that case, we also have our hub operations return a Task<IActionResult> that the front JS can handle. That acts more like a HTTP status code response.
In the end, each hub operation we invoke has at least 1 response, which is the IActionResult:
{"type":3,"invocationId":"0","result":{"statusCode":200}}
This approach allows us to setup a reusable client that behaves more like a normal REST client in that we can use the IActionResult response to trigger exception handling.
Example:
try
{
const result = await this.connection.invoke(callSettings.operation, callSettings.args);
if (responseHandler){
const apiResponse = new ApiResponse({ statusCode: result.statusCode });
responseHandler.handleStatusCode(apiResponse, callSettings.operation, callSettings.args);
}
hubResponse.success = result.statusCode < 300;
hubResponse.httpStatusCode = result.statusCode;
hubResponse.body = result;
}
catch (err)
{
hubResponse.success = false;
this.loggerService.logException(err, callSettings.operation);
throw(err);
}
|
unknown
| |
d805
|
train
|
This literal "TESTEEEE" is of type char const[9]. When used as an argument to a function, it can decay to char const* but not to char*. Hence to use your function, you have to make the parameter fit to your argument or the opposite as follows
#include <iostream>
using namespace std;
int PrintString(const char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
PrintString("TESTEEEE");
return 0;
}
live
OR
#include <iostream>
using namespace std;
int PrintString( char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
char myArr[] = "TESTEEEE";
PrintString(myArr);
return 0;
}
live
A: You have incorrect constness, it should be:
void PrintString(const char* s)
|
unknown
| |
d809
|
train
|
Is that java.awt.Frame? I think you need to explicitly add the handler for so:
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
}
I used this source for so.
If it were swing it would be something like jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
A: add aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
A: class Graph extends Canvas{
public Graph(){
setSize(200, 200);
setBackground(Color.white);
addWindowListener(
new java.awt.event.WindowAdapter() {
public void windowClosing( java.awt.event.WindowEvent e ) {
System.out.println( "Closing window!" );
dispose() ;
System.exit( 0 );
}
}
);
}
public static void main(String[] args){
Graph gr = new Graph();
Frame aFrame = new Frame();
aFrame.setSize(300, 300);
aFrame.add(gr);
aFrame.setVisible(true);
}
|
unknown
| |
d811
|
train
|
I think your best solution would be to debug your client and server in separate instances of visual studio and setting startup projects accordingly.
As for the second question, I normally set a guid and output on create and release of a lock. to see if this is happening. If it is, I set breakpoints and debug and look at the stack to see where on the calls are coming from. You may be able to output System.Environment.StackTrace to a log to get this information, but I've ever attempted it.
A: You can use 2 Visual studios. One starting the console, one starting the server
I Would check if you really need a lock statement.
What do you want to lock ?
Do you always need a exclusive lock ?
Or are there some operations which can happen in parallel and only some which are exclusive ?
In this case you could use the ReaderWriterLockSlim
This can reduce the risk of deadlocks.
|
unknown
| |
d815
|
train
|
I had the same problem and I could really only find one solution. I'm not sure why but yeah, something in android prevents task locking when booting up which boggles my mind since the task lock was designed to create these "kiosk" type of applications. The only solution I could find was to detect for a case when it didn't lock then restart the application. Its a little "hacky" but what else can you do?
To detect for the case where it didn't lock I created a state variable and assigning states (Locking, Locked, Unlocking, Unlocked). Then in the device admin receiver in onTaskModeExiting if the state isn't "Unlocking" then I know it unlocked on its own. So if this case happened where it failed, I then restart the application using this method (which schedules the application in the alarm manager then kills the application):
how to programmatically "restart" android app?
Here is some sample code:
DeviceAdminReceiver
@Override
public void onLockTaskModeEntering(Context context, Intent intent, String pkg) {
super.onLockTaskModeEntering(context, intent, pkg);
Lockdown.LockState = Lockdown.LOCK_STATE_LOCKED;
}
@Override
public void onLockTaskModeExiting(Context context, Intent intent) {
super.onLockTaskModeExiting(context, intent);
if (Lockdown.LockState != Lockdown.LOCK_STATE_UNLOCKING) {
MainActivity.restartActivity(context);
}
Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKED;
}
MainActivity
public static void restartActivity(Context context) {
if (context != null) {
PackageManager pm = context.getPackageManager();
if (pm != null) {
Intent intent = pm.getLaunchIntentForPackage(context.getPackageName());
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int pendingIntentId = 223344;
PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
System.exit(0);
}
}
}
}
private void lock() {
Lockdown.LockState = Lockdown.LOCK_STATE_LOCKING;
startLockTask();
}
private void unlock() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED) {
Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKING;
stopLockTask();
}
}
In truth this is a simplified version of what I implemented. But it should hopefully get you pointed towards a solution.
A: The only solution I found as for now : make another launcher app, without locktask, which will trigger main app every time when launcher appears. This prevent user for waiting few more seconds before LockTasked app is being called with on BOOT_COMPLETED receiver. So we can meet this problem only when lockTask app has launcher properties for some activity in manifest.
A: Sorry for late answering, but...
Anyone has this problem can do this tricky work in first (LAUNCHER/HOME) activity (e.g. MainActivity):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mSharedPreferences.getBoolean(KEY_PREF_RECREATED, false)) {
mSharedPreferences.edit().putBoolean(KEY_PREF_RECREATED, false).apply();
// start LOCK TASK here
} else {
mSharedPreferences.edit().putBoolean(KEY_PREF_RECREATED, true).apply();
finish(); // close the app
startActivity(new Intent(this, MainActivity.class)); // reopen the app
return;
}
setContentView(R.layout.activity_main);
// other codes
}
|
unknown
| |
d821
|
train
|
you are doing some graphical changes in secondary thread .. you must do all the graphical changes in your main thread. check you thread code.
|
unknown
| |
d825
|
train
|
Unfortunately, there is no option in Xcode to warn you about an API that does not exists on your deployment target. However, there is a workaround to use the API:
Class TheClass = NSClassFromString(@"NewerClassName");
if(TheClass != nil)
{
NewerClassName *newClass = [[NewerClassName alloc] init];
if(newClass != nil)
{
//Now, you can use NewerClassName safely
}
}
This probably won't provide warnings for that API, but it will allow you to pass Apple's validation process.
|
unknown
| |
d827
|
train
|
The solution using usort and explode functions:
$selectTableRows = array("1_6", "3_4", "10_1", "2_2", "5_7");
usort($selectTableRows, function ($a, $b){
return explode('_', $a)[1] - explode('_', $b)[1];
});
print_r($selectTableRows);
The output:
Array
(
[0] => 10_1
[1] => 2_2
[2] => 3_4
[3] => 1_6
[4] => 5_7
)
|
unknown
| |
d835
|
train
|
Your SQL is ending up like this:
WHERE dbo.InvMaster.InvCurrency = '@varCURRENCY'
So you are not looking for the value of the parameter, you are looking for @Currency, I am not sure why you are using Dynamic SQL, the following should work fine:
CREATE PROCEDURE [dbo].[SP_SLINVOICE] @varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster
INNER JOIN dbo.invdetail
ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company
ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> 'MC'
ORDER BY dbo.invmaster.InvNumber ASC;
END
If you need Dynamic SQL for some other reason you can use the following to pass @varCURRENCY as a parameter to sp_executesql:
DECLARE @SQL NVARCHAR(MAX);
SELECT @SQL = N'SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> ''MC''
ORDER BY dbo.invmaster.InvNumber ASC;';
EXEC sp_executesql @sql, N'@varCURRENCY VARCHAR(3)', @varCURRENCY;
A: If you want to pass a variable to an sp_executesql context, you need to pass it as a parameter.
EXECUTE sp_executesql
@sql,
N'@varCurrency varchar(3)',
@varcurrency= @varCurrency;
http://msdn.microsoft.com/en-gb/library/ms188001.aspx
Although why you don't just use
select ... where dbo.InvMaster.InvCurrency = @varCURRENCY
instead of the executesql is beyond me.
A: You need to pass @varCURRENCY as a parameter, Remove extra ' from your Sp.
WHERE dbo.InvMaster.InvCurrency = ' + @varCURRENCY + '
Or do not use dynamic query
CREATE PROCEDURE [dbo].[SP_SLINVOICE]
@varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> 'MC'
ORDER BY dbo.invmaster.InvNumber ASC;
|
unknown
| |
d837
|
train
|
You can avoid Error Handing and GoTo statements all together (which is definitely best practice) by testing within the code itself and using If blocks and Do loops (et. al.).
See this code which should accomplish the same thing:
Dim pf As PivotField, pi As PivotItem
Set pf = PivotTables(1).PivotField("myField") 'adjust to your needs
For i = 1 To repNumber
Do
Dim bFound As Boolean
bFound = False
repName = InputBox("Enter rep name you want to exclude.", "Name of Rep")
For Each pi In pf.PivotItems
If pi.Value = repName Then
pi.Visible = False
bFound = True
Exit For
End If
Next pi
Loop Until bFound = True
Next i
A: Try Resume TryAgain instead of GoTo TryAgain.
(You don't need : in these statements, it is by coincidence allowed because it is also used to seperate multiple statements within a line, so it is just meaningless here).
|
unknown
| |
d843
|
train
|
You can do the following to get what you are looking for :
WITH CTE AS(SELECT Employee.EmployeeId,
EmployeeName,
ProjectName
FROM Employee
JOIN ProjEmp
ON Employee.EmployeeId=ProjEmp.EmployeeId
JOIN Project
ON Project.ProjectId=ProjEmp.ProjectId)
SELECT EmployeeId,EmployeeName,
ProjectName = STUFF((
SELECT ',' + convert(varchar(10),T2.ProjectName)
FROM CTE T2
WHERE T1.EmployeeName = T2.EmployeeName
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM CTE T1
GROUP BY EmployeeId,EmployeeName
ORDER BY EmployeeId
Result:
EMPLOYEEID EMPLOYEENAME PROJECTNAME
1 Emp1 ProjA,ProjB
3 Emp3 ProjC
4 Emp4 ProjC,ProjD
5 Emp5 ProjE
7 Emp7 ProjE
8 Emp8 ProjE
See result in SQL Fiddle.
|
unknown
| |
d845
|
train
|
Your filename should be a string.
Filename e, m, g should be "e", "m", "g", result should be "result".
Refer to code below:
#!/usr/bin/python
# -*- coding: utf-8 -*-
filenames= ["e","g","m"]
with open("results", "w") as outfile:
for file in filenames:
with open(file) as infile:
for line in infile:
outfile.write(line)
|
unknown
| |
d853
|
train
|
Logic:
*
*Read the file
*Replace "<?xml version='1.0' encoding='UTF-8'?>" with ""
*Write the data to a temp file. If you are ok with replacing the original file then you can do that as well. Amend the code accordingly.
*Open the text file in Excel
Is this what you are trying? (UNTESTED)
Code:
Option Explicit
Sub Sample()
Dim MyData As String
Dim FlName As String, tmpFlName As String
'~~> I am hardcoding the paths. Please change accordingly
FlName = "C:\Sample.xml"
tmpFlName = "C:\Sample.txt"
'~~> Kill tempfile name if it exists
On Error Resume Next
Kill tmpFlName
On Error GoTo 0
'~~> Open the xml file and read the data
Open FlName For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
'~~> Replace the relevant tag
MyData = Replace(MyData, "<?xml version='1.0' encoding='UTF-8'?>", "")
Close #1
'~~> Write to a temp text file
Open tmpFlName For Output As #1
Print #1, MyData
Close #1
Workbooks.OpenText Filename:=tmpFlName, _
StartRow:=1, _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
Other:=True, _
OtherChar:="|"
End Sub
Alternative Way:
After
'~~> Open the xml file and read the data
Open FlName For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
'~~> Replace the relevant tag
MyData = Replace(MyData, "<?xml version='1.0' encoding='UTF-8'?>", "")
Close #1
use
strData() = Split(MyData, vbCrLf)
and then write this array to Excel and use .TextToColumns
|
unknown
| |
d855
|
train
|
This is gotten from the manual, and is for windows (Since you didn't specify the OS.) using the COM class.
Note : This has nothing to do with the client side.
<?php
$fso = new COM('Scripting.FileSystemObject');
$D = $fso->Drives;
$type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk");
foreach($D as $d ){
$dO = $fso->GetDrive($d);
$s = "";
if($dO->DriveType == 3){
$n = $dO->Sharename;
}else if($dO->IsReady){
$n = $dO->VolumeName;
$s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize);
}else{
$n = "[Drive not ready]";
}
echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>";
}
function file_size($size)
{
$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
}
?>
Would output something similar to
Drive C: - Fixed - Bla - 88.38 GB free of: 444.14 GB
Drive D: - Fixed - Blas - 3.11 GB free of: 21.33 GB
Drive E: - Fixed - HP_TOOLS - 90.1 MB free of: 99.02 MB
Drive F: - CD-ROM - [Drive not ready] -
Drive G: - CD-ROM - Usb - 0 Bytes free of: 24.75 MB
Drive H: - Removable - [Drive not ready] -
|
unknown
| |
d861
|
train
|
Sadly you didn't follow the tutorial, otherwise you'd have noticed that inside the tutorial they define a function getObjectManager() inside the Controller. You don't define this function and therefore the Controller assumes this to be a ControllerPlugin and therefore asks the ControllerPluginManager to create an instance for this plugin. But no such Plugin was ever registered and that's why you see this error.
TL/DR -> do the tutorial step by step. Understand what you're doing, don't blindly copy paste the lines you think are important.
A: You forgot to implement the getObjectManager for your controller :
protected function getObjectManager()
{
if (!$this->_objectManager) {
$this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->_objectManager;
}
this method is included at the end of the IndexController in the tutorial you mentionned.
|
unknown
| |
d863
|
train
|
I found the answer to your question. After updating yajra/laravel-datatables-orakle package to version 7.* - All columns escaped by default to protect from XSS attack. To allow columns to have an html content, use rawColumns api. doc
|
unknown
| |
d869
|
train
|
From the storage side, maybe this is safe, but your single replica is only able to be read / sent from a single broker.
If that machine goes down, the data will still be available on your backend, sure, but you cannot serve requests for it without knowing there is another replica for that topic (replication factor < 2).
|
unknown
| |
d871
|
train
|
Just use a backslash, as it will revert to the default grep command and not your alias:
\grep -I --color
A: You could use command to remove all arguments.
command grep -I --color
A: I realize this is an older question, but I've been running up against the same problem. This solution works, but isn't the most elegant:
# Not part of your original question, but I learned that if an alias
# contains a trailing space, it will use alias expansion. For the case
# of 'xargs', it allows you to use the below grep aliases, such as the
# 'chgrep' alias defined below:
# grep -l 'something' file1 file2 ... | xargs chgrep 'something else'
alias xargs='xargs '
export GREP_OPT='-n'
# Note the $(...) INSIDE the 'single quotes'
alias grep_='\grep --color=auto -I $(echo "$GREP_OPT")'
# Due to alias expansion, the below aliases benefit from the 'GREP_OPT' value:
alias cgrep='grep_ -r --include=\*.{c,cc,cpp}'
alias hgrep='grep_ -r --include=\*.{h,hh,hpp}'
alias chgrep=cgrep_ --include=\*.{h,hh,hpp}' # Not sure if there's a way to combine cgrep+hgrep
...
alias pygrep='grep_ -r --include=\*.py'
In the situations where you want a non-numbered output, unset GREP_OPT (or remove -n from it, like if you're using it to include other flags).
I've used grep_ instead of grep in the above example just to show that aliases will happily chain/use alias expansion as needed all the way back to the original command. Feel free to name them grep instead. You'll note that the original grep_ uses the command \grep so the alias expansion stops at that point.
I'm totally open to suggestions if there is a better way of doing this (since setting/unsetting the GREP_OPT isn't always the most elegant).
|
unknown
| |
d875
|
train
|
It depends exactly on the OS, but in general, another desktop program can register a specific protocol, or URI scheme, to open up a program. Then, when Chrome doesn't know how to deal with a protocol, it'll just hand it over to the OS to deal with.
In Windows for example, they're configured by putting something into the system registry under a specific key (https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx).
Most applications will setup themselves as a default for the particular protocol when installed.
A: Chrome is a "desktop" program. It can open any program exposed from the operating system.
A link can contain a specific protocol instead of http://, the OS can have a map that ties protocols directly to installed programs. Chrome is not communicating with the app at any point. It only tells the os to open a resource at a given url with a given program.
|
unknown
| |
d877
|
train
|
Both jqt and jconsole read the command line arguments and box them:
jqt script.ijs arg1 arg2
ARGV
┌───┬──────────┬────┬────┐
│jqt│script.ijs│arg1│arg2│
└───┴──────────┴────┴────┘
2}. ARGV
┌────┬────┐
│arg1│arg2│
└────┴────┘
] x =: > 3 { ARGV
arg2
example script:
$ cat script.ijs
x =: ". every 2 }. ARGV
echo +/ x
$ jqt script.ijs 1 2 3
6
|
unknown
| |
d879
|
train
|
A compiler that warned about all constructs that violate the constraints in N1570 6.5p7 as written would generate a lot of warnings about constructs which all quality implementations would support without difficulty. The only way those parts of the Standard would make any sense would be if the authors expected quality implementations to extend the semantics of the language to support use cases which, even if they're not mandated by the Standard, they should have no reason not to support. The use case illustrated in the presented code is an example of this.
Although the Standard would not forbid implementations from using N1570 6.5p7 as an excuse to behave nonsensically even in situations where an object is only ever used as a single type of storage, the stated purpose of the rules is to describe situations where implementations would or would not be required to allow for the possibility of pointer aliasing. Forbidding the particular construct at issue even in cases where storage is only used as a single type would do nothing to further that aim. If code were to use the subscripting operator on buffer, in addition to accessing the storage via a struct thing*, a compiler might legitimately fail to recognize the possibility that accesses using the latter lvalue might interact with those using the former. In the presented code, however, the storage is only used as type struct thing or via memcpy, usage cases that there would have been no reason to prohibit. Writing the rules in such a way as to only forbid use of a char[] to hold data of some other type in situations where it was also subscripted would definitely add complexity, but would not have been expected to make compilers support any constructs they wouldn't have supported anyway.
If the Standard had been intended to characterize programs into those that were correct or incorrect, it would need to have been worthwhile to write more detailed rules. Since it made no attempt to distinguish constructs which are erroneous from those which are correct but "non-portable" (in the sense that there might exist some implementations which don't process them meaningfully), however, there was no need to try to explicitly identify and provide for all of the constructs which compilers would have no reason not to process meaningfully.
|
unknown
| |
d881
|
train
|
Your custom tag can grab and remove all page attributes before evaluating the body, and then clear and restore afterwards.
|
unknown
| |
d883
|
train
|
You can get the download URL like this
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
final Uri download_url = uri;
}
}):
A: You can get your download path after uploading the file as follows (you need to call a second method on your reference object (getDownloadUrl):
profilePicUploadTask = fileRef.putFile(imgUrl).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
// note: you can get the download path only after the file is uploaded successfully.
// To get the download path you have to call another method like follows:
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
@Override
public void onSuccess(Uri uri)
{
// uri is your download path
}
}
});
|
unknown
| |
d885
|
train
|
You need to import the matplotlib.dates module explicitly:
import matplotlib.dates
before it is available.
Alternatively, import the function into your local namespace:
from matplotlib.dates import date2num
dates = date2num(listOfDates)
A: this error usually comes up when the date and time of your system is not correct. just correct and restart the whole console and it should work perfect.
|
unknown
| |
d889
|
train
|
Replace:
event_router.register(r'events', views.EventViewSet, base_name='events')
with
event_router.register(r'events', views.EventViewSet, base_name='event')
|
unknown
| |
d897
|
train
|
Though the Question is super Old.
Still if anyone faces the same issue,
Also it can be used as a UILabel. Though
Below solution will do the job : [There isn't a need for any library..]
So I've used MFMailcomposer() and UITexView [ Code is in Swift 3.0 - Xcode 8.3.2 ]
A 100% Crash Proof and Working Code Handles all the corner cases. =D
Step 1.
import MessageUI
Step 2. Add the delegate
class ViewController: UITextViewDelegate, MFMailComposeViewControllerDelegate{
Step 3. Add the textView IBOutlet From StoryBoard
@IBOutlet weak var infoTextView: UITextView!
Step 4. Call the below method in your viewDidload()
func addInfoToTextView() {
let attributedString = NSMutableAttributedString(string: "For further info call us on : \(phoneNumber)\nor mail us at : \(email)")
attributedString.addAttribute(NSLinkAttributeName, value: "tel://", range: NSRange(location: 30, length: 10))
attributedString.addAttribute(NSLinkAttributeName, value: "mailto:", range: NSRange(location: 57, length: 18))
self.infoTextView.attributedText = attributedString
self.infoTextView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blue, NSUnderlineStyleAttributeName:NSNumber(value: 0)]
self.infoTextView.textColor = .white
self.infoTextView.textAlignment = .center
self.infoTextView.isEditable = false
self.infoTextView.dataDetectorTypes = UIDataDetectorTypes.all
self.infoTextView.delegate = self
}
Step 5. Implement delegate methods for TextView
@available(iOS, deprecated: 10.0)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -> Bool {
if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
openMFMail()
}
if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
callNumber()
}
return false
}
//For iOS 10
@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
openMFMail()
}
if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
callNumber()
}
return false
}
Step 6. Write the helper Methods to open MailComposer and Call App
func callNumber() {
if let phoneCallURL = URL(string: "tel://\(phoneNumber)")
{
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL))
{
let alert = UIAlertController(title: "Call", message: "\(phoneNumber)", preferredStyle: UIAlertControllerStyle.alert)
if #available(iOS 10.0, *)
{
alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
application.open(phoneCallURL, options: [:], completionHandler: nil)
}))
}
else
{
alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
application.openURL(phoneCallURL)
}))
}
alert.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
else
{
self.showAlert("Couldn't", message: "Call, cannot open Phone Screen")
}
}
func openMFMail(){
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
mailComposer.setToRecipients(["\(email)"])
mailComposer.setSubject("Subject..")
mailComposer.setMessageBody("Please share your problem.", isHTML: false)
present(mailComposer, animated: true, completion: nil)
}
Step 7. Write MFMailComposer's Delegate Method
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .cancelled:
print("Mail cancelled")
case .saved:
print("Mail saved")
case .sent:
print("Mail sent")
case .failed:
print("Mail sent failure: \(String(describing: error?.localizedDescription))")
default:
break
}
controller.dismiss(animated: true, completion: nil)
}
That's it you're Done... =D
Here is the swift file for the above code :
textViewWithEmailAndPhone.swift
Set the below properties to Use it as a UILabel
A: A note on detecting email addresses: The Mail app must be installed (it's not on the iOS Simulator) for email links to open a message compose screen.
A: Swift 3.0 +
As of swift 3.0, use the following code if you want to do it programmatically.
textview.isEditable = false
textview.dataDetectorTypes = .all
Or if you have a storyboard
A: If you are using OS3.0
you can do it like the following
textview.editable = NO;
textview.dataDetectorTypes = UIDataDetectorTypeAll;
A: Step 1. Create a subclass of UITextview and override the canBecomeFirstResponder function
KDTextView.h Code:
@interface KDTextView : UITextView
@end
KDTextView.m Code:
#import "KDTextView.h"
// Textview to disable the selection options
@implementation KDTextView
- (BOOL)canBecomeFirstResponder {
return NO;
}
@end
Step 2. Create the Textview using subclass KDTextView
KDTextView*_textView = [[KDTextView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[_textView setScrollEnabled:false];
[_textView setEditable:false];
_textView.delegate = self;
[_textView setDataDetectorTypes:UIDataDetectorTypeAll];
_textView.selectable = YES;
_textView.delaysContentTouches = NO;
_textView.userInteractionEnabled = YES;
[self.view addSubview:_textView];
Step 3: Implement the delegate method
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
return true;
}
A: I'm curious, do you have control over the text shown? If so, you should probably just stick it in a UIWebView and throw some links in there to do it "the right way".
A: Swift 4.2 Xcode 10.1
func setupContactUsTextView() {
let text = NSMutableAttributedString(string: "Love your App, but need more help? Text, Call (123) 456-1234 or email ")
if let font = UIFont(name: "Calibri", size: 17) {
text.addAttribute(NSAttributedStringKey.font,
value: font,
range: NSRange(location: 0, length: text.length))
} else {
text.addAttribute(NSAttributedStringKey.font,
value: UIFont.systemFont(ofSize: 17),
range: NSRange(location: 0, length: text.length))
}
text.addAttribute(NSAttributedStringKey.foregroundColor,
value: UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0),
range: NSRange(location: 0, length: text.length))
text.addAttribute(NSAttributedStringKey.link, value: "tel://", range: NSRange(location: 49, length: 15))
let interactableText = NSMutableAttributedString(string: "[email protected]")
if let font = UIFont(name: "Calibri", size: 17) {
interactableText.addAttribute(NSAttributedStringKey.font,
value: font,
range: NSRange(location: 0, length: interactableText.length))
} else {
interactableText.addAttribute(NSAttributedStringKey.font,
value: UIFont.systemFont(ofSize: 17),
range: NSRange(location: 0, length: interactableText.length))
}
interactableText.addAttribute(NSAttributedStringKey.link,
value: "[email protected]",
range: NSRange(location: 0, length: interactableText.length))
interactableText.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: NSRange(location: 0, length: interactableText.length))
text.append(interactableText)
videoDescTextView.attributedText = text
videoDescTextView.textAlignment = .center
videoDescTextView.isEditable = false
videoDescTextView.isSelectable = true
videoDescTextView.delegate = self
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (characterRange.location > 48 && characterRange.location < 65){
print("open phone")
}else{
print("open gmail")
}
return false
}
Steps -
1. Set the delegate to your text field and don't forget to implement UITextViewDelegate
2. Take the textView outlet - @IBOutlet weak var videoDescTextView: UITextView!
3. Add these two functions given above.
This function shows how to detect phone numbers, email from textView, how to underline your email id, how to give custom color to your text, custom font, how to call a function when tapping on phone or email, etc.
Hope this will help someone to save their valuable time. Happy Coding :)
A: If you want to auto detect links, email etc Please make sure "isSelectable" is set to true.
textview.isSelectable = true
textview.editable = false
textview.dataDetectorTypes = .all
|
unknown
| |
d899
|
train
|
VB implicitly try's to cast the DBNull Value to DateTime, since the method signature of DateTime.TryParse is
Public Shared Function TryParse(s As String, ByRef result As Date) As Boolean
which fails. You can use a variable instead:
dim startDate as DateTime
If DateTime.TryParse(dr("IX_ArticleStartDate").ToString(), startDate) Then
dr("startDate") = startDate
End If
A: A DateTime is a value type and cannot have a null value. You can do something like this:
Dim result As DateTime
Dim myDate As DateTime? = If(Not dr.IsNull("IX_ArticleStartDate") AndAlso _
DateTime.TryParse(dr.IsNull("IX_ArticleStartDate").ToString(), result), _
result, New DateTime?)
In this example, the variable myDate is not actually a DateTime, it's a Nullable(Of DateTime) as indicated by the question mark ? after DateTime in the declaration (see MSDN). The TryParse method actually takes a string value as the first argument and an output parameter which is a DateTime value as the second argument. If the parse is successful, it returns True and sets the output parameter to the parsed DateTime value; on the other hand, if the parse is not successful, it returns False and sets the output parameter to DateTime.MinDate which is not very useful because it's difficult to distinguish between a valid use of DateTime.MinDate and null.
The example makes use of a ternary operator which either parses and returns the date value, if it's not null, or else returns a nullable date instead (New DateTime?).
You would then use myDate.HasValue() accordingly to determine if the value is null, and if it's not null, you can use its value: myDate.Value.
|
unknown
| |
d901
|
train
|
Just use TRY_TO_DATE, it will return NULL for values where it can't parse the input.
A: If you are certain that all of your values other than NULLs are of the string 'yyyymmdd' then the following will work in snowflake.
TO_DATE(TO_CHAR(datekey),'yyyymmdd')
A: Sounds like some of your col4 entries are NULL or empty strings. Try maybe
... FROM df_old WHERE col4 ~ '[0-9]{8}'
to select only valid inputs. To be clear, if you give the format as 'YYYYMMDD' (you should use uppercase) an entry in col4 has to look like '20190522'.
A: All dates are stored in an internal format.
You cannot influence how a date is STORED. However you have it format it the way you want when you pull the data from the database via query.
A: I was able to resolve by the following:
CREATE OR REPLACE TABLE df_new
AS SELECT
,col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN "col4" = '' then NULL ELSE TO_DATE(col4, 'YYYYMMDD') AS date
FROM df_old
A: I resolved the issue as follows:
CREATE OR REPLACE TABLE df_new
AS SELECT
col1 AS NAME
,col2 AS first_name
,col3 AS last_name
,CASE WHEN col4 = '' THEN NULL ELSE TO_DATE(col4, 'YYYY-MM-DD') END AS date
FROM df_old
|
unknown
| |
d903
|
train
|
Change normalized_term function:
def normalized_term(document):
result = []
for term in document:
if term in normalizad_word_dict:
for word in normalizad_word_dict[term].split(' '):
result.append(word)
else:
result.append(term)
return result
Or if you want to use inline loop:
import itertools
def normalized_term(document):
return list(itertools.chain(*[normalizad_word_dict[term].split() if term in normalizad_word_dict else term.split() for term in document]))
|
unknown
| |
d907
|
train
|
Use slash at the beginning like
<img src="/images/header.jpg" width="790" height="228" alt="" />
You can also use image_tag (which is better for routing)
image_tag('/images/header.jpg', array('alt' => __("My image")))
In the array with parameters you can add all HTML attributes like width, height, alt etc.
P.S. IT's not easy to learn Symfony. You need much more time
A: If you don't want a fully PHP generated image tag but just want the correct path to your image, you can do :
<img src="<?php echo image_path('header.jpg'); ?>"> width="700" height="228" alt="" />
Notice that the path passed to image_path excludes the /images part as this is automatically determined and created for you by Symfony, all you need to supply is the path to the file relative to the image directory.
You can also get to your image directory a little more crudely using
sfConfig::get('sf_web_dir')."/images/path/to/your/image.jpg"
It should be noted that using image_tag has a much larger performance cost attached to it than using image_path as noted on thirtyseven's blog
Hope that helps :)
|
unknown
| |
d909
|
train
|
Git has self-detected an internal error. Report this to the Git mailing list ([email protected]). The output from git config --list --show-origin may also be useful to the Git maintainers, along with the output of git ls-remote on the remote in question (origin, probably). (The bug itself is in your Windows Git; the server version of Git should be irrelevant, but it won't hurt to mention that too.)
A: Based on reporting problem to git team, the problem was caused by branch with an empty name "". After removing this form .git/config, pushing works again.
However, the problem is passed to git team and will probably be solved in future version.
|
unknown
| |
d911
|
train
|
Install the btree_gist contrib module.
Then you have a gist_int8_ops operator class that you can use to create a GiST index on a bigint column.
|
unknown
| |
d913
|
train
|
You really shouldn't rely on the output of ls in this way, since you can have filenames with embedded spaces, newlines and so on.
Thankfully there's a way to do this in a more reliable manner:
((i == 0))
for fspec in *pattern_* ; do
((i = i + 1))
doSomethingWith "$(printf "%03d" $i)"
done
This loop will run the exact number of times related to the file count regardless of the weirdness of said files. It will also use the correctly formatted (three-digit) argument as requested.
|
unknown
| |
d915
|
train
|
Depending on the testing framework you are using junit or testng you can use the concept of soft assertion. Basically it will collect all the errors and throw an assertion error if something is amiss.
To fail a scenario you just need an assertion to fail, no need to set the status of the scenario. Cucumber will take care of that if an assertion fails.
For testng you can use the SoftAssert class - http://testng.org/javadocs/org/testng/asserts/SoftAssert.html You will get plenty tutorials for this. Call to doAssert will trigger of the verification of all stored assertions.
For junit you can use the ErrorCollector Rule class -
http://junit.org/junit4/javadoc/4.12/org/junit/rules/ErrorCollector.htmlenter link description here As cucumber does not support @Rule annotation, you need to inherit from this class and override the verify property to change its modifier to public in place of protected. Create an instance of the new class and add the assertions. Call to verify method will start the verification.
A: QAF provides assertion and verification concepts, where on assertion failure scenario exited with failed status and in case of verification scenario continue for next step and final status of step/scenario is failed if one or more verification failure.
You also can set step status failure using step listener which result in test failure. With use of step listener, you also can continue even step failure by converting exception to verification failure.
A: It is not a good idea to continue executing steps after a step failure because a step failure can leave the World with an invariant violation. A better strategy is to increase the granularity of your scenarios. Instead of writing a single scenario with several "Then" statements, use a list of examples to separately test each postconditions. Sometimes a scenario outline and list of examples can consolidate similar stories. https://cucumber.io/docs/reference#scenario-outline
There is some discussion about adding a feature to tag certain steps to continue after failure. https://github.com/cucumber/cucumber/issues/79
There are some other approaches to continuing through scenario steps after a failure here: continue running cucumber steps after a failure
|
unknown
| |
d917
|
train
|
java.lang.Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler)
Is this what you want?
A: Extend Application class
import android.app.Application;
import android.util.Log;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("MyApplication", ex.getMessage());
}
});
}
}
Add the following line in AndroidManifest.xml file as Application attribute
android:name=".MyApplication"
|
unknown
| |
d923
|
train
|
You'll want to read-up about the offline_access permission.
https://developers.facebook.com/docs/reference/api/permissions/
With this permission, you'll be able to query facebook for information about one of your users even when that user is offline. It gives you a "long living" access token. This token does expire after a while or if the user changes his/her facebook password.
A: I would suggest looking into the Facbook Realtime API https://developers.facebook.com/docs/reference/api/realtime/
You can subscribe to different user fields (e.g. user.friends), and whenever these fields update, FB hit your server. It doesn't say whether you can subscribe to user.friendlists or not, but it would be worth a try.
With regards to the answer from Lix; the offline_access permission is being deprecated. See here: https://developers.facebook.com/docs/offline-access-deprecation/
|
unknown
| |
d925
|
train
|
Maybe something like:
Espresso.onView(withId(R.id.tv))
.perform(object :ViewAction{
override fun getDescription(): String {
return "Normalizing the string"
}
override fun getConstraints(): Matcher<View> {
return isAssignableFrom(TextView::class.java)
}
override fun perform(uiController: UiController?, view: View?) {
val tv = view as TextView
if (tv.text.matches(Regex("You saved (.)*? with (.)*"))) {
tv.text = "You saved %1\$s with %2\$s"
}
}
}).check(matches(withText(R.string.saving)))
|
unknown
| |
d927
|
train
|
Demo Fiddle
You were very close:
body {
counter-reset: listCounter;
}
ol {
counter-increment: listCounter;
counter-reset: itemCounter;
list-style:none;
}
li{
counter-increment: itemCounter;
}
li:before {
content: counter(listCounter) "." counter(itemCounter);
left:10px;
position:absolute;
}
|
unknown
| |
d929
|
train
|
Use nginx reverse proxy to redirect based on url which will point to your different applications.
You can maintain the same IP for all of them.
|
unknown
| |
d931
|
train
|
One of the simplest ways to backup a mysql database is by creating a dump file. And that is what mysqldump is for. Please read the documentation for mysqldump.
In its simplest syntax, you can create a dump with the following command:
mysqldump [connection parameters] database_name > dump_file.sql
where the [connection parameters] are those you need to connect your local client to the MySQL server where the database resides.
mysqldump will create a dump file: a plain text file which contains the SQL instructions needed to create and populate the tables of a database. The > character will redirect the output of mysqldump to a file (in this example, dump_file.sql). You can, of course, compress this file to make it more easy to handle.
You can move that file wherever you want.
To restore a dump file:
*
*Create an empty database (let's say restore) in the destination server
*Load the dump:
mysql [connection parameters] restore < dump_file.sql
There are, of course, some other "switches" you can use with mysqldump. I frequently use these:
*
*-d: this wil tell mysqldump to create an "empty" backup: the tables and views will be exported, but without data (useful if all you want is a database "template")
*-R: include the stored routines (procedures and functions) in the dump file
*--delayed-insert: uses insert delayed instead of insert for populating tables
*--disable-keys: Encloses the insert statements for each table between alter table ... disable keys and alter table ... enable keys; this can make inserts faster
You can include the mysqldump command and any other compression and copy / move command in a batch file.
A: My solution to extract a backup and push it onto Dropbox is as below.
A sample of Ubuntu batch file can be downloaded here.
In brief
*
*Prepare a batch script backup.sh
*Run backup.sh to create a backup version e.g. backup.sql
*Copy backup.sql to Dropbox folder
*Schedule Ubuntu/Windows task to run backup.sh task e.g. every day at night
Detail steps
*
*All about backing up and restoring an MySQL database can be found here.
Back up to compressed file
mysqldump -u [uname] -p [dbname] | gzip -9 > [backupfile.sql.gz]
*How to remote from Windows to execute the 'backup' command can be found here.
plink.exe -ssh -pw -i "Path\to\private-key\key.ppk" -noagent username@server-ip
*How to bring the file to Dropbox can be found here
Create a app
https://www2.dropbox.com/developers/apps
Add an app and choose Dropbox API App. Note the created app key and app secret
Install Dropbox API in Ubuntu; use app key and app secret above
$ wget https://raw.github.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh
$ chmod +x dropbox_uploader.sh
Follow the instruction to authorize access for the app e.g.
http://www2.dropbox.com/1/oauth/authorize?oauth_token=XXXXXXX
Test the app if it is working right - should be ok
$ ./dropbox_uploader.sh info
The app is created and a folder associating with it is YourDropbox\Apps\<app name>
Commands to use
List files
$ ./dropbox_uploader.sh list
Upload file
$ ./dropbox_uploader.sh upload <filename> <dropbox location>
e.g.
$ ./dropbox_uploader.sh upload backup.sql .
This will store file backup.sql to YourDropbox\Apps\<app name>\backup.sql
Done
*How to schedule a Ubuntu can be view here using crontab
Call command
sudo crontab -e
Insert a line to run backup.sh script everyday as below
0 0 * * * /home/userName/pathTo/backup.sh
Explaination:
minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
Or simply we can use
@daily /home/userName/pathTo/backup.sh
Note:
*
*To mornitor crontab tasks, here is a very good guide.
|
unknown
| |
d935
|
train
|
You don't actually have to specify any fields for the get_stats method, but the reason you're not seeing any actions is probably because you don't have any. Try it against a campaign that you know people have taken action on. :)
Evan
|
unknown
| |
d941
|
train
|
Your best bet is to have that attribute's value in a hidden input field somewhere on the page, so you can then read it in with jQuery.
Unforunately, to the best of my knowledge jQuery or javascript does not have access to request, session or application scope variables.
So, if you do something like this:
<input type='hidden' name='${sessionVarName}' value='${sessionVarValue}' id='sessionVar'/>
You can access it after the page loads like this:
$(function(){
var sessionVar = $('#sessionVar').val();
alert(sessionVar);
});
This is the solution I've used when needing to get tomcat session vars into javascript, the method should work for you too.
Hope this helps
A: I suggest u to send a AttributeName which will successfully make u to get the sessionScope Attribute,that will be simple.
|
unknown
| |
d945
|
train
|
You don't need combinations at all. What you want looks more like a sliding window.
for i in range(2, 6):
for j in range(len(lst) - i + 1):
print(lst[j:j + i])
A: You can loop over the list as following:
a = [1,2,3,4,5,6]
for i in range(2, len(a)):
for j in range(len(a)-i + 1):
print(a[j:j+i])
print()
The trick here is that a[j:j+i] returns the list from j, up until j+i.
Putting this into a function form:
def continuous(lst, length):
slices = []
for j in range(len(lst)-length + 1):
slices.append(a[j:j+length])
return slices
A: You can loop through the list in the following method
lst = [1, 2, 3, 4, 5 ,6]
def continuous(lst, length):
result = []
for i in range (0, len(lst)-length):
entry = []
for j in range (0, length):
entry.append(lst[i+j])
result.append(entry)
return result
print(continuous(lst, 2))
or if you are just looking to print it line by line
def continuous(lst, length):
for i in range (0, len(lst)-length):
entry = []
for j in range (0, length):
entry.append(lst[i+j])
print(entry)
|
unknown
| |
d949
|
train
|
To get a distance from a Google Maps you can use Google Directions API and JSON parser to retrieve the distance value.
Sample Method
private double getDistanceInfo(double lat1, double lng1, String destinationAddress) {
StringBuilder stringBuilder = new StringBuilder();
Double dist = 0.0;
try {
destinationAddress = destinationAddress.replaceAll(" ","%20");
String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false";
HttpPost httppost = new HttpPost(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
Log.i("Distance", distance.toString());
dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dist;
}
For details on parameters and more details on what are the different options available, please refer this.
https://developers.google.com/maps/documentation/directions/
A: public class ApiDirectionsAsyncTask extends AsyncTask<URL, Integer, StringBuilder> {
private static final String TAG = makeLogTag(ApiDirectionsAsyncTask.class);
private static final String DIRECTIONS_API_BASE = "https://maps.googleapis.com/maps/api/directions";
private static final String OUT_JSON = "/json";
// API KEY of the project Google Map Api For work
private static final String API_KEY = "YOUR_API_KEY";
@Override
protected StringBuilder doInBackground(URL... params) {
Log.i(TAG, "doInBackground of ApiDirectionsAsyncTask");
HttpURLConnection mUrlConnection = null;
StringBuilder mJsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(DIRECTIONS_API_BASE + OUT_JSON);
sb.append("?origin=" + URLEncoder.encode("Your origin address", "utf8"));
sb.append("&destination=" + URLEncoder.encode("Your destination address", "utf8"));
sb.append("&key=" + API_KEY);
URL url = new URL(sb.toString());
mUrlConnection = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(mUrlConnection.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1){
mJsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(TAG, "Error processing Distance Matrix API URL");
return null;
} catch (IOException e) {
System.out.println("Error connecting to Distance Matrix");
return null;
} finally {
if (mUrlConnection != null) {
mUrlConnection.disconnect();
}
}
return mJsonResults;
}
}
I hope that help you!
A: Just check below link. You will probably get idea of it and try it on your own.
http://about-android.blogspot.in/2010/03/sample-google-map-driving-direction.html
Also you can use Google Distance Matrix API
https://developers.google.com/maps/documentation/distancematrix/
A: String url = getDirectionsUrl(pickupLatLng, dropLatLng);
new GetDisDur().execute(url);
Create URL using latlng
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String mode = "mode=driving";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
String output = "json";
return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
}
Class GetDisDur
private class GetDisDur extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject routes1 = routes.getJSONObject(0);
JSONArray legs = routes1.getJSONArray("legs");
JSONObject legs1 = legs.getJSONObject(0);
JSONObject distance = legs1.getJSONObject("distance");
JSONObject duration = legs1.getJSONObject("duration");
distanceText = distance.getString("text");
durationText = duration.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
unknown
| |
d951
|
train
|
First you have to add display: flex; to #Container
#Container{
display: flex;
}
If you want to equally distribute the space between children then you can use flex property as
.item{
flex: 1;
}
Above CSS is minimum required styles, rest is for demo
#Container {
display: flex;
margin-top: 1rem;
}
.item {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
}
.item:nth-child(1) {
background-color: red;
}
.item:nth-child(2) {
background-color: blueviolet;
}
.item:nth-child(3) {
background-color: aquamarine;
}
<div id="Container">
<div class="item">33 %</div>
<div class="item">33 %</div>
<div class="item">33 %</div>
</div>
<div id=Container>
<div class="item"> 50 % </div>
<div class="item"> 50 % </div>
</div>
<div id=Container>
<div class="item">100 %</div>
</div>
A: I think that this example could give you an idea of how to achieve what you want:
https://codepen.io/Eylen/pen/vYJBpMQ
.Container {
display: flex;
flex-wrap: wrap;
margin-bottom: 8px;
}
.item {
flex-grow: 1;
margin: 0 12px;
background: #f1f1f1;
}
Your main issue in the code that you gave, is that you're missing the flex item behaviour. I have just set that the item can grow to fill the space with the flex-grow:1.
A: You can make sure a flex child covers up the space if it can, you can provide flex-grow: 1
#Container {
display:flex;
}
.item {
width: 100%;
flex-grow: 1;
border: 1px solid;
text-align: center;
}
<h1> Scenario 1 </h1>
<div id=Container>
<div class="item">33 %</div>
<div class="item">33 %</div>
<div class="item">33%</div>
</div>
<h1> Scenario 2 </h1>
<div id=Container>
<div class="item">50 %</div>
<div class="item">50 %</div>
</div>
<h1> Scenario 3 </h1>
<div id=Container>
<div class="item">100 %</div>
</div>
A: Added a demo below.
$( document ).ready(function() {
$( "#add" ).click(function() {
$('#container').append('<div class="item"></div>');
});
$( "#remove" ).click(function() {
$('#container').children().last().remove();
});
});
#container {
width:100%;
height:500px;
background-color:#ebebeb;
display:flex;
flex-direction: column;
}
.item {
width:100%;
display: flex;
flex: 1;
border-bottom:1px solid #007cbe;
}
.item1 {
background:#007cbe;
}
.item2 {
background: #d60000;
}
.item3 {
background: #938412
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div class="item item1">1</div>
<div class="item item2">2</div>
<div class="item item3">3</div>
</div>
<button id="add"> Add </div>
<button id="remove"> Remove </div>
A: Apply to the below CSS to fulfill your requirement.
#Container {
display: flex;
}
.item {
width: 100%;
min-height: 100px;
border: 1px solid;
}
|
unknown
| |
d953
|
train
|
If this is a long-running process I doubt that using blob storage would add that much overhead, although you don't specify what the tasks are.
On Zudio long-running tasks update Table Storage tables with progress and completion status, and we use polling from the browser to check when a task has finished. In the case of a large result returning to the user, we provide a direct link with a shared access signature to the blob with the completion message, so they can download it directly from storage. We're looking at replacing the polling with SignalR running over Service Bus, and having the worker roles send updates directly to the client, but we haven't started that development work yet so I can't tell you how that will actually work.
|
unknown
| |
d957
|
train
|
You are passing a string....cast it to number
$scope.range = function(n) {
return new Array(+n||0);
};
DEMO
|
unknown
| |
d959
|
train
|
You need to use expression, here an example:
tibble(x = 1,y = 1) %>%
ggplot(aes(x = 1,y = 1))+
geom_point()+
scale_x_continuous(
breaks = 1,
labels = expression(paste("Ambient ",CO[2]))
)
|
unknown
| |
d961
|
train
|
Assuming you're using jQuery validate, you can use the submitHandler property to run code when the validation passes, for example:
$("#myForm").validate({
submitHandler: function(form) {
// display overlay
form.submit();
}
});
Further reading
A: Try to return false; on validation errors while submiting.
|
unknown
| |
d963
|
train
|
127.0.0.1 as an IP address means "this machine". More formally, it's the loopback interface. On your laptop you have a MySQL server running. Your heroku dyno does not, so your connection attempt fails.
You won't be able to connect from your program running on your heroku dyno to your laptop's MySQL server without some network configuration work on your office or home router / firewall. But to begin doing that work you'll need to come up to speed on networking. (Teaching you how is beyond the scope of a Stack Overflow answer.)
You can add a MySQL add-on to your Heroku app from a third party. Heroku themselves offer a postgreSQL add-on with a free tier, but not MySql. For US$10 per month you can subscribe to one of these MySQL add-ons and you'll be up and running.
|
unknown
| |
d971
|
train
|
It would not be recommended to start all of your custom properties with the same dollar convention. The dollar sign convention is meant to denote properties that the Mixpanel SDKs track automatically or properties that have some special meaning within Mixpanel itself. That link you shared is great for the default properties and there is also documentation for the reserved user profile properties and reserved event properties if you were curious about those.
|
unknown
| |
d975
|
train
|
The SIGSTOP signal does this. With a negative PID, the kill command will send it to the entire process group.
kill -s SIGSTOP -$pid
Send a SIGCONT to resume.
|
unknown
| |
d977
|
train
|
Try this:
from tkinter import *
def entry():
ent[i].configure(state = NORMAL)
window=Tk()
nac = {}
ent = {}
for i in range(10):
de = IntVar()
nac[i]=IntVar()
na=Checkbutton(window, text='%s' % (i), borderwidth=1,variable = nac[i],
onvalue = 1, offvalue = 0,command=entry)
na.grid(row=i, column=0)
ent[i]=Entry(window,textvariable=de, state = DISABLED)
ent[i].grid(column=1,row=i,padx=20)
window.mainloop()
|
unknown
| |
d979
|
train
|
WebChimera.js could not be used with regular browser. It could be used only with NW.js or Electron or any other Node.js based frameworks.
|
unknown
| |
d981
|
train
|
From CSV Examples:
Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.
|
unknown
| |
d983
|
train
|
I'll hazard a guess that you're working in a form, so add type="button" to the button <button class="btn btn-success" (click)="addData(newData.value)">ADD</button>. That should prevent it from thinking the form is submitting and clearing the data.
|
unknown
| |
d995
|
train
|
System Events doesn't have a "copy" command. Where did you get that? You might try "move" instead. Plus "aVolume" is not a folder, it's a disk. You probably want to change "folder aVolume" to "disk aVolume". And you might even need to use "disk (contents of aVolume)"
EDIT: Try the following script. I didn't test it but it should work. Good luck.
property ignoredVolumes : {"DD APPLE", "MobileBackups", "home", "net"} -- leave home and net in this list
set Destination_Folder to ((path to downloads folder as text) & "Test:") as alias
set mountedVolumes to list disks
repeat with i from 1 to count of mountedVolumes
set thisVolume to item i of mountedVolumes
if thisVolume is not in ignoredVolumes then
tell application "Finder"
set theItems to items of disk thisVolume
move theItems to Destination_Folder
end tell
end if
end repeat
|
unknown
| |
d1001
|
train
|
You have missed one of the conditions. You also want whenever PARENT is NULL the Value of PRIMARY_PARENT be equal to the value of PARENT in the next row. You can take care of it this way:
SELECT * FROM
(SELECT *, LEAD(PARENT) OVER(Order BY (SELECT NULL)) as LeadParent FROM COMPANY_TABLE) T
WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL
OR ((PARENT IS NULL) AND LeadParent != PRIMARY_PARENT);
A: As Kumar stated, you could try and test to see if the values Parent and Primary_Parent by default are NULL's or blanks.
Did you try:
SELECT * FROM COMPANY_TABLE WHERE PARENT <> '' AND PRIMARY_PARENT <> ''
|
unknown
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.