You could use KEY
unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.
Like the error says, row
is a tuple, so you can't do row["pool_number"]
. You need to use the index: row[0]
.
request.args
is a MultiDict with the parsed contents of the query string.
From the documentation of get
method:
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.
For those working with AngularJS front-end, it does not use the Ajax header laravel is expecting. (Read more)
Use Request::wantsJson() for AngularJS:
if(Request::wantsJson()) {
// Client wants JSON returned
}
You can try/catch PDOException
s (your configs could differ but the important part is the try/catch):
try {
$dbh = new PDO(
DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
DB_USER,
DB_PASS,
[
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE
]
);
} catch ( PDOException $e ) {
echo 'ERROR!';
print_r( $e );
}
The print_r( $e );
line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'
.
@Service: It tells that particular class is a Service to the client. Service class contains mainly business Logic. If you have more Service classes in a package than provide @Qualifier otherwise it should not require @Qualifier.
Case 1:
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
}
Case2:
@Service
public class EmployeeServiceImpl implements EmployeeService{
}
both cases are working...
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)The functional way of achieving this is to unzip the list using:
sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)
(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
A very simple way to read an external script into an sqlite database in python is using executescript()
:
import sqlite3
conn = sqlite3.connect('csc455_HW3.db')
with open('ZooDatabase.sql', 'r') as sql_file:
conn.executescript(sql_file.read())
conn.close()
A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor
is that list(cursor)
will always give you a list, while cursor.fetchall()
gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.
Given the above, I suggest always favouring list(cursor)
over cursor.fetchall()
, to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.
MySQLdb will not raise an exception if the result set is empty. Additionally cursor.execute() function will return a long value which is number of rows in the fetched result set. So if you want to check for empty results, your code can be re-written as
rows_count = cursor.execute(query_sql)
if rows_count > 0:
rs = cursor.fetchall()
else:
// handle empty result set
In order to receive actual data stored in the table, you should use one of fetch...() functions or use the cursor as an iterator (i.e. "for row in cursor"...). This is described in the documentation:
cursor.execute("select user_id, user_name from users where user_id < 100")
rows = cursor.fetchall()
for row in rows:
print row.user_id, row.user_name
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
A bit late, but to anyone who is wondering why they are getting the "Warning: Cannot use a scalar value as an array" message;
the reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.
hope that helps
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php
refer below link for getting ScanResult with redundant ssid removed from the list
No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:
$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).
Have been trying every variation on João's solution to get an IN List query to work with Tornado's mysql wrapper, and was still getting the accursed "TypeError: not enough arguments for format string" error. Turns out adding "*" to the list var "*args" did the trick.
args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
db.query(sql, *args)
I've got this exact error, but in my case I was binding values for the LIMIT
clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset;
resulted in LIMIT '10' OFFSET '1';
instead of LIMIT 10 OFFSET 1;
. What helps to correct that is the following:
$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);
Here's a custom-made extension of the PDO class, with a helper function to retrieve the number of rows included by the last query's "WHERE" criteria.
You may need to add more 'handlers', though, depending on what commands you use. Right now it only works for queries that use "FROM " or "UPDATE ".
class PDO_V extends PDO
{
private $lastQuery = null;
public function query($query)
{
$this->lastQuery = $query;
return parent::query($query);
}
public function getLastQueryRowCount()
{
$lastQuery = $this->lastQuery;
$commandBeforeTableName = null;
if (strpos($lastQuery, 'FROM') !== false)
$commandBeforeTableName = 'FROM';
if (strpos($lastQuery, 'UPDATE') !== false)
$commandBeforeTableName = 'UPDATE';
$after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
$table = substr($after, 0, strpos($after, ' '));
$wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));
$result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
if ($result == null)
return 0;
return $result->fetchColumn();
}
}
If you are lazy like me, you can start using Picasso library to load images.
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
I would do it like this:
dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value));
Simple and easy. According to this blog post it's even faster than most loops as its underlying implementation accesses elements by index rather than enumerator (see this answer).
It will of course throw an exception if there are duplicates, so you'll have to check before merging.
For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:
http://thecodeplayer.com/walkthrough/css3-family-tree
<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li>
<a href="#">Child</a>
<ul>
<li>
<a href="#">Grand Child</a>
</li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li>
<a href="#">Grand Child</a>
<ul>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
</ul>
</li>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
* {margin: 0; padding: 0;}
.tree ul {
padding-top: 20px; position: relative;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
.tree li {
float: left; text-align: center;
list-style-type: none;
position: relative;
padding: 20px 5px 0 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*We will use ::before and ::after to draw the connectors*/
.tree li::before, .tree li::after{
content: '';
position: absolute; top: 0; right: 50%;
border-top: 1px solid #ccc;
width: 50%; height: 20px;
}
.tree li::after{
right: auto; left: 50%;
border-left: 1px solid #ccc;
}
/*We need to remove left-right connectors from elements without
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
display: none;
}
/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}
/*Remove left connector from first child and
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
border-right: 1px solid #ccc;
border-radius: 0 5px 0 0;
-webkit-border-radius: 0 5px 0 0;
-moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
border-radius: 5px 0 0 0;
-webkit-border-radius: 5px 0 0 0;
-moz-border-radius: 5px 0 0 0;
}
/*Time to add downward connectors from parents*/
.tree ul ul::before{
content: '';
position: absolute; top: 0; left: 50%;
border-left: 1px solid #ccc;
width: 0; height: 20px;
}
.tree li a{
border: 1px solid #ccc;
padding: 5px 10px;
text-decoration: none;
color: #666;
font-family: arial, verdana, tahoma;
font-size: 11px;
display: inline-block;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after,
.tree li a:hover+ul li::before,
.tree li a:hover+ul::before,
.tree li a:hover+ul ul::before{
border-color: #94a0b4;
}
PS: apart from the code, I also like the way the site shows it in action... really innovative.
Besides calling omp_get_num_threads()
outside of the parallel region in your case, calling omp_set_num_threads()
still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads()
is used to override the value of the environment variable OMP_NUM_THREADS
and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS
) or for any consequent parallel region (after a call to omp_set_num_threads()
). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0)
or by setting the environment variable OMP_DYNAMIC
to false
.
To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads()
:
omp_set_dynamic(0); // Explicitly disable dynamic teams
omp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions
#pragma omp parallel ...
{
... 4 threads used here ...
}
or with the num_threads
OpenMP clause:
omp_set_dynamic(0); // Explicitly disable dynamic teams
// Spawn 4 threads for this parallel region only
#pragma omp parallel ... num_threads(4)
{
... 4 threads used here ...
}
Seems there's an easier way, at least in Kendo UI v2015.2.624:
$('#myDropDownSelector').data('kendoDropDownList').search('Text value to find');
If there's not a match in the dropdown, Kendo appears to set the dropdown to an unselected value, which makes sense.
I couldn't get @Gang's answer to work, but if you swap his value
with search
, as above, we're golden.
PHP regex strings need delimiters. Try:
$numpattern="/^([0-9]+)$/";
Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/
.
Example: http://ideone.com/Ec3zh
See also: PHP - Delimiters
Here's a problem, not so obvious. Somehow I had added a debug breakpoint at the very last line of my program. }
Not sure how I did that, perhaps with an erroneous mouse click while jumping between different screens. I'm working in VS Code.
And when I go to debug, the system jumps immediately to that breakpoint. No error message, no interim output, nothing. I'm like, how did the program rush thru all my set breakpoints? This took too long to figure out.
Apparently the system sees that last line breakpoint as a "first" stop. The simple fix? Delete that breakpoint, doh! (insert forehead slap here.)
You could also do something like this:
df = df[['x', 'y', 'a', 'b']]
You can get the list of columns with:
cols = list(df.columns.values)
The output will produce something like this:
['a', 'b', 'x', 'y']
...which is then easy to rearrange manually before dropping it into the first function
Easiest
eval(myvar)(parameter1, parameter2)
You don't have a function "pointer". You have a function "name".
While this works well, you will have a large number of folks telling you it's "insecure" or a "security risk".
Here is example to draw stroke circle canvas
val paint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = 10f
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(200f, 100f, 100f, paint)
}
Result
Example to draw solid circle canvas
val paint = Paint().apply {
color = Color.RED
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(200f, 100f, 100f, paint)
}
Result
Hope it help
Select "Tab key: Indents always" in Preferences->Text Editing->Indentation Then you can indent a single line or a selection of lines by pressing TAB or SHIFT+TAB Sadly this removes altogether the possibility to insert tabs where you want, and conflict badly with the tab key being used to switch between "autocompletion fields".
I guess we need more tab keys in the keyboard, one is not enough...
<c:if test="${companies.size() > 0}">
</c:if>
This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt
instead of >
.
<c:if test="${companies.size() gt 0}">
</c:if>
If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length()
function then. From the documentation:
length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.
Put this at the top of JSP page to allow the fn
namespace:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Or if you're using JSPX or Facelets:
<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
And use like this in your page:
<p>The length of the companies collection is: ${fn:length(companies)}</p>
So to test with length of a collection:
<c:if test="${fn:length(companies) gt 0}">
</c:if>
Alternatively, for this specific case you can also simply use the EL empty
operator:
<c:if test="${not empty companies}">
</c:if>
This worked for me. Running android API 19 and above.
FragmentManager fragMan = getFragmentManager();
Note: With ConcurrentMap you can use the more efficient
values.putIfAbsent(NoteColumns.CREATED_DATE, now);
I prefer the less verbose solution and avoid methods like IsTrue or IsFalse or their like.
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.
If treating strings as bytes is more your thing, you can use the following functions
function u_atob(ascii) {
return Uint8Array.from(atob(ascii), c => c.charCodeAt(0));
}
function u_btoa(buffer) {
var binary = [];
var bytes = new Uint8Array(buffer);
for (var i = 0, il = bytes.byteLength; i < il; i++) {
binary.push(String.fromCharCode(bytes[i]));
}
return btoa(binary.join(''));
}
// example, it works also with astral plane characters such as ''
var encodedString = new TextEncoder().encode('?');
var base64String = u_btoa(encodedString);
console.log('?' === new TextDecoder().decode(u_atob(base64String)))
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
For a JavaScript object stored in a Django field as text, which needs to again become a JavaScript object dynamically inserted into on-page script, you need to use both escapejs
and JSON.parse()
:
var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");
Django's escapejs
handles the quoting properly, and JSON.parse()
converts the string back into a JS object.
If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the
System.DirectoryServices.AccountManagement namespace.
It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.
Brent
For those coming from Google (etc.) such as myself:
convert_objects
has been deprecated since 0.17 - if you use it, you get a warning like this one:
FutureWarning: convert_objects is deprecated. Use the data-type specific converters
pd.to_datetime, pd.to_timedelta and pd.to_numeric.
You should do something like the following:
df =
df.astype(np.float)
df["A"] =
pd.to_numeric(df["A"])
To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.
Open the properties for the project, go to the Build
tab and check the Allow unsafe code
checkbox.
In response to the original question, I typically add the config file in my test project as a link; you can then use the DeploymentItem attribute to addit to the Out folder of the test run.
[TestClass]
[DeploymentItem("MyProject.Cache.dll.config")]
public class CacheTest
{
.
.
.
.
}
In response to the comments that Assemblies can't be project specific, they can and it provides great flexibility esp. when working with IOC frameworks.
Here's how I managed to fix it on my Kali machine:
Locate to the directory:
cd /etc/nginx/sites-enabled/
Edit the 'default' configuration file:
sudo nano default
Add the following lines in the location
block:
location /yourdirectory {
autoindex on;
autoindex_exact_size off;
}
Note that I have activated auto-indexing in a specific directory
/yourdirectory
only. Otherwise, it will be enabled for all of your folders on your computer and you don't want it.
Now restart your server and it should be working now:
sudo service nginx restart
It very much depends on quite how robust you want your caching to be. For example, the squid proxy server (and possibly others) defaults to not caching URLs served with a querystring - at least, it did when that article was written. If you don't mind certain use cases causing unnecessary cache misses, then go ahead with query params. But it's very easy to set up a filename-based cache-busting scheme which avoids this problem.
For example if I had an application source code structure that looked like this:
Then I would do:
javadoc -d "C:\docs" -sourcepath "C:\b2b" -subpackages com
And that should create javadocs for source code of the com package, and all subpackages (recursively), found inside the "C:\b2b" directory.
Once you have a good MYSQL table of some bad words you want to filter (I started with one of the links in this thread), you can do something like this:
$errors = array(); //Initialize error array (I use this with all my PHP form validations)
$SCREENNAME = mysql_real_escape_string($_POST['SCREENNAME']); //Escape the input data to prevent SQL injection when you query the profanity table.
$ProfanityCheckString = strtoupper($SCREENNAME); //Make the input string uppercase (so that 'BaDwOrD' is the same as 'BADWORD'). All your values in the profanity table will need to be UPPERCASE for this to work.
$ProfanityCheckString = preg_replace('/[_-]/','',$ProfanityCheckString); //I allow alphanumeric, underscores, and dashes...nothing else (I control this with PHP form validation). Pull out non-alphanumeric characters so 'B-A-D-W-O-R-D' shows up as 'BADWORD'.
$ProfanityCheckString = preg_replace('/1/','I',$ProfanityCheckString); //Replace common numeric representations of letters so '84DW0RD' shows up as 'BADWORD'.
$ProfanityCheckString = preg_replace('/3/','E',$ProfanityCheckString);
$ProfanityCheckString = preg_replace('/4/','A',$ProfanityCheckString);
$ProfanityCheckString = preg_replace('/5/','S',$ProfanityCheckString);
$ProfanityCheckString = preg_replace('/6/','G',$ProfanityCheckString);
$ProfanityCheckString = preg_replace('/7/','T',$ProfanityCheckString);
$ProfanityCheckString = preg_replace('/8/','B',$ProfanityCheckString);
$ProfanityCheckString = preg_replace('/0/','O',$ProfanityCheckString); //Replace ZERO's with O's (Capital letter o's).
$ProfanityCheckString = preg_replace('/Z/','S',$ProfanityCheckString); //Replace Z's with S's, another common substitution. Make sure you replace Z's with S's in your profanity database for this to work properly. Same with all the numbers too--having S3X7 in your database won't work, since this code would render that string as 'SEXY'. The profanity table should have the "rendered" version of the bad words.
$CheckProfanity = mysql_query("SELECT * FROM DATABASE.TABLE p WHERE p.WORD = '".$ProfanityCheckString."'");
if(mysql_num_rows($CheckProfanity) > 0) {$errors[] = 'Please select another Screen Name.';} //Check your profanity table for the scrubbed input. You could get real crazy using LIKE and wildcards, but I only want a simple profanity filter.
if (count($errors) > 0) {foreach($errors as $error) {$errorString .= "<span class='PHPError'>$error</span><br /><br />";} echo $errorString;} //Echo any PHP errors that come out of the validation, including any profanity flagging.
//You can also use these lines to troubleshoot.
//echo $ProfanityCheckString;
//echo "<br />";
//echo mysql_error();
//echo "<br />";
I'm sure there is a more efficient way to do all those replacements, but I'm not smart enough to figure it out (and this seems to work okay, albeit inefficiently).
I believe that you should err on the side of allowing users to register, and use humans to filter and add to your profanity table as required. Though it all depends on the cost of a false positive (okay word flagged as bad) versus a false negative (bad word gets through). That should ultimately govern how aggressive or conservative you are in your filtering strategy.
I would also be very careful if you want to use wildcards, since they can sometimes behave more onerously than you intend.
To create frames from video:
ffmpeg\ffmpeg -i %video% test\thumb%04d.jpg -hide_banner
Optional: remove frames you don't want in output video
(more accurate than trimming video with -ss
& -t
)
Then create video from image/frames eg.:
ffmpeg\ffmpeg -framerate 30 -start_number 56 -i test\thumb%04d.jpg -vf format=yuv420p test/output.mp4
An important difference is that list comprehension will return a list
while the filter returns a filter
, which you cannot manipulate like a list
(ie: call len
on it, which does not work with the return of filter
).
My own self-learning brought me to some similar issue.
That being said, if there is a way to have the resulting list
from a filter
, a bit like you would do in .NET when you do lst.Where(i => i.something()).ToList()
, I am curious to know it.
EDIT: This is the case for Python 3, not 2 (see discussion in comments).
Use FROM_UNIXTIME()
:
SELECT
FROM_UNIXTIME(timestamp)
FROM
your_table;
See also: MySQL documentation on FROM_UNIXTIME()
.
I created https://yt-embed.herokuapp.com/ to simplify this. The usage is direct, from the examples above:
[![Everything Is AWESOME](https://yt-embed.herokuapp.com/embed?v=StTqXEQ2l-Y)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")
Will result in:
Just make a call to: https://yt-embed.herokuapp.com/embed?v=[video_id] as the image instead of https://img.youtube.com/vi/.
Genealogical data is cyclic and does not fit into an acyclic graph, so if you have assertions against cycles you should remove them.
The way to handle this in a view without creating a custom view is to treat the cyclic parent as a "ghost" parent. In other words, when a person is both a father and a grandfather to the same person, then the grandfather node is shown normally, but the father node is rendered as a "ghost" node that has a simple label like ("see grandfather") and points to the grandfather.
In order to do calculations you may need to improve your logic to handle cyclic graphs so that a node is not visited more than once if there is a cycle.
append
"extends" the list (in place) by only one item, the single object passed (as argument).
extend
"extends" the list (in place) by as many items as the object passed (as argument) contains.
This may be slightly confusing for str
objects.
append
will add a single string item at the end but
extend
will add as many "single" 'str' items as the length of that string.append
will still add a single 'list' item at the end and
extend
will add as many 'list' items as the length of the passed list.def append_o(a_list, element): a_list.append(element) print('append:', end = ' ') for item in a_list: print(item, end = ',') print() def extend_o(a_list, element): a_list.extend(element) print('extend:', end = ' ') for item in a_list: print(item, end = ',') print() append_o(['ab'],'cd') extend_o(['ab'],'cd') append_o(['ab'],['cd', 'ef']) extend_o(['ab'],['cd', 'ef']) append_o(['ab'],['cd']) extend_o(['ab'],['cd'])
produces:
append: ab,cd,
extend: ab,c,d,
append: ab,['cd', 'ef'],
extend: ab,cd,ef,
append: ab,['cd'],
extend: ab,cd,
Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested and does work!
On the PHP page where you want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>, you need to first of all include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>, below the jQuery, paste this:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.org/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the URL to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above URL)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
Distinct the Note class by Author
var DistinctItems = Note.GroupBy(x => x.Author).Select(y => y.First());
foreach(var item in DistinctItems)
{
//Add to other List
}
Index is actually available like;
_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){ });
The previous answers are fine, just adding my preferred way of handling this:
var timePortion = myDate.getTime() % (3600 * 1000 * 24);
var dateOnly = new Date(myDate - timePortion);
If you start with a string, you first need to parse it like so:
var myDate = new Date(dateString);
And if you come across timezone related problems as I have, this should fix it:
var timePortion = (myDate.getTime() - myDate.getTimezoneOffset() * 60 * 1000) % (3600 * 1000 * 24);
For windows, If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --
SHOW VARIABLES WHERE Variable_name = 'port';
mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port | 3306 |
+---------------+-------+
1 row in set (0.00 sec)
It will give you the port number on which MySQL is running.
Now this may include more than you need (and may not even work for command line applications in a non-graphical environment, I don't know), but there is nw.js. It's Blink (i.e. Chromium/Webkit) + io.js (i.e. Node.js).
You can use node-webkit-builder to build native executable binaries for Linux, OS X and Windows.
If you want a GUI, that's a huge plus. You can build one with web technologies.
If you don't, specify "node-main"
in the package.json
(and probably "window": {"show": false}
although maybe it works to just have a node-main
and not a main
)
I haven't tried to use it in exactly this way, just throwing it out there as a possibility. I can say it's certainly not an ideal solution for non-graphical Node.js applications.
A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-
, i.e. data-my-attribute="true"
.
I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause
DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave
I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered
for react-router v4.3,
const addQuery = (key, value) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.set(key, value);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
const removeQuery = (key) => {
let pathname = props.location.pathname;
// returns path: '/app/books'
let searchParams = new URLSearchParams(props.location.search);
// returns the existing query string: '?type=fiction&author=fahid'
searchParams.delete(key);
this.props.history.push({
pathname: pathname,
search: searchParams.toString()
});
};
```
```
function SomeComponent({ location }) {
return <div>
<button onClick={ () => addQuery('book', 'react')}>search react books</button>
<button onClick={ () => removeQuery('book')}>remove search</button>
</div>;
}
```
// To know more on URLSearchParams from
[Mozilla:][1]
var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
[1]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
one short way would be
$id = $this -> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users')
-> row()
->id;
echo "ID is ".$id;
if you're after the catalina.out log and you are using eclispe with tomcat, this works for me:
TypeScript isn't giving you a gun to shoot yourself in the foot with.
The iterator variable is a string because it is a string, full stop. Observe:
var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';
for(var key in obj) {
console.log('Type: ' + typeof key);
console.log(key + ' => ' + obj[key]);
}
How many key/value pairs are in obj
now? 6, more or less? No, 3, and all of the keys are strings:
Type: string
0 => zero point zero
Type: string
[object Object] => this obj;
Type: string
undefined => the literal string "undefined"
you can try writing the command using 'sudo':
sudo mkdir DirName
Options -Indexes perfectly works for me ,
here is .htaccess
file :
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes <---- This Works for Me :)
</IfModule>
....etc stuff
</IfModule>
After :
I tried a lot of methods on Chrome but the only thing that worked for me was "Clear browsing data"
Had to do the "advanced" version because standard didn't work. I suspect it was "Content Settings" that was doing it.
This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:
<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">
The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:
"Y-m-d\TH:i:s"
I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.
According to the C99 spec,
NULL
expands to a null pointer constant, which is not required to be, but typically is of type void *
'\0'
is a character constant; character constants are of type int
, so it's equivalen to plain 0
"\0"
is a null-terminated string literal and equivalent to the compound literal (char [2]){ 0, 0 }
NULL
, '\0'
and 0
are all null pointer constants, so they'll all yield null pointers on conversion, whereas "\0"
yields a non-null char *
(which should be treated as const
as modification is undefined); as this pointer may be different for each occurence of the literal, it can't be used as sentinel value.
Although you may use any integer constant expression of value 0
as a null pointer constant (eg '\0'
or sizeof foo - sizeof foo + (int)0.0
), you should use NULL
to make your intentions clear.
An import is required, import scipy.io
...
import scipy.io
mat = scipy.io.loadmat('file.mat')
Maybe try this:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
As NT3RP told us that:
... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...
So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]
This site says:
No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]
I hope I've helped and this is of some use to you (and others too). : )
If you're open to a Perl solution...
perl -lane 'print join " ",@F[1..$#F,0]' file
is a simple solution with an input/output separator of one space, which produces:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
This next one is slightly more complex
perl -F` ` -lane 'print join " ",@F[1..$#F,0]' file
and assumes that the input/output separator is two spaces:
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN
These command-line options are used:
-n
loop around every line of the input file, do not automatically print every line
-l
removes newlines before processing, and adds them back in afterwards
-a
autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace
-F
autosplit modifier, in this example splits on ' ' (two spaces)
-e
execute the following perl code
@F
is the array of words in each line, indexed starting with 0
$#F
is the number of words in @F
@F[1..$#F]
is an array slice of element 1 through the last element
@F[1..$#F,0]
is an array slice of element 1 through the last element plus element 0
First, add a textView in the XML file
<TextView
android:id="@+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate()
method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener()
on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});
You could add in your code a call system with the new definition:
sprintf(newdef,"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s:%s",ld1,ld2);
system(newdef);
But, I don't know it that is the rigth solution but it works.
Regards
Please find the below logic where it works on the condition.
If we simply call taskkill /im applicationname.exe
, it will kill only if this process is running. If this process is not running, it will throw an error.
So as to check before takskill
is called, a check can be done to make sure execute taskkill
will be executed only if the process is running, so that it won't throw error.
tasklist /fi "imagename eq applicationname.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "applicationname.exe"
You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.
So here's the complete walkthrough:
*InstallUtil.exe can be usually found here: C:\windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.ex??e
Program.cs
using System;
using System.IO;
using System.ServiceProcess;
namespace MyService
{
class Program
{
public const string ServiceName = "MyService";
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
// running as console app
Start(args);
Console.WriteLine("Press any key to stop...");
Console.ReadKey(true);
Stop();
}
else
{
// running as service
using (var service = new Service())
{
ServiceBase.Run(service);
}
}
}
public static void Start(string[] args)
{
File.AppendAllText(@"c:\temp\MyService.txt", String.Format("{0} started{1}", DateTime.Now, Environment.NewLine));
}
public static void Stop()
{
File.AppendAllText(@"c:\temp\MyService.txt", String.Format("{0} stopped{1}", DateTime.Now, Environment.NewLine));
}
}
}
MyService.cs
using System.ServiceProcess;
namespace MyService
{
class Service : ServiceBase
{
public Service()
{
ServiceName = Program.ServiceName;
}
protected override void OnStart(string[] args)
{
Program.Start(args);
}
protected override void OnStop()
{
Program.Stop();
}
}
}
MyServiceInstaller.cs
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace MyService
{
[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
public MyServiceInstaller()
{
var spi = new ServiceProcessInstaller();
var si = new ServiceInstaller();
spi.Account = ServiceAccount.LocalSystem;
spi.Username = null;
spi.Password = null;
si.DisplayName = Program.ServiceName;
si.ServiceName = Program.ServiceName;
si.StartType = ServiceStartMode.Automatic;
Installers.Add(spi);
Installers.Add(si);
}
}
}
When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.
Open Arduino IDE and go to files and click on the preference in the Arduino IDE.
Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.
Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.
You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.
If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric)
.
I can assure you that raw speed ultimately lies in the non-standard use of Indexes for blazing speed using large tables.
with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :
npm install consolidate --save
then you should change the default engine to html template by this:
app.set('view engine', 'html');
register the underscore template engine for the html extension:
app.engine('html', require('consolidate').underscore);
it's done !
Now for load for example an template called 'index.html':
res.render('index', { title : 'my first page'});
maybe you will need to install the underscore module.
npm install underscore --save
I hope this helped you!
If the format is "fixed" meaning you don't have to use other format you can have pure JavaScript instead of using whole library to format the date:
//Pad given value to the left with "0"_x000D_
function AddZero(num) {_x000D_
return (num >= 0 && num < 10) ? "0" + num : num + "";_x000D_
}_x000D_
_x000D_
window.onload = function() {_x000D_
var now = new Date();_x000D_
var strDateTime = [[AddZero(now.getDate()), _x000D_
AddZero(now.getMonth() + 1), _x000D_
now.getFullYear()].join("/"), _x000D_
[AddZero(now.getHours()), _x000D_
AddZero(now.getMinutes())].join(":"), _x000D_
now.getHours() >= 12 ? "PM" : "AM"].join(" ");_x000D_
document.getElementById("Console").innerHTML = "Now: " + strDateTime;_x000D_
};
_x000D_
<div id="Console"></div>
_x000D_
The variable strDateTime
will hold the date/time in the format you desire and you should be able to tweak it pretty easily if you need.
I'm using join
as good practice, nothing more, it's better than adding strings together.
What I have done with no memory leaks or lint warnings is to use @f.trajkovski's method, but instead of using MainActivity
, use WeakReference<MainActivity>
instead.
public class MainActivity extends AppCompatActivity {
public static WeakReference<MainActivity> weakActivity;
// etc..
public static MainActivity getmInstanceActivity() {
return weakActivity.get();
}
}
Then in MainActivity OnCreate()
weakActivity = new WeakReference<>(MainActivity.this);
Then in another class
MainActivity.getmInstanceActivity().yourMethod();
Works like a charm
You need this
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
'Code
End if
Well it simply means loading data you need currently instead of loading whole bunch of data at once which you won't use now. Thereby making application load time faster than usual.
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
Below Kotlin code can help to you
Create Marker
for (i in arrayList.indices) {
val marker = googleMap!!.addMarker(
MarkerOptions().position(
LatLng(
arrayList[i].location_latitude!!.toDoubleOrNull()!!,
arrayList[i].location_latitude!!.toDoubleOrNull()!!
)
).title(arrayList[i].business_name)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
)
marker.tag = i
}
Marker Click
googleMap!!.setOnMarkerClickListener { marker ->
Log.d(TAG, "Clicked on ${marker.tag}")
true
}
Simple:
Use <section>
.
and use <a href="page.html#tips">Visit the Useful Tips Section</a>
i am sort of new to go, but this is what i gathered up so far:
package srf
import (
"bytes"
"encoding/json"
"os"
)
func WriteDataToFileAsJSON(data interface{}, filedir string) (int, error) {
//write data as buffer to json encoder
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent("", "\t")
err := encoder.Encode(data)
if err != nil {
return 0, err
}
file, err := os.OpenFile(filedir, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return 0, err
}
n, err := file.Write(buffer.Bytes())
if err != nil {
return 0, err
}
return n, nil
}
This is the execution of the function, and just standard
b, _ := json.MarshalIndent(SomeType, "", "\t")
Code:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
minerals "./minerals"
srf "./srf"
)
func main() {
//array of Test struct
var SomeType [10]minerals.Test
//Create 10 units of some random data to write
for a := 0; a < 10; a++ {
SomeType[a] = minerals.Test{
Name: "Rand",
Id: 123,
A: "desc",
Num: 999,
Link: "somelink",
People: []string{"John Doe", "Aby Daby"},
}
}
//writes aditional data to existing file, or creates a new file
n, err := srf.WriteDataToFileAsJSON(SomeType, "test2.json")
if err != nil {
log.Fatal(err)
}
fmt.Println("srf printed ", n, " bytes to ", "test2.json")
//overrides previous file
b, _ := json.MarshalIndent(SomeType, "", "\t")
ioutil.WriteFile("test.json", b, 0644)
}
Wild guess: If your value is an empty string, you can use NULLIF to replace it for a NULL:
SELECT
NULLIF(your_value, '')::int
Just additional information to you guys:
take a look at the section "MP3 stuff and Metadata editors" in the page of PythonInMusic.
A quick way to do the thing now (previous ones haven't worked for me):
sudo wget https://github.com/mikefarah/yq/releases/download/v4.4.1/yq_linux_amd64 -O /usr/bin/yq &&\
sudo chmod +x /usr/bin/yq
Example asd.yaml:
a_list:
- key1: value1
key2: value2
key3: value3
parsing root:
user@vm:~$ yq e '.' asd.yaml
a_list:
- key1: value1
key2: value2
key3: value3
parsing key3:
user@vm:~$ yq e '.a_list[0].key3' asd.yaml
value3
Actually it's way easier to use ToolBucket plugin for Notepad++ to multiline replace.
To activate it just go to N++ menu:
Plugins > Plugin Manager > Show Plugin Manager > Check ToolBucket > Install.
Restart N++ and press ALT + SHIFT + F to multiline edit.
Here is the best way to do it in compilation time. I have used the arg_var count answer from here.
#define PP_NARG(...) \
PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) \
PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define PP_RSEQ_N() \
63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
#define TypedEnum(Name, ...) \
struct Name { \
enum { \
__VA_ARGS__ \
}; \
static const uint32_t Name##_MAX = PP_NARG(__VA_ARGS__); \
}
#define Enum(Name, ...) TypedEnum(Name, __VA_ARGS__)
To declare an enum:
Enum(TestEnum,
Enum_1= 0,
Enum_2= 1,
Enum_3= 2,
Enum_4= 4,
Enum_5= 8,
Enum_6= 16,
Enum_7= 32);
the max will be available here:
int array [TestEnum::TestEnum_MAX];
for(uint32_t fIdx = 0; fIdx < TestEnum::TestEnum_MAX; fIdx++)
{
array [fIdx] = 0;
}
Integer.toBinaryString((byteValue & 0xFF) + 256).substring(1)
In our case, it's an iOS app, built on Xcode 11.5, using cocoapods (and cocoapods-binary if you will).
We were seeing this crash:
dyld: Library not loaded: @rpath/PINOperation.framework/PINOperation
Referenced from: /private/var/containers/Bundle/Application/4C5F5E4C-8B71-4351-A0AB-C20333544569/Tellus.app/Frameworks/PINRemoteImage.framework/PINRemoteImage
Reason: image not found
Turns out that I had to delete the pods cache and re-run pod install, so Xcode would point this diff:
The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.
At the time of writing, supported platforms are:
The library consists of whereami.c
and whereami.h
and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:
#include "whereami.h"
int main() {
int length = wai_getExecutablePath(NULL, 0, NULL);
char* path = (char*)malloc(length + 1);
wai_getExecutablePath(path, length, &dirname_length);
path[length] = '\0';
printf("My path: %s", path);
free(path);
return 0;
}
The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.
And as said in the first comment: you can add info to any line you feel the need to
SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS
As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.
SOME CODE
GOTO LABEL ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL
SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP
:LABEL
CODE TO EXECUTE
Just having final
will have the intended effect.
final int x = 5;
...
x = 10; // this will cause a compilation error because x is final
Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
A new operator has been added, ??=
. This is equivalent to value = value ?? defaultValue
.
||=
and &&=
are similar, links below.
This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
// Equivalent to
a = a ?? true
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
function config(options) {
options.duration ??= 100
options.speed ??= 25
return options
}
config({ duration: 555 }) // { duration: 555, speed: 25 }
config({}) // { duration: 100, speed: 25 }
config({ duration: null }) // { duration: 100, speed: 25 }
??= Browser Support Nov 2020 - 77%
We can use ng-src
but when ng-src's value
became null
, ''
or undefined
, ng-src
will not work.
So just use ng-if
for this case:
http://jsfiddle.net/Hx7B9/299/
<div ng-app>
<div ng-controller="AppCtrl">
<a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
<button ng-click="changeLink()">Change Image</button>
</div>
</div>
var form = document.getElementById("idOfForm");
form.onsubmit = function() {
return false;
}
The way to use expr:
i=0
i=`expr $i + 1`
the way to use i++
((i++)); echo $i;
Tested in gnu bash
If you want to send additional parameters to the buttonClicked method, for example an indexPath or urlString, you can subclass the UIButton:
class SubclassedUIButton: UIButton {
var indexPath: Int?
var urlString: String?
}
Make sure to change the button's class in the identity inspector to subclassedUIButton. You can access the parameters inside the buttonClicked method using sender.indexPath
or sender.urlString
.
Note: If your button is inside a cell you can set the value of these additional parameters in the cellForRowAtIndexPath method (where the button is created).
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.
A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges
response. Chrome always sends a Range: bytes=0-
with its first GET request for a video, so it's something you can't dismiss.
Whenever a client includes Range:
in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:
Range: bytes=3744-
So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.
You can handle the type of 'range' you specified in your question in two ways:
First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927
Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*
Tips:
You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:
Request: Range: bytes=500-1000
Response: Content-Range: bytes 500-1000/123456
Remember that the range is zero-indexed, so Range: bytes=0-999
is actually requesting 1000 bytes, not 999, so respond with something like:
Content-Length: 1000
Content-Range: bytes 0-999/123456
Or:
Content-Length: 1000
Content-Range: bytes 0-999/*
But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:
X-Content-Duration: 63.23
This must be a floating point. Unlike Content-Length
, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:
X-Content-Duration: 7200.00
With some media types, such as webm, you must also include the content-type, such as:
Content-Type: video/webm
All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.
X-Content-Duration
is being phased out in favor of Content-Duration
, so I'd include that too. A basic, response to a "0-" request would include at least the following:
HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53
One more point: Chrome always starts its first video request with the following:
Range: bytes=0-
Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.
In Visual Basic, do this to select a row in a DataGridView
; the selected row will appear with a highlighted color but note that the cursor position will not change:
Grid.Rows(0).Selected = True
Do this change the position of the cursor:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Combining the lines above will position the cursor and select a row. This is the standard procedure for focusing and selecting a row in a DataGridView
:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Grid.Rows(0).Selected = True
Another option that works fine for me is to use ConEmu, see http://conemu.github.io/en/ConEmuArgs.html
"C:\Program Files\ConEmu\ConEmu64.exe" -min -run myfile.bat
In case anyone is still confused - if you are on a Mac, do the following:
open .bash_profile
export PYTHONPATH=$PYTHONPATH:foo/bar
I had met this problem too.And I found that happend beacuse I forgot to add the user-name before the host name: like this:
ssh -i test.pem ec2-32-122-42-91.us-west-2.compute.amazonaws.com
and I add the user name:
ssh -i test.pem [email protected]
it works!
node-sass
(the official SASS wrapper for node.js
) provides a command line option --include-path
to help with such requirements.
Example:
In package.json
:
"scripts": {
"build-css": "node-sass src/ -o src/ --include-path src/",
}
Now, if you have a file src/styles/common.scss
in your project, you can import it with @import 'styles/common';
anywhere in your project.
Refer https://github.com/sass/node-sass#usage-1 for more details.
The bandwidth of a link is the theoretical maximum amount of data that could be sent over that channel without regard to practical considerations. For example, you could pump 10^9 bits per second down a Gigabit Ethernet link over a Cat-6e or fiber optic cable. Unfortunately this would be a completely unformatted stream of bits.
To make it actually useful there's a start of frame sequence which precedes any actual data bits, a frame check sequence at the end for error detection and an idle period between transmitted frames. All of those occupy what is referred to as "bit times" meaning the amount of time it takes to transmit one bit over the line. This is all necessary overhead, but is subtracted from the total bandwidth of the link.
And this is only for the lowest level protocol which is stuffing raw data out onto the wire. Once you start adding in the MAC addresses, an IP header and a TCP or UDP header, then you've added even more overhead.
Check out http://en.wikipedia.org/wiki/Ethernet_frame. Similar problems exist for other transmission media.
The original questions seems to come from confusion about a) where is the file, and b) where is it being looked for (and why can't we find it there when we do a locate or grep). I think Alnitak's point was that you want to find where it was linked to - but grep will not show you a link, right? The file doesn't live there, since it's a link it is just a pointer. You still need to know where to put the link.
my sock file is definitely in /tmp and the ERROR I am getting is looking for it in /var/lib/ (not just /var) I have linked to /var and /var/lib now, and I still am getting the error "Cannot connect to local MySQL server through socket 'var/lib/mysql.sock' (2)".
Note the (2) after the error.... I found on another thread that this means the socket might be indeed attempted to be used, but something is wrong with the socket itself - so to shut down the machine - completely - so that the socket closes. Then a restart should fix it. I tried this, but it didn't work for me (now I question if I restarted too quickly? really?) Maybe it will be a solution for someone else.
Main two reasons only as mentioned in above comments
UseDefaultCredentials
to false first and then set Credentials
Or
Put smtp.UseDefaultCredentials = false;
above the smtp.Credentials assignment
.This is actually a multi-step process. First you'll need to add all your files to the current stage:
git add .
You can verify that your files will be added when you commit by checking the status of the current stage:
git status
The console should display a message that lists all of the files that are currently staged, like this:
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: README
# new file: src/somefile.js
#
If it all looks good then you're ready to commit. Note that the commit action only commits to your local repository.
git commit -m "some message goes here"
If you haven't connected your local repository to a remote one yet, you'll have to do that now. Assuming your remote repository is hosted on GitHub and named "Some-Awesome-Project", your command is going to look something like this:
git remote add origin [email protected]:username/Some-Awesome-Project
It's a bit confusing, but by convention we refer to the remote repository as 'origin' and the initial local repository as 'master'. When you're ready to push your commits to the remote repository (origin), you'll need to use the 'push' command:
git push origin master
For more information check out the tutorial on GitHub: http://learn.github.com/p/intro.html
This should do it:
for (var i = 0; i < bank_holidays.length; i++) {
if (bank_holidays[i] === '06/04/2012') {
alert('LOL');
}
}
The same problem when I used 'org.springframework.android:spring-android-rest-template:2.0.0.M1' in Android Studio 1.0.1. I need include this in build.gradle
android{
...
packagingOptions{
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
}
...
}
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
I had the same issue and did all the tips with no luck. Finally when I changed password to something different, for some reason it worked! (the initial password or the new one did not have any special characters)
For me I just noticed that it was my .h archive with a '{'. Maye that can help someone =)
Inspired by this post and by the Stack Overflow question that led me here -- Is it possible to insert multiple rows at a time in an SQLite database? -- I've posted my first Git repository:
https://github.com/rdpoor/CreateOrUpdate
which bulk loads an array of ActiveRecords into MySQL, SQLite or PostgreSQL databases. It includes an option to ignore existing records, overwrite them or raise an error. My rudimentary benchmarks show a 10x speed improvement compared to sequential writes -- YMMV.
I'm using it in production code where I frequently need to import large datasets, and I'm pretty happy with it.
Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.
_dsACL.Documents.FirstOrDefault(o => o.ID == id);
Range("A:B,D:E,G:H").Select
can help
Edit note: I just saw you have used different column sequence, I have updated my answer
I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard
or a branch -D
fail to work, try
git pull origin
git reset --hard
It's two steps but I like to do it this way:
First create a file with a particular date/time. In this case, the file is 2008-10-01 at midnight
touch -t 0810010000 /tmp/t
Now we can find all files that are newer or older than the above file (going by file modified date. You can also use -anewer for accessed and -cnewer file status changed).
find / -newer /tmp/t
find / -not -newer /tmp/t
You could also look at files between certain dates by creating two files with touch
touch -t 0810010000 /tmp/t1
touch -t 0810011000 /tmp/t2
This will find files between the two dates & times
find / -newer /tmp/t1 -and -not -newer /tmp/t2
You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
You can find an overview of a lot of design patterns in Wikipedia. It also mentions which patterns are mentioned by GoF. I'll sum them up here and try to assign as many pattern implementations as possible, found in both the Java SE and Java EE APIs.
javax.xml.parsers.DocumentBuilderFactory#newInstance()
javax.xml.transform.TransformerFactory#newInstance()
javax.xml.xpath.XPathFactory#newInstance()
java.lang.StringBuilder#append()
(unsynchronized)java.lang.StringBuffer#append()
(synchronized)java.nio.ByteBuffer#put()
(also on CharBuffer
, ShortBuffer
, IntBuffer
, LongBuffer
, FloatBuffer
and DoubleBuffer
)javax.swing.GroupLayout.Group#addComponent()
java.lang.Appendable
java.util.stream.Stream.Builder
java.util.Calendar#getInstance()
java.util.ResourceBundle#getBundle()
java.text.NumberFormat#getInstance()
java.nio.charset.Charset#forName()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String)
(Returns singleton object per protocol)java.util.EnumSet#of()
javax.xml.bind.JAXBContext#createMarshaller()
and other similar methodsjava.lang.Object#clone()
(the class has to implement java.lang.Cloneable
)java.util.Arrays#asList()
java.util.Collections#list()
java.util.Collections#enumeration()
java.io.InputStreamReader(InputStream)
(returns a Reader
)java.io.OutputStreamWriter(OutputStream)
(returns a Writer
)javax.xml.bind.annotation.adapters.XmlAdapter#marshal()
and #unmarshal()
new LinkedHashMap(LinkedHashSet<K>, List<V>)
which returns an unmodifiable linked map which doesn't clone the items, but uses them. The java.util.Collections#newSetFromMap()
and singletonXXX()
methods however comes close.java.awt.Container#add(Component)
(practically all over Swing thus)javax.faces.component.UIComponent#getChildren()
(practically all over JSF UI thus)java.io.InputStream
, OutputStream
, Reader
and Writer
have a constructor taking an instance of same type.java.util.Collections
, the checkedXXX()
, synchronizedXXX()
and unmodifiableXXX()
methods.javax.servlet.http.HttpServletRequestWrapper
and HttpServletResponseWrapper
javax.swing.JScrollPane
javax.faces.context.FacesContext
, it internally uses among others the abstract/interface types LifeCycle
, ViewHandler
, NavigationHandler
and many more without that the enduser has to worry about it (which are however overrideable by injection).javax.faces.context.ExternalContext
, which internally uses ServletContext
, HttpSession
, HttpServletRequest
, HttpServletResponse
, etc.java.lang.Integer#valueOf(int)
(also on Boolean
, Byte
, Character
, Short
, Long
and BigDecimal
)java.lang.reflect.Proxy
java.rmi.*
javax.ejb.EJB
(explanation here)javax.inject.Inject
(explanation here)javax.persistence.PersistenceContext
java.lang.Runnable
javax.swing.Action
java.util.Pattern
java.text.Normalizer
java.text.Format
javax.el.ELResolver
java.util.Iterator
(thus among others also java.util.Scanner
!).java.util.Enumeration
java.util.Timer
(all scheduleXXX()
methods)java.util.concurrent.Executor#execute()
java.util.concurrent.ExecutorService
(the invokeXXX()
and submit()
methods)java.util.concurrent.ScheduledExecutorService
(all scheduleXXX()
methods)java.lang.reflect.Method#invoke()
java.util.Date
(the setter methods do that, Date
is internally represented by a long
value)java.io.Serializable
javax.faces.component.StateHolder
java.util.Observer
/java.util.Observable
(rarely used in real world though)java.util.EventListener
(practically all over Swing thus)javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener
javax.faces.lifecycle.LifeCycle#execute()
(controlled by FacesServlet
, the behaviour is dependent on current phase (state) of JSF lifecycle)java.util.Comparator#compare()
, executed by among others Collections#sort()
.javax.servlet.http.HttpServlet
, the service()
and all doXXX()
methods take HttpServletRequest
and HttpServletResponse
and the implementor has to process them (and not to get hold of them as instance variables!).javax.servlet.Filter#doFilter()
java.io.InputStream
, java.io.OutputStream
, java.io.Reader
and java.io.Writer
.java.util.AbstractList
, java.util.AbstractSet
and java.util.AbstractMap
.javax.servlet.http.HttpServlet
, all the doXXX()
methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them.Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:
CREATE PROCEDURE ExecuteMyHugeQuery
@SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
-- Now, if the length is greater than some arbitrary value
-- Let's say 2000 for this example
-- Let's chunk it
-- Let's also assume we won't allow anything larger than 8000 total
DECLARE @len INT
SELECT @len = LEN(@SQL)
IF (@len > 8000)
BEGIN
RAISERROR ('The query cannot be larger than 8000 characters total.',
16,
1);
END
-- Let's declare our possible chunks
DECLARE @Chunk1 VARCHAR(2000),
@Chunk2 VARCHAR(2000),
@Chunk3 VARCHAR(2000),
@Chunk4 VARCHAR(2000)
SELECT @Chunk1 = '',
@Chunk2 = '',
@Chunk3 = '',
@Chunk4 = ''
IF (@len > 2000)
BEGIN
-- Let's set the right chunks
-- We already know we need two chunks so let's set the first
SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)
-- Let's see if we need three chunks
IF (@len > 4000)
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)
-- Let's see if we need four chunks
IF (@len > 6000)
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
END
ELSE
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
END
END
ELSE
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
END
END
-- Alright, now that we've broken it down, let's execute it
EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END
You can iterate using the index access,
To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.
code:
void erase(std::vector<int>& v, int num)
{
size_t j = 0;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != num) v[j++] = v[i];
}
// trim vector to new size
v.resize(j);
}
In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.
This code does not use erase
method, but solves your task.
Using pure stl you can do this in the following way (this is similar to the Motti's answer):
#include <algorithm>
void erase(std::vector<int>& v, int num) {
vector<int>::iterator it = remove(v.begin(), v.end(), num);
v.erase(it, v.end());
}
Not quite sure what the 300 is supposed to mean? Miss typo? However for iframes it would be best to use CSS :) - Ive found befor when importing youtube videos that it ignores inline things.
<style>
#myFrame { width:100%; height:100%; }
</style>
<iframe src="html_intro.asp" id="myFrame">
<p>Hi SOF</p>
</iframe>
I've got a one liner to make HTML Tables look BootStrapped:
<table class="table table-striped table-bordered table-hover">
The theme suits other controls and it supports alternate row highlighting.
One simple way to do that is:
String url = "http://test.com/Services/rest/{id}/Identifier"
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));
and then adds the query params.
I've recently stumbled upon the following solution to this problem:
Source: Multiple versions of Chrome
...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):
Install Chrome 2, you'll find it
Application Data
folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
and run Chrome
Open registry and save
[HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}] [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
keys, put them into one chrome2.reg file and copy this file next to
chrome.exe
(ChromeDir\Application)Rename Chrome folder to something else (e.g. Chrome2)
Install Chrome 3, it will install to Chrome folder again and run Chrome
- Save the same keys (there are changes due to different version) and save it to the
chrome3.reg
file next tochrome.exe
file of this new version againRename the folder again (e.g. Chrome3)
the result would be that there is no Chrome dir (only Chrome2 and Chrome3)
Go to the Application folder of Chrome2, create
chrome.bat
file with this content:@echo off regedit /S chrome2.reg START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data" rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
the first line is generic batch command, the second line will update registry with the content of
chrome2.reg
file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.Notice short name format passed as
-user-data-dir
parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3
Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.
Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.
Bronislav Klucka
Check if IIS Express is installed. If IIS Express is missing, Visual Studio might discard the setting <UseIISExpress>false</UseIISExpress>
and still look for the express.
I think this distinction can best be explained via the logical order of operations in SQL, which is, simplified:
FROM
(including joins)WHERE
GROUP BY
HAVING
WINDOW
SELECT
DISTINCT
UNION
, INTERSECT
, EXCEPT
ORDER BY
OFFSET
FETCH
Joins are not a clause of the select statement, but an operator inside of FROM
. As such, all ON
clauses belonging to the corresponding JOIN
operator have "already happened" logically by the time logical processing reaches the WHERE
clause. This means that in the case of a LEFT JOIN
, for example, the outer join's semantics has already happend by the time the WHERE
clause is applied.
I've explained the following example more in depth in this blog post. When running this query:
SELECT a.actor_id, a.first_name, a.last_name, count(fa.film_id)
FROM actor a
LEFT JOIN film_actor fa ON a.actor_id = fa.actor_id
WHERE film_id < 10
GROUP BY a.actor_id, a.first_name, a.last_name
ORDER BY count(fa.film_id) ASC;
The LEFT JOIN
doesn't really have any useful effect, because even if an actor did not play in a film, the actor will be filtered, as its FILM_ID
will be NULL
and the WHERE
clause will filter such a row. The result is something like:
ACTOR_ID FIRST_NAME LAST_NAME COUNT
--------------------------------------
194 MERYL ALLEN 1
198 MARY KEITEL 1
30 SANDRA PECK 1
85 MINNIE ZELLWEGER 1
123 JULIANNE DENCH 1
I.e. just as if we inner joined the two tables. If we move the filter predicate in the ON
clause, it now becomes a criteria for the outer join:
SELECT a.actor_id, a.first_name, a.last_name, count(fa.film_id)
FROM actor a
LEFT JOIN film_actor fa ON a.actor_id = fa.actor_id
AND film_id < 10
GROUP BY a.actor_id, a.first_name, a.last_name
ORDER BY count(fa.film_id) ASC;
Meaning the result will contain actors without any films, or without any films with FILM_ID < 10
ACTOR_ID FIRST_NAME LAST_NAME COUNT
-----------------------------------------
3 ED CHASE 0
4 JENNIFER DAVIS 0
5 JOHNNY LOLLOBRIGIDA 0
6 BETTE NICHOLSON 0
...
1 PENELOPE GUINESS 1
200 THORA TEMPLE 1
2 NICK WAHLBERG 1
198 MARY KEITEL 1
Always put your predicate where it makes most sense, logically.
Try this script.
http://www.biterscripting.com/SS_URLs.html
When I use it with this url,
script SS_URLs.txt URL("http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c")
It shows me all the links on the page for this thread.
http://sstatic.net/so/all.css
http://sstatic.net/so/favicon.ico
http://sstatic.net/so/apple-touch-icon.png
.
.
.
You can modify that script to check for images, variables, whatever.
Running a from class inside your JAR file load.jar
is possible via
java -jar load.jar
When doing so, you have to define the application entry point. Usually this is done by providing a manifest file that contains the Main-Class
tag. For documentation and examples have a look at this page.
The argument load=2
can be supplied like in a normal Java applications:
java -jar load.jar load=2
Having also the current directory contained in the classpath, required to also make use of the Class-Path
tag. See here for more information.
Simply move the file and stage with:
git add .
Before commit you can check the status:
git status
That will show:
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
renamed: old-folder/file.txt -> new-folder/file.txt
I tested with Git version 2.26.1.
Extracted from GitHub Help Page.
I got the following example here
/*
7) Join Strings using separator >>>AB$#$CD$#$EF
*/
import org.apache.commons.lang.StringUtils;
public class StringUtilsTrial {
public static void main(String[] args) {
// Join all Strings in the Array into a Single String, separated by $#$
System.out.println("7) Join Strings using separator >>>"
+ StringUtils.join(new String[] { "AB", "CD", "EF" }, "$#$"));
}
}
Oracle JRockit, which can handle a non-contiguous heap, can have a Java heap size of 2.85 GB on Windows 2003/XP with the /3GB switch. It seems that fragmentation can have quite an impact on how large a Java heap can be.
I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.
My solution (assuming we're looking for all cpp
files living directly in arch
directories):
find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print
I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.
Open your.gitconfig file to add the longpaths property. So it will look like the following:
[core]
symlinks = false
autocrlf = true
longpaths = true
Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.
you can find more info it you look in android/app
or com\android\internal\policy\impl
Good Luck !
Rather than mucking around with virtualenv-specific shebangs, just prepend PATH
onto the crontab.
From an activated virtualenv, run these three commands and python scripts should just work:
$ echo "PATH=$PATH" > myserver.cron
$ crontab -l >> myserver.cron
$ crontab myserver.cron
The crontab's first line should now look like this:
PATH=/home/me/virtualenv/bin:/usr/bin:/bin: # [etc...]
I use the CSS properties :
1) "overflow-x: auto
";
2) "overflow-y: hidden
";
3) "white-space: nowrap
";
Don't forget to set a Width, both for the container and inner DIVS components. The property "white-space : nowrap" allows the inner DIVS not to drop on a different line.
Considering the following HTML:
<div class="container">
<div class="inner-1"></div>
<div class="inner-2"></div>
<div class="inner-3"></div>
</div>
I use the following CSS to have an horizontal scroll only:
.container {
height: 80px;
width: 600px;
overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;
}
.inner-1,.inner-2,.inner-3 {
height: 60px;
max-width: 250px;
display: inline-block; /* this should fix it */
}
Fiddle: https://jsfiddle.net/qrjh93x8/ (not working with the above code)
The answer from @zags is comprehensive and should suffice but the #5 method (which is the best one IMO) throws an error so I improved the helper function.
As the OP requested for converting many_to_many
fields into a list of primary keys rather than a list of objects, I enhanced the function so the return value is now JSON serializable - by converting datetime
objects into str
and many_to_many
objects to a list of id's.
import datetime
def ModelToDict(instance):
'''
Returns a dictionary object containing complete field-value pairs of the given instance
Convertion rules:
datetime.date --> str
many_to_many --> list of id's
'''
concrete_fields = instance._meta.concrete_fields
m2m_fields = instance._meta.many_to_many
data = {}
for field in concrete_fields:
key = field.name
value = field.value_from_object(instance)
if type(value) == datetime.datetime:
value = str(field.value_from_object(instance))
data[key] = value
for field in m2m_fields:
key = field.name
value = field.value_from_object(instance)
data[key] = [rel.id for rel in value]
return data
in some cases it's the best practice in other it's not a good idea it's context driven if you chose to do so using the following is the best way to pass from an activity to her sons :
Intent i = new Intent(myCurrentActivityName.this,activityIWishToRun.class);
startActivityForResult(i, GlobalDataStore.STATIC_INTEGER_VALUE);
the thing is whenever you finish() from activityIWishToRun you return to your a living activity
Even if both work, I would use the latter.
location
is an object, and assigning a string to an object doesn't bode well for readability or maintenance.
You can also press F1 to open the Command Palette
and then remove the >
via Backspace. Now you can search for files, too.
@Mark Rajcok gave a great solution for ion projects that include a range type input.
In any other case of non ion projects I will suggest this:
HTML:
<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">
Component:
onChangeAchievement(eventStr: string, eRef): string {
//Do something (some manipulations) on input and than return it to be saved:
//In case you need to force of modifing the Element-Reference value on-focus of input:
var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
if (eventStr != eventStrToReplace) {
eRef.value = eventStrToReplace;
}
return this.getNumberOnChange(eventStr);
}
The idea here:
Letting the (ngModelChange)
method to do the Setter job:
(ngModelChange)="range=saverange($event, points)
Enabling direct access to the native Dom element using this call:
eRef.value = eventStrToReplace;
If you have PHP5 and the HTTP stream wrapper enabled on your server, it's incredibly simple to copy it to a local file:
copy('http://somedomain.com/file.jpeg', '/tmp/file.jpeg');
This will take care of any pipelining etc. that's needed. If you need to provide some HTTP parameters there is a third 'stream context' parameter you can provide.
Same problem happened with me when i try to show popup menu in activity i also got same excpetion but i encounter problem n resolve by providing context
YourActivityName.this
instead of getApplicationContext()
at
Dialog dialog = new Dialog(getApplicationContext());
and yes it worked for me may it will help someone else
Just took a look over the mustache docs and they support "inverted sections" in which they state
they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list
http://mustache.github.io/mustache.5.html#Inverted-Sections
{{#value}}
value is true
{{/value}}
{{^value}}
value is false
{{/value}}
selection=selection.values
this do things at a very fast way.
Why would you want length in this case?
If you do want to check for length, have the server return a JSON array with key-value pairs like this:
[
{key:value},
{key:value}
]
In JSON, [ and ] represents an array (with a length property), { and } represents a object (without a length property). You can iterate through the members of a object, but you will get functions as well, making a length check of the numbers of members useless except for iterating over them.
ArrayList.clear(From Java Doc):
Removes all of the elements from this list. The list will be empty after this call returns
In more modern browsers (including IE 10+) you can now use calc()
:
.moveto {
top: 0px;
left: calc(100% - 50px);
}
To run multiple commands just add &&
between two commands like this: command1 && command2
And if you want to run them in two different terminals then you do it like this:
gnome-terminal -e "command1" && gnome-terminal -e "command2"
This will open 2 terminals with command1
and command2
executing in them.
Hope this helps you.
You can't set X-Frame-Options
on the iframe
. That is a response header set by the domain from which you are requesting the resource (google.com.ua
in your example). They have set the header to SAMEORIGIN
in this case, which means that they have disallowed loading of the resource in an iframe
outside of their domain. For more information see The X-Frame-Options response header on MDN.
A quick inspection of the headers (shown here in Chrome developer tools) reveals the X-Frame-Options
value returned from the host.
Generally you don't kill, stop, or interrupt a thread (or check wheter it is interrupted()), but let it terminate naturally.
It is simple. You can use any loop together with (volatile) boolean variable inside run() method to control thread's activity. You can also return from active thread to the main thread to stop it.
This way you gracefully kill a thread :) .
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
If you're struggling with such an issue using Lollipop (Android 5.*) probably you guys should do one simple step that I'd done before my ADB (I use Ubuntu) got my phone:
Change USB PC connection type to "Send images(PTP)" (before I've been using "Media device(MTP)")
Just like this:
And don't forget to activate checkbox "USB debugging".
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
You may check service status of MS SQL Server 2014. In Windows 7 you can do that by:
There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.
Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.
If you want upgrade only packaged installed by pip, and to avoid upgrading packages that are installed by other tools (like apt, yum etc.), then you can use this script that I use on my Ubuntu (maybe works also on other distros) - based on this post:
printf "To update with pip: pip install -U"
pip list --outdated 2>/dev/null | gawk '{print $1;}' | while read; do pip show "${REPLY}" 2>/dev/null | grep 'Location: /usr/local/lib/python2.7/dist-packages' >/dev/null; if (( $? == 0 )); then printf " ${REPLY}"; fi; done; echo
String s = "";
s.length();
String s = null;
s.length();
A reference to an empty string ""
points to an object in the heap - so you can call methods on it.
But a reference pointing to null
has no object to point in the heap and thus you'll get a NullPointerException
.
Example:
<songs>
<song dateplayed="2011-07-24 19:40:26">
<title>I left my heart on Europa</title>
<artist>Ship of Nomads</artist>
</song>
<song dateplayed="2011-07-24 19:27:42">
<title>Oh Ganymede</title>
<artist>Beefachanga</artist>
</song>
<song dateplayed="2011-07-24 19:23:50">
<title>Kallichore</title>
<artist>Jewitt K. Sheppard</artist>
</song>
then:
<?php
$mysongs = simplexml_load_file('songs.xml');
echo $mysongs->song[0]->artist;
?>
Output on your browser: Ship of Nomads
credits: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
The way you're doing it you're querying for the process twice. Also Lynn raises a good point about being nice first. I'd probably try something like the following:
# get Firefox process
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
# try gracefully first
$firefox.CloseMainWindow()
# kill after five seconds
Sleep 5
if (!$firefox.HasExited) {
$firefox | Stop-Process -Force
}
}
Remove-Variable firefox
Unfortuantely, as div
elements can't be direct descendants of table
elements, the way I know to do this is to apply the CSS rules you want to each tr
element that you want to apply it to.
<table>
<tr><th>Test Table</th><tr>
<tr><td>123456789</td><tr>
<tr style="display: none; other-property: value;"><td>123456789</td><tr>
<tr style="display: none; other-property: value;"><td>123456789</td><tr>
<tr><td>123456789</td><tr>
<tr><td>123456789</td><tr>
</table>
If you have more than one CSS rule to apply to the rows in question, give the applicable rows a class
instead and offload the rules to external CSS.
<table>
<tr><th>Test Table</th><tr>
<tr><td>123456789</td><tr>
<tr class="something"><td>123456789</td><tr>
<tr class="something"><td>123456789</td><tr>
<tr><td>123456789</td><tr>
<tr><td>123456789</td><tr>
</table>
Do check if you have marked the controller class with @RestController annotation.
One of the subtleties in this question involves the "leading delimiter" question: if you are going to have a combined array of tokens and delimiters you have to know whether it starts with a token or a delimiter. You could of course just assume that a leading delim should be discarded but this seems an unjustified assumption. You might also want to know whether you have a trailing delim or not. This sets two boolean flags accordingly.
Written in Groovy but a Java version should be fairly obvious:
String tokenRegex = /[\p{L}\p{N}]+/ // a String in Groovy, Unicode alphanumeric
def finder = phraseForTokenising =~ tokenRegex
// NB in Groovy the variable 'finder' is then of class java.util.regex.Matcher
def finderIt = finder.iterator() // extra method added to Matcher by Groovy magic
int start = 0
boolean leadingDelim, trailingDelim
def combinedTokensAndDelims = [] // create an array in Groovy
while( finderIt.hasNext() )
{
def token = finderIt.next()
int finderStart = finder.start()
String delim = phraseForTokenising[ start .. finderStart - 1 ]
// Groovy: above gets slice of String/array
if( start == 0 ) leadingDelim = finderStart != 0
if( start > 0 || leadingDelim ) combinedTokensAndDelims << delim
combinedTokensAndDelims << token // add element to end of array
start = finder.end()
}
// start == 0 indicates no tokens found
if( start > 0 ) {
// finish by seeing whether there is a trailing delim
trailingDelim = start < phraseForTokenising.length()
if( trailingDelim ) combinedTokensAndDelims << phraseForTokenising[ start .. -1 ]
println( "leading delim? $leadingDelim, trailing delim? $trailingDelim, combined array:\n $combinedTokensAndDelims" )
}
It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/
It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, AndroidLocalize.class);
finish();
startActivity(refresh);
}
Make sure you imported following packages:
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
add in manifest to activity android:configChanges="locale|orientation"
I've face this problem, i fixed it by deleting the emulator then created a new one with higher API level.
In my case I've created API-30
2D array:
int sum(int array[][COLS], int rows)
{
}
3D array:
int sum(int array[][B][C], int A)
{
}
4D array:
int sum(int array[][B][C][D], int A)
{
}
and nD array:
int sum(int ar[][B][C][D][E][F].....[N], int A)
{
}
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
You can't modify items in tuple, but you can modify properties of mutable objects in tuples (for example if those objects are lists or actual class objects)
For example
my_list = [1,2]
tuple_of_lists = (my_list,'hello')
print(tuple_of_lists) # ([1, 2], 'hello')
my_list[0] = 0
print(tuple_of_lists) # ([0, 2], 'hello')
The .get() method will return an array from a jQuery object. In addition you can use .map to project to something before calling get()
var idarray = $("#myDiv")
.find("span") //Find the spans
.map(function() { return this.id; }) //Project Ids
.get(); //ToArray
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
C99 way, also supported by VC++ compiler.
#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)
It seems they offer a js
option for the format parameter, which will return JSONP. You can retrieve JSONP like so:
function getJSONP(url, success) {
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
console.log(data);
});
const
is to the left of *
, it refers to the value (it doesn't matter whether it's const int
or int const
)const
is to the right of *
, it refers to the pointer itselfAn important point: const int *p
does not mean the value you are referring to is constant!!. It means that you can't change it through that pointer (meaning, you can't assign $*p = ...`). The value itself may be changed in other ways. Eg
int x = 5;
const int *p = &x;
x = 6; //legal
printf("%d", *p) // prints 6
*p = 7; //error
This is meant to be used mostly in function signatures, to guarantee that the function can't accidentally change the arguments passed.
If you want to append a value to myList, use myList.append(s)
.
Strings are immutable -- you can't append to them.
Your initial statement in the marked solution isn't entirely true. While your new solution may accomplish your original goal, it is still possible to circumvent the original error while preserving your AuthorizationHandler logic--provided you have basic authentication scheme handlers in place, even if they are functionally skeletons.
Speaking broadly, Authentication Handlers and schemes are meant to establish + validate identity, which makes them required for Authorization Handlers/policies to function--as they run on the supposition that an identity has already been established.
ASP.NET Dev Haok summarizes this best best here: "Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)." https://github.com/aspnet/Security/issues/1469
In my case, the solution I'm working on provided its own implicit concept of identity, so we had no need for authentication schemes/handlers--just header tokens for authorization. So until our identity concepts changes, our header token authorization handlers that enforce the policies can be tied to 1-to-1 scheme skeletons.
Tags on endpoints:
[Authorize(AuthenticationSchemes = "AuthenticatedUserSchemeName", Policy = "AuthorizedUserPolicyName")]
Startup.cs:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "AuthenticatedUserSchemeName";
}).AddScheme<ValidTokenAuthenticationSchemeOptions, ValidTokenAuthenticationHandler>("AuthenticatedUserSchemeName", _ => { });
services.AddAuthorization(options =>
{
options.AddPolicy("AuthorizedUserPolicyName", policy =>
{
//policy.RequireClaim(ClaimTypes.Sid,"authToken");
policy.AddAuthenticationSchemes("AuthenticatedUserSchemeName");
policy.AddRequirements(new ValidTokenAuthorizationRequirement());
});
services.AddSingleton<IAuthorizationHandler, ValidTokenAuthorizationHandler>();
Both the empty authentication handler and authorization handler are called (similar in setup to OP's respective posts) but the authorization handler still enforces our authorization policies.
Use the string's constructor
basic_string(const charT* s,size_type n, const Allocator& a = Allocator());
EDIT:
OK, then if the C string length is not given explicitly, use the ctor:
basic_string(const charT* s, const Allocator& a = Allocator());
Have you tried flip-flopping it a bit?
var newcurrentpageTemp = parseInt($(this).attr("id"));
newcurrentpageTemp++;
alert(newcurrentpageTemp));
You can either use:
<button onclick="window.history.back()">Back</button>
or..
<button onclick="window.history.go(-1)">Back</button>
The difference, of course, is back()
only goes back 1 page but go()
goes back/forward the number of pages you pass as a parameter, relative to your current page.
Yes it possible to have constructor in structure here is one example:
#include<iostream.h>
struct a {
int x;
a(){x=100;}
};
int main() {
struct a a1;
getch();
}
I use a singleton class, so that I can mock the class and change the constants if necessary for testing. The constants class looks like this:
#import <Foundation/Foundation.h>
@interface iCode_Framework : NSObject
@property (readonly, nonatomic) unsigned int iBufCapacity;
@property (readonly, nonatomic) unsigned int iPort;
@property (readonly, nonatomic) NSString * urlStr;
@end
#import "iCode_Framework.h"
static iCode_Framework * instance;
@implementation iCode_Framework
@dynamic iBufCapacity;
@dynamic iPort;
@dynamic urlStr;
- (unsigned int)iBufCapacity
{
return 1024u;
};
- (unsigned int)iPort
{
return 1978u;
};
- (NSString *)urlStr
{
return @"localhost";
};
+ (void)initialize
{
if (!instance) {
instance = [[super allocWithZone:NULL] init];
}
}
+ (id)allocWithZone:(NSZone * const)notUsed
{
return instance;
}
@end
And it is used like this (note the use of a shorthand for the constants c - it saves typing [[Constants alloc] init]
every time):
#import "iCode_FrameworkTests.h"
#import "iCode_Framework.h"
static iCode_Framework * c; // Shorthand
@implementation iCode_FrameworkTests
+ (void)initialize
{
c = [[iCode_Framework alloc] init]; // Used like normal class; easy to mock!
}
- (void)testSingleton
{
STAssertNotNil(c, nil);
STAssertEqualObjects(c, [iCode_Framework alloc], nil);
STAssertEquals(c.iBufCapacity, 1024u, nil);
}
@end
Simple solution for all gaps:
public boolean isNowTimeBetween(String startTime, String endTime) {
LocalTime start = LocalTime.parse(startTime);//"22:00"
LocalTime end = LocalTime.parse(endTime);//"10:00"
LocalTime now = LocalTime.now();
if (start.isBefore(end))
return now.isAfter(start) && now.isBefore(end);
return now.isBefore(start)
? now.isBefore(start) && now.isBefore(end)
: now.isAfter(start) && now.isAfter(end);
}
Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:
try {
File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}
You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task
or Task<T>
, if you return nothing and you want your method will be run asyncronously you should define your method like this:
private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); }
And in Main method you can't await for DoDownloadAsync
, because you can't use await keyword in non-async function, and you can't make Main
async. So consider this:
var result = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); result.Wait();
Have you tried using Unix style slashes (/ instead of \)?
\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.
Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.
none of the answers worked for me in 2017 with capybara 2.7. I got "ArgumentError: wrong number of arguments (given 2, expected 0)"
But this did:
find('#organizationSelect').all(:css, 'option').find { |o| o.value == 'option_name_here' }.select_option
I read so many blogs and tried so many tricks but my problem not resolved. I was able to run the code but not able to generate the jar file. :( Sad..
But I tried something which might be very silly but worked for me and bought eclipse on trace. What I did was.. Just deleted the main method from the class. Saved it. Did undo to bring the main class back. Tada... Issue resolved... Just one think would like to say, keep your eclipse in "Build Autometically" mode.
in KotlinDSL you can use like this :
flavorDimensions ("PlaceApp")
productFlavors {
create("tapsi") {
setDimension("PlaceApp")
buildConfigField("String", "API_BASE_URL", "https://xxx/x/x/")
}
}
According to the w3c, cols and rows are both required attributes for textareas. Rows and Cols are the number of characters that are going to fit in the textarea rather than pixels or some other potentially arbitrary value. Go with the rows/cols.
A CSS selector approach could definitely work here. Try:
driver.findElement(By.CssSelector("a.item")).Click();
This will not work if there are other anchors before this one of the class item. You can better specify the exact element if you do something like "#my_table > a.item" where my_table is the id of a table that the anchor is a child of.
You can try Mailkit
. It gives you better and advance functionality for send mail. You can find more from this Here is an example
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("FromName", "[email protected]"));
message.To.Add(new MailboxAddress("ToName", "[email protected]"));
message.Subject = "MyEmailSubject";
message.Body = new TextPart("plain")
{
Text = @"MyEmailBodyOnlyTextPart"
};
using (var client = new SmtpClient())
{
client.Connect("SERVER", 25); // 25 is port you can change accordingly
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");
client.Send(message);
client.Disconnect(true);
}
The built-in timeit module works best from the IPython command line.
To time functions from within a module:
from timeit import default_timer as timer
import sys
def timefunc(func, *args, **kwargs):
"""Time a function.
args:
iterations=3
Usage example:
timeit(myfunc, 1, b=2)
"""
try:
iterations = kwargs.pop('iterations')
except KeyError:
iterations = 3
elapsed = sys.maxsize
for _ in range(iterations):
start = timer()
result = func(*args, **kwargs)
elapsed = min(timer() - start, elapsed)
print(('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, elapsed)))
return result
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#008">
<RelativeLayout
android:id="@+id/paneltamrin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
>
<Button
android:id="@+id/BtnT1"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:drawableTop="@android:drawable/ic_menu_edit"
android:drawablePadding="6dp"
android:padding="15dp"
android:text="AndroidDhina"
android:textColor="#000"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/paneltamrin2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
>
<Button
android:layout_width="wrap_content"
android:layout_height="150dp"
android:drawableTop="@android:drawable/ic_menu_edit"
android:drawablePadding="6dp"
android:padding="15dp"
android:text="AndroidDhina"
android:textColor="#000"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
In core-site.xml:
<configuration>
<property>
<name>fs.defaultFS</name>
<value>hdfs://localhost:9000</value>
</property>
<property>
<name>hadoop.tmp.dir</name>
<value>/home/yourusername/hadoop/tmp/hadoop-${user.name}
</value>
</property>
</configuration>
and format of namenode with :
hdfs namenode -format
worked for hadoop 2.8.1
If the XAMPP server
is running for the moment, stop XAMPP server.
Follow these steps to change the port number.
Open the file in following location.
[XAMPP Installation Folder]/apache/conf/httpd.conf
Open the httpd.conf
file and search for the String:
Listen 80
This is the port number used by XAMMP.
Then search for the string ServerName and update the Port Number which you entered earlier for Listen
Now save and re-start XAMPP server.
These instructions work fine in Linux. In Windows, they are not working for me today.
I found an answer that helps for me, maybe this will help OP. I kissed a lot of frogs trying to solve this. You need to add your new non-standard-named key file with "ssh-add"! Here's instruction for the magic bullet: Generating a new SSH key and adding it to the ssh-agent. Once you know the magic search terms are "add key with ssh-add in windows" you find plenty of other links.
If I were using Windows often, I'd find some way to make this permanent. https://github.com/raeesbhatti/ssh-agent-helper.
The ssh key agent looks for default "id_rsa" and other keys it knows about. The key you create with a non-standard name must be added to the ssh key agent.
First, I start the key agent in the Git BASH shell:
$ eval $(ssh-agent -s)
Agent pid 6276
$ ssh-add ~/.ssh/Paul_Johnson-windowsvm-20180318
Enter passphrase for /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318:
Identity added: /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318 (/c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318)
Then I change to the directory where I want to clone the repo
$ cd ~/Documents/GIT/
$ git clone [email protected]:test/spr2018.git
Cloning into 'spr2018'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
I fought with this for a long long time.
Here are other things I tried along the way
At first I was certain it is because of file and folder permissions. On Linux, I have seen .ssh settings rejected if the folder is not set at 700. Windows has 711. In Windows, I cannot find any way to make permissions 700.
After fighting with that, I think it must not be the problem. Here's why. If the key is named "id_rsa" then git works! Git is able to connect to server. However, if I name the key file something else, and fix the config file in a consistent way, no matter what, then git fails to connect. That makes me think permissions are not the problem.
A thing you can do to debug this problem is to watch verbose output from ssh commands using the configured key.
In the git bash shell, run this
$ ssh -T git@name-of-your-server
Note, the user name should be "git" here. If your key is set up and the config file is found, you see this, as I just tested in my Linux system:
$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!
On the other hand, in Windows I have same trouble you do before applying "ssh-add". It wants git's password, which is always a fail.
$ ssh -T [email protected]
[email protected]'s password:
Again, If i manually copy my key to "id_rsa" and "id_rsa.pub", then this works fine. After running ssh-add, observe the victory in Windows Git BASH:
$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!
You would hear the sound of me dancing with joy if you were here.
To figure out what was going wrong, you can I run 'ssh' with "-Tvv"
In Linux, I see this when it succeeds:
debug1: Offering RSA public key: pauljohn@pols124
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp SHA256:bCoIWSXE5fkOID4Kj9Axt2UOVsRZz9JW91RQDUoasVo
debug1: Authentication succeeded (publickey).
In Windows, when this fails, I see it looking for default names:
debug1: Found key in /c/Users/pauljohn32/.ssh/known_hosts:1
debug2: set_newkeys: mode 1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 4294967296 blocks
debug2: key: /c/Users/pauljohn32/.ssh/id_rsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_dsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ecdsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ed25519 (0x0)
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_rsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_dsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ed25519
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
[email protected]'s password:
That was the hint I needed, it says it finds my ~/.ssh/config file but never tries the key I want it to try.
I only use Windows once in a long while and it is frustrating. Maybe the people who use Windows all the time fix this and forget it.
You could try a setInterval, if you know the exact length of the sound. You could have the setInterval play the sound every x seconds. X would be the length of your sound.
you can Try the following snippet:
var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)
and your output like that
My Result: H,w are y,u d,ing t,day?
To do without reinstalling spyder in all environments follow official reference here.
In summary (tested with conda):
From the system prompt:
Create an new environment. Note that depending on how you create it (conda, virtualenv) the environment folder will be located at different place on your system)
Activate the environment (e.g., conda activate [yourEnvName]
)
Install spyder-kernels inside the environment (e.g., conda install spyder-kernels
)
Find and copy the path for the python executable inside the environment. Finding this path can be done using from the prompt this command python -c "import sys; print(sys.executable)"
Deactivate the environment (i.e., return to base conda deactivate
)
run spyder (spyder3
)
Finally in spyder Tool menu go to Preferences > Python Interpreter > Use the following interpreter and paste the environment python executable path
Restart the ipython console
PS: in spyder you should see at the bottom something like this
Voila
You can use jQuery toggle
to show and hide the div. The script will be like this
<script type="text/javascript">
jQuery(function(){
jQuery("#music").click(function () {
jQuery("#musicinfo").toggle("slow");
});
});
</script>
You are using the beta version of angular CLI you can do this way.
npm uninstall -g @angular/cli
npm uninstall -g angular/cli
Then type,
npm cache clean
Then go to the AppData folder which is hidden in your users and go to roaming folder which is inside AppData then go to npm folder and delete angular files in there and also go to npm-cache folder and delete angular components in there.After that restart your PC and type
npm install -g @angular/cli@latest
This worked for me ??
How to execute Python scripts in Windows?
You could install pylauncher. It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:
T\:> blah.py argument
You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:
T:\> blah argument
It adds support for shebang (#!
header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python
.
You can specify version explicitly e.g., to run using the latest installed Python 3 version:
T:\> py -3 blah.py argument
It should also fix your sys.argv
issue as a side-effect.
Whatever method you choose is not freeing you from performing the same validation on at the back end.
JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:
send an email without refreshing the page
You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)
If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
You can use "Gena" library. It closely resembles stl::vector
in pure C89.
From the README, it features:
vec[k][j]
;You can check it out here:
Just created a github repo with a small script, that creates a RAM disk. If you point your DerivedData folder to /Volumes/ramdisk
, after ejecting disk all files will be gone.
It speeds up compiling, also eliminates this problem
Best launched using DTerm