I came across this one while debugging a virtualmin/apache related error.
In my case, I am running virtualmin and had in my virtual machine's php.ini safe_mode=On.
In my Virtual Machine's error log, I was getting the fcgi Connection reset by peer: mod_fcgid: error reading data from FastCGI server
In my main apache error log I was getting: PHP Fatal error: Directive 'safe_mode' is no longer available in PHP in Unknown on line 0
In my case, I simply set safe_mode = Off in my php.ini and restarted apache.
stackoverflow.com/questions/18683177/where-to-start-with-deprecated-directive-safe-mode-on-line-0-in-apache-error
If you have SELinux running, you might have to grant httpd permission to read from /home dir using:
sudo setsebool httpd_read_user_content=1
Just to follow up, problem solved! I mentioned mod_sec settings for my server as being the possible culprit as suggested and they were able to fix this issue. Here's what the tech agent said to tell them when you go to support:
Just let them know you need the rule 340163 whitelisted for domain.com as its hitting a mod_sec rule.
Apparently you will need to do this for each domain that is having the issue, but it works. Thanks for all the suggestions everyone!
Where ever you use a <button>
element by default it considers that button type="submit"
so if you define the button type="button"
then it won't consider that <button>
as submit button.
One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource
and supply it with StringReader
.
String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException
) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)
You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
I recommend using the incredible requests
module.
http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
To set the range of the x-axis, you can use set_xlim(left, right)
, here are the docs
Update:
It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:
ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)
If your file idea/workspace.xml
is added to .gitignore (or its parent folder) just add
it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.
There are quite a few ways to check if a device is an iPad. This is my favorite way to check whether the device is in fact an iPad:
if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
return YES; /* Device is iPad */
}
#define IDIOM UI_USER_INTERFACE_IDIOM()
#define IPAD UIUserInterfaceIdiomPad
if ( IDIOM == IPAD ) {
/* do something specifically for iPad. */
} else {
/* do something specifically for iPhone or iPod touch. */
}
if ( [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] ) {
return YES; /* Device is iPad */
}
#define IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
if ( IPAD )
return YES;
For a Swift solution, see this answer: https://stackoverflow.com/a/27517536/2057171
var interval = $interval(function() {
console.log('say hello');
}, 1000);
$interval.cancel(interval);
You can use multiprocessing.Pool
:
from multiprocessing import Pool
class Engine(object):
def __init__(self, parameters):
self.parameters = parameters
def __call__(self, filename):
sci = fits.open(filename + '.fits')
manipulated = manipulate_image(sci, self.parameters)
return manipulated
try:
pool = Pool(8) # on 8 processors
engine = Engine(my_parameters)
data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
pool.close()
pool.join()
You can use the password_verify function with the PHP. It verifies that a password matches with the hash
password_verify ( string $password , string $hash ) : bool
more details: https://www.php.net/manual/en/function.password-verify.php
Try this command:
Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess
I:
partition of your Windows DVD.
You can use $anchorScroll
.
Just inject $anchorScroll
as a dependency, and call $anchorScroll()
whenever you want to scroll to top.
With Docker, the proper way to pass this sort of information is through environment variables.
So with the same Dockerfile, change the script to
#!/bin/bash
echo $FOO
After building, use the following docker command:
docker run -e FOO="hello world!" test
You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:
// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
final char[] buf = new char[32];
for (int i = 31; i >= 0; i--) {
buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
}
return new String(buf);
}
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Should be:
Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
Can't you just set left
to 50%
and then have margin-left
set to -25px
to account for it's width: http://jsfiddle.net/9AbYc/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 50%;
margin-left: -50px;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 0;
right: 0;
margin: 0 auto;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
Just adding some extra sorting if needed
=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)
if its mysql, you can try something like this.
select
(select count(*) from TABLENAME WHERE a = 'null') as total_null,
(select count(*) from TABLENAME WHERE a != 'null') as total_not_null
FROM TABLENAME
assert
is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if
statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug.
Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char
version.
You can create a stored procedure and put the table names in a cursor, then loop through your table names to show the data.
Getting started with stored procedure: http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx
Creating a cursor: http://www.mysqltutorial.org/mysql-cursor/
For example,
CREATE PROCEDURE `ShowFromTables`()
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE c_table varchar(100) DEFAULT "";
DECLARE table_cursor CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_name like 'wp_1%';
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN table_cursor;
get_data: LOOP
FETCH table_cursor INTO c_table;
IF v_finished = 1 THEN
LEAVE get_data;
END IF;
SET @s=CONCAT("SELECT * FROM ",c_table,";");
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP get_data;
CLOSE table_cursor;
END
Then call the stored procedure:
CALL ShowFromTables();
First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties
. In a WAR, WEB-INF/classes
is a classpath entry, so it will work just fine.
After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties
:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
There's usually not any reason to define them separately, though.
If you've installed .NET framework 4.6, you may see this error due to a VS bug. Workarounds and resolutions here:
EDIT:
As noted in some of the comments, this can happen behind the scenes after upgrading to Windows 10 or Visual Studio 2015.
As per the comment by Cody, this has nothing to do with Linux, but is a hint to the compiler. What happens will depend on the architecture and compiler version.
This particular feature in Linux is somewhat mis-used in drivers. As osgx points out in semantics of hot attribute, any hot
or cold
function called with in a block can automatically hint that the condition is likely or not. For instance, dump_stack()
is marked cold
so this is redundant,
if(unlikely(err)) {
printk("Driver error found. %d\n", err);
dump_stack();
}
Future versions of gcc
may selectively inline a function based on these hints. There have also been suggestions that it is not boolean
, but a score as in most likely, etc. Generally, it should be preferred to use some alternate mechanism like cold
. There is no reason to use it in any place but hot paths. What a compiler will do on one architecture can be completely different on another.
OR you could just use javac file1.java
and then also use javac file2.java
afterwards.
Try using this library: https://github.com/jakiestfu/Blur.js-II
That should do it for ya.
My understanding is if you set controls.Visible = false
during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server
. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false
. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false
, it doesn't get rendered in the client response.
Look in the MySQL config file C:\xampp\mysql\bin\my.ini
.
At the top of that file are some comments:
# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.
There it tells you where to find your .my.cnf
file.
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
self.window.rootViewController = [storyboard instantiateInitialViewController];
Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26
A general version:
$parts = explode($start, $full, 2);
if ($parts[0] === '') {
$end = $parts[1];
} else {
$fail = true;
}
Some benchmarks:
<?php
$iters = 100000;
$start = "/aaaaaaa/bbbbbbbbbb";
$full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee";
$end = '';
$fail = false;
$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
if (strpos($full, $start) === 0) {
$end = substr($full, strlen($start));
} else {
$fail = true;
}
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "strpos+strlen", $t);
$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
$parts = explode($start, $full, 2);
if ($parts[0] === '') {
$end = $parts[1];
} else {
$fail = true;
}
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "explode", $t);
On my quite old home PC:
$ php bench.php
Outputs:
strpos+strlen : 0.158388 s
explode : 0.126772 s
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); return des.data.Count.ToString();
In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.
If I was to be the designer of Python3, I will:
That should be optimal.
A slightly more elegant way, adapting Greg Dean's function:
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
Call it like:
"pascal".toProperCase();
Try the following.
string input = "someString";
string[] toSearchFor = GetSearchStrings();
var containsAll = toSearchFor.All(x => input.Contains(x));
Try to connect with the users in SQL Plus, whose password has expired. it will prompt for the new password. Enter the new password and confirm password.
It will work
I believe
rgba( 0, 0, 0, 0.8 )
is equivalent in shade with #333
.
Live demo: http://jsfiddle.net/8MVC5/1/
match_parent is used in place of fill_parent and sets it to go as far as the parent goes. Just use match_parent and forget about fill_parent. I completely ditched fill_parent and everything is perfect as usual.
Check here for more.
Post both multiple text inputs plus multiple files via Ajax in one Ajax request
HTML
<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">
Jquery Code
$(document).on('click','#btnSendData',function (event) {
event.preventDefault();
var form = $('#myform')[0];
var formData = new FormData(form);
// Set header if need any otherwise remove setup part
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
url: "{{route('sendFormWithImage')}}",// your request url
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log(data);
},
error: function () {
}
});
});
Pekka has the correct answer (hence my making this answer a Community Wiki): Use src
, not href
, to specify the file.
Regarding:
When i try it this way:
<script type="text/javascript"> document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>'); </script>the first tag in the document.write function closes
what is the correct way to do this?
You don't want or need document.write
for this, but just in case you ever do need to put the characters </script>
inside a script
tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>
. There are a couple of ways of doing that. One way is to escape the /
even though you don't need to:
<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
// ^--- note the seemingly-unnecessary backslash
</script>
Or if you're feeling more paranoid:
<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>
...since in each case, JavaScript sees the string as </script>
but the HTML parser doesn't.
Maintain an array which stores data in the cellforindexPath
method itself :-
[arryname objectAtIndex:indexPath.row];
Using same code in the didselectaAtIndexPath
method too.. Good luck :)
Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.
more information check this article class and object keyword in scala programming
Instead of flex: 1 0 auto
just use flex: 1
main, aside, article {_x000D_
margin: 10px;_x000D_
border: solid 1px #000;_x000D_
border-bottom: 0;_x000D_
height: 50px;_x000D_
}_x000D_
main {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
flex: 1;_x000D_
}
_x000D_
<main>_x000D_
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
Just one note I could not find in the answers above. In this code:
context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)
What the third parameter context_instance
actually does? Being RequestContext it sets up some basic context which is then added to user_context
. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS
in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user
and variable perm
which are then accessible in the template.
In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.
Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.
Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.
Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.
It's very simple:
foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}
Very simply, a delegate provides functionality for how a function pointer SHOULD work. There are many limitations of function pointers in C++. A delegate uses some behind-the-scenes template nastyness to create a template-class function-pointer-type-thing that works in the way you might want it to.
ie - you can set them to point at a given function and you can pass them around and call them whenever and wherever you like.
There are some very good examples here:
Take a look at GregorianCalendar
, something like:
final Calendar now = GregorianCalendar.getInstance()
final int dayNumber = now.get(Calendar.DAY_OF_MONTH);
Use Arrays
class in Java which will return you an ArrayList
:
final List<String> characters = Arrays.asList("+","-");
You will need a bit more work if you need a List<Character>
.
Here is a function I use to execute sql commands. You just have to change $sqlCommand.CommandText to the name of your sproc and $SqlCommand.CommandType to CommandType.StoredProcedure.
function execute-Sql{
param($server, $db, $sql )
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db
$sqlConnection.Open()
$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandTimeout = 120
$sqlCommand.Connection = $sqlConnection
$sqlCommand.CommandText= $sql
$text = $sql.Substring(0, 50)
Write-Progress -Activity "Executing SQL" -Status "Executing SQL => $text..."
Write-Host "Executing SQL => $text..."
$result = $sqlCommand.ExecuteNonQuery()
$sqlConnection.Close()
}
I had the same issue with one of my netbeans project.
Check whether you have correctly put the package name on all the classes. I got the same error message because i forgot to put the package name of a certain class (which was copied from another project).
The .cpp
file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".
If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.
Try the below code:
$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);
Use this code to remove the last character of the string.
Another option to undo changes that weren't staged for commit is to run:
git restore <file>
To discard changes in the working directory.
You can use unirest, It provides easy method to post request. `
import unirest
def callback(response):
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# consume async post request
def consumePOSTRequestASync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
unirest.post(url, headers = headers,params = params, callback = callback)
# post async request multipart/form-data
consumePOSTRequestASync()
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection
, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection
.
public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
private void Handle(object sender, PropertyChangedEventArgs args)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (object t in e.NewItems) {
((T) t).PropertyChanged += Handle;
}
}
if (e.OldItems != null) {
foreach (object t in e.OldItems) {
((T) t).PropertyChanged -= Handle;
}
}
base.OnCollectionChanged(e);
}
While Items are added or removed the class forwards the items PropertyChanged
event to the collections PropertyChanged
event.
usage:
public abstract class ParameterBase : INotifyPropertyChanged
{
protected readonly CultureInfo Ci = new CultureInfo("en-US");
private string _value;
public string Value {
get { return _value; }
set {
if (value == _value) return;
_value = value;
OnPropertyChanged();
}
}
}
public class AItem {
public NotifyObservableCollection<ParameterBase> Parameters {
get { return _parameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_parameters != null) _parameters.CollectionChanged -= cceh;
_parameters = value;
//needed for Binding to AItem at xaml directly
_parameters.CollectionChanged += cceh;
}
}
public NotifyObservableCollection<ParameterBase> DefaultParameters {
get { return _defaultParameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
_defaultParameters = value;
//needed for Binding to AItem at xaml directly
_defaultParameters.CollectionChanged += cceh;
}
}
public class MyViewModel {
public NotifyObservableCollection<AItem> DataItems { get; set; }
}
If now a property of an item in DataItems
changes, the following xaml will get a notification, though it binds to Parameters[0]
or to the item itself except to the changing property Value
of the item (Converters at Triggers are called reliable on every change).
<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Aqua" />
<Style.Triggers>
<DataTrigger Value="False">
<!-- Bind to Items with changing properties -->
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ParameterCompareConverter}">
<Binding Path="DefaultParameters[0]" />
<Binding Path="Parameters[0]" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="DeepPink" />
</DataTrigger>
<!-- Binds to AItem directly -->
<DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
<Setter Property="FontWeight" Value="ExtraBold" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
You can access characters in strings in the same way as you would access an array index, e.g.
$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
$thisWordCodeVerdeeld[$i] = $string[$i];
}
You could also do:
$thisWordCodeVerdeeld = str_split($string);
However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.
when you have one certificate and 2 different web servers here how I fixed it:
I solved it through googling:
var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception,
// the 'param' must consist of more than 12 characters.
User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]},
function(err,docs){
if(!err) res.send(docs);
});
I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:
$(document).ready(function(){}
is being called after you have loaded the JQuery library
Are you asking in php or javascript.
If it is in php, give the name of that and use the post or get method, after that you can use the option of isset or that particular button name is checked to that value.
If it is in js, use getElementById for that
When you have several words like this which you want to concatenate in a string, I recommend using format
or f-strings
which increase readability dramatically (in my opinion).
To give an example:
s = "a word that needs quotation marks"
s2 = "another word"
Now you can do
print('"{}" and "{}"'.format(s, s2))
which will print
"a word that needs quotation marks" and "another word"
As of Python 3.6 you can use:
print(f'"{s}" and "{s2}"')
yielding the same output.
Another solution could be using in JSP:
<input type="hidden" id="jsonBom" value='${jsonBom}'/>
and getting the value in Javascript with jQuery:
var jsonBom = $('#jsonBom').val();
When you have own struct
, you could have own convert-to-string function.
package main
import (
"fmt"
)
type Color struct {
Red int `json:"red"`
Green int `json:"green"`
Blue int `json:"blue"`
}
func (c Color) String() string {
return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}
func main() {
c := Color{Red: 123, Green: 11, Blue: 34}
fmt.Println(c) //[123, 11, 34]
}
using jquery $.each
you can access all data and also set in table like this
<table style="width: 100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Category</th>
<th>Color</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "</tr>";
$('#tbody').append(eachrow);
});
Maybe you can wrap the PowerShell invocation in a .bat
file like so:
rem ps.bat
@echo off
powershell.exe -command "%*"
If you then placed this file under a folder in your PATH
, you could call PowerShell scripts like this:
ps foo 1 2 3
Quoting can get a little messy, though:
ps write-host """hello from cmd!""" -foregroundcolor green
EDIT 2020
From npm v7.0.0, npm automatically installs peer dependencies. It is one of the reasons to upgrade to v7.
https://github.blog/2020-10-13-presenting-v7-0-0-of-the-npm-cli/
Also this page explains the rationale of peer dependencies very well. https://github.com/npm/rfcs/blob/latest/implemented/0025-install-peer-deps.md
This answer doesn’t apply all cases, but if you can’t solve the error by simply typing npm install
, this steps might help.
Let`s say you got this error.
UNMET PEER DEPENDENCY [email protected]
npm WARN [email protected] requires a peer of packageA@^3.1.0 but none was installed.
This means you installed version 4.2.0 of packageA, but [email protected] needs version 3.x.x of pakageA. (explanation of ^)
So you can resolve this error by downgrading packageA to 3.x.x, but usually you don`t want to downgrade the package.
Good news is that in some cases, packageB is just not keeping up with packageA and maintainer of packageB is trying hard to raise the peer dependency of packageA to 4.x.x.
In that case, you can check if there is a higher version of packageB that requires version 4.2.0 of packageA in the npm or github.
For example, Go to release page
Oftentimes you can find breaking change about dependency like this.
packageB v4.0.0-beta.0
BREAKING CHANGE
package: requires packageA >= v4.0.0
If you don’t find anything on release page, go to issue page and search issue by keyword like peer
. You may find useful information.
At this point, you have two options.
If you choose option1:
In many cases, the version does not have latest
tag thus not stable. So you have to check what has changed in this update and make sure anything won`t break.
If you choose option2:
If upgrade of pakageA from version 3 to 4 is trivial, or if maintainer of pakageB didn’t test version 4 of pakageA yet but says it should be no problem, you may consider leaving the error.
In both case, it is best to thoroughly test if it does not break anything.
Lastly, if you wanna know why you have to manually do such a thing, this link explains well.
Configure static ip for your laptop and raspberry pi. On the rapberryPI configure it as following.
pi@rpi>sudo nano /etc/network/interfaces
Then configure following as required to connect to your laptop.
iface eth0 inet static
address 192.168.1.81
netmask 255.255.255.0
broadcast 192.168.1.255
The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.
// this will return HttpResponseMessage as IHttpActionResult
return ResponseMessage(httpResponseMessage);
As others already mentioned, the package manager Bower, that was usually used for dependencies like this in application that do not rely on heavy client-side scripting, is on the way out and actively recommending to move to other solutions:
..psst! While Bower is maintained, we recommend yarn and webpack for new front-end projects!
So although you can still use it right now, Bootstrap has also announced to drop support for it. As a result, the built-in ASP.NET Core templates are slowly being edited to move away from it too.
Unfortunately, there is no clear path forward. This is mostly due to the fact that web applications are continuously moving further into the client-side, requiring complex client-side build systems and many dependencies. So if you are building something like that, you might already know how to solve this then, and you can expand your existing build process to simply also include Bootstrap and jQuery there.
But there are still many web applications out there that are not that heavy on the client-side, where the application still runs mainly on the server and the server serves static views as a result. Bower previously filled this by making it easy to just publish client-side dependencies without that much of a process.
In the .NET world we also have NuGet and with previous ASP.NET versions, we could use NuGet as well to add dependencies to some client-side dependencies since NuGet would just place the content into our project correctly. Unfortunately, with the new .csproj
format and the new NuGet, installed packages are located outside of our project, so we cannot simply reference those.
This leaves us with a few options how to add our dependencies:
This is what the ASP.NET Core templates, that are not single-page applications, are currently doing. When you use those to create a new application, the wwwroot
folder simply contains a folder lib
that contains the dependencies:
If you look closely at the files currently, you can see that they were originally placed there with Bower to create the template, but that is likely to change soon. The basic idea is that the files are copied once to the wwwroot
folder so you can depend on them.
To do this, we can simply follow Bootstrap’s introduction and download the compiled files directly. As mentioned on the download site, this does not include jQuery, so we need to download that separately too; it does contain Popper.js though if we choose to use the bootstrap.bundle
file later—which we will do. For jQuery, we can simply get a single “compressed, production” file from the download site (right-click the link and select "Save link as..." from the menu).
This leaves us with a few files which will simply extract and copy into the wwwroot
folder. We can also make a lib
folder to make it clearer that these are external dependencies:
That’s all we need, so now we just need to adjust our _Layout.cshtml
file to include those dependencies. For that, we add the following block to the <head>
:
<environment include="Development">
<link rel="stylesheet" href="~/lib/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="~/lib/css/bootstrap.min.css" />
</environment>
And the following block at the very end of the <body>
:
<environment include="Development">
<script src="~/lib/js/jquery-3.3.1.js"></script>
<script src="~/lib/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/js/jquery-3.3.1.min.js"></script>
<script src="~/lib/js/bootstrap.bundle.min.js"></script>
</environment>
You can also just include the minified versions and skip the <environment>
tag helpers here to make it a bit simpler. But that’s all you need to do to keep you starting.
The more modern way, also if you want to keep your dependencies updated, would be to get the dependencies from the NPM package repository. You can use either NPM or Yarn for this; in my example, I’ll use NPM.
To start off, we need to create a package.json
file for our project, so we can specify our dependencies. To do this, we simply do that from the “Add New Item” dialog:
Once we have that, we need to edit it to include our dependencies. It should something look like this:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.0.0",
"jquery": "3.3.1",
"popper.js": "1.12.9"
}
}
By saving, Visual Studio will already run NPM to install the dependencies for us. They will be installed into the node_modules
folder. So what is left to do is to get the files from there into our wwwroot
folder. There are a few options to do that:
bundleconfig.json
for bundling and minificationWe can use one of the various ways to consume a bundleconfig.json
for bundling and minification, as explained in the documentation. A very easy way is to simply use the BuildBundlerMinifier NuGet package which automatically sets up a build task for this.
After installing that package, we need to create a bundleconfig.json
at the root of the project with the following contents:
[
{
"outputFileName": "wwwroot/vendor.min.css",
"inputFiles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"minify": { "enabled": false }
},
{
"outputFileName": "wwwroot/vendor.min.js",
"inputFiles": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"minify": { "enabled": false }
}
]
This basically configures which files to combine into what. And when we build, we can see that the vendor.min.css
and vendor.js.css
are created correctly. So all we need to do is to adjust our _Layouts.html
again to include those files:
<!-- inside <head> -->
<link rel="stylesheet" href="~/vendor.min.css" />
<!-- at the end of <body> -->
<script src="~/vendor.min.js"></script>
If we want to move a bit more into client-side development, we can also start to use tools that we would use there. For example Webpack which is a very commonly used build tool for really everything. But we can also start with a simpler task manager like Gulp and do the few necessary steps ourselves.
For that, we add a gulpfile.js
into our project root, with the following contents:
const gulp = require('gulp');
const concat = require('gulp-concat');
const vendorStyles = [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
];
const vendorScripts = [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
];
gulp.task('build-vendor-css', () => {
return gulp.src(vendorStyles)
.pipe(concat('vendor.min.css'))
.pipe(gulp.dest('wwwroot'));
});
gulp.task('build-vendor-js', () => {
return gulp.src(vendorScripts)
.pipe(concat('vendor.min.js'))
.pipe(gulp.dest('wwwroot'));
});
gulp.task('build-vendor', gulp.parallel('build-vendor-css', 'build-vendor-js'));
gulp.task('default', gulp.series('build-vendor'));
Now, we also need to adjust our package.json
to have dependencies on gulp
and gulp-concat
:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.0.0",
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"jquery": "3.3.1",
"popper.js": "1.12.9"
}
}
Finally, we edit our .csproj
to add the following task which makes sure that our Gulp task runs when we build the project:
<Target Name="RunGulp" BeforeTargets="Build">
<Exec Command="node_modules\.bin\gulp.cmd" />
</Target>
Now, when we build, the default
Gulp task runs, which runs the build-vendor
tasks, which then builds our vendor.min.css
and vendor.min.js
just like we did before. So after adjusting our _Layout.cshtml
just like above, we can make use of jQuery and Bootstrap.
While the initial setup of Gulp is a bit more complicated than the bundleconfig.json
one above, we have now have entered the Node-world and can start to make use of all the other cool tools there. So it might be worth to start with this.
While this suddenly got a lot more complicated than with just using Bower, we also do gain a lot of control with those new options. For example, we can now decide what files are actually included within the wwwroot
folder and how those exactly look like. And we also can use this to make the first moves into the client-side development world with Node which at least should help a bit with the learning curve.
Try:
//category[@name='Sport' and ./author/text()='James Small']
One subtle but significant difference is in the way the two libraries approach scope. Mustache will fall back to parent scope if it can't find a variable within the current context; Handlebars will return a blank string.
This is barely mentioned in the GitHub README, where there's one line for it:
Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default.
However, as noted there, there is a flag to make Handlebars behave in the same way as Mustache -- but it affects performance.
This has an effect on the way you can use #
variables as conditionals.
For example in Mustache you can do this:
{{#variable}}<span class="text">{{variable}}</span>{{/variable}}
It basically means "if variable exists and is truthy, print a span with the variable in it". But in Handlebars, you would either have to:
{{this}}
instead{{../variable}}
to get back out to relevant scopevariable
value within the parent variable
objectMore details on this, if you want them, here.
This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.
from u in Users
join c in (
from crt in CompanyRolesToUsers
where CompanyRoleId == 2
|| CompanyRoleId == 3
|| CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;
Try using another temporary pair:
pair<string,double> temp;
vector<pair<string,double>> revenue;
// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);
I'll vote for sb.setLength(0);
not only because it's one function call, but because it doesn't actually copy the array into another array like sb.delete(0, builder.length());
. It just fill the remaining characters to be 0 and set the length variable to the new length.
You can take a look into their implementation to validate my point from here at setLength
function and delete0
function.
git diff > patchfile
and
patch -p1 < patchfile
work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile
if you need handle file adds, deletes and renames.
EDIT December 2015
Latest versions of patch
command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).
So provided one uses current/latest version of patch
there is no need to use git
to be able to apply its diff as a patch.
This is what I needed:
public static byte[] encode(byte[] arr, String fromCharsetName) {
return encode(arr, Charset.forName(fromCharsetName), Charset.forName("UTF-8"));
}
public static byte[] encode(byte[] arr, String fromCharsetName, String targetCharsetName) {
return encode(arr, Charset.forName(fromCharsetName), Charset.forName(targetCharsetName));
}
public static byte[] encode(byte[] arr, Charset sourceCharset, Charset targetCharset) {
ByteBuffer inputBuffer = ByteBuffer.wrap( arr );
CharBuffer data = sourceCharset.decode(inputBuffer);
ByteBuffer outputBuffer = targetCharset.encode(data);
byte[] outputData = outputBuffer.array();
return outputData;
}
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected: The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'. The output of jQuery code with val() will the file name that you selected.
Explanation: Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
You need to pass your components as children, like this:
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
<App>
<SampleComponent name="SomeName"/>
<App>,
document.body
);
And then append them in the component's body:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
{
this.props.children
}
</div>
);
}
});
You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:
var App = React.createClass({
getInitialState: function(){
return [
{id:1,name:"Some Name"}
]
},
addChild: function() {
// State change will cause component re-render
this.setState(this.state.concat([
{id:2,name:"Another Name"}
]))
}
render: function() {
return (
<div>
<h1>App main component! </h1>
<button onClick={this.addChild}>Add component</button>
{
this.state.map((item) => (
<SampleComponent key={item.id} name={item.name}/>
))
}
</div>
);
}
});
How to print on the same line:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm
as well as specifying norm
as an argument to scatter
and colorbar
. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list
.
Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1
, e.g., has 9 easily distinguishable colors, and tab20
could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.
import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)
which produces the image below. The n
in the call to Set1
specifies
the first n
colors of that colormap, and the last n
in the call to from_list
specifies to construct a map with n
colors (the default being 256). In order to set cm
as the default colormap with plt.set_cmap
, I found it to be necessary to give it a name and register it, viz:
cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)
jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:
$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });
Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.
Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.
That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.
The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.
Reference: https://developers.google.com/youtube/iframe_api_reference
sass --watch a.scss:a.css --style compressed
Consult the documentation for updates:
This is @Ben's answer updated for use with Ember...note you have to use Ember.get
because context is passed in as a String.
Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
var newContext = Ember.get(this, context);
for(var prop in newContext)
{
if (newContext.hasOwnProperty(prop)) {
ret = ret + options.fn({property:prop,value:newContext[prop]});
}
}
return ret;
});
Template:
{{#eachProperty object}}
{{key}}: {{value}}<br/>
{{/eachProperty }}
For me what did the trick was running the command
git config auto.crlf false
inside the folder of the project, I wanted it specifically for one project.
That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines
[auto]
crlf = false
at the end of the file. I suppose changing the file does the same trick as well.
This can also be done in the SDK for example python. If you already have a container built you can lookup the name via console ( docker ps -a
) name seems to be some concatenation of a scientist and an adjective (i.e. "relaxed_pasteur").
Check out help(container.get_archive)
:
Help on method get_archive in module docker.models.containers:
get_archive(path, chunk_size=2097152) method of docker.models.containers.Container instance
Retrieve a file or folder from the container in the form of a tar
archive.
Args:
path (str): Path to the file or folder to retrieve
chunk_size (int): The number of bytes returned by each iteration
of the generator. If ``None``, data will be streamed as it is
received. Default: 2 MB
Returns:
(tuple): First element is a raw tar data stream. Second element is
a dict containing ``stat`` information on the specified ``path``.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> f = open('./sh_bin.tar', 'wb')
>>> bits, stat = container.get_archive('/bin/sh')
>>> print(stat)
{'name': 'sh', 'size': 1075464, 'mode': 493,
'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}
>>> for chunk in bits:
... f.write(chunk)
>>> f.close()
So then something like this will pull out from the specified path ( /output) in the container to your host machine and unpack the tar.
import docker
import os
import tarfile
# Docker client
client = docker.from_env()
#container object
container = client.containers.get("relaxed_pasteur")
#setup tar to write bits to
f = open(os.path.join(os.getcwd(),"output.tar"),"wb")
#get the bits
bits, stat = container.get_archive('/output')
#write the bits
for chunk in bits:
f.write(chunk)
f.close()
#unpack
tar = tarfile.open("output.tar")
tar.extractall()
tar.close()
You want to use str.partition()
:
>>> my_string.partition("world")[2]
" , i'm a beginner "
because this option is faster than the alternatives.
Note that this produces an empty string if the delimiter is missing:
>>> my_string.partition("Monty")[2] # delimiter missing
''
If you want to have the original string, then test if the second value returned from str.partition()
is non-empty:
prefix, success, result = my_string.partition(delimiter)
if not success: result = prefix
You could also use str.split()
with a limit of 1:
>>> my_string.split("world", 1)[-1]
" , i'm a beginner "
>>> my_string.split("Monty", 1)[-1] # delimiter missing
"hello python world , i'm a beginner "
However, this option is slower. For a best-case scenario, str.partition()
is easily about 15% faster compared to str.split()
:
missing first lower upper last
str.partition(...)[2]: [3.745 usec] [0.434 usec] [1.533 usec] <3.543 usec> [4.075 usec]
str.partition(...) and test: 3.793 usec 0.445 usec 1.597 usec 3.208 usec 4.170 usec
str.split(..., 1)[-1]: <3.817 usec> <0.518 usec> <1.632 usec> [3.191 usec] <4.173 usec>
% best vs worst: 1.9% 16.2% 6.1% 9.9% 2.3%
This shows timings per execution with inputs here the delimiter is either missing (worst-case scenario), placed first (best case scenario), or in the lower half, upper half or last position. The fastest time is marked with [...]
and <...>
marks the worst.
The above table is produced by a comprehensive time trial for all three options, produced below. I ran the tests on Python 3.7.4 on a 2017 model 15" Macbook Pro with 2.9 GHz Intel Core i7 and 16 GB ram.
This script generates random sentences with and without the randomly selected delimiter present, and if present, at different positions in the generated sentence, runs the tests in random order with repeats (producing the fairest results accounting for random OS events taking place during testing), and then prints a table of the results:
import random
from itertools import product
from operator import itemgetter
from pathlib import Path
from timeit import Timer
setup = "from __main__ import sentence as s, delimiter as d"
tests = {
"str.partition(...)[2]": "r = s.partition(d)[2]",
"str.partition(...) and test": (
"prefix, success, result = s.partition(d)\n"
"if not success: result = prefix"
),
"str.split(..., 1)[-1]": "r = s.split(d, 1)[-1]",
}
placement = "missing first lower upper last".split()
delimiter_count = 3
wordfile = Path("/usr/dict/words") # Linux
if not wordfile.exists():
# macos
wordfile = Path("/usr/share/dict/words")
words = [w.strip() for w in wordfile.open()]
def gen_sentence(delimiter, where="missing", l=1000):
"""Generate a random sentence of length l
The delimiter is incorporated according to the value of where:
"missing": no delimiter
"first": delimiter is the first word
"lower": delimiter is present in the first half
"upper": delimiter is present in the second half
"last": delimiter is the last word
"""
possible = [w for w in words if delimiter not in w]
sentence = random.choices(possible, k=l)
half = l // 2
if where == "first":
# best case, at the start
sentence[0] = delimiter
elif where == "lower":
# lower half
sentence[random.randrange(1, half)] = delimiter
elif where == "upper":
sentence[random.randrange(half, l)] = delimiter
elif where == "last":
sentence[-1] = delimiter
# else: worst case, no delimiter
return " ".join(sentence)
delimiters = random.choices(words, k=delimiter_count)
timings = {}
sentences = [
# where, delimiter, sentence
(w, d, gen_sentence(d, w)) for d, w in product(delimiters, placement)
]
test_mix = [
# label, test, where, delimiter sentence
(*t, *s) for t, s in product(tests.items(), sentences)
]
random.shuffle(test_mix)
for i, (label, test, where, delimiter, sentence) in enumerate(test_mix, 1):
print(f"\rRunning timed tests, {i:2d}/{len(test_mix)}", end="")
t = Timer(test, setup)
number, _ = t.autorange()
results = t.repeat(5, number)
# best time for this specific random sentence and placement
timings.setdefault(
label, {}
).setdefault(
where, []
).append(min(dt / number for dt in results))
print()
scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
width = max(map(len, timings))
rows = []
bestrow = dict.fromkeys(placement, (float("inf"), None))
worstrow = dict.fromkeys(placement, (float("-inf"), None))
for row, label in enumerate(tests):
columns = []
worst = float("-inf")
for p in placement:
timing = min(timings[label][p])
if timing < bestrow[p][0]:
bestrow[p] = (timing, row)
if timing > worstrow[p][0]:
worstrow[p] = (timing, row)
worst = max(timing, worst)
columns.append(timing)
scale, unit = next((s, u) for s, u in scales if worst >= s)
rows.append(
[f"{label:>{width}}:", *(f" {c / scale:.3f} {unit} " for c in columns)]
)
colwidth = max(len(c) for r in rows for c in r[1:])
print(' ' * (width + 1), *(p.center(colwidth) for p in placement), sep=" ")
for r, row in enumerate(rows):
for c, p in enumerate(placement, 1):
if bestrow[p][1] == r:
row[c] = f"[{row[c][1:-1]}]"
elif worstrow[p][1] == r:
row[c] = f"<{row[c][1:-1]}>"
print(*row, sep=" ")
percentages = []
for p in placement:
best, worst = bestrow[p][0], worstrow[p][0]
ratio = ((worst - best) / worst)
percentages.append(f"{ratio:{colwidth - 1}.1%} ")
print("% best vs worst:".rjust(width + 1), *percentages, sep=" ")
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).
printf("%llu", 285212672);
Correct answer is:
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
data = {};
});
You need to flush the 'data' array.
data = {};
Same as @Sanchit Gupta.
in this part
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
x.innerHTML = "city name is: " + city;
}
just console the results array
if (results[0]) {
console.log(results[0]);
// choose from console whatever you need.
var city = results[0].address_components[3].short_name;
x.innerHTML = "city name is: " + city;
}
We can simply state that when a superclass is inherited, then the private members of superclass actually become private members of the subclass and cannot be further inherited or are inacessible to the objects of subclass.
I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:
public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public VndApiJsonMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
}
}
Which can be used simply like the following:
HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");
List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());
var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
Super simple and works exactly as I expected.
You can avoid compiler warning with workarounds like this one:
List<?> resultRaw = query.list();
List<MyObj> result = new ArrayList<MyObj>(resultRaw.size());
for (Object o : resultRaw) {
result.add((MyObj) o);
}
But there are some issues with this code:
And the difference is only cosmetic, so using such workarounds is - in my opinion - pointless.
You have to live with these warnings or suppress them.
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
Try this:
{[0-9]{1,3}:[0-9]{1,3}}
The {1,3}
means "match between 1 and 3 of the preceding characters".
my_list = sorted(dict.items(), key=lambda x: x[1])
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
SELECT (
SELECT COUNT(*)
FROM user_table
) AS tot_user,
(
SELECT COUNT(*)
FROM cat_table
) AS tot_cat,
(
SELECT COUNT(*)
FROM course_table
) AS tot_course
Hopefully this may help, and hopefully I'll get to try this during the week.
I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.
Just add a new empty directory that path is “/Users/username/Library/Android/sdk”. Then reopen it.
pack_forget
and grid_forget
will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy
method.
To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.
Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.
We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"
You essentially have two options:
Do exactly what you're currently doing, but call graph1.clear()
and graph2.clear()
before replotting the data. This is the slowest, but most simplest and most robust option.
Instead of replotting, you can just update the data of the plot objects. You'll need to make some changes in your code, but this should be much, much faster than replotting things every time. However, the shape of the data that you're plotting can't change, and if the range of your data is changing, you'll need to manually reset the x and y axis limits.
To give an example of the second option:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)
# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
for phase in np.linspace(0, 10*np.pi, 500):
line1.set_ydata(np.sin(x + phase))
fig.canvas.draw()
fig.canvas.flush_events()
Your data
variable contains an object, not an array, and objects do not have the push
function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
Use addToBackStack method when replacing one fragment by another:
getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("my_fragment").commit();
Then in your activity, use the following code to go back from a fragment to another (the previous one).
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Here are both fixes.
First, regarding the fixed sidebar, you need to give it a height for it to overflow:
HTML Code:
<div id="sidebar">Menu</div>
<div id="content">Text</div>
CSS Code:
body {font:76%/150% Arial, Helvetica, sans-serif; color:#666; width:100%; height:100%;}
#sidebar {position:fixed; top:0; left:0; width:20%; height:100%; background:#EEE; overflow:auto;}
#content {width:80%; padding-left:20%;}
@media screen and (max-height:200px){
#sidebar {color:blue; font-size:50%;}
}
Live example: http://jsfiddle.net/RWxGX/3/
It's impossible NOT to get a scroll bar if your content overflows the height of the div. That's why I've added a media query for screen height. Maybe you can adjust your styles for short screen sizes so the scroll doesn't need to appear.
Cheers, Ignacio
You can do this in two ways:
ElementMatch - $elemMatch
(as explained in above answers)
db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })
Use $and
with find
db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})
This may also happen if your JSON file is not just 1 JSON record. A JSON record looks like this:
[{"some data": value, "next key": "another value"}]
It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ]. If your json file contains more than one of those:
[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]
then loads() will fail.
I verified this with my own file that was failing.
import json
guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)
This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.
Error was
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)
PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.
In addition to the correct answer by mdma, you can also use the mail command as follows:
mail [email protected] -s"Subject Here" -a"Content-Type: text/html; charset=\"us-ascii\""
you will get what you're looking for. Don't forget to put <HTML>
and </HTML>
in the email. Here's a quick script I use to email a daily report in HTML:
#!/bin/sh
(cat /path/to/tomorrow.txt mysql -h mysqlserver -u user -pPassword Database -H -e "select statement;" echo "</HTML>") | mail [email protected] -s"Tomorrow's orders as of now" -a"Content-Type: text/html; charset=\"us-ascii\""
I got this problem while using Bootstrap and I had multiple columns in each rows.
I was trying to give page-break-inside: avoid;
or break-inside: avoid;
to the col-md-6
div elements. That was not working.
I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;
.
Instead, I had to give page-break-inside: avoid;
or break-inside: avoid;
to the <div class="row">
element. And I had multiple rows in my print page.
That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.
In another example case, if you want 4 columns in each row, then use col-md-3
.
builder.setCancelable(false);
public void Mensaje(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("¿Quieres ir a el Menú principal?");
builder.setMessage("Al presionar SI iras a el menú y saldras de la materia.");
builder.setPositiveButton("SI", null);
builder.setNegativeButton("NO", null);
builder.setCancelable(false);
builder.show();
}
It seems to me, that it is by design that this file is empty.
A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf
So, you should have a look for /etc/apache2/apache2.conf
Use a list comprehension (this is the way to go in pure Python):
>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]
Or numpy (a well-established module):
>>> numpy.array([1, 2, 3, 4])**2
array([ 1, 4, 9, 16])
In numpy
, math operations on arrays are, by default, executed element-wise. That's why you can **2
an entire array there.
Other possible solutions would be map
-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map
-based solution that requires lambda
s is slower than LC.
You just needed to read a little further and you would have been introduced to the *ngIf structural directive.
selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.
<div *ngIf="selectedHero">
<h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</div>
The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.
This document helped me understand structural directives.
Java Language Specification defines E1 op= E2
to be equivalent to E1 = (T) ((E1) op (E2))
where T
is a type of E1
and E1
is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int
. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b
doesn't work, that would mean a += b
would never work for bytes if it E1 += E2
was defined to be E1 = E1 + E2
. As the previous example shows, that would be indeed the case. As a hack to make +=
operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.
(ansible 2.9.6 ansible-lint 4.2.0)
See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string
when: test_myscript.stderr != ""
Correct syntax and also "Ansible Galaxy Warning-Free" option is
when: test_myscript.stderr | length > 0
Quoting from source code
"Use
when: var|length > 0
rather thanwhen: var != ""
(or ' 'converselywhen: var|length == 0
rather thanwhen: var == ""
)"
Notes
- debug:
msg: "Empty string '{{ var }}' evaluates to False"
when: not var
vars:
var: ''
- debug:
msg: "Empty list {{ var }} evaluates to False"
when: not var
vars:
var: []
give
"msg": "Empty string '' evaluates to False"
"msg": "Empty list [] evaluates to False"
ANSIBLE_CONDITIONAL_BARE_VARS=false
the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true
the condition will fail - debug:
msg: "String '{{ var }}' evaluates to True"
when: var
vars:
var: 'abc'
gives
fatal: [localhost]: FAILED! =>
msg: |-
The conditional check 'var' failed. The error was: error while
evaluating conditional (var): 'abc' is undefined
Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'
). When the filter bool
is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true
and ANSIBLE_CONDITIONAL_BARE_VARS=false
have no effect
- debug:
msg: "String '{{ var }}' evaluates to True"
when: var|bool
vars:
var: 'abc'
gives
skipping: [localhost]
- include_tasks: teardown.yml
when: teardown
- include_tasks: provision.yml
when: not teardown
" based on a variable you define as a string (with quotation marks around it):"
In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'
In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'
In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')
"Expect that this setting eventually will be deprecated after 2.12"
After 2017 Solution:
From the homepage, click My Apps, select your app.
Click the TestFlight tab.
In the sidebar, below Builds, click the platform (iOS or tvOS).
In the table on the right, in the Build column, click the app icon or build string for the build that is missing compliance information.
5.Click Expire Build.
Ta-da! Build expired at the App Store Connect.
See Role permissions.
For more information please visit.
case the column isn't string, use astype to convert:
df['col'] = df['col'].astype(str).str[:9]
If you'd like to see side-by-side diffs in a browser without involving GitHub, you might enjoy git webdiff, a drop-in replacement for git diff
:
$ pip install webdiff
$ git webdiff
This offers a number of advantages over traditional GUI difftools like tkdiff
in that it can give you syntax highlighting and show image diffs.
Read more about it here.
Use a for..in
loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.
var myObject = {foo: 'bar'};
for (var name in myObject) {
alert(name);
}
// results in a single alert of 'foo'
Object.prototype.baz = 'quux';
for (var name in myObject) {
alert(name);
}
// results in two alerts, one for 'foo' and one for 'baz'
To avoid including inherited properties in your enumeration, check hasOwnProperty()
:
for (var name in myObject) {
if (myObject.hasOwnProperty(name)) {
alert(name);
}
}
Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.
It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.
This is why JavaScript provides hasOwnProperty()
, and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty()
.
You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()
The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries()
does it's work.
If you can implement ReturnAllCountries()
to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries()
is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.
With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++);
is actually well defined and does what you're asking for, e.g.:
#include <stdio.h>
int main() {
int a = 100;
int *p = &a;
printf("%p\n",(void*)p);
++(*p++);
printf("%p\n",(void*)p);
printf("%d\n",a);
return 0;
}
It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.
On Python 3.4+ you can use statistics.mean()
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(l) # 20.11111111111111
On older versions of Python you can do
sum(l) / len(l)
On Python 2 you need to convert len
to a float to get float division
sum(l) / float(len(l))
There is no need to use reduce
. It is much slower and was removed in Python 3.
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
Essentially the original question can be broken down in 2 parts:
The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)
(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here"
or <i>..close italics with '</i>'-tag</i>
, where it is obvious one should escape/encode (something in) </i
and "
(or change container's quote-character from "
to '
).
So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).
That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):
PCDATA
(Parsed Character DATA): will expand entities and one must
escape <
, &
(and >
depending on markup language/version).
Most tags like body
, div
, pre
, etc, but also textarea
(until
HTML5) fall under this type.
So not only do you need to encode all the container's closing character-sequences
inside the snippet, you also have to encode all <
, &
(,>
) characters
(at minimum).
Needless to say, encoding/escaping this many characters falls outside this
objective's scope of embedding a raw snippet in the markup.
'..But a textarea seems to work...', yes, either because of the browsers
error-engine trying to make something out of it, or because HTML5:
RCDATA
(Replaceable Character DATA): will not not treat tags inside the
text as markup (but are still governed by rule 1), so one doesn't need to
encode <
(>
). BUT entities are still expanded, so they and 'ambiguous
ampersands' (&
) need special care.
The current HTML5 spec says the textarea is now a RCDATA
field and (quote):
The text in
raw text
andRCDATA
elements must not contain any occurrences of the string"</"
(U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).
Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!
CDATA
(Character Data) will not treat tags inside the text as
markup and will not expand entities.
So as long as the raw snippet code does not violate rule 1 (that one can't
have the containers closing character(sequence) inside the snippet), this
requires no other escaping/encoding.
Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).
So what 'containers' have this CDATA
context?
Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes ("
and '
) in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).
What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>
?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */
that wraps the raw snippet (script-tags can have an id
and you can access them by count). But since this obviously introduces a escaping problem with */
, ]]>
and </script
in the raw snippet, this doesn't seem like a solution either.
Please post other viable 'containers' in the comments to this answer.
By the way, encoding or counting the number of -
characters and balancing them out inside a comment tag <!-- -->
is just insane for this purpose (apart from rule 1).
That leaves us with Jukka K. Korpela's excellent answer: the <xmp>
tag seems the best option!
The 'forgotten' <xmp>
holds CDATA
, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre
) and the xmp
tag must still adhere to rule no 1. But that's the 'only' rule.
Consider the following markup:
<!-- ATTENTION: replace any occurrence of </xmp with </xmp -->
<xmp id="snippet-container">
<div>
<div>this is an example div & holds an xmp tag:<br />
<xmp>
<html><head> <!-- indentation col 0!! -->
<title>My Title</title>
</head><body>
<p>hello world !!</p>
</body></html>
</xmp> <!-- note this encoded/escaped tag -->
</div>
This line is also part of the snippet
</div>
</xmp>
The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container">
contains an (almost raw) code-snippet (containing div>div>xmp>html-document
).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).
So embedding/transporting the (sometimes almost) raw code is/seems solved.
What about displaying/rendering the snippet (and that encoded </xmp>
)?
The browser will (or it should) render the snippet (the contents inside snippet-container
) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &
), full tags, comments AND the encoded closing tag </xmp>
(just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true"
to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML
is also a breeze.
So you can... if the snippet doesn't contain the containers closing character-sequence.
However, should a raw snippet contain the closing character-sequence </xmp
(because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded </xmp>
like </xmp>
inside a textarea
(for editing/posting) or (for example) a pre
just to correctly render the snippet's code (or so it seems).
A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp
's innerHTML
revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.
But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:
Intended raw code-snippet:
<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>
Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/]
sequences, right?
So that gives us the following markup (using just a possible encoding):
<xmp id="container">
<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>
</xmp>
Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..
Using a regex like: xmp.innerHTML.replace(/<(?=\/xmp[> \n\r\t\f\/])/gi, '<');
, would translate 'back' to this:
<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>
Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.
Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.
Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <
, &
(and >
), just like the rest of the world.
Conclusion: (using the xmp
tag)
Hope this helps!
PS:
Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre
, textarea
, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).
UPDATE myTable
SET myColumn = NULL
WHERE myCondition
When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:
Project B depend on Library A
in Library A:
public class DocSearchResponse<T> {
private T data;
}
it has service to query data from external source, and use jackson to convert to concrete class
public class ServiceA<T>{
@Autowired
private ObjectMapper mapper;
@Autowired
private ClientDocSearch searchClient;
public DocSearchResponse<T> query(Criteria criteria){
String resultInString = searchClient.search(criteria);
return convertJson(resultInString)
}
}
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
in Project B:
public class Account{
private String name;
//come with other attributes
}
and i use ServiceA from library to make query and as well convert data
public class ServiceAImpl extends ServiceA<Account> {
}
and make use of that
public class MakingAccountService {
@Autowired
private ServiceA service;
public void execute(Criteria criteria){
DocSearchResponse<Account> result = service.query(criteria);
Account acc = result.getData(); // java.util.LinkedHashMap cannot be cast to com.testing.models.Account
}
}
it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson
in Project B to let jackson do its job
public class ServiceAImpl extends ServiceA<Account> {
@Override
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
}
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Necromancing.
The provided answers are incomplete.
First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.
It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.
This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.
// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{
public System.Web.HttpBrowserCapabilities Browser { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public string Platform { get; set; }
public bool IsMobileDevice { get; set; }
public string MobileBrand { get; set; }
public string MobileModel { get; set; }
public BrowserInfo(System.Web.HttpRequest request)
{
if (request.Browser != null)
{
if (request.UserAgent.Contains("Edge")
&& request.Browser.Browser != "Edge")
{
this.Name = "Edge";
}
else
{
this.Name = request.Browser.Browser;
this.Version = request.Browser.MajorVersion.ToString();
}
this.Browser = request.Browser;
this.Platform = request.Browser.Platform;
this.IsMobileDevice = request.Browser.IsMobileDevice;
if (IsMobileDevice)
{
this.Name = request.Browser.Browser;
}
}
}
}
void context_EndRequest(object sender, System.EventArgs e)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
try
{
// response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
// response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
// response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
// response.AppendHeader("X-Frame-Options", "DENY");
// response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
// response.AppendHeader("X-Frame-Options", "AllowAll");
if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
{
// "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome
string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
+ System.Web.HttpContext.Current.Request.UrlReferrer.Authority
;
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
// SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);
if (IsHostAllowed(refAuth))
{
BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);
// bi.Name = Firefox
// bi.Name = InternetExplorer
// bi.Name = Chrome
// Chrome wants entire path...
if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
// unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
// unsafe-inline: styles
// data: url(data:image/png:...)
// https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
// https://www.ietf.org/rfc/rfc7034.txt
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
// https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
// https://content-security-policy.com/
// http://rehansaeed.com/content-security-policy-for-asp-net-mvc/
// This is for Chrome:
// response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
ls.Add("default-src");
ls.Add("'self'");
ls.Add("'unsafe-inline'");
ls.Add("'unsafe-eval'");
ls.Add("data:");
// http://az416426.vo.msecnd.net/scripts/a/ai.0.js
// ls.Add("*.msecnd.net");
// ls.Add("vortex.data.microsoft.com");
ls.Add(selfAuth);
ls.Add(refAuth);
string contentSecurityPolicy = string.Join(" ", ls.ToArray());
response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
}
else
{
response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
}
else
response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
catch (System.Exception ex)
{
// WTF ?
System.Console.WriteLine(ex.Message); // Suppress warning
}
} // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
} // End Using context_EndRequest
private static string[] s_allowedHosts = new string[]
{
"localhost:49533"
,"localhost:52257"
,"vmcompany1"
,"vmcompany2"
,"vmpostalservices"
,"example.com"
};
public static bool IsHostAllowed(string host)
{
return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed
public static bool Contains(string[] allowed, string current)
{
for (int i = 0; i < allowed.Length; ++i)
{
if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
return true;
} // Next i
return false;
} // End Function Contains
You need to register the context_EndRequest function in the HTTP-module Init function.
public class RequestLanguageChanger : System.Web.IHttpModule
{
void System.Web.IHttpModule.Dispose()
{
// throw new NotImplementedException();
}
void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
{
// https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
context.EndRequest += new System.EventHandler(context_EndRequest);
}
// context_EndRequest Code from above comes here
}
Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:
namespace ChangeRequestLanguage
{
public class Global : System.Web.HttpApplication
{
System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();
public override void Init()
{
mod.Init(this);
base.Init();
}
protected void Application_Start(object sender, System.EventArgs e)
{
}
protected void Session_Start(object sender, System.EventArgs e)
{
}
protected void Application_BeginRequest(object sender, System.EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
{
}
protected void Application_Error(object sender, System.EventArgs e)
{
}
protected void Session_End(object sender, System.EventArgs e)
{
}
protected void Application_End(object sender, System.EventArgs e)
{
}
}
}
or you can add entries to Web.config if you don't own the application source-code:
<httpModules>
<add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
</modules>
</system.webServer>
</configuration>
The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.
The string in type is in the format "Namespace.Class, Assembly"
.
Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like
"[DefaultNameSpace.Namespace].Class, Assembly"
If you want to avoid this problem, write the DLL in C#.
From the docs of the flush
method:
Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.
The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.
Google allows you to search in the project, but not the code :(
you mentioned "entire line" , so i assumed mystring is the entire line.
if "token" in mystring:
print(mystring)
however if you want to just get "token qwerty",
>>> mystring="""
... qwertyuiop
... asdfghjkl
...
... zxcvbnm
... token qwerty
...
... asdfghjklñ
... """
>>> for item in mystring.split("\n"):
... if "token" in item:
... print (item.strip())
...
token qwerty
Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):
use YourDatabase
go
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
go
alter role [db_datareader] add member [YourDomain\YourUser]
go
Fully async version with ES6, only native packages, fs.promises and async/await, does file operations in parallel:
const fs = require('fs');
const path = require('path');
async function listDirectories(rootPath) {
const fileNames = await fs.promises.readdir(rootPath);
const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
.map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}
Tested, it works nicely.
Write an empty string to the file, flush, and close. Make sure that the file writer is not in append-mode. I think that should do the trick.
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"
npm install http-server -g
http-server [path] [options]
Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.
A very unusual scenario, which happened to me.
There was infinite recursion, which kept creating the objects.
More specifically, using DRF, I was overriding create method in a view, and I did
def create(self, request, *args, **kwargs):
....
....
return self.create(request, *args, **kwargs)
Replace [Your TABLE] with emp in the query below
select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
from all_constraints
where constraint_type='R'
and r_constraint_name in (select constraint_name
from all_constraints
where constraint_type in ('P','U')
and table_name='[YOUR TABLE]');
I configured the app.config
with the tool for EntLib configuration and set up my LoggingConfiguration
block. Then I copied this into the DotNetConfig.xsd
. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.
<xs:element name="loggingConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:attribute name="fileName" type="xs:string" use="required" />
<xs:attribute name="footer" type="xs:string" use="required" />
<xs:attribute name="formatter" type="xs:string" use="required" />
<xs:attribute name="header" type="xs:string" use="required" />
<xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
<xs:attribute name="rollInterval" type="xs:string" use="required" />
<xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
<xs:attribute name="timeStampPattern" type="xs:string" use="required" />
<xs:attribute name="listenerDataType" type="xs:string" use="required" />
<xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
<xs:attribute name="filter" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="formatters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="template" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="logFilters">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="enabled" type="xs:boolean" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="categorySources">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="add">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="specialSources">
<xs:complexType>
<xs:sequence>
<xs:element name="allEvents">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="notProcessed">
<xs:complexType>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="errors">
<xs:complexType>
<xs:sequence>
<xs:element name="listeners">
<xs:complexType>
<xs:sequence>
<xs:element name="add">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="switchValue" type="xs:string" use="required" />
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
<xs:attribute name="defaultCategory" type="xs:string" use="required" />
<xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
</xs:complexType>
</xs:element>
you can
float Lasttime;
public float Sec = 3f;
public int Num;
void Start(){
ExampleStart();
}
public void ExampleStart(){
Lasttime = Time.time;
}
void Update{
if(Time.time - Lasttime > sec){
// if(Num == step){
// Yourcode
//You Can Change Sec with => sec = YOURTIME(Float)
// Num++;
// ExampleStart();
}
if(Num == 0){
TextUI.text = "Welcome to Number Wizard!";
Num++;
ExampleStart();
}
if(Num == 1){
TextUI.text = ("The highest number you can pick is " + max);
Num++;
ExampleStart();
}
if(Num == 2){
TextUI.text = ("The lowest number you can pick is " + min);
Num++;
ExampleStart();
}
}
}
Khaled Developer
Easy For Gaming
Use this :
#Inputs
L1 = [1, 2]
L2 = [3,4,5]
#Code
L1+L2
#Output
[1, 2, 3, 4, 5]
By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.
Happy Learning...:)
To add to Alex Kucherenko solution: the issue with the cursor getting disappearing after calling setInputType(0)
is due to a framework bug on ICS (and JB).
The bug is documented here: https://code.google.com/p/android/issues/detail?id=27609.
To workaround this, call setRawInputType(InputType.TYPE_CLASS_TEXT)
right after the setInputType
call.
To stop the keyboard from appearing, just override OnTouchListener
of the EditText and return true (swallowing the touch event):
ed.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
The reasons for the cursor appearing on GB devices and not on ICS+ had me tearing my hair out for a couple of hours, so I hope this saves someone's time.
Above example is technically incorrect. Per latest jQuery, use the prop()
method should be used for things like disabled. See their API page.
To disable all form elements inside 'target', use the :input selector which matches all input, textarea, select and button elements.
$("#target :input").prop("disabled", true);
If you only want the elements, use this.
$("#target input").prop("disabled", true);
The most widely compatible way of doing this is likely going to be creating a second div under your auto-suggest box the same size as the box itself, nudged a few pixels down and to the right. You can use JS to create and position it, which shouldn't be terribly difficult if you're using a fairly modern framework.
To add rows to existing DataTable in Dataset:
DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);
The built-in string constructor will automatically call obj.__str__
:
''.join(map(str,list))
An elegant way could be as follows -
ids = np.flip(np.argsort(avgDists))
This will give you indices of elements sorted in descending order. Now you can use regular slicing...
top_n = ids[:n]
Similarly in Java, you can create a S4 class in R that encapsulates your information:
setClass(Class="Person",
representation(
height="numeric",
age="numeric"
)
)
Then your function can return an instance of this class:
myFunction = function(age=28, height=176){
return(new("Person",
age=age,
height=height))
}
and you can access your information:
aPerson = myFunction()
aPerson@age
aPerson@height
Iam confused a lot from morning whether it should be less than or greater than`
this can accept value less than "99999"
I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:
}elseif($("#seats").val() < 99999){
alert("Not a valid Number");
}else{
You are saying if it's less than 99999, then it's not valid. You want to do the opposite:
}elseif($("#seats").val() >= 99999){
alert("Not a valid Number");
}else{
Also, since you have $("#seats")
twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:
var seats = $("#seats").val();
var error = null;
if (seats == "") {
error = "Number is required";
} else {
var seatsNum = parseInt(seats);
if (isNaN(seatsNum)) {
error = "Not a valid number";
} else if (seatsNum >= 99999) {
error = "Number must be less than 99999";
}
}
if (error != null) {
alert(error);
} else {
alert("Valid number");
}
// If you really need setflag:
var setflag = error != null;
Here's a working sample: http://jsfiddle.net/LUY8q/
I spent time finding a proper way. This may be useful for others.
Create a UDF and refer in the query -
http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm
You can do this using list comprehensions and min() (Python 3.0 code):
>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)
Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division
so that 1/5 correctly equals 0.2 instead of 0.
The InterruptedException
is usually thrown when a sleep is interrupted.
Seems there is some demand to be able to access this statically.
How can I get such thing in static methods in non-spring-managed classes? – Aetherus
It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment()
before all beans have been created, since there is no guarantee when this component will be instantiated.
@Component
public class SpringContext
{
private static Environment environment;
public SpringContext(Environment environment) {
SpringContext.environment = environment;
}
public static Environment getEnvironment() {
if (environment == null) {
throw new RuntimeException("Environment has not been set yet");
}
return environment;
}
}
If you want to concatenate the fields using / as a separator, you can use concat_ws
:
select concat_ws('/', col1, col2, col3) from mytable
You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.
You can use CreateDefaultBuilder
which will automatically build and pass a configuration object to your startup class:
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
public class Startup
{
public Startup(IConfiguration configuration) // automatically injected
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
/* ... */
}
CreateDefaultBuilder
automatically includes the appropriate appsettings.Environment.json
file so add a separate appsettings file for each environment:
Then set the ASPNETCORE_ENVIRONMENT
environment variable when running / debugging
Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:
For Visual Studio go to Project > Properties > Debug > Environment Variables:
For Visual Studio Code, edit .vscode/launch.json
> env
:
Using Launch Settings, edit Properties/launchSettings.json
> environmentVariables
:
Which can also be selected from the Toolbar in Visual Studio
Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS
Note: When an app is launched with dotnet run,
launchSettings.json
is read if available, andenvironmentVariables
settings in launchSettings.json override environment variables.
Host.CreateDefaultBuilder
work?.NET Core 3.0 added Host.CreateDefaultBuilder
under platform extensions which will provide a default initialization of IConfiguration
which provides default configuration for the app in the following order:
appsettings.json
using the JSON configuration provider.appsettings.Environment.json
using the JSON configuration provider. For example:
appsettings.Production.json
orappsettings.Development.json
- App secrets when the app runs in the Development environment.
- Environment variables using the Environment Variables configuration provider.
- Command-line arguments using the Command-line configuration provider.
We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt
Or you can put that file in as the body
blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"
Python 3.6 changed the game for string concatenation of known components with Literal String Interpolation.
Given the test case from mkoistinen's answer, having strings
domain = 'some_really_long_example.com'
lang = 'en'
path = 'some/really/long/path/'
The contenders are
f'http://{domain}/{lang}/{path}'
- 0.151 µs
'http://%s/%s/%s' % (domain, lang, path)
- 0.321 µs
'http://' + domain + '/' + lang + '/' + path
- 0.356 µs
''.join(('http://', domain, '/', lang, '/', path))
- 0.249 µs (notice that building a constant-length tuple is slightly faster than building a constant-length list).
Thus currently the shortest and the most beautiful code possible is also fastest.
In alpha versions of Python 3.6 the implementation of f''
strings was the slowest possible - actually the generated byte code is pretty much equivalent to the ''.join()
case with unnecessary calls to str.__format__
which without arguments would just return self
unchanged. These inefficiencies were addressed before 3.6 final.
The speed can be contrasted with the fastest method for Python 2, which is +
concatenation on my computer; and that takes 0.203 µs with 8-bit strings, and 0.259 µs if the strings are all Unicode.
I had to right-click the project, and select "Reimport" under the "Run Maven" submenu.
Like vikingosgundo said, but keep in mind that if you use [UIImage imageNamed:image]
then the image is cached and eats away memory. So unless you plan on using the same image in many places, you should load the image, with imageWithContentsOfFile:
and imageWithData:
This will save you significant memory and speeds up your app.
You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-
Flexible
(child: new Text("This is Dummy Long Text",
style: TextStyle(
fontFamily: "Roboto",
color: Colors.black,
fontSize: 10.0,
fontWeight: FontWeight.bold),
overflow: TextOverflow.clip,),)
hope this help someone :)
A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:
@echo off
rem ****************** MAIN CODE SECTION
set STARTTIME=%TIME%
rem Your code goes here (remove the ping line)
ping -n 4 -w 1 127.0.0.1 >NUL
set ENDTIME=%TIME%
rem ****************** END MAIN CODE SECTION
rem Change formatting for the start and end times
for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do (
IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Calculate the elapsed time by subtracting values
set /A elapsed=end-start
rem Format the results for output
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %hh% lss 10 set hh=0%hh%
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
set DURATION=%hh%:%mm%:%ss%,%cc%
echo Start : %STARTTIME%
echo Finish : %ENDTIME%
echo ---------------
echo Duration : %DURATION%
Output:
Start : 11:02:45.92
Finish : 11:02:48.98
---------------
Duration : 00:00:03,06
For dynamic SQL use:
'IN(' ||array_to_string(some_array, ',')||')'
DO LANGUAGE PLPGSQL $$
DECLARE
some_array bigint[];
sql_statement text;
BEGIN
SELECT array[1, 2] INTO some_array;
RAISE NOTICE '%', some_array;
sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
RAISE NOTICE '%', sql_statement;
END;
$$;
Result:
NOTICE: {1,2}
NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)
Additionally if you want to get the round
value after finding the mean
.
#Create a DataFrame
df1 = {
'Subject':['semester1','semester2','semester3','semester4','semester1',
'semester2','semester3'],
'Score':[62.73,47.76,55.61,74.67,31.55,77.31,85.47]}
df1 = pd.DataFrame(df1,columns=['Subject','Score'])
rounded_mean = round(df1['Score'].mean()) # specified nothing as decimal place
print(rounded_mean) # 62
rounded_mean_decimal_0 = round(df1['Score'].mean(), 0) # specified decimal place as 0
print(rounded_mean_decimal_0) # 62.0
rounded_mean_decimal_1 = round(df1['Score'].mean(), 1) # specified decimal place as 1
print(rounded_mean_decimal_1) # 62.2
After hours of frustration... here's what i discovered.
I don't know how such an easy process could have worse documentation. It as if it was written by lawyers.
Limit is very simple, example limit first 50 rows
val df_subset = data.limit(50)
You can use code snippets to insert any lines you want.
Also, if you type three single quotation marks (''') on the line above the function header, it will insert the XML header template that you can then fill out.
These XML comments can be interpreted by documentation software, and they are included in the build output as an assembly.xml file. If you keep that XML file with the DLL and reference that DLL in another project, those comments become available in intellisense.
No real need for the JSON.NET package. You could use JavaScriptSerializer
. The Serialize
method will turn a managed type instance into a JSON string.
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);
I will try to explain with a interesting and easy to understand example. :)
Assume that a organization organizes a chess tournament where 10 players (with equal chess playing skills) will challenge a professional champion chess player. And since chess is 1:1 game thus organizers have to conduct 10 games in time efficient manner so that they can finish the whole event as quickly as possible.
Hopefully following scenarios will easily describe multiple ways of conducting these 10 games:
1) SERIAL - lets say that the professional plays with each person one by one i.e. starts and finishes the game with one person and then starts the next game with next person and so on. In other words, they decided to conduct the games sequentially. So if one game takes 10 mins to complete then 10 games will take 100 mins, also assume that transition from one game to other takes 6 secs then for 10 games it will be 54 secs (approx. 1 min).
so the whole event will approximately complete in 101 mins (WORST APPROACH)
2) CONCURRENT - lets say that professional plays his turn and moves on to next player so all 10 players are playing simultaneously but the professional player is not with two person at a time, he plays his turn and moves on to next person. Now assume professional player takes 6 sec to play his turn and also transition time of professional player b/w two players is 6 sec so total transition time to get back to first player will be 1min (10x6sec). Therefore, by the time he is back to first person with, whom event was started, 2mins have passed (10xtime_per_turn_by_champion + 10xtransition_time=2mins)
Assuming that all player take 45sec to complete their turn so based on 10mins per game from SERIAL event the no. of rounds before a game finishes should 600/(45+6) = 11 rounds (approx)
So the whole event will approximately complete in 11xtime_per_turn_by_player_&_champion + 11xtransition_time_across_10_players = 11x51 + 11x60sec= 561 + 660 = 1221sec = 20.35mins (approximately)
SEE THE IMPROVEMENT from 101 mins to 20.35 mins (BETTER APPROACH)
3) PARALLEL - lets say organizers get some extra funds and thus decided to invite two professional champion player (both equally capable) and divided the set of same 10 players (challengers) in two group of 5 each and assigned them to two champion i.e. one group each. Now the event is progressing in parallel in these two sets i.e. at least two players (one in each group) are playing against the two professional players in their respective group.
However within the group the professional player with take one player at a time (i.e. sequentially) so without any calculation you can easily deduce that whole event will approximately complete in 101/2=50.5mins to complete
SEE THE IMPROVEMENT from 101 mins to 50.5 mins (GOOD APPROACH)
4) CONCURRENT + PARALLEL - In above scenario, lets say that the two champion player will play concurrently (read 2nd point) with the 5 players in their respective groups so now games across groups are running in parallel but within group they are running concurrently.
So the games in one group will approximately complete in 11xtime_per_turn_by_player_&_champion + 11xtransition_time_across_5_players = 11x51 + 11x30 = 600 + 330 = 930sec = 15.5mins (approximately)
So the whole event (involving two such parallel running group) will approximately complete in 15.5mins
SEE THE IMPROVEMENT from 101 mins to 15.5 mins (BEST APPROACH)
NOTE: in above scenario if you replace 10 players with 10 similar jobs and two professional player with a two CPU cores then again the following ordering will remain true:
SERIAL > PARALLEL > CONCURRENT > CONCURRENT+PARALLEL
(NOTE: this order might change for other scenarios as this ordering highly depends on inter-dependency of jobs, communication needs b/w jobs and transition overhead b/w jobs)
you can unpack your tuples and get only the first element using a list comprehension:
l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]
output:
[1, 2]
this will work no matter how many elements you have in a tuple:
l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]
output:
[1, 2]
You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679
As mentioned by Stuart McLaughlin, make sure you get the x86 version even if you use a 64-bits OS because PHP needs some 32-bit libraries.
According to the documentation, it is better to handle multiple exceptions through tuples or like this:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error: ", sys.exc_info()[0]
raise
I've always come back here for the answer so I wanted to make a short simple one to go to.
There are multiple ways of doing this:
Add Namespaces:
System.Windows.Interactivitiy
Microsoft.Expression.Interactions
XAML:
Use the EventName
to call the event you want then specify your Method
name in the MethodName
.
<Window>
xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
<wi:Interaction.Triggers>
<wi:EventTrigger EventName="SelectionChanged">
<ei:CallMethodAction
TargetObject="{Binding}"
MethodName="ShowCustomer"/>
</wi:EventTrigger>
</wi:Interaction.Triggers>
</Window>
Code:
public void ShowCustomer()
{
// Do something.
}
Install GalaSoft NuGet package.
Get the namespaces:
System.Windows.Interactivity
GalaSoft.MvvmLight.Platform
XAML:
Use the EventName
to call the event you want then specify your Command
name in your binding. If you want to pass the arguments of the method, mark PassEventArgsToCommand
to true.
<Window>
xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="http://www.galasoft.ch/mvvmlight">
<wi:Interaction.Triggers>
<wi:EventTrigger EventName="Navigated">
<cmd:EventToCommand Command="{Binding CommandNameHere}"
PassEventArgsToCommand="True" />
</wi:EventTrigger>
</wi:Interaction.Triggers>
</Window>
Code Implementing Delegates: Source
You must get the Prism MVVM NuGet package for this.
using Microsoft.Practices.Prism.Commands;
// With params.
public DelegateCommand<string> CommandOne { get; set; }
// Without params.
public DelegateCommand CommandTwo { get; set; }
public MainWindow()
{
InitializeComponent();
// Must initialize the DelegateCommands here.
CommandOne = new DelegateCommand<string>(executeCommandOne);
CommandTwo = new DelegateCommand(executeCommandTwo);
}
private void executeCommandOne(string param)
{
// Do something here.
}
private void executeCommandTwo()
{
// Do something here.
}
Code Without DelegateCommand
: Source
using GalaSoft.MvvmLight.CommandWpf
public MainWindow()
{
InitializeComponent();
CommandOne = new RelayCommand<string>(executeCommandOne);
CommandTwo = new RelayCommand(executeCommandTwo);
}
public RelayCommand<string> CommandOne { get; set; }
public RelayCommand CommandTwo { get; set; }
private void executeCommandOne(string param)
{
// Do something here.
}
private void executeCommandTwo()
{
// Do something here.
}
You'll have to download it's NuGet Package.
XAML
:
<i:Interaction.Behaviors>
<telerek:EventToCommandBehavior
Command="{Binding DropCommand}"
Event="Drop"
PassArguments="True" />
</i:Interaction.Behaviors>
Code:
public ActionCommand<DragEventArgs> DropCommand { get; private set; }
this.DropCommand = new ActionCommand<DragEventArgs>(OnDrop);
private void OnDrop(DragEventArgs e)
{
// Do Something
}
For me following worked:
in directive declare it like this:
.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
myFunction: '=',
},
templateUrl: 'myDirective.html'
};
})
In directive template use it in following way:
<select ng-change="myFunction(selectedAmount)">
And then when you use the directive, pass the function like this:
<data-my-directive
data-my-function="setSelectedAmount">
</data-my-directive>
You pass the function by its declaration and it is called from directive and parameters are populated.
The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.
Comparable should be used when you compare instances of the same class.
Comparator can be used to compare instances of different classes.
Comparable is implemented by the class which needs to define a natural ordering for its objects. For example, String implements Comparable.
In case a different sorting order is required, then, implement comparator and define its own way of comparing two instances.
Before Java 7:
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Since Java 7, there is no need to close the stream, because it implements autocloseable
try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
Here's another way to work around the problem:
std::min(9, int(test::N));
(I think Crazy Eddie's answer correctly describes why the problem exists.)
You can Change Backcolor
row by row using your condition.and this function call after applying Datasource
of DatagridView
.
Here Is the function for that.
Simply copy that and put it after Databind
private void ChangeRowColor()
{
for (int i = 0; i < gvItem.Rows.Count; i++)
{
if (BindList[i].MainID == 0 && !BindList[i].SchemeID.HasValue)
gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#C9CADD");
else if (BindList[i].MainID > 0 && !BindList[i].SchemeID.HasValue)
gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#DDC9C9");
else if (BindList[i].MainID > 0)
gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#D5E8D7");
else
gvItem.Rows[i].DefaultCellStyle.BackColor = Color.White;
}
}
I used a combination of solutions shared in this thread to erase the trace in commands history. First, I verified where is saved commands history with:
echo $HISTFILE
I edited the history with:
vi <pathToFile>
After that, I flush current session history buffer with:
history -r && exit
Next time you enter to this session, the last command that you will see on command history is the last that you left on pathToFile.
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
NOTE: As of July 2020, text-overflow: ellipsis
works for <select>
on Chrome
HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal select
which, when open, looks totally different from the traditional pop-up menu).
If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select
.
Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in select
s might be the result of a years-old oversight that everyone copied, and it might be time for a change.
just use file_put_contents('file',$myarray);
file_put_contents() works with arrays too.
For those running wamp mysql server
Wamp tray Icon -> MySql -> my.ini
[wampmysqld]
port = 3306
socket = /tmp/mysql.sock
key_buffer_size = 16M
max_allowed_packet = 16M // --> changing this wont solve
sort_buffer_size = 512K
Scroll down to the end until u find
[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE
Add the line of packet_size in between
[mysqld]
port=3306
max_allowed_packet = 16M
explicit_defaults_for_timestamp = TRUE
Check whether it worked with this query
Select @@global.max_allowed_packet;
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
So here is the scenario that I faced, and how I solved it.
[branch-a]
[Hundreds of commits] -> [R] -> [I]
here R
is the commit that I needed to be removed, and I
is a single commit that comes after R
I made a revert commit and squashed them together
git revert [commit id of R]
git rebase -i HEAD~3
During the interactive rebase squash the last 2 commits.
Even better
#include <stdio.h>
int
main(void)
{
char *line = NULL;
size_t count;
char *dup_line;
getline(&line,&count, stdin);
dup_line=strdup(line);
puts(dup_line);
free(dup_line);
free(line);
return 0;
}
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("")
.
color=$( convert filename.png -format "%[pixel:p{0,0}]" info:- )
convert filename.png -alpha off -bordercolor $color -border 1 \
\( +clone -fuzz 30% -fill none -floodfill +0+0 $color \
-alpha extract -geometry 200% -blur 0x0.5 \
-morphology erode square:1 -geometry 50% \) \
-compose CopyOpacity -composite -shave 1 outputfilename.png
This is rather a bit longer than the simple answers previously given, but it gives much better results: (1) The quality is superior due to antialiased alpha, and (2) only the background is removed as opposed to a single color. ("Background" is defined as approximately the same color as the top left pixel, using a floodfill from the picture edges.)
Additionally, the alpha channel is also eroded by half a pixel to avoid halos. Of course, ImageMagick's morphological operations don't (yet?) work at the subpixel level, so you can see I am blowing up the alpha channel to 200% before eroding.
Here is a comparison of the simple approach ("-fuzz 2% -transparent white") versus my solution, when run on the ImageMagick logo. I've flattened both transparent images onto a saddle brown background to make the differences apparent (click for originals).
Notice how the Wizard's beard has disappeared in the simple approach. Compare the edges of the Wizard to see how antialiased alpha helps the figure blend smoothly into the background.
Of course, I completely admit there are times when you may wish to use the simpler solution. (For example: It's a heck of a lot easier to remember and if you're converting to GIF, you're limited to 1-bit alpha anyhow.)
Since it's unlikely you'll want to type this command repeatedly, I recommend wrapping it in a script. You can download a BASH shell script from github which performs my suggested solution. It can be run on multiple files in a directory and includes helpful comments in case you want to tweak things.
By the way, ImageMagick actually comes with a script called "bg_removal" which uses floodfill in a similar manner as my solution. However, the results are not great because it still uses 1-bit alpha. Also, the bg_removal script runs slower and is a little bit trickier to use (it requires you to specify two different fuzz values). Here's an example of the output from bg_removal.
For some reason, a question about GET requests was merged with this one, so I'll respond to it here.
This simple function will asynchronously get an HTTP status reply from a CORS-enabled page. If you run it, you'll see that only a page with the proper headers returns a 200 status if accessed via XMLHttpRequest -- whether GET or POST is used. Nothing can be done on the client side to get around this except possibly using JSONP if you just need a json object.
The following can be easily modified to get the data held in the xmlHttpRequestObject object:
function checkCorsSource(source) {_x000D_
var xmlHttpRequestObject;_x000D_
if (window.XMLHttpRequest) {_x000D_
xmlHttpRequestObject = new XMLHttpRequest();_x000D_
if (xmlHttpRequestObject != null) {_x000D_
var sUrl = "";_x000D_
if (source == "google") {_x000D_
var sUrl = "https://www.google.com";_x000D_
} else {_x000D_
var sUrl = "https://httpbin.org/get";_x000D_
}_x000D_
document.getElementById("txt1").innerHTML = "Request Sent...";_x000D_
xmlHttpRequestObject.open("GET", sUrl, true);_x000D_
xmlHttpRequestObject.onreadystatechange = function() {_x000D_
if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {_x000D_
document.getElementById("txt1").innerHTML = "200 Response received!";_x000D_
} else {_x000D_
document.getElementById("txt1").innerHTML = "200 Response failed!";_x000D_
}_x000D_
}_x000D_
xmlHttpRequestObject.send();_x000D_
} else {_x000D_
window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");_x000D_
}_x000D_
}_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Check if page is cors</title>_x000D_
</head>_x000D_
<body>_x000D_
<p>A CORS-enabled source has one of the following HTTP headers:</p>_x000D_
<ul>_x000D_
<li>Access-Control-Allow-Headers: *</li>_x000D_
<li>Access-Control-Allow-Headers: x-requested-with</li>_x000D_
</ul>_x000D_
<p>Click a button to see if the page allows CORS</p>_x000D_
<form name="form1" action="" method="get">_x000D_
<input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">_x000D_
<input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">_x000D_
</form>_x000D_
<p id="txt1" />_x000D_
</body>_x000D_
</html>
_x000D_
os.stat
does include the creation time. There's just no definition of st_anything for the element of os.stat()
that contains the time.
So try this:
os.stat('feedparser.py')[8]
Compare that with your create date on the file in ls -lah
They should be the same.
In Ronald's example, if the date formats are different (as displayed below) then modify the format
parameter
survey <- data.frame(date=c("2012-07-26","2012-07-25"),tx_start=c("2012-01-01","2012-01-01"))
survey$date_diff <- as.Date(as.character(survey$date), format="%Y-%m-%d")-
as.Date(as.character(survey$tx_start), format="%Y-%m-%d")
survey:
date tx_start date_diff
1 2012-07-26 2012-01-01 207 days
2 2012-07-25 2012-01-01 206 days
I have used _itoa(...) on RedHat 6 and GCC compiler. It works.
I had the same problem, all I did was to restart the command line and then navigate to the document folder rather than the user folder using the command '' cd documents '' . That should be all thats needed. Also ensure that the link is correct.
Gumbo gets my vote, however, the OP doesn't specify whether just "Id" is an allowable word, which means I'd make a minor modification:
\w+Id\b
1 or more word characters followed by "Id" and a breaking space. The [a-zA-Z] variants don't take into account non-English alphabetic characters. I might also use \s instead of \b as a space rather than a breaking space. It would depend if you need to wrap over multiple lines.
There is plenty of libraries out there and I'm using this one: https://github.com/nerde/rest-resource. This was created by me, and, as you can see in the documentation, it's way cleaner and simpler than the other ones. It's not focused on Android, but I'm using in it and it's working pretty well.
It supports HTTP Basic Auth. It does the dirty job of serializing and deserializing JSON objects. You will like it, specially if your API is Rails like.