To use foreach
would require you have an array that contains every row from the query result. Some DB libraries for PHP provide a fetch_all
function that provides an appropriate array but I could not find one for mysql
(however the mysqli extension does) . You could of course write your own, like so
function mysql_fetch_all($result) {
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
return $rows;
}
However I must echo the "why?" Using this function you are creating two loops instead of one, and requring the entire result set be loaded in to memory. For sufficiently large result sets, this could become a serious performance drag. And for what?
foreach (mysql_fetch_all($result) as $row)
vs
while ($row = mysql_fetch_array($result))
while
is just as concise and IMO more readable.
EDIT There is another option, but it is pretty absurd. You could use the Iterator Interface
class MysqlResult implements Iterator {
private $rownum = 0;
private $numrows = 0;
private $result;
public function __construct($result) {
$this->result = $result;
$this->numrows = mysql_num_rows($result);
}
public function rewind() {
$this->rownum = 0;
}
public function current() {
mysql_data_seek($this->result, $this->rownum);
return mysql_fetch_array($this->result);
}
public function key() {
return $this->rownum;
}
public function next() {
$this->rownum++;
}
public function valid() {
return $this->rownum < $this->numrows ? true : false;
}
}
$rows = new MysqlResult(mysql_query($query_select));
foreach ($rows as $row) {
//code...
}
In this case, the MysqlResult
instance fetches rows only on request just like with while
, but wraps it in a nice foreach-able package. While you've saved yourself a loop, you've added the overhead of class instantiation and a boat load of function calls, not to mention a good deal of added code complexity.
But you asked if it could be done without using while
(or for
I imagine). Well it can be done, just like that. Whether it should be done is up to you.
If you want to use baseAddressPrefixFilters in web.config, you must setup IIS (6) too. This helped me:
1/ In IIS find your site. 2/ Properties / Web site (tab) / IP address -> Advanced button 3/ Add new host header on the same port which you will use in web.config.
You can also try this for the double quotes:
JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);
You can do printing of reverse numbers with range() BIF Like ,
for number in range ( 10 , 0 , -1 ) :
print ( number )
Output will be [10,9,8,7,6,5,4,3,2,1]
range() - range ( start , end , increment/decrement ) where start is inclusive , end is exclusive and increment can be any numbers and behaves like step
This is old, just update new tidyverse workflow not mentioned above.
library(tidyverse)
jobsAFAM1 <- tibble(
date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
Percent.Change = runif(5, 0,1)
) %>%
mutate(serial='jobsAFAM1')
jobsAFAM2 <- tibble(
date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
Percent.Change = runif(5, 0,1)
) %>%
mutate(serial='jobsAFAM2')
jobsAFAM <- bind_rows(jobsAFAM1, jobsAFAM2)
ggplot(jobsAFAM, aes(x=date, y=Percent.Change, col=serial)) + geom_line()
@Chris Njuguna
tidyr::gather() is the one in tidyverse workflow to turn wide dataframe to long tidy layout, then ggplot could plot multiple serials.
Tony is a pure genius. However to achieve even better auto-completion try setting the triggers to this:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz =.(!+-*/~,[{@#$%^&
(specifically aranged in order of usage for faster performance :)
Try this code.
For showing Softkeyboard:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
For Hiding SoftKeyboard -
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
ReSharper - Ctrl + Alt + F
Visual Studio 2010 - Ctrl + K, Ctrl + D
This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Task
s instead of raw threads and then use Task.WaitAll()
to wait for them to complete.
The other option is to tell EF to allow the column to be null:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();
base.OnModelCreating(modelBuilder);
}
This code should be in the object that inherits from DbContext
.
Another way of doing this is to use ravel
model = forest.fit(train_fold, train_y.values.reshape(-1,))
In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".
Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.
The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)
License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.
That method will not work. The <title>
only supports plain text. You will need to create an .ico
image with the filename of favicon.ico
and save it into the root folder of your site (where your default page is).
Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head>
section of your HTML and reference your icon:
<link rel="shortcut icon" href="your_image_path_and_name.ico" />
You can use Photoshop (with a plug in) or GIMP (free) to create an .ico
file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).
Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.
Update 2: You can also use .png
images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico
files.
Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.
return n
from your main entry function will terminate your process and report to the parent process (the one that executed your process) the result of your process. 0 means SUCCESS. Other codes usually indicates a failure and its meaning.
The response provided by Trevor is correct.
But here is what you can directly add in your .gitconfig
:
# Enforce SSH
[url "ssh://[email protected]/"]
insteadOf = https://github.com/
[url "ssh://[email protected]/"]
insteadOf = https://gitlab.com/
[url "ssh://[email protected]/"]
insteadOf = https://bitbucket.org/
Here's a little "coup de pouce"
Public Class DataGridViewRHEx
Inherits DataGridView
Protected Overrides Function CreateRowsInstance() As System.Windows.Forms.DataGridViewRowCollection
Dim dgvRowCollec As DataGridViewRowCollection = MyBase.CreateRowsInstance()
AddHandler dgvRowCollec.CollectionChanged, AddressOf dvgRCChanged
Return dgvRowCollec
End Function
Private Sub dvgRCChanged(sender As Object, e As System.ComponentModel.CollectionChangeEventArgs)
If e.Action = System.ComponentModel.CollectionChangeAction.Add Then
Dim dgvRow As DataGridViewRow = e.Element
dgvRow.DefaultHeaderCellType = GetType(DataGridViewRowHeaderCellEx)
End If
End Sub
End Class
Public Class DataGridViewRowHeaderCellEx
Inherits DataGridViewRowHeaderCell
Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, dataGridViewElementState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts)
If Not Me.OwningRow.DataBoundItem Is Nothing Then
If TypeOf Me.OwningRow.DataBoundItem Is DataRowView Then
End If
End If
'HERE YOU CAN USE DATAGRIDROW TAG TO PAINT STRING
formattedValue = CStr(Me.DataGridView.Rows(rowIndex).Tag)
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
End Sub
End Class
just to add another solution, particularly useful if you are using the new pandas assessors, other solutions will replace the original pandas and lose the assessors
df.drop(df.loc[df['line_race']==0].index, inplace=True)
Simple jQuery, PHP and JSONP example is below:
window.onload = function(){_x000D_
$.ajax({_x000D_
cache: false,_x000D_
url: "https://jsonplaceholder.typicode.com/users/2",_x000D_
dataType: 'jsonp',_x000D_
type: 'GET',_x000D_
success: function(data){_x000D_
console.log('data', data)_x000D_
},_x000D_
error: function(data){_x000D_
console.log(data);_x000D_
}_x000D_
});_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
I was able to get a git 1.7.1 to work after quite some time.
First, I had to do disable SSL just so I could pull:
git config --global http.sslverify false
Then I could clone
git clone https://github.com/USERNAME/PROJECTNAME.git
Then after adding and committing i was UNABLE to push back. So i did
git remote -v
origin https://github.com/USERNAME/PROJECTNAME.git (fetch)
origin https://github.com/USERNAME/PROJECTNAME.git (push)
to see the pull and push adresses:
These must be modified with USERNAME@
git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git
It will still prompt you for a password, which you could add with
USERNAME:PASSWORD@github.....
But dont do that, as you save your password in cleartext for easy theft.
I had to do this combination since I could not get SSH to work due to firewall limitations.
it should help:
android {
...
useLibrary 'org.apache.http.legacy'
...
}
To avoid missing link errors add to dependencies
dependencies {
provided 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
or
dependencies {
compileOnly 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
because
Warning: Configuration 'provided' is obsolete and has been replaced with 'compileOnly'.
Convert.ToDecimal(the double you are trying to convert);
Basically you can send complex object without doing any extra fancy thing. Or without making changes to Web-Api. I mean why would we have to make changes to Web-Api, while the fault is in our code that's calling the Web-Api.
All you have to do use NewtonSoft's Json library as following.
string jsonObjectA = JsonConvert.SerializeObject(objectA);
string jsonObjectB = JsonConvert.SerializeObject(objectB);
string jSoNToPost = string.Format("\"content\": {0},\"config\":\"{1}\"",jsonObjectA , jsonObjectB );
//wrap it around in object container notation
jSoNToPost = string.Concat("{", jSoNToPost , "}");
//convert it to JSON acceptible content
HttpContent content = new StringContent(jSoNToPost , Encoding.UTF8, "application/json");
var response = httpClient.PutAsync("api/process/StartProcessiong", content);
Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String.format
. The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.
String.format("This is an integer: %d", myInt);
String.format("This is an integer: %d and a string: %s", myInt, myString);
In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.
It's simply pointless to create variable variable names. Why?
exec
or globals()
exec/globals()
againUsing a list is much easier:
# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
print string
print string[6] # or pick any of them
In SQL Management Studio, right-click on a database and select "Properties" from the context menu. Look at the "Size" figure.
Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.
Contacts is here for example.
Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.
To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.
And others:
In the code you have posted there would be no advantages, as you are misusing the StringBuilder. You build the same String in both cases. Using StringBuilder you can avoid the +
operation on Strings using the append
method.
You should use it this way:
return new StringBuilder("select id1, ").append(" id2 ").append(" from ").append(" table").toString();
In Java, the String type is an inmutable sequence of characters, so when you add two Strings the VM creates a new String value with both operands concatenated.
StringBuilder provides a mutable sequence of characters, which you can use to concat different values or variables without creating new String objects, and so it can sometimes be more efficient than working with strings
This provides some useful features, as changing the content of a char sequence passed as parameter inside another method, which you can't do with Strings.
private void addWhereClause(StringBuilder sql, String column, String value) {
//WARNING: only as an example, never append directly a value to a SQL String, or you'll be exposed to SQL Injection
sql.append(" where ").append(column).append(" = ").append(value);
}
More info at http://docs.oracle.com/javase/tutorial/java/data/buffers.html
You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.
For a hint, you could possibly do something like:
Record record = new Record();
PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(record, value);
}
Where value
is the value you're wanting to write in (so from your resultItems
array).
Display your file first and set its value into url.
index.php
<a href="download.php?download='.$row['file'].'" title="Download File">
download.php
<?php
/*db connectors*/
include('dbconfig.php');
/*function to set your files*/
function output_file($file, $name, $mime_type='')
{
if(!is_readable($file)) die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
$known_mime_types=array(
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"jpg" => "image/jpg",
"php" => "text/plain",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"pdf" => "application/pdf",
"txt" => "text/plain",
"html"=> "text/html",
"png" => "image/png",
"jpeg"=> "image/jpg"
);
if($mime_type==''){
$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
$mime_type=$known_mime_types[$file_extension];
} else {
$mime_type="application/force-download";
};
};
@ob_end_clean();
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}
$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}
$chunksize = 1*(1024*1024);
$bytes_send = 0;
if ($file = fopen($file, 'r'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length)
)
{
$buffer = fread($file, $chunksize);
echo($buffer);
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
die('Error - can not open file.');
die();
}
set_time_limit(0);
/*set your folder*/
$file_path='uploads/'."your file";
/*output must be folder/yourfile*/
output_file($file_path, ''."your file".'', $row['type']);
/*back to index.php while downloading*/
header('Location:index.php');
?>
I have used this way and getting values "0" or if checked "1". This telling that if checkbox input name is not exist in serialized form_data
then it means it is not checked then add value as zero (form_data += '&' + name + '=0'
), but if checked serialize()
function automatically adds it.
/*get all other form inputs*/
var form_data = form.serialize();
/*get checkboxes*/
$.each($("#form_id input[type='checkbox']"), function(){
var name = $(this).attr('name');
if(form_data.indexOf(name)===-1)form_data += '&' + name + '=0';
});
AngularJS Developer Guide - CSS classes used by AngularJS
- @property {boolean} $untouched True if control has not lost focus yet.
- @property {boolean} $touched True if control has lost focus.
- @property {boolean} $pristine True if user has not interacted with the control yet.
- @property {boolean} $dirty True if user has already interacted with the control.
char *charPtr = "test string";
cout << charPtr << endl;
string str = charPtr;
cout << str << endl;
Answers here are a bit outdated. Though the code remains the same there are some changes in the behavior.
public class MyListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
TextView footerView = (TextView) ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
getListView().addFooterView(footerView);
setListAdapter(new ArrayAdapter<String>(this, getResources().getStringArray(R.array.news)));
}
}
Info about addFooterView()
method
Add a fixed view to appear at the bottom of the list. If
addFooterView()
is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.
Most of the answers above stress very important point -
addFooterView()
must be called before callingsetAdapter()
.This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.
From Kitkat this has changed.
Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.
Here is another (working) solution : just resize your images to the size you want :)
.pdflink:after {
display: block;
width: 20px;
height: 10px;
content:url('/images/pdf.png');
}
you need pdf.png to be 20px * 10px for this to work. The 20px/10px in the css are here to give the size of the block so that the elements that come after the block are not all messed up with the image
Don't forget to keep a copy of the raw image in its original size
You do it exactly as you showed with this line:
get.setHeader("Content-Type", "application/x-zip");
So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.
The ->
operator makes the code more readable than the *
operator in some situations.
Such as: (quoted from the EDK II project)
typedef
EFI_STATUS
(EFIAPI *EFI_BLOCK_READ)(
IN EFI_BLOCK_IO_PROTOCOL *This,
IN UINT32 MediaId,
IN EFI_LBA Lba,
IN UINTN BufferSize,
OUT VOID *Buffer
);
struct _EFI_BLOCK_IO_PROTOCOL {
///
/// The revision to which the block IO interface adheres. All future
/// revisions must be backwards compatible. If a future version is not
/// back wards compatible, it is not the same GUID.
///
UINT64 Revision;
///
/// Pointer to the EFI_BLOCK_IO_MEDIA data for this device.
///
EFI_BLOCK_IO_MEDIA *Media;
EFI_BLOCK_RESET Reset;
EFI_BLOCK_READ ReadBlocks;
EFI_BLOCK_WRITE WriteBlocks;
EFI_BLOCK_FLUSH FlushBlocks;
};
The _EFI_BLOCK_IO_PROTOCOL
struct contains 4 function pointer members.
Suppose you have a variable struct _EFI_BLOCK_IO_PROTOCOL * pStruct
, and you want to use the good old *
operator to call it's member function pointer. You will end up with code like this:
(*pStruct).ReadBlocks(...arguments...)
But with the ->
operator, you can write like this:
pStruct->ReadBlocks(...arguments...)
.
Which looks better?
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
I was able to fix this!
Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.
I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.
The fix. Make sure you backup your system first!
Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc
)
Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.
a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'
b. on command prompt type sc delete service
, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4
). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"
c. press enter. Now refresh or close/open your services window and you'll see it`s gone.
DO THIS for all services that XAMPP finds as running with an incorrect path.
Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts
Here is the a quick solution for multiple checkbox validation using jquery validation plugin:
jQuery.validator.addMethod('atLeastOneChecked', function(value, element) {
return ($('.cbgroup input:checked').length > 0);
});
$('#subscribeForm').validate({
rules: {
list0: { atLeastOneChecked: true }
},
messages: {
list0: { 'Please check at least one option' }
}
});
$('.cbgroup input').click(function() {
$('#list0').valid();
});
One of the most beautiful ways in my opinion (since it is now commonly available) is using behaviours.
It requires:
Microsoft.Xaml.Behaviors.Wpf
xaml code:
xmlns:Interactions="http://schemas.microsoft.com/xaml/behaviors"
AND
<Hyperlink NavigateUri="{Binding Path=Link}">
<Interactions:Interaction.Behaviors>
<behaviours:HyperlinkOpenBehaviour ConfirmNavigation="True"/>
</Interactions:Interaction.Behaviors>
<Hyperlink.Inlines>
<Run Text="{Binding Path=Link}"/>
</Hyperlink.Inlines>
</Hyperlink>
behaviour code:
using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;
namespace YourNameSpace
{
public class HyperlinkOpenBehaviour : Behavior<Hyperlink>
{
public static readonly DependencyProperty ConfirmNavigationProperty = DependencyProperty.Register(
nameof(ConfirmNavigation), typeof(bool), typeof(HyperlinkOpenBehaviour), new PropertyMetadata(default(bool)));
public bool ConfirmNavigation
{
get { return (bool) GetValue(ConfirmNavigationProperty); }
set { SetValue(ConfirmNavigationProperty, value); }
}
/// <inheritdoc />
protected override void OnAttached()
{
this.AssociatedObject.RequestNavigate += NavigationRequested;
this.AssociatedObject.Unloaded += AssociatedObjectOnUnloaded;
base.OnAttached();
}
private void AssociatedObjectOnUnloaded(object sender, RoutedEventArgs e)
{
this.AssociatedObject.Unloaded -= AssociatedObjectOnUnloaded;
this.AssociatedObject.RequestNavigate -= NavigationRequested;
}
private void NavigationRequested(object sender, RequestNavigateEventArgs e)
{
if (!ConfirmNavigation || MessageBox.Show("Are you sure?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
OpenUrl();
}
e.Handled = true;
}
private void OpenUrl()
{
// Process.Start(new ProcessStartInfo(AssociatedObject.NavigateUri.AbsoluteUri));
MessageBox.Show($"Opening {AssociatedObject.NavigateUri}");
}
/// <inheritdoc />
protected override void OnDetaching()
{
this.AssociatedObject.RequestNavigate -= NavigationRequested;
base.OnDetaching();
}
}
}
If you are hosting your Laravel app on Heroku, you can create custom_php.ini
in the root of your project and simply add max_execution_time = 60
In DOS you couldn't use environment variables on the command line, only in batch files, where they used the %
sign as a delimiter. If you wanted a literal %
sign in a batch file, e.g. in an echo
statement, you needed to double it.
This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your %
signs in a .cmd file.
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:
DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';
I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database
getcwd();
or
dirname(__FILE__);
or (PHP5)
basename(__DIR__)
http://php.net/manual/en/function.getcwd.php
http://php.net/manual/en/function.dirname.php
You can use basename()
to get the trailing part of the path :)
In your case, I'd say you are most likely looking to use getcwd()
, dirname(__FILE__)
is more useful when you have a file that needs to include another library and is included in another library.
Eg:
main.php
libs/common.php
libs/images/editor.php
In your common.php
you need to use functions in editor.php
, so you use
common.php
:
require_once dirname(__FILE__) . '/images/editor.php';
main.php
:
require_once libs/common.php
That way when common.php is require'd
in main.php
, the call of require_once
in common.php
will correctly includes editor.php
in images/editor.php
instead of trying to look in current directory where main.php
is run.
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
I'm not 100% sure if this works in all cases (needs at least Java 1.5):
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Main
{
public class A
{
}
public class B extends A
{
}
public Map<A, B> map = new HashMap<Main.A, Main.B>();
public static void main(String[] args)
{
try
{
Field field = Main.class.getField("map");
System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());
Type genericType = field.getGenericType();
if(genericType instanceof ParameterizedType)
{
ParameterizedType type = (ParameterizedType) genericType;
Type[] typeArguments = type.getActualTypeArguments();
for(Type typeArgument : typeArguments)
{
Class<?> classType = ((Class<?>)typeArgument);
System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This will output:
Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B
For all of you who are interested in this, now you can just copy and paste to get started within minutes. I took the advice in the comments as well as I could. Let me know if I'm missing something.
"COMPLEX VERSION":
events
+----------+----------------+ | ID | NAME | +----------+----------------+ | 1 | Sample event 1 | | 2 | Second event | | 3 | Third event | +----------+----------------+
events_meta
+----+----------+--------------+------------------+-------------+--------------+------------+-------------+----------------+ | ID | event_id | repeat_start | repeat_interval | repeat_year | repeat_month | repeat_day | repeat_week | repeat_weekday | +----+----------+--------------+------------------+-------------+--------------+------------+-------------+----------------+ | 1 | 1 | 2014-07-04 | 7 | NULL | NULL | NULL | NULL | NULL | | 2 | 2 | 2014-06-26 | NULL | 2014 | * | * | 2 | 5 | | 3 | 3 | 2014-07-04 | NULL | * | * | * | * | 5 | +----+----------+--------------+------------------+-------------+--------------+------------+-------------+----------------+
SQL code:
CREATE TABLE IF NOT EXISTS `events` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `events`
--
INSERT INTO `events` (`ID`, `NAME`) VALUES
(1, 'Sample event'),
(2, 'Another event'),
(3, 'Third event...');
CREATE TABLE IF NOT EXISTS `events_meta` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`event_id` int(11) NOT NULL,
`repeat_start` date NOT NULL,
`repeat_interval` varchar(255) NOT NULL,
`repeat_year` varchar(255) NOT NULL,
`repeat_month` varchar(255) NOT NULL,
`repeat_day` varchar(255) NOT NULL,
`repeat_week` varchar(255) NOT NULL,
`repeat_weekday` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `events_meta`
--
INSERT INTO `events_meta` (`ID`, `event_id`, `repeat_start`, `repeat_interval`, `repeat_year`, `repeat_month`, `repeat_day`, `repeat_week`, `repeat_weekday`) VALUES
(1, 1, '2014-07-04', '7', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL'),
(2, 2, '2014-06-26', 'NULL', '2014', '*', '*', '2', '5'),
(3, 3, '2014-07-04', 'NULL', '*', '*', '*', '*', '1');
also available as MySQL export (for easy access)
PHP example code index.php:
<?php
require 'connect.php';
$now = strtotime("yesterday");
$pushToFirst = -11;
for($i = $pushToFirst; $i < $pushToFirst+30; $i++)
{
$now = strtotime("+".$i." day");
$year = date("Y", $now);
$month = date("m", $now);
$day = date("d", $now);
$nowString = $year . "-" . $month . "-" . $day;
$week = (int) ((date('d', $now) - 1) / 7) + 1;
$weekday = date("N", $now);
echo $nowString . "<br />";
echo $week . " " . $weekday . "<br />";
$sql = "SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE ( DATEDIFF( '$nowString', repeat_start ) % repeat_interval = 0 )
OR (
(repeat_year = $year OR repeat_year = '*' )
AND
(repeat_month = $month OR repeat_month = '*' )
AND
(repeat_day = $day OR repeat_day = '*' )
AND
(repeat_week = $week OR repeat_week = '*' )
AND
(repeat_weekday = $weekday OR repeat_weekday = '*' )
AND repeat_start <= DATE('$nowString')
)";
foreach ($dbConnect->query($sql) as $row) {
print $row['ID'] . "\t";
print $row['NAME'] . "<br />";
}
echo "<br /><br /><br />";
}
?>
PHP example code connect.php:
<?
// ----------------------------------------------------------------------------------------------------
// Connecting to database
// ----------------------------------------------------------------------------------------------------
// Database variables
$username = "";
$password = "";
$hostname = "";
$database = "";
// Try to connect to database and set charset to UTF8
try {
$dbConnect = new PDO("mysql:host=$hostname;dbname=$database;charset=utf8", $username, $password);
$dbConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
// ----------------------------------------------------------------------------------------------------
// / Connecting to database
// ----------------------------------------------------------------------------------------------------
?>
Also the php code is available here (for better readability):
index.php
and
connect.php
Now setting this up should take you minutes. Not hours. :)
I just had this problem and was because the skip test option in the run configuration was checked. made that unchecked and build, then run the testNg, worked.
If you can't create an locally valid security token, it seems like you've ruled all out every option bar Win32 API and WNetAddConnection*.
Tons of information on MSDN about WNet - PInvoke information and sample code that connects to a UNC path here:
http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection2.html#
MSDN Reference here:
http://msdn.microsoft.com/en-us/library/aa385391(VS.85).aspx
For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple.
Here is the code for helper:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
if (enabled)
{
return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes);
}
var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
htmlAttributesAsDict.Add("disabled", "disabled");
string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
htmlAttributesAsDict.Add("id", selectClientId + "_disabled");
var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression);
var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict);
return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString());
}
and usage, goal is to disable select if there is just one item in options, markup:
@Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { @class = "some-class" }, Model.SomeList > 1)
And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's):
public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false)
{
if (disabled)
{
var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" };
var doc = new HtmlDocument();
doc.LoadHtml(previous.ToString());
var rootElements = doc.DocumentNode.Descendants().Where(
hn => hn.NodeType == HtmlNodeType.Element &&
canBeDisabled.Contains(hn.Name.ToLower()) &&
(disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document));
foreach (var element in rootElements)
{
element.SetAttributeValue("disabled", "");
}
string html = doc.DocumentNode.OuterHtml;
return MvcHtmlString.Create(html);
}
return previous;
}
For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled:
@Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled)
@Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
$gender = $_POST['gender'];
echo $gender;
it will echoes the selected value.
Using onBackPressed()
method:
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
or use the finish()
method, I have something like
//Password Error, I call function
Quit();
protected void Quit() {
super.finish();
}
With super.finish() you close the super class's activity.
Please refer the below-detailed explanation.
I have used Built-in data frame in R, called mtcars.
> mtcars
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
............
The top line of the table is called the header which contains the column names. Each horizontal line afterward denotes a data row, which begins with the name of the row, and then followed by the actual data. Each data member of a row is called a cell.
To retrieve data in a cell, we would enter its row and column coordinates in the single square bracket "[]" operator. The two coordinates are separated by a comma. In other words, the coordinates begin with row position, then followed by a comma, and ends with the column position. The order is important.
Eg 1:- Here is the cell value from the first row, second column of mtcars.
> mtcars[1, 2]
[1] 6
Eg 2:- Furthermore, we can use the row and column names instead of the numeric coordinates.
> mtcars["Mazda RX4", "cyl"]
[1] 6
We reference a data frame column with the double square bracket "[[]]" operator.
Eg 1:- To retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].
mtcars[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
Eg 2:- We can retrieve the same column vector by its name.
mtcars[["am"]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
Or mayby even more simple with convert
from hablar
:
library(hablar)
dat %>%
convert(fct(fac1, fac2, fac3),
num(dbl1, dbl2, dbl3))
or combines with tidyselect
:
dat %>%
convert(fct(contains("fac")),
num(contains("dbl")))
I came across the same issue of this question...
Wondering myself about it, I did a small alias function inside my .bashrc
file:
gitPullAll() {
for branch in `git branch | sed -E 's/^\*/ /' | awk '{print $1}'`; do
git checkout $branch
git pull -p
printf "\n"
done
echo "Done"
}
Worked for me (:
I think it's best to explicitly state where the form posts. If you want to be totally safe, enter the same URL the form is on in the action attribute if you want it to submit back to itself. Although mainstream browsers evaluate ""
to the same page, you can't guarantee that non-mainstream browsers will.
And of course, the entire URL including GET data like Juddling points out.
getResource by example:
package szb.testGetResource;
public class TestGetResource {
private void testIt() {
System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
System.out.println("test2: "+getClass().getResource("test.css"));
}
public static void main(String[] args) {
new TestGetResource().testIt();
}
}
output:
test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
Hope this would help:
-> And that serial number is UDID
Apparently The “right” JSON (well JavaScript) date format is 2012-04-23T18:25:43.511Z - UTC and "Z". Without this JavaScript will use the web browser's local timezone when creating a Date() object from the string.
For a "naive" time (what Python calls a time with no timezone and this assumes is local) the below will force local timezone so that it can then be correctly converted to UTC:
def default(obj):
if hasattr(obj, "json") and callable(getattr(obj, "json")):
return obj.json()
if hasattr(obj, "isoformat") and callable(getattr(obj, "isoformat")):
# date/time objects
if not obj.utcoffset():
# add local timezone to "naive" local time
# https://stackoverflow.com/questions/2720319/python-figure-out-local-timezone
tzinfo = datetime.now(timezone.utc).astimezone().tzinfo
obj = obj.replace(tzinfo=tzinfo)
# convert to UTC
obj = obj.astimezone(timezone.utc)
# strip the UTC offset
obj = obj.replace(tzinfo=None)
return obj.isoformat() + "Z"
elif hasattr(obj, "__str__") and callable(getattr(obj, "__str__")):
return str(obj)
else:
print("obj:", obj)
raise TypeError(obj)
def dump(j, io):
json.dump(j, io, indent=2, default=default)
why is this so hard.
As for today (2011-04-05, updated 2017-11-29) you will need the lastest versions of:
After that, do a full install in a directory of your preference without spaces in the name. I suggest C:\GnuWin32
. Do not install it in the default (C:\Program Files (x86)\GnuWin32) because bison has problems with spaces in directory names, not to say parenthesis.
Also, consider installing Dev-CPP in the default directory (C:\Dev-Cpp
)
After that, set the PATH variable to include the bin directories of gcc
(in C:\Dev-Cpp\bin
) and flex\bison
(in C:\GnuWin32\bin
). To do that, copy this: ;C:\Dev-Cpp\bin;C:\GnuWin32\bin
and append it to the end of the PATH
variable, defined in the place show by this figure:
If the figure is not in good resolution, you can see a step-by-step here.
Open a prompt, cd to the directory where your ".l" and ".y" are, and compile them with:
flex hello.l
bison -dy hello.y
gcc lex.yy.c y.tab.c -o hello.exe
You will be able to run the program. I made the sources for a simple test (the infamous Hello World
):
%{
#include "y.tab.h"
int yyerror(char *errormsg);
%}
%%
("hi"|"oi")"\n" { return HI; }
("tchau"|"bye")"\n" { return BYE; }
. { yyerror("Unknown char"); }
%%
int main(void)
{
yyparse();
return 0;
}
int yywrap(void)
{
return 0;
}
int yyerror(char *errormsg)
{
fprintf(stderr, "%s\n", errormsg);
exit(1);
}
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
int yyerror(const char *s);
%}
%token HI BYE
%%
program:
hi bye
;
hi:
HI { printf("Hello World\n"); }
;
bye:
BYE { printf("Bye World\n"); exit(0); }
;
Edited: avoiding "warning: implicit definition of yyerror and yylex".
Disclaimer: remember, this answer is very old (since 2011!) and if you run into problems due to versions and features changing, you might need more research, because I can't update this answer to reflect new itens. Thanks and I hope this will be a good entry point for you as it was for many.
Updates: if something (really small changes) needs to be done, please check out the official repository at github: https://github.com/drbeco/hellex
Happy hacking.
DATEPART(HOUR, [date])
returns the hour in military time ( 00 to 23 )
If you want 1AM, 3PM etc, you need to case it out:
SELECT Run_Time_Hour =
CASE DATEPART(HOUR, R.date_schedule)
WHEN 0 THEN '12AM'
WHEN 1 THEN '1AM'
WHEN 2 THEN '2AM'
WHEN 3 THEN '3AM'
WHEN 4 THEN '4AM'
WHEN 5 THEN '5AM'
WHEN 6 THEN '6AM'
WHEN 7 THEN '7AM'
WHEN 8 THEN '8AM'
WHEN 9 THEN '9AM'
WHEN 10 THEN '10AM'
WHEN 11 THEN '11AM'
WHEN 12 THEN '12PM'
ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
END
FROM
dbo.ARCHIVE_RUN_SCHEDULE R
CTRL+N-- to open a new document.
Right Edge find "MORE SHAPES" then "SOFTWARES AND DATABASES" and finaly "SOFTWARES". All UML DIAGRAMS are available here.
This is the format of /etc/crontab:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.
To run something every minute:
* * * * * username /var/www/html/a.php
To run something at midnight of every day:
0 0 * * * username /var/www/html/reset.php
You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which interpreter to use:
#!/usr/bin/php
<?php
// your code here
If you're just interested in the properties and data types from the database, you can use Model.inspect
.
irb(main):001:0> User.inspect
=> "User(id: integer, email: string, encrypted_password: string,
reset_password_token: string, reset_password_sent_at: datetime,
remember_created_at: datetime, sign_in_count: integer,
current_sign_in_at: datetime, last_sign_in_at: datetime,
current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime,
updated_at: datetime)"
Alternatively, having run rake db:create
and rake db:migrate
for your development environment, the file db/schema.rb
will contain the authoritative source for your database structure:
ActiveRecord::Schema.define(version: 20130712162401) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
end
Use doubleValue method present in BigDecimal class :
double doubleValue()
Converts this BigDecimal
to a double
.
You can Trim your String value by creating a trim function for your Strings.
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
now it will be available for your every String and you can use it as
str.trim().length// Result will be 0
You can also use this method to remove the white spaces at the start and end of the String i.e
" hello ".trim(); // Result will be "hello"
Use Do...Loop with Until keyword
num=0
Do Until //certain_condition_to_break_loop
num=num+1
Loop
This loop will continue to execute, Until the condition becomes true
While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops
If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.
This also happened to me when a PercentageRelativeLayout https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html was used and the build was targeting Android 0 = 26. PercentageRelativeLayout layout is obsolete starting from Android O and obviously sometime was changed in the resource generation. Replacing the layout with a ConstraintLayout or just a RelativeLayout solved it.
Thanks @Trott for your code, I just used the same code and added with a real time working example for the benefit of others.
<html>_x000D_
<body >_x000D_
_x000D_
<p>The **instanceof** operator returns true if the specified object is an instance of the specified object.</p>_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
var myError = new Error("TypeError: Cannot set property 'innerHTML' of null"); // error type when element is not defined_x000D_
myError instanceof Error // true_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function test(){_x000D_
_x000D_
var v1 = document.getElementById("myid").innerHTML ="zunu"; // to change with this_x000D_
_x000D_
try {_x000D_
var v1 = document.getElementById("myidd").innerHTML ="zunu"; // exception caught_x000D_
} _x000D_
_x000D_
catch (e) {_x000D_
if (e instanceof Error) {_x000D_
console.error(e.name + ': ' + e.message) // error will be displayed at browser console_x000D_
}_x000D_
}_x000D_
finally{_x000D_
var v1 = document.getElementById("myid").innerHTML ="Text Changed to Zunu"; // finally innerHTML changed to this._x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
<p id="myid">This text will change</p>_x000D_
<input type="button" onclick="test();">_x000D_
</body>_x000D_
</html>
_x000D_
Your first CSS selector—social.h2
—is looking for the "social" element in the "h2", class, e.g.:
<social class="h2">
Class selectors are proceeded with a dot (.
). Also, use a space () to indicate that one element is inside of another. To find an
<h2>
descendant of an element in the social
class, try something like:
.social h2 {
color: pink;
font-size: 14px;
}
To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.
A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.
create and add:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];
and retrieve:
int myNumber = [[dict objectForKey:@"A cool number"] intValue];
Since we are doing this one to death - you don't have to specify a year:
select * from demo
where somedate between to_date('01/01 00:00:00', 'DD/MM HH24:MI:SS')
and to_date('31/12 23:59:59', 'DD/MM HH24:MI:SS');
However the accepted answer by FerranB makes more sense if you want to specify all date values that fall within the current year.
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
sub selectVar ()
dim x,y as integer
let srange = "A" & x & ":" & "m" & y
range(srange).select
end sub
I think this is the simplest way.
I just had this issue, but needed to handle multiple tab levels. The code is rather ugly (see comments), but does its job: https://gist.github.com/JensRantil/4721860 Hopefully someone else will find it useful (and feel free to propose better solutions!).
<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> HtmlSelect Example </title>
<script runat="server">
void Button_Click (Object sender, EventArgs e)
{
Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
+ ", value: " + Select1.Value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
Select an item:
<select id="Select1" runat="server">
<option value="Text for Item 1" selected="selected"> Item 1 </option>
<option value="Text for Item 2"> Item 2 </option>
<option value="Text for Item 3"> Item 3 </option>
<option value="Text for Item 4"> Item 4 </option>
</select>
<button onserverclick="Button_Click" runat="server" Text="Submit"/>
<asp:Label id="Label1" runat="server"/>
</form>
</body>
</html>
Source from Microsoft. Hope this is helpful!
It may be time consuming to get all the application Ids from YARN and kill them one by one. You can use a Bash for loop to accomplish this repetitive task quickly and more efficiently as shown below:
Kill all applications on YARN which are in ACCEPTED state:
for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
Kill all applications on YARN which are in RUNNING state:
for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
Sounds to me like at least one of those tables has defined UserID
as a uniqueidentifier
, not an int
. Did you check the data in each table? What does SELECT TOP 1 UserID FROM
each table yield? An int
or a GUID
?
EDIT
I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership
table in your script, since it's not really one of "your" tables.
If you meant to design your tables around the aspnet_Membership
database, then why are the rest of the columns int
when that table clearly uses a uniqueidentifier
for the UserID
column?
From within gdb press Ctrl
x
2
and the screen will split into 3 parts.
First part will show you the normal code in high level language.
Second will show you the assembly equivalent and corresponding instruction Pointer
.
Third will present you the normal gdb
prompt to enter commands.
I realize this is a very old question, but I stumbled across this problem today and I got it to work with
<div style="text-align:center;">
<button>button1</button>
<button>button2</button>
</div>
Cheers, Mark
Also, in .NET 4 this is even easier if you use the dynamic keyword:
dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);
if android browser can access internet you can run emulator from terminal by this command
go to SDK path then
$ /tools/emulator -avd Nexus_5X_API_23 -netdelay none -netspeed full
it solve your internet problem...
I manged to set the MinDate & the MaxDate programmatically like this :
final Calendar c = Calendar.getInstance();
int maxYear = c.get(Calendar.YEAR) - 20; // this year ( 2011 ) - 20 = 1991
int maxMonth = c.get(Calendar.MONTH);
int maxDay = c.get(Calendar.DAY_OF_MONTH);
int minYear = 1960;
int minMonth = 0; // january
int minDay = 25;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_account);
BirthDateDP = (DatePicker) findViewById(R.id.create_account_BirthDate_DatePicker);
BirthDateDP.init(maxYear - 10, maxMonth, maxDay, new OnDateChangedListener()
{
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < minYear)
view.updateDate(minYear, minMonth, minDay);
if (monthOfYear < minMonth && year == minYear)
view.updateDate(minYear, minMonth, minDay);
if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
view.updateDate(minYear, minMonth, minDay);
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}}); // BirthDateDP.init()
} // activity
it works fine for me, enjoy :)
I am not sure but I think there is one command using which you can copy the schema of database into new database, once you have done this you can delete the old database and after this you can again copy the database schema to the old name.
You can use Func which encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
void Method()
{
Func<string,string> inlineFunction = source =>
{
// add your functionality here
return source ;
};
// call the inline function
inlineFunction("prefix");
}
Time Zone Handling
I just want to clarify, even though this has been commented so future people don't miss this very important distinction.
DateTime.strptime("1318996912",'%s') # => Wed, 19 Oct 2011 04:01:52 +0000
displays a return value in UTC and requires the seconds to be a String and outputs a UTC Time object, whereas
Time.at(1318996912) # => 2011-10-19 00:01:52 -0400
displays a return value in the LOCAL time zone, normally requires a FixNum argument, but the Time object itself is still in UTC even though the display is not.
So even though I passed the same integer to both methods, I seemingly two different results because of how the class' #to_s
method works. However, as @Eero had to remind me twice of:
Time.at(1318996912) == DateTime.strptime("1318996912",'%s') # => true
An equality comparison between the two return values still returns true. Again, this is because the values are basically the same (although different classes, the #==
method takes care of this for you), but the #to_s
method prints drastically different strings. Although, if we look at the strings, we can see they are indeed the same time, just printed in different time zones.
Method Argument Clarification
The docs also say "If a numeric argument is given, the result is in local time." which makes sense, but was a little confusing to me because they don't give any examples of non-integer arguments in the docs. So, for some non-integer argument examples:
Time.at("1318996912")
TypeError: can't convert String into an exact number
you can't use a String argument, but you can use a Time argument into Time.at
and it will return the result in the time zone of the argument:
Time.at(Time.new(2007,11,1,15,25,0, "+09:00"))
=> 2007-11-01 15:25:00 +0900
Benchmarks
After a discussion with @AdamEberlin on his answer, I decided to publish slightly changed benchmarks to make everything as equal as possible. Also, I never want to have to build these again so this is as good a place as any to save them.
Time.at(int).to_datetime ~ 2.8x faster
09:10:58-watsw018:~$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]
09:11:00-watsw018:~$ irb
irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> require 'date'
=> true
irb(main):003:0>
irb(main):004:0* format = '%s'
=> "%s"
irb(main):005:0> times = ['1318996912', '1318496913']
=> ["1318996912", "1318496913"]
irb(main):006:0> int_times = times.map(&:to_i)
=> [1318996912, 1318496913]
irb(main):007:0>
irb(main):008:0* datetime_from_strptime = DateTime.strptime(times.first, format)
=> #<DateTime: 2011-10-19T04:01:52+00:00 ((2455854j,14512s,0n),+0s,2299161j)>
irb(main):009:0> datetime_from_time = Time.at(int_times.first).to_datetime
=> #<DateTime: 2011-10-19T00:01:52-04:00 ((2455854j,14512s,0n),-14400s,2299161j)>
irb(main):010:0>
irb(main):011:0* datetime_from_strptime === datetime_from_time
=> true
irb(main):012:0>
irb(main):013:0* Benchmark.measure do
irb(main):014:1* 100_000.times {
irb(main):015:2* times.each do |i|
irb(main):016:3* DateTime.strptime(i, format)
irb(main):017:3> end
irb(main):018:2> }
irb(main):019:1> end
=> #<Benchmark::Tms:0x00007fbdc18f0d28 @label="", @real=0.8680500000045868, @cstime=0.0, @cutime=0.0, @stime=0.009999999999999998, @utime=0.86, @total=0.87>
irb(main):020:0>
irb(main):021:0* Benchmark.measure do
irb(main):022:1* 100_000.times {
irb(main):023:2* int_times.each do |i|
irb(main):024:3* Time.at(i).to_datetime
irb(main):025:3> end
irb(main):026:2> }
irb(main):027:1> end
=> #<Benchmark::Tms:0x00007fbdc3108be0 @label="", @real=0.33059399999910966, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.32000000000000006, @total=0.32000000000000006>
****edited to not be completely and totally incorrect in every way****
****added benchmarks****
One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.
@SpringBootApplication
public class ChildApplication extends ParentApplication{
public static void main(String[] args) {
SpringApplication.run(ChildApplication.class, args);
}
}
The explode() function breaks a string into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']
You can use the Screen.PrimaryScreen.Bounds
to retrieve the size of the primary monitor (or inspect the Screen
object to retrieve all monitors). Use those with MyForms.Bounds
to figure out where to place your form.
For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.
Go to Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>
.
I don't have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.
Update:
Note: Pycharm now supports virtual environments directly and it seems to work well for me - so my workaround not needed anymore.
If you can modify the client, then have it print out the remote reference and you will see what port it's using. E.g.
ServerApi server = (ServerApi) registry.lookup(ServerApi.RMI_NAME);
System.out.println("Got server handle " + server);
will produce something like:
Got server handle Proxy[ServerApi,RemoteObjectInvocationHandler[UnicastRef [liveRef: [endpoint:172.17.3.190:9001,objID:[-7c63fea8:...
where you can see the port is 9001. If the remote class is not specifying the port, then it will change across reboots. If you want to use a fixed port then you need to make sure the remote class constructor does something like:
super(rmiPort)
Guys, don´t scare the crap out of others (hey! just kidding), but it´s really all a question of equivalences and synonyms:
firstly:
"XAND" doesn´t exist logically, neither does "XNAND", however "XAND" is normally thought-up by a studious but confused initiating logic student.(wow!). It com from the thought that, if there´s a XOR(exclusive OR) it´s logical to exist a "XAND"("exclusive" AND). The rational suggestion would be an "IAND"("inclusive" AND), which isn´t used or recognised as well. So:
XNOR <=> !XOR <=> EQV
And all this just discribes a unique operator, called the equivalency operator(<=>, EQV) so:
A | B | A <=> B | A XAND B | A XNOR B | A !XOR B | ((NOT(A) AND B)AND(A AND NOT(B)))
---------------------------------------------------------------------------------------
T | T | T | T | T | T | T
T | F | F | F | F | F | F
F | T | F | F | F | F | F
F | F | T | T | T | T | T
And just a closing comment: The 'X' prefix is only possible if and only if the base operator isn´t unary. So, XNOR <=> NOT XOR <=/=> X NOR.
Peace.
For Laravel >=6
composer require laravel/ui
php artisan ui vue --auth
php artisan migrate
Reference : Laravel Documentation for authentication
it looks you are not using Laravel 5.2, these are the available make commands in L5.2 and you are missing more than just the make:auth command
make:auth Scaffold basic login and registration views and routes
make:console Create a new Artisan command
make:controller Create a new controller class
make:entity Create a new entity.
make:event Create a new event class
make:job Create a new job class
make:listener Create a new event listener class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:policy Create a new policy class
make:presenter Create a new presenter.
make:provider Create a new service provider class
make:repository Create a new repository.
make:request Create a new form request class
make:seeder Create a new seeder class
make:test Create a new test class
make:transformer Create a new transformer.
Be sure you have this dependency in your composer.json file
"laravel/framework": "5.2.*",
Then run
composer update
Let me clear two points here :
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b) are positional parameter
(c=none) is optional parameter
(r="w") is keyword parameter
(d=[]) is list parameter
(*ae) is keyword-only
(**ab) is var-keyword parameter
def example(a, b, c=a,d=b):
argument is not defined when default values are saved,Python computes and saves default values when you define the function
c and d are not defined, does not exist, when this happens (it exists only when the function is executed)
"a,a=b" its not allowed in parameter.
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
The file .bashrc
is read when you start an interactive shell. This is the file that you should update. E.g:
export PATH=$PATH:/opt/ActiveTcl-8.5/bin
Restart the shell for the changes to take effect or source it, i.e.:
source .bashrc
and to get it :
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(getLocalClassName(), "onItemClick(" + view + ","
+ position + "," + id + ")");
}
});
Here is more functional example with some ES6 features:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
Two alternative strategies to get consistent about line-endings in mixed environments (Microsoft + Linux + Mac):
1) Convert all to one format
find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'
2) Set core.autocrlf
to input
on Linux/UNIX or true
on MS Windows (repository or global)
git config --global core.autocrlf input
3) [ Optional ] set core.safecrlf
to true
(to stop) or warn
(to sing:) to add extra guard comparing if the reversed newline transformation would result in the same file
git config --global core.safecrlf true
1) Convert all to one format
find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'
2) add .gitattributes
file to your repository
echo "* text=auto" > .gitattributes
git add .gitattributes
git commit -m 'adding .gitattributes for unified line-ending'
Don't worry about your binary files - Git should be smart enough about them.
Summary.
Can I nest git repositories?
Yes. However, by default git does not track the .git
folder of the nested repository. Git has features designed to manage nested repositories (read on).
Does it make sense to git init/add the /project_root to ease management of everything locally or do I have to manage my_project and the 3rd party one separately?
It probably doesn't make sense as git has features to manage nested repositories. Git's built in features to manage nested repositories are submodule
and subtree
.
Here is a blog on the topic and here is a SO question that covers the pros and cons of using each.
For me, I had typed image with a lower case "i" instead of Image. So I did:
from PIL import Image
NOT from PIL import image
On OSX use fn instead of shift.
$('body').delegate('.deletelanguage','click',function(){
alert("success");
});
or
$('body').on('click','.deletelanguage',function(){
alert("success");
});
If you are using Jackson to deserialize the response body, one very simple solution is to use request.getResponseBodyAsStream()
instead of request.getResponseBodyAsString()
Remember that a single =
is always an assignment in C or C++.
Your test should be if ( match == 0 && k == M )
you made a typo on the k == M
test.
If you really mean k=M
(i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0)
but most coding rules advise not writing that.
BTW, your mistake suggests to ask for all warnings (e.g. -Wall
option to g++
), and to upgrade to recent compilers. The next GCC 4.8 will give you:
% g++-trunk -Wall -c ederman.cc
ederman.cc: In function ‘void foo()’:
ederman.cc:9:30: error: lvalue required as left operand of assignment
if ( match == 0 && k = M )
^
and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable
So use recent versions of free compilers and enable all the warnings when using them.
As RAND
produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND
to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)
So to produce the range you need:
SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users
A backreference to the whole match value is \g<0>
, see re.sub
documentation:
The backreference
\g<0>
substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
Pass a duration to show()
and hide()
:
When a duration is provided,
.show()
becomes an animation method.
E.g. element.delay(1000).show(0)
Check if your commits have Change-Id: ...
in their descriptions. Every commit should have them.
If no, use git rebase -i
to reword the commit messages and add proper Change-Ids (usually this is a SHA1 of the first version of the reviewed commit).
For the future, you should install commit hook, which automatically adds the required Change-Id.
Execute scp -p -P 29418 username@your_gerrit_address:hooks/commit-msg .git/hooks/
in the repository directory
or download them from
http://your_gerrit_address/tools/hooks/commit-msg
and copy to .git/hooks
The syntax for crontab
* * * * *
Minute(0-59) Hour(0-24) Day_of_month(1-31) Month(1-12) Day_of_week(0-6) Command_to_execute
Your syntax
* 22 * * * test > /dev/null
your job will Execute every minute at 22:00 hrs all week, month and year.
adding an option (0-59) at the minute place will run it once at 22:00 hrs all week, month and year.
0 22 * * * command_to_execute
$RANDOM
is a number between 0 and 32767. You want a port between 2000 and 65000. These are 63001 possible ports. If we stick to values of $RANDOM + 2000
between 2000 and 33500, we cover a range of 31501 ports. If we flip a coin and then conditionally add 31501 to the result, we can get more ports, from 33501 to 65001. Then if we just drop 65001, we get the exact coverage needed, with a uniform probability distribution for all ports, it seems.
random-port() {
while [[ not != found ]]; do
# 2000..33500
port=$((RANDOM + 2000))
while [[ $port -gt 33500 ]]; do
port=$((RANDOM + 2000))
done
# 2000..65001
[[ $((RANDOM % 2)) = 0 ]] && port=$((port + 31501))
# 2000..65000
[[ $port = 65001 ]] && continue
echo $port
break
done
}
Testing
i=0
while true; do
i=$((i + 1))
printf "\rIteration $i..."
printf "%05d\n" $(random-port) >> ports.txt
done
# Then later we check the distribution
sort ports.txt | uniq -c | sort -r
FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them.
FSPL (dB) = 20log10(d) + 20log10(f) + K
d = distance
f = frequency
K= constant that depends on the units used for d and f
If d is measured in kilometers, f in MHz, the formula is:
FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44
From the Fade Margin equation, Free Space Path Loss can be computed with the following equation.
Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin
With the above two Free Space Path Loss equations, we can find out the Distance in km.
Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20
The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant.
FSPLr=17.32*v(d/4f)
d = distance [km]
f = frequency [GHz]
r = radius [m]
Here is an R
version based on the @Pirijan answer above.
points <- 8
radius <- 10
center_x <- 5
center_y <- 5
drawCirclePoints <- function(points, radius, center_x, center_y) {
slice <- 2 * pi / points
angle <- slice * seq(0, points, by = 1)
newX <- center_x + radius * cos(angle)
newY <- center_y + radius * sin(angle)
plot(newX, newY)
}
drawCirclePoints(points, radius, center_x, center_y)
I think it's worth answering the generic question "R - test if string contains string" here.
For that, use the grep function.
# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"
A solution without using imported modules or sets:
text = "ask not what your country can do for you ask what you can do for your country"
sentence = text.split(" ")
noduplicates = [(sentence[i]) for i in range (0,len(sentence)) if sentence[i] not in sentence[:i]]
print(noduplicates)
Gives output:
['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']
When you want to display information encoded in UTF-8 you may not face problems. Declare for example an HTML document as UTF-8 and you will have everything displayed in your browser that is contained in the body of the document.
But this is not the case when we have text, CSV and XML files, either on Windows or Linux.
For example, a text file in Windows or Linux, one of the easiest things imaginable, it is not (usually) UTF-8.
Save it as XML and declare it as UTF-8:
<?xml version="1.0" encoding="UTF-8"?>
It will not display (it will not be be read) correctly, even if it's declared as UTF-8.
I had a string of data containing French letters, that needed to be saved as XML for syndication. Without creating a UTF-8 file from the very beginning (changing options in IDE and "Create New File") or adding the BOM at the beginning of the file
$file="\xEF\xBB\xBF".$string;
I was not able to save the French letters in an XML file.
I have tried your example and it works just fine:
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/test',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: {application: app, from: d1, to: d2}
});
Output:
Content-Length:91
Content-Type:application/json
Host:localhost:1234
Origin:http://localhost:1234
Referer:http://localhost:1234/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{"application":"AirFare","from":"2013-10-10T11:47:50.681Z","to":"2013-10-10T11:47:50.681Z"}
Are you using the latest version of AngularJS?
Do like this
List<Object[]> list = HQL.list(); // get your lsit here but in Object array
your query is : "SELECT houses.id, addresses.country, addresses.region,..."
for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
create a textbox:
<TextBox Name="tb">
..hello..
</TextBox>
focus() ---> it is used to set input focus to the textbox control
tb.focus()
You can also run your app like any other console applications but only after the publish.
Let's suppose you have the simple console app named MyTestConsoleApp. Open the package manager console and run the following command:
dotnet publish -c Debug -r win10-x64
-c flag mean that you want to use the debug configuration (in other case you should use Release value) - r flag mean that your application will be runned on Windows platform with x64 architecture.
When the publish procedure will be finished your will see the *.exe file located in your bin/Debug/publish directory.
Now you can call it via command line tools. So open the CMD window (or terminal) move to the directory where your *.exe file is located and write the next command:
>> MyTestConsoleApp.exe argument-list
For example:
>> MyTestConsoleApp.exe --input some_text -r true
In my case, I was getting this error despite registering an existing instance for the interface in question.
Turned out, it was because I was using Unity in WebForms by way of the Unity.WebForms Nuget package, and I had specified a Hierarchical Lifetime manager for the dependency I was providing an instance for, yet a Transient lifetime manager for a subsequent type that depended on the previous type - not usually an issue - but with Unity.WebForms, the lifetime managers work a little differently... your injected types seem to require a Hierarchical lifetime manager, but a new container is still created for every web request (because of the architecture of web forms I guess) as explained excellently in this post.
Anyway, I resolved it by simply not specifying a lifetime manager for the types/instances when registering them.
i.e.
container.RegisterInstance<IMapper>(MappingConfig.GetMapper(), new HierarchicalLifetimeManager());
container.RegisterType<IUserContext, UserContext>(new TransientLifetimeManager());
becomes
container.RegisterInstance<IMapper>(MappingConfig.GetMapper());
container.RegisterType<IUserContext, UserContext>();
So that IMapper can be resolved successfully here:
public class UserContext : BaseContext, IUserContext
{
public UserContext(IMapper _mapper) : base(_mapper)
{
}
...
}
You should give the new monkeyrunner a go. Maybe this can solve your problems. You put keycodes in it for testing, maybe touch events are also possible.
echo -e $lines | while read line
...
done
The while
loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.
Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines
will run in a subshell:
while read line
do
if [[ "$line" == "second line" ]]
then
foo=2
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"
You can get rid of the rather ugly echo
in the here-string above by expanding the backslash sequences immediately when assigning lines
. The $'...'
form of quoting can be used there:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
try this:
public class SomAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private CallBack callBack;
public interface CallBack {
void async( JSONObject jsonResult );
void sync( JSONObject jsonResult );
void progress( Integer... status );
void cancel();
}
public SomAsyncTask(CallBack callBack) {
this.callBack = callBack;
}
@Override
protected JSONObject doInBackground(String... strings) {
JSONObject dataJson = null;
//TODO query, get some dataJson
if(this.callBack != null)
this.callBack.async( dataJson );// asynchronize with MAIN LOOP THREAD
return dataJson;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(this.callBack != null)
this.callBack.progress(values);// synchronize with MAIN LOOP THREAD
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(this.callBack != null)
this.callBack.sync(jsonObject);// synchronize with MAIN LOOP THREAD
}
@Override
protected void onCancelled() {
super.onCancelled();
if(this.callBack != null)
this.callBack.cancel();
}
}
And usage example:
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context _localContext = getContext();
SomeAsyncTask.CallBack someCallBack = new SomeAsyncTask.CallBack() {
@Override
public void async(JSONObject jsonResult) {//async thread
//some async process, e.g. send data to server...
}
@Override
public void sync(JSONObject jsonResult) {//sync thread
//get result...
//get some resource of Activity variable...
Resources resources = _localContext.getResources();
}
@Override
public void progress(Integer... status) {//sync thread
//e.g. change status progress bar...
}
@Override
public void cancel() {
}
};
new SomeAsyncTask( someCallBack )
.execute("someParams0", "someParams1", "someParams2");
}
You can get the device ip address by this way:
adb shell ip route > addrs.txt
#Case 1:Nexus 7
#192.168.88.0/23 dev wlan0 proto kernel scope link src 192.168.89.48
#Case 2: Smartsian T1,Huawei C8813
#default via 192.168.88.1 dev eth0 metric 30
#8.8.8.8 via 192.168.88.1 dev eth0 metric 30
#114.114.114.114 via 192.168.88.1 dev eth0 metric 30
#192.168.88.0/23 dev eth0 proto kernel scope link src 192.168.89.152 metric 30
#192.168.88.1 dev eth0 scope link metric 30
ip_addrs=$(awk {'if( NF >=9){print $9;}'} addrs.txt)
echo "the device ip address is $ip_addrs"
First, in your database, create the following two objects:
CREATE TYPE dbo.IDList
AS TABLE
(
ID INT
);
GO
CREATE PROCEDURE dbo.DoSomethingWithEmployees
@List AS dbo.IDList READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT ID FROM @List;
END
GO
Now in your C# code:
// Obtain your list of ids to send, this is just an example call to a helper utility function
int[] employeeIds = GetEmployeeIds();
DataTable tvp = new DataTable();
tvp.Columns.Add(new DataColumn("ID", typeof(int)));
// populate DataTable from your List here
foreach(var id in employeeIds)
tvp.Rows.Add(id);
using (conn)
{
SqlCommand cmd = new SqlCommand("dbo.DoSomethingWithEmployees", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@List", tvp);
// these next lines are important to map the C# DataTable object to the correct SQL User Defined Type
tvparam.SqlDbType = SqlDbType.Structured;
tvparam.TypeName = "dbo.IDList";
// execute query, consume results, etc. here
}
If you are using SQL Server 2005, I would still recommend a split function over XML. First, create a function:
CREATE FUNCTION dbo.SplitInts
(
@List VARCHAR(MAX),
@Delimiter VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT Item = CONVERT(INT, Item) FROM
( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
Now your stored procedure can just be:
CREATE PROCEDURE dbo.DoSomethingWithEmployees
@List VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
SELECT EmployeeID = Item FROM dbo.SplitInts(@List, ',');
END
GO
And in your C# code you just have to pass the list as '1,2,3,12'
...
I find the method of passing through table valued parameters simplifies the maintainability of a solution that uses it and often has increased performance compared to other implementations including XML and string splitting.
The inputs are clearly defined (no one has to guess if the delimiter is a comma or a semi-colon) and we do not have dependencies on other processing functions that are not obvious without inspecting the code for the stored procedure.
Compared to solutions involving user defined XML schema instead of UDTs, this involves a similar number of steps but in my experience is far simpler code to manage, maintain and read.
In many solutions you may only need one or a few of these UDTs (User defined Types) that you re-use for many stored procedures. As with this example, the common requirement is to pass through a list of ID pointers, the function name describes what context those Ids should represent, the type name should be generic.
$date = strtotime("+1 day");
echo date('m-d-y',$date);
There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.
Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.
Just put your images in the assets folder refer them in your html
pages or ts
files with that link.
Within your click
handler, the mistake is the .validate()
method; it only initializes the plugin, it does not validate the form
.
To eliminate the need to have a submit
button within the form
, use .valid()
to trigger a validation check...
$('#btn').on('click', function() {
$("#form1").valid();
});
.validate()
- to initialize the plugin (with options) once on DOM ready.
.valid()
- to check validation state (boolean value) or to trigger a validation test on the form
at any time.
Otherwise, if you had a type="submit"
button within the form
container, you would not need a special click
handler and the .valid()
method, as the plugin would capture that automatically.
EDIT:
You also have two issues within your HTML...
<input id="field1" type="text" class="required">
You don't need class="required"
when declaring rules within .validate()
. It's redundant and superfluous.
The name
attribute is missing. Rules are declared within .validate()
by their name
. The plugin depends upon unique name
attributes to keep track of the inputs.
Should be...
<input name="field1" id="field1" type="text" />
You can access tempfile in Spring by casting if the class of interface MultipartFile
is CommonsMultipartFile
.
public File getTempFile(MultipartFile multipartFile)
{
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);
//trick to implicitly save on disk small files (<10240 bytes by default)
if (!file.exists()) {
file.createNewFile();
multipartFile.transferTo(file);
}
return file;
}
To get rid of the trick with files less than 10240 bytes maxInMemorySize
property can be set to 0 in @Configuration
@EnableWebMvc
class. After that, all uploaded files will be stored on disk.
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxInMemorySize(0);
return resolver;
}
class Class1(object):
pass
class Class2(Class1):
pass
Class2 is a sub-class of Class1
Answered this in 'top question' about emails verification https://stackoverflow.com/a/41129750/1848217
For me the right way for checking emails is:
- Check that symbol @ exists, and before and after it there are some non-@ symbols:
/^[^@]+@[^@]+$/
- Try to send an email to this address with some "activation code".
- When the user "activated" his email address, we will see that all is right.
Of course, you can show some warning or tooltip in front-end when user typed "strange" email to help him to avoid common mistakes, like no dot in domain part or spaces in name without quoting and so on. But you must accept the address "hello@world" if user really want it.
Also, you must remember that email address standard was and can evolute, so you can't just type some "standard-valid" regexp once and for all times. And you must remember that some concrete internet servers can fail some details of common standard and in fact work with own "modified standard".
So, just check @, hint user on frontend and send verification emails on given address.
The problem for me turned out to be that the Properties->Build->Optimize code checkbox had been turned on in the Debug configuration. Turned it off, rebuilt, and debugging worked as normal.
Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:
CSS:
.div-wrapper {
position: relative;
height: 300px;
width: 300px;
}
.div-wrapper img {
position: absolute;
left: 0;
bottom: 0;
}
HTML:
<div class="div-wrapper">
<img src="blah.png"/>
</div>
Now the image sits at the bottom of the div.
Create a repository folder under your project. Let's take
${project.basedir}/src/main/resources/repo
Then, install your custom jar to this repo:
mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]
Lastly, add the following repo and dependency definitions to the projects pom.xml:
<repositories>
<repository>
<id>project-repo</id>
<url>file://${project.basedir}/src/main/resources/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>[GROUP]</groupId>
<artifactId>[ARTIFACT]</artifactId>
<version>[VERS]</version>
</dependency>
</dependencies>
Try this code,
public void ConnectToAccess()
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data source= C:\Documents and Settings\username\" +
@"My Documents\AccessFile.mdb";
try
{
conn.Open();
// Insert code to process data.
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}
http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx
ooxml for dealing the .xlsx files and the ooxml refers to the xml, hence we will be needed to refer the below three dependedncies in the pom.xml for the
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
<exclusions>
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
</exclusions>
</dependency>
If you wanna create dropdown menu and having a problem with z-index, you can solve it by creating z-indexes of same value (z-index:999; for example).. Just put z-index in parent and child div's and that will solve problem. I solve the problem with that. If i put different z-indexes, sure, it will show my child div over my parent div, but, once i want to move my mouse from menu tab to the sub-menu div (dropdown list), it dissapear... then i put z-indexes of same value and solve the problem..
built-in types in Python have built in names:
>>> s = "hallo"
>>> type(s) is str
True
>>> s = {}
>>> type(s) is dict
True
btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.
jQuery should be the first:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
There are a lot of misconceptions regarding these words.
This is from a previous post (https://stackoverflow.com/a/24582076/3163691) which fits superb here:
1) Critical Section= User object used for allowing the execution of just one active thread from many others within one process. The other non selected threads (@ acquiring this object) are put to sleep.
[No interprocess capability, very primitive object].
2) Mutex Semaphore (aka Mutex)= Kernel object used for allowing the execution of just one active thread from many others, among different processes. The other non selected threads (@ acquiring this object) are put to sleep. This object supports thread ownership, thread termination notification, recursion (multiple 'acquire' calls from same thread) and 'priority inversion avoidance'.
[Interprocess capability, very safe to use, a kind of 'high level' synchronization object].
3) Counting Semaphore (aka Semaphore)= Kernel object used for allowing the execution of a group of active threads from many others. The other non selected threads (@ acquiring this object) are put to sleep.
[Interprocess capability however not very safe to use because it lacks following 'mutex' attributes: thread termination notification, recursion?, 'priority inversion avoidance'?, etc].
4) And now, talking about 'spinlocks', first some definitions:
Critical Region= A region of memory shared by 2 or more processes.
Lock= A variable whose value allows or denies the entrance to a 'critical region'. (It could be implemented as a simple 'boolean flag').
Busy waiting= Continuosly testing of a variable until some value appears.
Finally:
Spin-lock (aka Spinlock)= A lock which uses busy waiting. (The acquiring of the lock is made by xchg or similar atomic operations).
[No thread sleeping, mostly used at kernel level only. Ineffcient for User level code].
As a last comment, I am not sure but I can bet you some big bucks that the above first 3 synchronizing objects (#1, #2 and #3) make use of this simple beast (#4) as part of their implementation.
Have a good day!.
References:
-Real-Time Concepts for Embedded Systems by Qing Li with Caroline Yao (CMP Books).
-Modern Operating Systems (3rd) by Andrew Tanenbaum (Pearson Education International).
-Programming Applications for Microsoft Windows (4th) by Jeffrey Richter (Microsoft Programming Series).
Also, you can take a look at look at: https://stackoverflow.com/a/24586803/3163691
I also like to define my own functions that take and return arguments in degrees rather than radians. I am sure there some capitalization purest who don't like my names, but I just use a capital first letter for my custom functions. The definitions and testing code are below.
#Definitions for trig functions using degrees.
def Cos(a):
return cos(radians(a))
def Sin(a):
return sin(radians(a))
def Tan(a):
return tan(radians(a))
def ArcTan(a):
return degrees(arctan(a))
def ArcSin(a):
return degrees(arcsin(a))
def ArcCos(a):
return degrees(arccos(a))
#Testing Code
print(Cos(90))
print(Sin(90))
print(Tan(45))
print(ArcTan(1))
print(ArcSin(1))
print(ArcCos(0))
Note that I have imported math (or numpy) into the namespace with
from math import *
Also note, that my functions are in the namespace in which they were defined. For instance,
math.Cos(45)
does not exist.
The default location to put all the web projects in ubuntu
with LAMPP
is :
/var/www/
You may make symbolic link to public_html directory from this directory.Refered. Hope this is helpful.
Yes. You can have a span
within a span
. Your problem stems from something else.
fsevents
is dealt differently in mac and other linux system. Linux system ignores fsevents
whereas mac install it. As the above error message states that fsevents
is optional and it is skipped in installation process.
You can run npm install --no-optional
command in linux system to avoid above warning.
Further information
I hope I understood the question right, which is: how to download a file from a server when the URL is stored in a string type?
I download files and save it locally using the below code:
import requests
url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
file.write(chunk)
file.close()
A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):
template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
{
printf("%p\n", &arr);
}
int main()
{
double a1[10][10];
double a2[5][5];
printf("%p\n%p\n\n", &a1, &a2);
func(a1);
func(a2);
return 0;
}
The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)
Try this in a Thread (not the UI-Thread):
final CountDownLatch latch = new CountDownLatch(1);
handler.post(new Runnable() {
@Override
public void run() {
OnClickListener okListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
latch.countDown();
}
};
AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
.setMessage(msg).setPositiveButton("OK", okListener).create();
dialog.show();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Sometimes the array element may be very long, at that time you can create an array in this way:
set list=a
set list=%list%;b
set list=%list%;c
set list=%list%;d
Then show it:
@echo off
for %%a in (%list%) do (
echo %%a
echo/
)
Or you may use Selenium Action Class to simulate user interaction -- For example
WebDriver = new FirefoxDriver();
WebElement menu = driver.findElement(By.xpath("")); // the triger event element
Actions build = new Actions(driver); // heare you state ActionBuider
build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden
WebElement m2m= driver.findElement(By.xpath(""));//the previous non visible element
m2m.click();
This saves the absolute path of the current working directory to the variable cwd
:
cwd=$(pwd)
In your case you can just do:
export PATH=$PATH:$(pwd)+somethingelse
You can look for regular expression
Regex.IsMatch(str, @"^[a-zA-Z]+$");
If you have a SharedPreferenceActivity by which you have saved your values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");
if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.
and this is how you can retrieve the values.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));
Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.
mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
Yes, ==
is bad for comparing Strings (any objects really, unless you know they're canonical). ==
just compares object references. .equals()
tests for equality. For Strings, often they'll be the same but as you've discovered, that's not guaranteed always.
CREATE ROLE blog WITH
LOGIN
SUPERUSER
INHERIT
CREATEDB
CREATEROLE
REPLICATION;
COMMENT ON ROLE blog IS 'Test';
ie ---> Tools ----> Internet options -----> Programe ------> Make Defualt
We use a custom provider for multi language support and put all texts in a database table. It works well except we sometimes face caching problems when updating texts in the database without updating the web application.
The easiest and cleanest way, without any hacks, is to just to indent the ul
(or ol
), like so:
ol {
padding-left: 40px; // Or whatever padding your font size needs
}
This gives the same result as the accepted answer: https://jsfiddle.net/5wxf2ayu/
Screenshot:
@echo off
::Ask
echo Your Source Path:
set INPUT1=
set /P INPUT1=Type input: %=%
echo Your Destination Path:
set INPUT2=
set /P INPUT2=Type input: %=%
xcopy %INPUT1% %INPUT2% /y /s
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
Using the new 'on' method in jQuery (1.7): http://api.jquery.com/on/
$('#myform').on('change', 'input[type=checkbox]', function(e) {
console.log(this.name+' '+this.value+' '+this.checked);
});
var custApp = angular.module("custApp", [])
.controller('FirstController', FirstController)
.controller('SecondController',SecondController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
SecondController.$inject['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default Value'
}
}
First Controller
<div ng-controller="FirstController as vm">
<input type=text ng-model="vm.data.value" />
</div>
Second Controller
<div ng-controller="SecondController as vm">
Second Controller<br>
{{vm.data.value}}
</div>
This works for me:
try {
$statusUpdate = $facebook->api('/me/feed', 'post',
array('name'=>'My APP on Facebook','message'=> 'I am here working',
'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
'description'=>'testing my description',
'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
} catch (FacebookApiException $e) {
d($e);
}
In addition with what @Camilo Silva already mentioned, if you want to give free access to create databases, read, write databases, etc, but you don't want to create a root role, you can change the 3rd step with the following:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" } ]
}
)
And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)
can check it in packages.config file.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net40-Client" />
</packages>
You can use browser default prompt window.
Instead of basic <input type="submit" (...) >
try:
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
You can simply assign the B
to the new column , Like -
df['D'] = df['B']
Example/Demo -
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([['a.1','b.1','c.1'],['a.2','b.2','c.2'],['a.3','b.3','c.3']],columns=['A','B','C'])
In [3]: df
Out[3]:
A B C
0 a.1 b.1 c.1
1 a.2 b.2 c.2
2 a.3 b.3 c.3
In [4]: df['D'] = df['B'] #<---What you want.
In [5]: df
Out[5]:
A B C D
0 a.1 b.1 c.1 b.1
1 a.2 b.2 c.2 b.2
2 a.3 b.3 c.3 b.3
In [6]: df.loc[0,'D'] = 'd.1'
In [7]: df
Out[7]:
A B C D
0 a.1 b.1 c.1 d.1
1 a.2 b.2 c.2 b.2
2 a.3 b.3 c.3 b.3
$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);
if ($validator->fails()) { return $validator->errors(); }
There is no equivalent to $scope.emit()
or $scope.broadcast()
from AngularJS.
EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.
In Angular, there are other alternatives which I'll try to explain below.
@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component.
Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.
To answer your questions:
What if I need to communicate between sibling components?
Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.
Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.
Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.
How can I communicate between a Root component and a component nested several levels deep?
$scope.broadcast()
from Angular 1. The next section describes this idea in more detail.Example of an Observable Service that uses Service Events to Propagate Changes
Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.
export class TodoItem {
constructor(public name: string, public done: boolean) {
}
}
export class TodoService {
public itemAdded$: EventEmitter<TodoItem>;
private todoList: TodoItem[] = [];
constructor() {
this.itemAdded$ = new EventEmitter();
}
public list(): TodoItem[] {
return this.todoList;
}
public add(item: TodoItem): void {
this.todoList.push(item);
this.itemAdded$.emit(item);
}
}
Here is how a root component would subscribe to the event:
export class RootComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
A child component nested several levels deep would subscribe to the event in the same way:
export class GrandChildComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):
@Component({
selector: 'todo-list',
template: `
<ul>
<li *ngFor="#item of model"> {{ item.name }}
</li>
</ul>
<br />
Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>
`
})
export class TriggeringComponent{
private model: TodoItem[];
constructor(private todoService: TodoService) {
this.model = todoService.list();
}
add(value: string) {
this.todoService.add(new TodoItem(value, false));
}
}
Reference: Change Detection in Angular
I am working on a tutorial for REST web services at www.udemy.com (REST Java Web Services). The example in the tutorial said that in order to have SSL, we must have a folder called "trust_store" in my eclipse "client" project that should contain a "key store" file (we had a "client" project to call the service, and "service" project that contained the REST web service - 2 projects in the same eclipse workspace, one the client, the other the service). To keep things simple, they said to copy "keystore.jks" from the glassfish app server (glassfish\domains\domain1\config\keystore.jks) we are using and put it into this "trust_store" folder that they had me make in the client project. That seems to make sense: the self-signed certs in the server's key_store would correspond to the certs in the client trust_store. Now, doing this, I was getting the error that the original post mentions. I have googled this and read that the error is due to the "keystore.jks" file on the client not containing a trusted/signed certificate, that the certificate it finds is self-signed.
To keep things clear, let me say that as I understand it, the "keystore.jks" contains self-signed certs, and the "cacerts.jks" file contains CA certs (signed by the CA). The "keystore.jks" is the "keystore" and the "cacerts.jks" is the "trust store". As "Bruno", a commenter, says above, "keystore.jks" is local, and "cacerts.jks" is for remote clients.
So, I said to myself, hey, glassfish also has the "cacerts.jks" file, which is glassfish's trust_store file. cacerts.jsk is supposed to contain CA certificates. And apparently I need my trust_store folder to contain a key store file that has at least one CA certificate. So, I tried putting the "cacerts.jks" file in the "trust_store" folder I had made, on my client project, and changing the VM properties to point to "cacerts.jks" instead of "keystore.jks". That got rid of the error. I guess all it needed was a CA cert to work.
This may not be ideal for production, or even for development beyond just getting something to work. For instance you could probably use "keytool" command to add CA certs to the "keystore.jks" file in the client. But anyway hopefully this at least narrows down the possible scenarios that could be going on here to cause the error.
ALSO: my approach seemed to be useful for the client (server cert added to client trust_store), it looks like the comments above to resolve the original post are useful for the server (client cert added to server trust_store). Cheers.
Eclipse project setup:
Snippet from MyClientProject.java file:
static {
// Setup the trustStore location and password
System.setProperty("javax.net.ssl.trustStore","trust_store/cacerts.jks");
// comment out below line
System.setProperty("javax.net.ssl.trustStore","trust_store/keystore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
//System.setProperty("javax.net.debug", "all");
// for localhost testing only
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return hostname.equals("localhost");
}
});
}
Not possible without assigning height value to div.
Add this
body, html{height:100%}
div{height:100%}
table{background:green; width:450px} ?
In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx
Yes, it's
use Illuminate\Support\Facades\Redirect;
return Redirect::to('http://heera.it');
Update: Redirect::away('url')
(For external link, Laravel Version 4.19):
public function away($path, $status = 302, $headers = array())
{
return $this->createRedirect($path, $status, $headers);
}
String
is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer
is used to represent characters that can be modified.
Performance wise, StringBuffer
is faster when performing concatenations. This is because when you concatenate a String
, you are creating a new object (internally) every time since String
is immutable.
You can also use StringBuilder
which is similar to StringBuffer
except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE
(231 - 1 = 2,147,483,647) or maximum heap size divided by 2 (see How many characters can a Java String have?).
More information here.
As others have mentioned, Environment.NewLine
returns a platform-specific string for beginning a new line, which should be:
"\r\n"
(\u000D\u000A) for Windows"\n"
(\u000A) for Unix"\r"
(\u000D) for Mac (if such implementation existed)Note that when writing to the console, Environment.NewLine is not strictly necessary. The console stream will translate "\n"
to the appropriate new-line sequence, if necessary.
On OS X, where date
does not support the %N
flag, I recommend installing coreutils
using Homebrew. This will give you access to a command called gdate
that will behave as date
does on Linux systems.
brew install coreutils
For a more "native" experience, you can always add this to your .bash_aliases
:
alias date='gdate'
Then execute
$ date +%s%N
As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):
As much as we might hate to admit it, there are still no Windows PowerShell cmdlets from Microsoft that permit creating local user accounts or local user groups. We finally have a Desired State Configuration (DSC ) provider that can do this—but to date, no cmdlets.
The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>
The address could be something like
1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)
or simply
1600 Amphitheatre Parkway, Mountain View, CA
By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.
{"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4222556,
"lng" : -122.0838589
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4236045802915,
"lng" : -122.0825099197085
},
"southwest" : {
"lat" : 37.4209066197085,
"lng" : -122.0852078802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}],"status" : "OK"}
Web Frameworks such like AngularJS allow us to perform these queries with ease.
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
HTML5 has several goals which differentiate it from HTML4.
The primary one is consistent, defined error handling. As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed).
So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this.
The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas>
, <video>
, and <audio>
. Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript).
There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements (<strong>
and <em>
now actually mean something different, and even <b>
and <i>
have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article>
, <section>
, <header>
, <aside>
, and <nav>
should replace the majority of <div>
s used on a web page, making your pages a bit more semantic, but more importantly, easier to read. No more painful scanning to see just what that random </div>
is closing - instead you'll have an obvious </header>
, or </article>
, making the structure of your document much more intuitive.
If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:
launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"
To directly answer your question, you can add launchctl line in your ~/.bash_profile
As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.
ng-class
is a Directive of core AngularJs. In which you can use "String Syntax", "Array Syntax", "Evaluated Expression", " Ternary Operator" and many more options described below:
This is the simplest way to use ngClass. You can just add an Angular variable to ng-class and that is the class that will be used for that element.
<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">
<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!
Demo Example of ngClass Using String Syntax
This is similar to the string syntax method except you are able to apply multiple classes.
<!-- both input boxes below will be classes for the div -->
<input type="text" ng-model="styleOne">
<input type="text" ng-model="styleTwo">
<!-- this div will take on both classes from above -->
<div ng-class="[styleOne, styleTwo]">Look! I'm Words!
A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true
, you can apply a certain class. If not, then the class won't be applied.
<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?
<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">
Example of ngClass Using Evaluated Expression
This is similar to the evaluated expression method except you just able to compares multiple values with the only variable.
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:
ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
If you are using the ngRepeat
directive and you want to apply classes to the first
, last
, or a specific number in the list, you can use special properties of ngRepeat
. These include $first
, $last
, $even
, $odd
, and a few others. Here's an example of how to use these.
<!-- add a class to the first item -->
<ul>
<li ng-class="{ 'text-success': $first }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the last item -->
<ul>
<li ng-class="{ 'text-danger': $last }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the even items and a different class to the odd items -->
<ul>
<li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
Here is another way to do the same.
fadeIn effect
.visible {
visibility: visible;
opacity: 1;
transition: opacity 2s linear;
}
fadeOut effect
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
UPDATE 1:
I found more up-to-date tutorial CSS3 Transition: fadeIn and fadeOut like effects to hide show elements and Tooltip Example: Show Hide Hint or Help Text using CSS3 Transition here with sample code.
UPDATE 2:
(Added details requested by @big-money)
When showing the element (by switching to the visible class), we want the visibility:visible
to kick in instantly, so it’s ok to transition only the opacity property. And when hiding the element (by switching to the hidden class), we want to delay the visibility:hidden
declaration, so that we can see the fade-out transition first. We’re doing this by declaring a transition on the visibility property, with a 0s duration and a delay. You can see a detailed article here.
I know I am too late to answer but posting this answer to save others time. Hope it helps you!!
C# has a static constructor for this purpose.
static class YourClass
{
static YourClass()
{
// perform initialization here
}
}
From MSDN:
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced
.
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
Using ggpubr:
library(ggpubr)
# reproducible data
set.seed(1)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
# By default showing Pearson R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300) +
stat_regline_equation(label.y = 280)
# Use R2 instead of R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300,
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"))) +
stat_regline_equation(label.y = 280)
## compare R2 with accepted answer
# m <- lm(y ~ x, df)
# round(summary(m)$r.squared, 2)
# [1] 0.85
Modify "Workspace.xml" (press Ctrl + Shft + R to search it)
Modify the activity name with package name
Make sure to change "name="USE_COMMAND_LINE" to value="false"
Reload the project
Done!
I'd use something like:
dim customer = (from c in xmldoc...<Customer>
where c.<ID>.Value=22
select c).SingleOrDefault
Edit:
missed the c# tag, sorry......the example is in VB.NET
I ran into this myself and ended up with a solution, that is similar to several answers here, but implemented slightly differently. I didn't like many pieces of javascript, or a placeholder div somewhere. I wanted a generalized solution, that could then be used in HTML without adding javascript for each use. Here is what I came up with (this requires jquery ui):
Javascript:
$(function() {
$("a.confirm").button().click(function(e) {
e.preventDefault();
var target = $(this).attr("href");
var content = $(this).attr("title");
var title = $(this).attr("alt");
$('<div>' + content + '</div>'). dialog({
draggable: false,
modal: true,
resizable: false,
width: 'auto',
title: title,
buttons: {
"Confirm": function() {
window.location.href = target;
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
});
});
And then in HTML, no javascript calls or references are needed:
<a href="http://www.google.com/"
class="confirm"
alt="Confirm test"
title="Are you sure?">Test</a>
Since the title attribute is used for the div content, the user can even get the confirmation question by hovering over the button (which is why i didn't user the title attribute for the tile). The title of the confirmation window is the content of the alt tag. The javascript snip can be included in a generalized .js include, and simply by applying a class you have a pretty confirmation window.
The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)
After some trial and error, this gave me roughly what I wanted:
git log --graph --decorate --oneline --all ^master^!
This approach works well very till 2.3 And by adding hardwareaccelerated=true it even works from 3.0 to ICS One problem i am facing currently is upon second launch of media player application is getting crashed because i have not stopped playback and released Media player. As VideoSurfaceView object, which we get in onShowCustomView function from 3.0 OS, are specific to browser and not a VideoView object as in, till 2.3 OS How can i access it and stopPlayback and release resources?
As a specialisation of Greg's answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2:
>>> a= [0, 1, 2, 3, 4]
>>> del a[0:3:2]
>>> a
[1, 3, 4]
This doesn't cover any arbitrary selection, of course, but it can certainly work for deleting any two items.
Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read}
and all was fine.
I’ve been using ng cli lately, and it was really tough to find a good way to structure my code.
The most efficient one I've seen so far comes from mrholek repository (https://github.com/mrholek/CoreUI-Angular).
This folder structure allows you to keep your root project clean and structure your components, it avoids redundant (sometimes useless) naming convention of the official Style Guide.
Also it’s, this structure is useful to group import when it’s needed and avoid having 30 lines of import for a single file.
src
|
|___ app
|
| |___ components/shared
| | |___ header
| |
| |___ containers/layout
| | |___ layout1
| |
| |___ directives
| | |___ sidebar
| |
| |___ services
| | |___ *user.service.ts*
| |
| |___ guards
| | |___ *auth.guard.ts*
| |
| |___ views
| | |___ about
| |
| |___ *app.component.ts*
| |
| |___ *app.module.ts*
| |
| |___ *app.routing.ts*
|
|___ assets
|
|___ environments
|
|___ img
|
|___ scss
|
|___ *index.html*
|
|___ *main.ts*
Here is another solution that may be helpful to others. The code below selects a small number of rows and columns from a large data set. The columns are selected as in one of juba's answers except that I use a paste function to select a set of columns with names that are numbered sequentially:
df = read.table(text = "
state county city region mmatrix X1 X2 X3 A1 A2 A3 B1 B2 B3 C1 C2 C3
1 1 1 1 111010 1 0 0 2 20 200 4 8 12 NA NA NA
1 2 1 1 111010 1 0 0 4 NA 400 5 9 NA NA NA NA
1 1 2 1 111010 1 0 0 6 60 NA NA 10 14 NA NA NA
1 2 2 1 111010 1 0 0 NA 80 800 7 11 15 NA NA NA
1 1 3 2 111010 0 1 0 1 2 1 2 2 2 10 20 30
1 2 3 2 111010 0 1 0 2 NA 1 2 2 NA 40 50 NA
1 1 4 2 111010 0 1 0 1 1 NA NA 2 2 70 80 90
1 2 4 2 111010 0 1 0 NA 2 1 2 2 10 100 110 120
1 1 1 3 010010 0 0 1 10 20 10 200 200 200 1 2 3
1 2 1 3 001000 0 0 1 20 NA 10 200 200 200 4 5 9
1 1 2 3 101000 0 0 1 10 10 NA 200 200 200 7 8 NA
1 2 2 3 011010 0 0 1 NA 20 10 200 200 200 10 11 12
", sep = "", header = TRUE, stringsAsFactors = FALSE)
df
df2 <- df[df$region == 2, names(df) %in% c(paste("C", seq_along(1:3), sep=''))]
df2
# C1 C2 C3
# 5 10 20 30
# 6 40 50 NA
# 7 70 80 90
# 8 100 110 120