Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
No, it is not (Ruby 1.9.x)
require 'benchmark'
h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
many = 100_000
Benchmark.bm do |b|
GC.start
b.report("hash sort") do
many.times do
Hash[h.sort]
end
end
GC.start
b.report("keys sort") do
many.times do
nh = {}
h.keys.sort.each do |k|
nh[k] = h[k]
end
end
end
end
user system total real
hash sort 0.400000 0.000000 0.400000 ( 0.405588)
keys sort 0.250000 0.010000 0.260000 ( 0.260303)
For big hashes difference will grow up to 10x and more
I work in WordPress a lot so use PHP.
My method is to contain my HTML in a PHP Variable, and then echo the variable in data-content
.
$my-data-content = '<form><input type="text"/></form>';
along with
data-content='<?php echo $my-data-content; ?>'
Use this as it can also act as responsive. :
background-size: cover;
Use the formaction
HTML attribute (5th line):
<form action="/action_page.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<button type="submit">Submit</button><br>
<button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>
I do not believe there is a callback-function like the one you describe.
What is normal here is to do the alterations using some server-side language, like PHP.
In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.
PHP:
$someHiddenVar = $_POST["hidden_field"];
if (!empty($someHiddenVar)) {
// do something
}
One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.
$.post("test.php", $("#testform").serialize(), function(data) {
$('.result').html(data);
});
A pure JavaScript solution ought to be offered as well, as the solution is not difficult:
var a = [].filter.call(el.attributes, function(at) { return /^data-/.test(at.name); });
This gives an array of attribute objects, which have name
and value
properties:
if (a.length) {
var firstAttributeName = a[0].name;
var firstAttributeValue = a[0].value;
}
Edit: To take it a step further, you can get a dictionary by iterating the attributes and populating a data object:
var data = {};
[].forEach.call(el.attributes, function(attr) {
if (/^data-/.test(attr.name)) {
var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
return $1.toUpperCase();
});
data[camelCaseName] = attr.value;
}
});
You could then access the value of, for example, data-my-value="2"
as data.myValue
;
Edit: If you wanted to set data attributes on your element programmatically from an object, you could:
Object.keys(data).forEach(function(key) {
var attrName = "data-" + key.replace(/[A-Z]/g, function($0) {
return "-" + $0.toLowerCase();
});
el.setAttribute(attrName, data[key]);
});
EDIT: If you are using babel or TypeScript, or coding only for es6 browsers, this is a nice place to use es6 arrow functions, and shorten the code a bit:
var a = [].filter.call(el.attributes, at => /^data-/.test(at.name));
I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.
import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
, password="***"
, port="5432"
, database="myDB"
, host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()
myList = [...]
for item in myList:
cursor_psql.execute('''
-- The query goes here
''')
connection_psql.commit()
cursor_psql.close()
If you're using AngularJS and your jQuery click event is INSIDE THE CONTROLLER, it will get disturbed by the Angular's framework itself and fire twice. To solve this, move it out of the controller and do the following:
// Make sure you're using $(document), or else it won't fire.
$(document).on("click", "#myTemplateId #myButtonId", function () {
console.log("#myButtonId is fired!");
// Do something else.
});
angular.module("myModuleName")
.controller("myController", bla bla bla)
In short, its because of recycling the views and using them again!
how can you avoid that :
1.In onBindViewHolder
check whether you should check or uncheck boxes.
don't forget to put both if and else
if (...)
holder.cbSelect.setChecked(true);
else
holder.cbSelect.setChecked(false);
myItems
array ! so whenever a new view is shown, it read the newest statue of the object.Any reason you can't use a nested for loop?
for i in range(x):
for j in range(y):
#code that uses i and j
top.frames.location.reload(false);
To get the no. of days in a month we can directly use Day() available in SQL.
Follow the link posted at the end of my answer for SQL Server 2005 / 2008.
The following example and the result are from SQL 2012
alter function dbo.[daysinm]
(
@dates nvarchar(12)
)
returns int
as
begin
Declare @dates2 nvarchar(12)
Declare @days int
begin
select @dates2 = (select DAY(EOMONTH(convert(datetime,@dates,103))))
set @days = convert(int,@dates2)
end
return @days
end
--select dbo.daysinm('08/12/2016')
Result in SQL Server SSMS
(no column name)
1 31
Process:
When EOMONTH is used, whichever the date format we use it is converted into DateTime format of SQL-server. Then the date output of EOMONTH() will be 2016-12-31 having 2016 as Year, 12 as Month and 31 as Days. This output when passed into Day() it gives you the total days count in the month.
If we want to get the instant result for checking we can directly run the below code,
select DAY(EOMONTH(convert(datetime,'08/12/2016',103)))
or
select DAY(EOMONTH(convert(datetime,getdate(),103)))
for reference to work in SQL Server 2005/2008/2012, please follow the following external link ...
For one line!
Try using for wmic OS Get localdatetime^|find "."
in for /f
without tokens
and/or delims
, this works in any language / region and also, no user settings interfere with the layout of the output.
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo=month: !_date:~4,2!&echo= day: !_date:~6,2!"
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo=month: !_date:~4,2!&echo= day: !_date:~6,2!"
Results:
year: 2019
month: 06
day: 12
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo= month: !_date:~4,2!&echo= day: !_date:~6,2!&echo= hour: !_date:~8,2!&echo=minute: !_date:~10,2!"
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo= month: !_date:~4,2!&echo= day: !_date:~6,2!&echo= hour: !_date:~8,2!&echo=minute: !_date:~10,2!"
Results:
year: 2020
month: 05
day: 16
hour: 00
minute: 46
In C#, I would normally use multiple forms of the method:
void GetFooBar(int a) { int defaultBValue; GetFooBar(a, defaultBValue); }
void GetFooBar(int a, int b)
{
// whatever here
}
UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:
public EDIDocument ApplyEDIEnvelop(EDIVanInfo sender,
EDIVanInfo receiver,
EDIDocumentInfo info,
EDIDocumentType type
= new EDIDocumentType(EDIDocTypes.X12_814),
bool Production = false)
{
// My code is here
}
As far as I can read in API's. The event is only fired when the user clicks on an option.
For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
You can use mosquitto_sub
(which is part of the mosquitto-clients
package) and subscribe to the wildcard topic #
:
mosquitto_sub -v -h broker_ip -p 1883 -t '#'
An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.
The following sets the username and password if provided or just adds the host and port if no username and password is set.
task setHttpProxyFromEnv {
def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
for (e in System.getenv()) {
def key = e.key.toUpperCase()
if (key in map) {
def base = map[key]
//Get proxyHost,port, username, and password from http system properties
// in the format http://username:password@proxyhost:proxyport
def (val1,val2) = e.value.tokenize( '@' )
def (val3,val4) = val1.tokenize( '//' )
def(userName, password) = val4.tokenize(':')
def url = e.value.toURL()
//println " - systemProp.${base}.proxy=${url.host}:${url.port}"
System.setProperty("${base}.proxyHost", url.host.toString())
System.setProperty("${base}.proxyPort", url.port.toString())
System.setProperty("${base}.proxyUser", userName.toString())
System.setProperty("${base}.proxyPassword", password.toString())
}
}
}
Create setenv.bat file in nib folder of Tomcat. Add SET JPDA_ADDRESS = 8787 ; Override the jpda port Open cmd, go to bin folder of Tomcat and Start tomcat using catalina jpda start Set up a debug point on eclipse Next compile your project. Check localhost:8080/ Deploy the war or jar under webapps folder and this must deploy war on Tomcat. Then send the request. the debug point will get hit NOTE : Don't edit catalina.bat file. make changes in setenv.bat file
You haven't specified how would you like to see these details.
For the first sight I would suggest to check Server Management Studio.
You can see the jobs and current statuses in the SQL Server Agent part, under Jobs. If you pick a job, the Property page shows a link to the Job History, where you can see the start and end time, if there any errors, which step caused the error, and so on.
You can specify alerts and notifications to email you or to page you when the job finished successfully or failed.
There is a Job Activity Monitor, but actually I never used it. You can have a try.
If you want to check it via T-SQL, then I don't know how you can do that.
The CONVERT
function helps.Check this:
declare @erro_event_timestamp as Timestamp;
set @erro_event_timestamp = CONVERT(Timestamp, '2020-07-06 05:19:44.380', 121);
The magic number 121 I found here: https://www.w3schools.com/SQL/func_sqlserver_convert.asp
It depends on your definition of what memory query you wish to get.
Usually, you'd like to know the status of the heap memory, since if it uses too much memory, you get OOM and crash the app.
For this, you can check the next values:
final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;
The more the "usedMemInMB" variable gets close to "maxHeapSizeInMB", the closer availHeapSizeInMB
gets to zero, the closer you get OOM. (Due to memory fragmentation, you may get OOM BEFORE this reaches zero.)
That's also what the DDMS tool of memory usage shows.
Alternatively, there is the real RAM usage, which is how much the entire system uses - see accepted answer to calculate that.
Update: since Android O makes your app also use the native RAM (at least for Bitmaps storage, which is usually the main reason for huge memory usage), and not just the heap, things have changed, and you get less OOM (because the heap doesn't contain bitmaps anymore,check here), but you should still keep an eye on memory use if you suspect you have memory leaks. On Android O, if you have memory leaks that should have caused OOM on older versions, it seems it will just crash without you being able to catch it. Here's how to check for memory usage:
val nativeHeapSize = Debug.getNativeHeapSize()
val nativeHeapFreeSize = Debug.getNativeHeapFreeSize()
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
But I believe it might be best to use the profiler of the IDE, which shows the data in real time, using a graph.
So the good news on Android O is that it's much harder to get crashes due to OOM of storing too many large bitmaps, but the bad news is that I don't think it's possible to catch such a case during runtime.
EDIT: seems Debug.getNativeHeapSize()
changes over time, as it shows you the total max memory for your app. So those functions are used only for the profiler, to show how much your app is using.
If you want to get the real total and available native RAM , use this:
val memoryInfo = ActivityManager.MemoryInfo()
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
val nativeHeapSize = memoryInfo.totalMem
val nativeHeapFreeSize = memoryInfo.availMem
val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
"free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
"used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")
The simplest solution simply is:
<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>
It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)
<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' +
Math.round(new Date().getTime() / 1000);"
href="http://www.domain.com/docs/thingy.pdf">
If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.
I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.
ReImg.fromCanvas(yourCanvasElement).toPng()
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
There is something out there, context aware resizing, don't know if you will be able to use it, but it's worth looking at, that's for sure
A nice video demo (Enlarging appears towards the middle) http://www.youtube.com/watch?v=vIFCV2spKtg
Here there could be some code. http://www.semanticmetadata.net/2007/08/30/content-aware-image-resizing-gpl-implementation/
Was that overkill? Maybe there are some easy filters you can apply to an enlarged image to blur the pixels a bit, you could look into that.
You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.
Also, check out the informative blog:
Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).
MSDN: ROW_NUMBER (Transact-SQL)
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
The following example returns rows with numbers 50 to 60 inclusive in the order of the OrderDate.
WITH OrderedOrders AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY FirstName DESC) AS RowNumber,
FirstName, LastName, ROUND(SalesYTD,2,1) AS "Sales YTD"
FROM [dbo].[vSalesPerson]
)
SELECT RowNumber,
FirstName, LastName, Sales YTD
FROM OrderedOrders
WHERE RowNumber > 50 AND RowNumber < 60;
RowNumber FirstName LastName SalesYTD
--- ----------- ---------------------- -----------------
1 Linda Mitchell 4251368.54
2 Jae Pak 4116871.22
3 Michael Blythe 3763178.17
4 Jillian Carson 3189418.36
5 Ranjit Varkey Chudukatil 3121616.32
6 José Saraiva 2604540.71
7 Shu Ito 2458535.61
8 Tsvi Reiter 2315185.61
9 Rachel Valdez 1827066.71
10 Tete Mensa-Annan 1576562.19
11 David Campbell 1573012.93
12 Garrett Vargas 1453719.46
13 Lynn Tsoflias 1421810.92
14 Pamela Ansman-Wolfe 1352577.13
You define a class
and add the Unicode private function insert the class
like
class example:
def __init__(self, name):
self.name = name
def __unicode__(self):
return self.name
Of course you have to add extra variable self.name
which is the name of the object.
Using LINQ:
arr = (arr ?? Enumerable.Empty<string>()).Concat(new[] { newitem }).ToArray();
I like using this as it is a one-liner and very convenient to embed in a switch statement, a simple if-statement, or pass as argument.
EDIT:
Some people don't like new[] { newitem }
because it creates a small, one-item, temporary array. Here is a version using Enumerable.Repeat
that does not require creating any object (at least not on the surface -- .NET iterators probably create a bunch of state machine objects under the table).
arr = (arr ?? Enumerable.Empty<string>()).Concat(Enumerable.Repeat(newitem,1)).ToArray();
And if you are sure that the array is never null
to start with, you can simplify it to:
arr.Concat(Enumerable.Repeat(newitem,1)).ToArray();
Notice that if you want to add items to a an ordered collection, List
is probably the data structure you want, not an array to start with.
If you're using HTML 5, i.e. the doctype
<!doctype html>
then you can just use block-level links.
<a href="google.com">
<div class="hello">
..
</div>
</a>
The simplest and clean way to do that (actually svn 1.9, released 2015) is using:
svn info --show-item revision [--no-newline] [SVNURL/SVNPATH]
The output is the number of the last revision (joungest) for the SVNURL,
or the number of the current revision of the working copy of SVNPATH.
The --no-newline
is optional, instructs svn
not to emit a cosmetic newline (\n
) after the value, if you need minimal output (only the revision number).
See: https://subversion.apache.org/docs/release-notes/1.9.html#svn-info-item
Running VS Code on Android is not possible, at least until Android support is implemented in Electron. This has been rejected by the Electron team in the past, see electron#562
Visual Studio Codespaces and GitHub Codespaces an upcoming services that enables running VS Code in a browser. Since everything runs in a browser, it seems likely that mobile OS' will be supported.
Just to add Python 3 f-string solution
prob = 1.0/3.0
print(f"{prob:.0%}")
socket.isConnected()
returns always true once the client connects (and even after the disconnect) weird !!socket.getInputStream().read()
returns -1
if the client disconnectedsocket.getInetAddress().isReachable(int timeout)
: From isReachable(int timeout)
Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
Many answers here are rather old,
thanks to the pointer from @Simplans (https://stackoverflow.com/a/37759871/417747) and the home page...
What worked for me (Ubuntu bionic):
sudo apt-get install python3-lxml
(+ sudo apt-get install libxml2-dev libxslt1-dev
I installed before it, but not sure if that's the requirement still)
Download
Call
ilmerge /target:winexe /out:c:\output.exe c:\input.exe C:\input.dll
As thirtydot said, you can use the CSS3 background-size
syntax:
For example:
-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;
However, as also stated by thirtydot, this does not work in IE6, 7 and 8.
See the following links for more information about background-size
:
http://www.w3.org/TR/css3-background/#the-background-size
My experience in Visual Studio 2010 is that there are two changes needed so as to not need DLL's. From the project property page (right click on the project name in the Solution Explorer window):
Under Configuration Properties --> General, change the "Use of MFC" field to "Use MFC in a Static Library".
Under Configuration Properties --> C/C++ --> Code Generation, change the "Runtime Library" field to "Multi-Threaded (/MT)"
Not sure why both were needed. I used this to remove a dependency on glut32.dll.
Added later: When making these changes to the configurations, you should make them to "All Configurations" --- you can select this at the top of the Properties window. If you make the change to just the Debug configuration, it won't apply to the Release configuration, and vice-versa.
From the grep(1)
man page:
-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.)
What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry_page function:
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
title = request.form['blog_title']
post = request.form['blog_main']
post_entry = models.BlogPost(date = date, title = title, post = post)
db.session.add(post_entry)
db.session.commit()
return redirect(url_for('database'))
else:
return render_template('entry.html')
@app.route('/database', methods=['GET', 'POST'])
def database():
query = []
for i in session.query(models.BlogPost):
query.append((i.title, i.post, i.date))
return render_template('database.html', query = query)
How about this
$.validate.addMethod(cb_selectone,
function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
},
'Please select a least one')
Now you ca do
$.validate({rules:{checklist:"cb_selectone"}});
You can even go further a specify the minimum number to select with a third param in the callback function.I have not tested it yet so tell me if it works.
If you haven't already committed your changes, just use git checkout
to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.
If you have already committed your changes:
git log
and remember the SHA of the commit you want to move.git cherry-pick SHA
substituting the SHA from above.git reset HEAD~1
to reset back before your wrong-branch commit.cherry-pick
takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.
You could try using a casting operator to convert it to an integer:
$page = (int) $_GET['p'];
if($page == "")
{
$page = 1;
}
if(empty($page) || !$page)
{
setcookie("error", "Invalid page.", time()+3600);
header("location:somethingwentwrong.php");
die();
}
//else continue with code
I've had a similar issue, and I've resolved it by statically linking libstdc++
into the program I was compiling, like so:
$ LIBS=-lstdc++ ./configure ... etc.
instead of the usual
$ ./configure ... etc.
There might be problems with this solution to do with loading shared libraries at runtime, but I haven't looked into the issue deeply enough to comment.
As mentioned multiprocessing pool is much slower than basic threading. Using queues as proposeded in some answers here is a very effective alternative. I have use it with dictionaries in order to be able run a lot of small threads and recuperate multiple answers by combining them with dictionaries:
#!/usr/bin/env python3
import threading
# use Queue for python2
import queue
import random
LETTERS = 'abcdefghijklmnopqrstuvwxyz'
LETTERS = [ x for x in LETTERS ]
NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def randoms(k, q):
result = dict()
result['letter'] = random.choice(LETTERS)
result['number'] = random.choice(NUMBERS)
q.put({k: result})
threads = list()
q = queue.Queue()
results = dict()
for name in ('alpha', 'oscar', 'yankee',):
threads.append( threading.Thread(target=randoms, args=(name, q)) )
threads[-1].start()
_ = [ t.join() for t in threads ]
while not q.empty():
results.update(q.get())
print(results)
Without a nicer solution, what I found to work is simply building my query string in the bean return:
public String submit() {
// Do something
return "/page2.xhtml?faces-redirect=true&id=" + id;
}
Not the most flexible of solutions, but seems to work how I want it to.
Also using this approach to clean up the process of building the query string: http://www.warski.org/blog/?p=185
Here is a more complete example of an XML filter (the example above by itself will not work since it just shows a snippet and is missing the <FindBugsFilter>
begin and end tags):
<FindBugsFilter>
<Match>
<Class name="com.mycompany.foo" />
<Method name="bar" />
<Bug pattern="NP_BOOLEAN_RETURN_NULL" />
</Match>
</FindBugsFilter>
If you are using the Android Studio FindBugs plugin, browse to your XML filter file using File->Other Settings->Default Settings->Other Settings->FindBugs-IDEA->Filter->Exclude filter files->Add.
extern "C"
doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).
What extern "C"
does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.
Code inside an extern "C"
is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example.
extern "C"
blocks nest nicely. There's also extern "C++"
if you find yourself hopelessly trapped inside of extern "C"
regions, but it isn't such a good idea from a cleanliness perspective.
Now, specifically regarding your numbered questions:
Regarding #1: __cplusplus will stay defined inside of extern "C"
blocks. This doesn't matter, though, since the blocks should nest neatly.
Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C"
when being interpreted as C++, and they should not have extern "C"
when being interpreted as C -- hence the #ifdef __cplusplus
checking.
To answer your question #3: functions without prototypes will have C++ linkage if they are in .cpp files and not inside of an extern "C"
block. This is fine, though, because if it has no prototype, it can only be called by other functions in the same file, and then you don't generally care what the linkage looks like, because you aren't planning on having that function be called by anything outside the same compilation unit anyway.
For #4, you've got it exactly. If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must extern "C"
the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic
when you were looking for void h(int, char)
5: This sort of mixing is a common reason to use extern "C"
, and I don't see anything wrong with doing it this way -- just make sure you understand what you are doing.
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Also, if this doesn't solve your problem, there's a similar thread here.
What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...
:Cleanup_Temporary_Files_and_Folders
Erase /F /S /Q C:\MyDir
RMDir /S /Q C:\MyDir
If Exist C:\MyDir GoTo Cleanup_Temporary_Files_and_Folders
OK, here is how I did it in Notepad++:
I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.
The simplest approach would be to use any of these class utilities that Bootstrap provides:
<div class="position-fixed">...</div>
<div class="position-sticky">...</div>
<div class="fixed-top">...</div>
<div class="fixed-bottom">...</div>
<div class="sticky-top">...</div>
SELECT *, (
6371 * acos(cos(radians(search_lat)) * cos(radians(lat) ) *
cos(radians(lng) - radians(search_lng)) + sin(radians(search_lat)) * sin(radians(lat)))
) AS distance
FROM table
WHERE lat != search_lat AND lng != search_lng AND distance < 25
ORDER BY distance
FETCH 10 ONLY
for distance of 25 km
Others explained very well and just want to give with simple examples.
Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.
$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.'
It will give this:
All sorts of things are ignored in single quotes, like $ & * ; |.
The only thing that cannot be put within single quotes is a single quote.
Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.
$ echo "Here's how we can use single ' and double \" quotes within double quotes"
It will give this:
Here's how we can use single ' and double " quotes within double quotes
It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.
$ echo "The current Oracle SID is $ORACLE_SID"
It will give this:
The current Oracle SID is test
Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.
$ today=`date '+%A, %B %d, %Y'`
$ echo $today
It will give this:
Monday, September 28, 2015
This error is fairly self-explanatory. Dictionary keys are unique and you cannot have more than one of the same key. To fix this, you should modify your code like so:
Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();
foreach (string line in rct3Lines)
{
string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
if (!rct3Features.ContainsKey(items[0]))
{
rct3Features.Add(items[0], items[1]);
}
////To print out the dictionary (to see if it works)
//foreach (KeyValuePair<string, string> item in rct3Features)
//{
// Console.WriteLine(item.Key + " " + item.Value);
//}
}
This simple if
statement ensures that you are only attempting to add a new entry to the Dictionary when the Key (items[0]
) is not already present.
try this
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-include="'myTable.htm'"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function (response) {
$scope.names = response.data.records;
});
});
</script>
Try this, your dot source was a little off. Edit, adding lastexitcode bits for OP.
$A = Start-Process -FilePath .\my-app\my-fle.bat -Wait -passthru;$a.ExitCode
add -WindowStyle Hidden
for invisible batch.
You can get columns number from ResultSetMetaData:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
Only the reference is changing. First a
was referencing to the string "a", and later you changed it to "ty". The string "a" remains the same.
Probably, the fastest, efficient and more generic way is this (you can merge any number of objects and even copy to the first one ->assign):
function object_merge(){
for (var i=1; i<arguments.length; i++)
for (var a in arguments[i])
arguments[0][a] = arguments[i][a];
return arguments[0];
}
It also allows you to modify the first object as it passed by reference. If you don't want this but want to have a completely new object containing all properties, then you can pass {} as the first argument.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3);
combined_object and object1 both contain the properties of object1,object2,object3.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3);
In this case, the combined_object contains the properties of object1,object2,object3 but object1 is not modified.
Check here: https://jsfiddle.net/ppwovxey/1/
Note: JavaScript objects are passed by reference.
@Luch Filip's solution works well if you just want to rename the App package. In my case, I also want to rename the source package too, so as not to confuse things.
Only 2 steps are needed:
Click on your source folder e.g. com.company.example
> Shift + F6 (Refactor->Rename...) > Rename Package > enter your desired name.
Go to your AndroidManifest.xml, click on your package name > Shift + F6 (Refactor->Rename...) > enter same name as above.
Step 1 will automatically rename your R.java folder, and you can build straight away.
Rendering text to a texture is simpler than what the Sprite Text demo make it looks like, the basic idea is to use the Canvas class to render to a Bitmap and then pass the Bitmap to an OpenGL texture:
// Create an empty, mutable bitmap
Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);
// get a background image from resources
// note the image format must match the bitmap format
Drawable background = context.getResources().getDrawable(R.drawable.background);
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap
// Draw the text
Paint textPaint = new Paint();
textPaint.setTextSize(32);
textPaint.setAntiAlias(true);
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
// draw the text centered
canvas.drawText("Hello World", 16,112, textPaint);
//Generate one texture pointer...
gl.glGenTextures(1, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
//Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
//Clean up
bitmap.recycle();
Use copy()
instead, which is willing to overwrite destination files. If you then want the first tree to go away, just rmtree()
it separately once you are done iterating over it.
http://docs.python.org/library/shutil.html#shutil.copy
http://docs.python.org/library/shutil.html#shutil.rmtree
Update:
Do an os.walk()
over the source tree. For each directory, check if it exists on the destination side, and os.makedirs()
it if it is missing. For each file, simply shutil.copy()
and the file will be created or overwritten, whichever is appropriate.
You can use WellFormedJson
class from Validol declarative validation library.
The declaration itself could look like the following:
new WellFormedJson(
new Unnamed<>(Either.right(new Present<>(jsonRequestString)))
)
The check phase looks like that:
Result<JsonElement> result =
(new WellFormedJson(
new Named<>(
"vasya",
Either.right(
new Present<>(
"{\"guest\":{\"name\":\"Vadim Samokhin\",\"email\":\"[email protected]\"},\"source\":1,\"items\":[{\"id\":1900},{\"id\":777}]}"
)
)
)
))
.result();
assertTrue(result.isSuccessful());
assertEquals(
"{\"guest\":{\"name\":\"Vadim Samokhin\",\"email\":\"[email protected]\"},\"source\":1,\"items\":[{\"id\":1900},{\"id\":777}]}",
result.value().raw().toString()
);
assertEquals(
"{\"name\":\"Vadim Samokhin\",\"email\":\"[email protected]\"}",
result.value().raw().getAsJsonObject().get("guest").toString()
);
It might seem like an overkill for such a simple task, but it shines when you have to validate a complex request. Check out validol's quick start section.
I also meet that problems,and just delete bottom code:
DELETE THESE LINES:
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
}
it worked?
There are several ways to concatenate two strings together.
Use the concatenation operator .
(and .=
)
In PHP .
is the concatenation operator which returns the concatenation of its right and left arguments
$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;
If you want to append a string to another string you would use the .=
operator:
$data1 = "the color is ";
$data1 .= "red"
Complex (curly) syntax / double quotes strings
In PHP variables contained in double quoted strings are interpolated (i.e. their values are "swapped out" for the variable). This means you can place the variables in place of the strings and just put a space in between them. The curly braces make it clear where the variables are.
$result = "{$data1} {$data2}";
Note: this will also work without the braces in your case:
$result = "$data1 $data2";
You can also concatenate array values inside a string :
$arr1 = ['val' => 'This is a'];
$arr2 = ['val' => 'test'];
$variable = "{$arr1['val']} {$arr2['val']}";
Use sprintf()
or printf()
sprintf()
allows us to format strings using powerful formatting options. It is overkill for such simple concatenation but it handy when you have a complex string and/or want to do some formatting of the data as well.
$result = sprintf("%s %s", $data1, $data2);
printf()
does the same thing but will immediately display the output.
printf("%s %s", $data1, $data2);
// same as
$result = sprintf("%s %s", $data1, $data2);
echo $result;
Heredoc
Heredocs can also be used to combine variables into a string.
$result= <<<EOT
$data1 $data2
EOT;
Use a ,
with echo()
This only works when echoing out content and not assigning to a variable. But you can use a comma to separate a list of expressions for PHP to echo out and use a string with one blank space as one of those expressions:
echo $data1, ' ', $data2;
for knowing the object properties var_dump(object) is the best way. It will show all public, private and protected properties associated with it without knowing the class name.
But in case of methods, you need to know the class name else i think it's difficult to get all associated methods of the object.
On the subject of ugly hacks, you can always use a combination of exec
and a regular function to define a multiline function like this:
f = exec('''
def mlambda(x, y):
d = y - x
return d * d
''', globals()) or mlambda
You can wrap this into a function like:
def mlambda(signature, *lines):
exec_vars = {}
exec('def mlambda' + signature + ':\n' + '\n'.join('\t' + line for line in lines), exec_vars)
return exec_vars['mlambda']
f = mlambda('(x, y)',
'd = y - x',
'return d * d')
Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:
$ cat junk.c
#include <stdio.h>
char* string = "Hello\0";
int main(int argv, char** argc)
{
printf("-->%s<--\n", string);
}
$ gcc -S junk.c
$ cat junk.s
... eliding the unnecessary parts ...
.LC0:
.string "Hello"
.string ""
...
.LC1:
.string "-->%s<--\n"
...
Note here how the string I used for printf is just "-->%s<---\n"
while the global string is in two parts: "Hello"
and ""
. The GNU assembler also terminates strings with an implicit NUL
character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NUL
s. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S
(for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.
When you do str = in.readLine()) != null
you read one line into str
variable and if it's not null execute the while
block. You do not need to read the line one more time in arr[i] = in.readLine();
. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> output = new LinkedList<String>();
while((str = in.readLine()) != null){
output.add(str);
}
String[] arr = output.toArray(new String[output.size()]);
In Python2, input
is evaluated, input()
is equivalent to eval(raw_input())
. When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.
Use raw_input
to get a string from the user in Python2.
Demo 1: klj
is not defined:
>>> input()
klj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'klj' is not defined
Demo 2: klj
is defined:
>>> klj = 'hi'
>>> input()
klj
'hi'
Demo 3: getting a string with raw_input
:
>>> raw_input()
klj
'klj'
According to me the best way of dealing with such problems and avoiding couple of condition required for checking the the height of device, is using the relative frame for views or any UI element which you are adding to you view for example: if you are adding some UI element which you want should at the bottom of view or just above tab bar then you should take the y origin with respect to your view's height or with respect to tab bar (if present) and we have auto resizing property as well. I hope this will work for you
I have just rewritten the code to the following:
$dbhost = "localhost";
$dbname = "pdo";
$dbusername = "root";
$dbpassword = "845625";
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
VALUES(?,?,?)");
$statement->execute(array("Bob","Desaunois",18));
And it seems to work now. BUT. if I on purpose cause an error to occur, it does not say there is any. The code works, but still; should I encounter more errors, I will not know why.
Better
if ! wget -q --spider --tries=10 --timeout=20 google.com
then
echo 'Sorry you are Offline'
exit 1
fi
getElementById will return false if the element was not found in the DOM.
var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
//The element was found and the value is empty.
}
First Activity Code :
Intent mIntent = new Intent(ActivityA.this, ActivityB.class);
mIntent.putExtra("easyPuzzle", easyPuzzle);
Second Activity Code :
String easyPuzzle = getIntent().getStringExtra("easyPuzzle");
So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.
Intuitively (and wrongly), most people assume that it looks something like this:
Local Computer | Remote Computer
--------------------------------
<local_ip>:80 | <foreign_ip>:80
^^ not actually what happens, but this is the conceptual model a lot of people have in mind.
This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.
Three things must be understood:
1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.
2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.
3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.
So, this is really what gets created when a client connects to a server:
Local Computer | Remote Computer | Role
-----------------------------------------------------------
0.0.0.0:80 | <none> | LISTENING
127.0.0.1:80 | 10.1.2.3:<random_port> | ESTABLISHED
First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).
netstat -atnp | grep -i ":500 "
As expected, the output is blank. Now let's start a web server:
sudo python3 -m http.server 500
Now, here is the output of running netstat again:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all". An easy mistake to make is to listen on address 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.
So now, let's connect a user to our machine:
quicknet -m tcp -t localhost:500 -p Test payload.
This is a simple script (https://github.com/grokit/dcore/tree/master/apps/quicknet) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:54240 ESTABLISHED -
If you connect with another client and do netstat again, you will see the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:26813 ESTABLISHED -
... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.
Sounds like a good opportunity to use an AlertDialog.
As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.
If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).
Within your class:
private String m_Text = "";
Within the OnClickListener of your button (or in a function called from there):
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
hope you are doing well.
you can use my code to crop image.you just have to make a class and use this class into your XMl
and java
classes.
Crop image.
you can crop your selected image into circle and square into many of option.
hope fully it will works for you.because this is totally manageable for you and you can change it according to you.
enjoy your work :)
the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face
@font-face {
font-family: 'Name You Font';
src: url('assets/font/xxyourfontxxx.eot');
src: local('Cera Pro Medium'), local('CeraPro-Medium'),
url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
url('assets/font/xxyourfontxxx.woff') format('woff'),
url('assets/font/xxyourfontxxx.ttf') format('truetype');
font-weight: 500;
font-style: normal;
}
So you can just indicate your fontfamily name that you already choosed
NOTE: the font-weight and font-style depend on your .woff .ttf ... files
Initialy both dropdown have same option ,the option you select in firstdropdown is hidden in seconddropdown."value" is custom attribute which is unique.
$(".seconddropdown option" ).each(function() {
if(($(this).attr('value')==$(".firstdropdown option:selected").attr('value') )){
$(this).hide();
$(this).siblings().show();
}
});
Source: PHP Function that Generates Random Characters
This simple PHP function worked for me:
function cvf_ps_generate_random_code($length=10) {
$string = '';
// You can define your own characters here.
$characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
Usage:
echo cvf_ps_generate_random_code(5);
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
I have the same problem and so I remove the Apache and make it again and the problem was solved.
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");
(Use my method if you want to accept HTML-style hex colors.)
You cannot exactly get a list of commands started with nohup
but you can see them along with your other processes by using the command ps x
. Commands started with nohup
will have a question mark in the TTY column.
I have this code in my application today
File log4jfile = new File("./conf/log4j.properties");
PropertyConfigurator.configure(log4jfile.getAbsolutePath());
The relative path is from the working directory of the JVM (where the JVM starts).
Please never do this in real projects:
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
You need to use the as.Date formats correctly.
Eg.
x = '2012/07/25'
xd = as.Date(x,'%Y/%m/%d')
xd # Prints "2012-07-25"
R date formats are similary to *nix ones.
Doing a typeof(xd) shows it as a double ie. days since 1970.
You should check all your files if it don't have errors and again rebuild your project in:
Or in:
Check use external build
and after rebuild the project.
It is good to know about the differences between margin
and padding
. As I know:
auto
value to margin. However, it's not allowed for padding. See this.
margin: auto
to center a block element inside its parent horizontally. Also, it's possible to center an element inside a flexbox vertically or horizontally or both, by setting margin to auto. See this.
background-color
property to black, its inner space (i.e. padding) will be black, but not its outer space (i.e. margin).
Here is a solution for those, who want to remove it from the database with Entity Framework:
prods.RemoveWhere(s => s.ID == 1);
And the extension method itself:
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
namespace LivaNova.NGPDM.Client.Services.Data.Extensions
{
public static class DbSetExtensions
{
public static void RemoveWhere<TEntity>(this DbSet<TEntity> entities, Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
var records = entities
.Where(predicate)
.ToList();
if (records.Count > 0)
entities.RemoveRange(records);
}
}
}
P.S. This simulates the method RemoveAll()
that's not available for DB sets of the entity framework.
Use set()
to remove duplicates if all values are hashable:
>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
True
For Python 2.7 and Pandas 0.24.2 and using Psycopg2
Psycopg2 Connection Module
def dbConnect (db_parm, username_parm, host_parm, pw_parm):
# Parse in connection information
credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
conn = psycopg2.connect(**credentials)
conn.autocommit = True # auto-commit each entry to the database
conn.cursor_factory = RealDictCursor
cur = conn.cursor()
print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
return conn, cur
Connect to the database
conn, cur = dbConnect(databaseName, dbUser, dbHost, dbPwd)
Assuming dataframe to be present already as df
output = io.BytesIO() # For Python3 use StringIO
df.to_csv(output, sep='\t', header=True, index=False)
output.seek(0) # Required for rewinding the String object
copy_query = "COPY mem_info FROM STDOUT csv DELIMITER '\t' NULL '' ESCAPE '\\' HEADER " # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()
Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:
array.length * array[0].length
A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.
Just run code snippet right away and try going back
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
_x000D_
NOTE: While I agree with @Stefan in many things, I only needed a simple match highlighting:
module myApp.Search {
'use strict';
export class Utils {
private static regexFlags = 'gi';
private static wrapper = 'mark';
private static wrap(match: string): string {
return '<' + Utils.wrapper + '>' + match + '</' + Utils.wrapper + '>';
}
static highlightSearchTerm(term: string, searchResult: string): string {
let regex = new RegExp(term, Utils.regexFlags);
return searchResult.replace(regex, match => Utils.wrap(match));
}
}
}
And then constructing the actual result:
module myApp.Search {
'use strict';
export class SearchResult {
id: string;
title: string;
constructor(result, term?: string) {
this.id = result.id;
this.title = term ? Utils.highlightSearchTerm(term, result.title) : result.title;
}
}
}
public ActionResult ViewNextItem(int? id)
makes the id
integer a nullable type, no need for string<->int conversions.
If you want a vertical divider between 2 columns, all you need is add
class="col-6 border-left"
to one of your column div-s
BUT
In the world of responsive design, you may need to make it disappear sometimes.
The solution is disappearing <hr>
+ disappearing <div>
+ margin-left: -1px;
<div class="container">
<div class="row">
<div class="col-md-7">
1 of 2
</div>
<div class="border-left d-sm-none d-md-block" style="width: 0px;"></div>
<div class="col-md-5" style="margin-left: -1px;">
<hr class="d-sm-block d-md-none">
2 of 2
</div>
</div>
</div>
https://jsfiddle.net/8z1pag7s/
tested on Bootstrap 4.1
The closest you say... Let me think... This must be fork() I guess :)
For details see Does Interix implement fork()?
Take a look at the MSDN Topic Thread Synchronization (C# Programming Guide)
Generally, it is best to avoid locking on a public type, or on object instances beyond the control of your application. For example, lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object. Locking on a public data type, as opposed to an object, can cause problems for the same reason. Locking on literal strings is especially risky because literal strings are interned by the common language runtime (CLR). This means that there is one instance of any given string literal for the entire program, the exact same object represents the literal in all running application domains, on all threads. As a result, a lock placed on a string with the same contents anywhere in the application process locks all instances of that string in the application. As a result, it is best to lock a private or protected member that is not interned. Some classes provide members specifically for locking. The Array type, for example, provides SyncRoot. Many collection types provide a SyncRoot member as well.
If it cannot be avoided the suggested pattern extracted from the React docs would be:
import React, { Component } from 'react';
const Child = ({ setRef }) => <input type="text" ref={setRef} />;
class Parent extends Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
// Calling a function on the Child DOM element
this.childRef.focus();
}
setRef(input) {
this.childRef = input;
}
render() {
return <Child setRef={this.setRef} />
}
}
The Parent forwards a function as prop bound to Parent's this
. When React calls the Child's ref
prop setRef
it will assign the Child's ref
to the Parent's childRef
property.
Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.
We create Components that forward their ref
with React.forwardRef
.
The returned Component ref prop must be of the same type as the return type of React.createRef
. Whenever React mounts the DOM node then property current
of the ref
created with React.createRef
will point to the underlying DOM node.
import React from "react";
const LibraryButton = React.forwardRef((props, ref) => (
<button ref={ref} {...props}>
FancyButton
</button>
));
class AutoFocus extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
this.onClick = this.onClick.bind(this);
}
componentDidMount() {
this.childRef.current.focus();
}
onClick() {
console.log("fancy!");
}
render() {
return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
}
}
Created Components are forwarding their ref
to a child node.
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
See Forwarding Refs in React docs.
If you change your inc() function to this
public static Integer inc(Integer i) {
Integer iParam = i;
i = i+1; // I think that this must be **sneakally** creating a new integer...
System.out.println(i == iParam);
return i;
}
then you will see that it always prints "false". That means that the addition creates a new instance of Integer and stores it in the local variable i ("local", because i is actually a copy of the reference that was passed), leaving the variable of the calling method untouched.
Integer is an immutable class, meaning that you cannot change it's value but must obtain a new instance. In this case you don't have to do it manually like this:
i = new Integer(i+1); //actually, you would use Integer.valueOf(i.intValue()+1);
instead, it is done by autoboxing.
You need to use JSON.stringify
to first serialize your object to JSON, and then specify the contentType
so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON
object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
Simply copy your script and put under """ your entire code """ ...
specify this line in a variable.. like,
a = """ your entire code """
print a.replace(' ',' ') # first 4 spaces tab second four space from space bar
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..
now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
Yes, you are using it incorrectly, Series.replace()
is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace
keyword argument as True
Example -
data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)
Also, you can combine the above into a single replace
function call by using list
for both to_replace
argument as well as value
argument , Example -
data['sex'].replace([0,1],['Female','Male'],inplace=True)
Example/Demo -
In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)
In [12]: data
Out[12]:
sex split
0 Male 0
1 Female 1
2 Male 0
3 Female 1
You can also use a dictionary, Example -
In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)
In [17]: data
Out[17]:
sex split
0 Male 0
1 Female 1
2 Male 0
3 Female 1
I tried to fix the 'no public DNS' once the EC2 was up and running, I couldnt add a public DNS
this is even after following the above steps making mods to the VPC or the Subnet
so, I had to make modifications to the subnet and the vpc, before starting another instance, and THEN start up a new instance.
the new instance had a public DNS. That is how it worked for me.
Update: This answer is outdated as newer versions of libraries mentioned are released since then.
Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.
"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.
See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539
Special thanks to Jeff and vapcguy your interactivity is really encouraging.
Here is a more complex statement that is useful when the length between '/' is unknown::
SELECT * FROM tableName
WHERE julianday(
substr(substr(date, instr(date, '/')+1), instr(substr(date, instr(date, '/')+1), '/')+1)
||'-'||
case when length(
substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1),'/')-1)
)=2
then
substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1), '/')-1)
else
'0'||substr(date, instr(date, '/')+1, instr(substr(date, instr(date, '/')+1), '/')-1)
end
||'-'||
case when length(substr(date,1, instr(date, '/')-1 )) =2
then substr(date,1, instr(date, '/')-1 )
else
'0'||substr(date,1, instr(date, '/')-1 )
end
) BETWEEN julianday('2015-03-14') AND julianday('2015-03-16')
Create a page call it my-page.php and save it under your theme directory. Now, edit this php file and write the following line at the top of the page
<?php /* Template Name: My Page */ ?>
Write your PHP code under the custom page definition line, you can call your other WP template, functions inside this file.
Start like
<?php require_once("header.php");?>
OR
whatever way you are integrating your header and footer to keep the layout consistent.
Since this is a my page, you NEED TO CREATE A PAGE from WordPress admin panel. Go to Admin => Pages => Add New
Add a page title, depending upon how you have coded the custom page, you might add page body (description) as well. You can fully skip the description if it’s written in the custom php page.
At right hand side, select Template. Choose My Custom Page from the dropdown. You are all set! Go to the slug (permalink) created by [wordpress][1] and see the page.
And also ng update @angular/material
will update your code and fix all imports
I think the complete func should look like :
function siteURL()
{
$protocol = "http://";
if (
//straight
isset($_SERVER['HTTPS']) && in_array($_SERVER['HTTPS'], ['on', 1])
||
//proxy forwarding
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
) {
$protocol = 'https://';
}
$domainName = $_SERVER['HTTP_HOST'];
return $protocol . $domainName;
}
Notes:
Your also have to register the receiver in onCreate(), like this:
IntentFilter filter = new IntentFilter();
filter.addAction("csinald.meg");
registerReceiver(receiver, filter);
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
Not the answer for this question
I got this exception when trying to delete a folder where i deleted the file inside.
Example:
createFolder("folder");
createFile("folder/file");
deleteFile("folder/file");
deleteFolder("folder"); // error here
While deleteFile("folder/file");
returned that it was deleted, the folder will only be considered empty after the program restart.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-
You could also just re-install Anaconda, and tick the option add variable to Path.. This will prevent you from making mistakes when editing environment variables. If you make mistakes here, your operating system could start malfunctioning.
amount = list()
for col in df.columns:
val = list(df[col])
for v in val:
amount.append(v)
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
As always the best solution is to use recursion:
loop(document);
function loop(node){
// do some thing with the node here
var nodes = node.childNodes;
for (var i = 0; i <nodes.length; i++){
if(!nodes[i]){
continue;
}
if(nodes[i].childNodes.length > 0){
loop(nodes[i]);
}
}
}
Unlike other suggestions, this solution does not require you to create an array for all the nodes, so its more light on the memory. More importantly, it finds more results. I am not sure what those results are, but when testing on chrome it finds about 50% more nodes compared to document.getElementsByTagName("*");
Probably because the original version of Python (CPython) was written in C, not C++.
The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.
You can get the events from pygame and then watch out for the KEYDOWN
event, instead of looking at the keys returned by get_pressed()
(which gives you keys that are currently pressed down, whereas the KEYDOWN
event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.
move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if move_ticker == 0:
move_ticker = 10
location -= 1
if location == -1:
location = 0
if keys[K_RIGHT]:
if move_ticker == 0:
move_ticker = 10
location+=1
if location == 5:
location = 4
Then somewhere during the game loop you would do something like this:
if move_ticker > 0:
move_ticker -= 1
This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)
Python, at startup, loads a bunch of values into sys.path
(which is "implemented" via a list of strings), including:
$PYTHONPATH
rcfiles
)$PYTHONPATH
is only one part of the eventual value of sys.path
.
If you're after the value of sys.path
, the best way would be to ask Python (thanks @Codemonkey):
python -c "import sys; print sys.path"
In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)
However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
str = str.substring(1);
}
pid_t child_pid, wpid;
int status = 0;
//Father code (before child processes start)
for (int id=0; id<n; id++) {
if ((child_pid = fork()) == 0) {
//child code
exit(0);
}
}
while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes
//Father code (After all child processes end)
wait
waits for a child process to terminate, and returns that child process's pid
. On error (eg when there are no child processes), -1
is returned. So, basically, the code keeps waiting for child processes to finish, until the wait
ing errors out, and then you know they are all finished.
Just another clarification for those starting out. When you add C:\PythonXX
to your path, make sure there are NO SPACES between variables e.g.
This:
SomeOtherDirectory;C:\Python27
Not this:
SomeOtherDirectory; C:\Python27
That took me a good 15 minutes of headache to figure out (I'm on windows 7, might be OS dependent). Happy coding.
I use a Mac, this worked for me:
Open System Preferences, then search for 'sharing'.
Choose Remote Login, make sure it is on and remember to add required users.
WITH q AS
(
SELECT TOP 1 *
FROM mytable
/* You may want to add ORDER BY here */
)
DELETE
FROM q
Note that
DELETE TOP (1)
FROM mytable
will also work, but, as stated in the documentation:
The rows referenced in the
TOP
expression used withINSERT
,UPDATE
, orDELETE
are not arranged in any order.
Therefore, it's better to use WITH
and an ORDER BY
clause, which will let you specify more exactly which row you consider to be the first.
user2540984, as well as many others have pointed out that you can try increasing your timeout settings. I myself faced a similar issue to this one and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This, however, did not help me a single bit; there was no apparent change in NGINX' timeout settings. After many hours of searching, I finally managed to solve my issue.
The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
This might not be the solution to your particular problem, but if anyone else notices that the timeout changes in /etc/nginx/nginx.conf don't do anything, I hope this answer helps!
The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization.
Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int>s;
s.push_back(11);
s.push_back(22);
s.push_back(33);
s.push_back(55);
for (int it=s.begin();it!=s.end();it++){
cout<<*it<<endl;
}
}
Line 12: error: cannot convert '__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*, __gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >' to 'int' in initialization
The auto keyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!
I have used GetPot for some projects: http://getpot.sourceforge.net/
Main feature: everything is in a single header file, no build hassles. Just save it somewhere on your machine and "#include" it in your file holding main()
Hasn't be updated recently, but it is nicely documented, and works well.
In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:
my_list = [1,2,4,6,7]
del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list
In your case the appropriate method to use is pop, because it takes the index to be removed:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
_stats/indices
gives the result with indices
.
$ curl -XGET "localhost:9200/_stats/indices?pretty=true"
{
"_shards" : {
"total" : 10,
"successful" : 5,
"failed" : 0
},
"_all" : {
"primaries" : { },
"total" : { }
},
"indices" : {
"visitors" : {
"primaries" : { },
"total" : { }
}
}
}
$(this).find(".bgHeaderH2").html();
or
$(this).find(".bgHeaderH2").text();
Also, if you have a variable,
CabRes::where('m_Id', 46)
->where('t_Id', 2)
->where(function($q) use ($variable){
$q->where('Cab', 2)
->orWhere('Cab', $variable);
})
->get();
Hyper Text Transfer Protocol (HTTP) is a protocol used for transferring web pages (like the one you're reading right now). A protocol is really nothing but a standard way of doing things. If you were to meet the President of the United States, or the king of a country, there would be specific procedures that you'd have to follow. You couldn't just walk up and say "hey dude". There would be a specific way to walk, to talk, a standard greeting, and a standard way to end the conversation. Protocols in the TCP/IP stack serve the same purpose.
The TCP/IP stack has four layers: Application, Transport, Internet, and Network. At each layer there are different protocols that are used to standardize the flow of information, and each one is a computer program (running on your computer) that's used to format the information into a packet as it's moving down the TCP/IP stack. A packet is a combination of the Application Layer data, the Transport Layer header (TCP or UDP), and the IP layer header (the Network Layer takes the packet and turns it into a frame).
...consists of all applications that use the network to transfer data. It does not care about how the data gets between two points and it knows very little about the status of the network. Applications pass data to the next layer in the TCP/IP stack and then continue to perform other functions until a reply is received. The Application Layer uses host names (like www.dalantech.com) for addressing. Examples of application layer protocols: Hyper Text Transfer Protocol (HTTP -web browsing), Simple Mail Transfer Protocol (SMTP -electronic mail), Domain Name Services (DNS -resolving a host name to an IP address), to name just a few.
The main purpose of the Application Layer is to provide a common command language and syntax between applications that are running on different operating systems -kind of like an interpreter. The data that is sent by an application that uses the network is formatted to conform to one of several set standards. The receiving computer can understand the data that is being sent even if it is running a different operating system than the sender due to the standards that all network applications conform to.
...is responsible for assigning source and destination port numbers to applications. Port numbers are used by the Transport Layer for addressing and they range from 1 to 65,535. Port numbers from 0 to 1023 are called "well known ports". The numbers below 256 are reserved for public (standard) services that run at the Application Layer. Here are a few: 25 for SMTP, 53 for DNS (udp for domain resolution and tcp for zone transfers) , and 80 for HTTP. The port numbers from 256 to 1023 are assigned by the IANA to companies for the applications that they sell.
Port numbers from 1024 to 65,535 are used for client side applications -the web browser you are using to read this page, for example. Windows will only assign port numbers up to 5000 -more than enough port numbers for a Windows based PC. Each application has a unique port number assigned to it by the transport layer so that as data is received by the Transport Layer it knows which application to give the data to. An example is when you have more than one browser window running. Each window is a separate instance of the program that you use to surf the web, and each one has a different port number assigned to it so you can go to www.dalantech.com in one browser window and this site does not load into another browser window. Applications like FireFox that use tabbed windows simply have a unique port number assigned to each tab
...is the "glue" that holds networking together. It permits the sending, receiving, and routing of data.
...consists of your Network Interface Card (NIC) and the cable connected to it. It is the physical medium that is used to transmit and receive data. The Network Layer uses Media Access Control (MAC) addresses, discussed earlier, for addressing. The MAC address is fixed at the time an interface was manufactured and cannot be changed. There are a few exceptions, like DSL routers that allow you to clone the MAC address of the NIC in your PC.
For more info:
In Flask you just need to write:
curs = conn.cursor()
curs.execute("ROLLBACK")
conn.commit()
P.S. Documentation goes here https://www.postgresql.org/docs/9.4/static/sql-rollback.html
Depending if you have Underscore or Babel here is a Benchmark of the different way of deep cloning an array.
https://jsperf.com/object-rest-spread-vs-clone/2
Look like babel is the fastest.
var x = babel({}, obj)
Here is what I'm doing:
git clone repo /tmp/folder
cp -rf /tmp/folder/.git /dest/folder/
cd /dest/folder
git checkout -f master
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
I believe you have libx264
installed and configured with ffmpeg
to convert video to h264
... Then you can try with -vcodec libx264
... The -format
option is for showing available formats, this is not a conversion option I think...
stdout
is the standard output stream in UNIX. See http://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#Standard-Streams.
When running in a terminal, you will see data written to stdout
in the terminal and you can redirect it as you choose.
Invalid Example:
function findAll() {
$query=<<<SQL
SELECT * FROM `table_1`;
SQL;
// ... omitted
}
This will throw an exception that resembles the following:
<br />
<b>Parse error</b>: syntax error, unexpected end of file in <b>[...][...]</b> on line <b>5</b><br />
where number 5 might be the last line number of your file.
According to php manual:
Warning It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including macOS. The closing delimiter must also be followed by a newline.
TLDR: Closing identifiers should NOT be indented.
Valid Example:
function findAll() {
$query=<<<SQL
SELECT * FROM `table_1`;
SQL;
// closing identifier should not be indented, although it might look ugly
// ... omitted
}
In your case height will be calculated automatically, so you have to provide the height
use this
.list-content{
width: 100%;
height:150px;
}
Try this...
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
You should be able to get an IWin32Window by by using PresentationSource.FromVisual and casting the result to HwndSource which implements IWin32Window.
Also in the comments here:
Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:
Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:
<configuration>
<system.serviceModel>
<services>
<service name="com.aschneider.examples.wcf.services.EchoService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/EchoService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors></serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IEchoService"/>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address = "net.pipe://localhost/EchoService"
binding = "netNamedPipeBinding"
bindingConfiguration = "NetNamedPipeBinding_IEchoService"
contract = "EchoServiceReference.IEchoService"
name = "NetNamedPipeBinding_IEchoService"/>
</client>
</system.serviceModel>
</configuration>
The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).
Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...
In flutter, there are a few ways to deal with Asynchronous actions.
A lazy way to do it can be using a modal. Which will block the user input, thus preventing any unwanted actions.
This would require very little change to your code. Just modifying your _onLoading
to something like this :
void _onLoading() {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Dialog(
child: new Row(
mainAxisSize: MainAxisSize.min,
children: [
new CircularProgressIndicator(),
new Text("Loading"),
],
),
);
},
);
new Future.delayed(new Duration(seconds: 3), () {
Navigator.pop(context); //pop dialog
_login();
});
}
The most ideal way to do it is using FutureBuilder
and a stateful widget. Which is what you started.
The trick is that, instead of having a boolean loading = false
in your state, you can directly use a Future<MyUser> user
And then pass it as argument to FutureBuilder
, which will give you some info such as "hasData" or the instance of MyUser
when completed.
This would lead to something like this :
@immutable
class MyUser {
final String name;
MyUser(this.name);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<MyUser> user;
void _logIn() {
setState(() {
user = new Future.delayed(const Duration(seconds: 3), () {
return new MyUser("Toto");
});
});
}
Widget _buildForm(AsyncSnapshot<MyUser> snapshot) {
var floatBtn = new RaisedButton(
onPressed:
snapshot.connectionState == ConnectionState.none ? _logIn : null,
child: new Icon(Icons.save),
);
var action =
snapshot.connectionState != ConnectionState.none && !snapshot.hasData
? new Stack(
alignment: FractionalOffset.center,
children: <Widget>[
floatBtn,
new CircularProgressIndicator(
backgroundColor: Colors.red,
),
],
)
: floatBtn;
return new ListView(
padding: const EdgeInsets.all(15.0),
children: <Widget>[
new ListTile(
title: new TextField(),
),
new ListTile(
title: new TextField(obscureText: true),
),
new Center(child: action)
],
);
}
@override
Widget build(BuildContext context) {
return new FutureBuilder(
future: user,
builder: (context, AsyncSnapshot<MyUser> snapshot) {
if (snapshot.hasData) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Hello ${snapshot.data.name}"),
),
);
} else {
return new Scaffold(
appBar: new AppBar(
title: new Text("Connection"),
),
body: _buildForm(snapshot),
);
}
},
);
}
}
//go through this code I have made several changes in it//
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (i<11)
{
i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}
while (i<12)
{
i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}
}
}
I could resolve this problem by updating macOS and XCode.
I beleive
$("#myElement").attr("title", "new title value")
or
$("#myElement").prop("title", "new title value")
should do the trick...
I think you can find all the core functions in the jQuery Docs, although I hate the formatting.
I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:
<projectDescription>
<name>Project-Name</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
2- Now instead of "Project-Name", write your project name, maybe current directory name
3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )
4- Now go to Eclips and open project and add your files to it.
The above description wasn't sufficient to get things working for me (probably dense or lazy) so I created this script once I found the answer to help me in the future. Hope it helps others
vim fixperms.sh
#!/bin/sh
for D in `find . -type d`
do
echo $D;
chown -R mysql:mysql $D;
chmod -R 660 $D;
chown mysql:mysql $D;
chmod 700 $D;
done
echo Dont forget to restart mysql: /etc/init.d/mysqld restart;
I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:
// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
alert(timeDifferenceInDays);
You can skip some steps in the code, I have written it so to make it easy to understand.
You'll find a running example here: http://jsfiddle.net/matKX/
You can easily add multiple classes to divs... So:
<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>
Then in the CSS call to the share class to apply the same styles:
.myclass {...}
And you can still use your other classes like this:
.myclass-three {...}
Or if you want to be more specific in the CSS like this:
.myclass.myclass-three {...}
getResourceAsStream
is the right way to do it for web apps (as you already learned).
The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.
If the imagestr was bitmap data (which we now know it isn't) you could use this
imagestr
is the base64 encoded string
width
is the width of the image
height
is the height of the image
from PIL import Image
from base64 import decodestring
image = Image.fromstring('RGB',(width,height),decodestring(imagestr))
image.save("foo.png")
Since the imagestr is just the encoded png data
from base64 import decodestring
with open("foo.png","wb") as f:
f.write(decodestring(imagestr))
Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.
Before you can do @import 'compass';
, you should:
Install Compass as a Ruby gem:
gem install compass
After that, you should use Compass's own command line tool to compile your SASS code:
cd path/to/your/project/
compass compile
Note that Compass reqiures a configuration file called config.rb
. You should create it for Compass to work.
The minimal config.rb
can be as simple as this:
css_dir = "css"
sass_dir = "sass"
And your SASS code should reside in sass/
.
Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name>
and then copy your SASS code inside it.
Note that if you want to use Compass extensions, you will have to:
config.rb
;More info here: http://compass-style.org/help/
Since the id of the connect button is now changed to "colab-connect-button", the following code can be used to keep clicking on the button.
function ClickConnect(){
console.log("Clicked on connect button");
document.querySelector("colab-connect-button").click()
}
setInterval(ClickConnect,60000)
If still, this doesn't work, then follow the steps given below:
function ClickConnect(){
console.log("Clicked on connect button");
document.querySelector("Put ID here").click() // Change id here
}
setInterval(ClickConnect,60000)
It seems I don't have enough reputation to add a comment to Tobia's answer above, so I am adding this "answer" to help those of us wanting to experiment with xargs
the same way on the Windows platforms.
Here is a windows batch file that does the same thing as Tobia's quickly coded "show" script:
@echo off
REM
REM cool trick of using "set" to echo without new line
REM (from: http://www.psteiner.com/2012/05/windows-batch-echo-without-new-line.html)
REM
if "%~1" == "" (
exit /b
)
<nul set /p=Args: "%~1"
shift
:start
if not "%~1" == "" (
<nul set /p=, "%~1"
shift
goto start
)
echo.
Another possibility:
import subprocess
def num_lines_in_file(fpath):
return int(subprocess.check_output('wc -l %s' % fpath, shell=True).strip().split()[0])
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
I got the OP's link error about rc.exe
when trying to execute pip install
inside a bash
task within an Azure DevOps pipeline that I was using to build a Python package from source with C++ extensions. I was able to resolve it by adding the path to rc.exe
inside the bash
task just before calling pip install
, like so:
PATH="/c/Program Files (x86)/Windows Kits/10/bin/10.0.18362.0/x64":$PATH
That was inside an Azure job
that was using vmImage: 'windows-2019'
for its agent; i.e., Windows Server 2019 with Visual Studio 2019.
I branched off from the accepted answer to only run when the click is being HELD down and dragged.
My function was running when I wasn't holding the mouse down. Here's the updated code if you also want this functionality:
var isDragging = false;
var mouseDown = false;
$('.test_area')
.mousedown(function() {
isDragging = false;
mouseDown = true;
})
.mousemove(function(e) {
isDragging = true;
if (isDragging === true && mouseDown === true) {
my_special_function(e);
}
})
.mouseup(function(e) {
var wasDragging = isDragging;
isDragging = false;
mouseDown = false;
if ( ! wasDragging ) {
my_special_function(e);
}
}
);
I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.
position: fixed
to the CSS definition, but I see this won't work for youtop
.UPDATED:
CSS
#ActionBox {
position: relative;
float: right;
}
Script
var alert_top = 0;
var alert_margin_top = 0;
$(function() {
alert_top = $("#ActionBox").offset().top;
alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);
$(window).scroll(function () {
var scroll_top = $(window).scrollTop();
if (scroll_top > alert_top) {
$("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
} else {
$("#ActionBox").css("margin-top", alert_margin_top+"px");
};
});
});
Also it is important to add a base (10 in this case) to your parseInt()
, e.g.
parseInt($("#ActionBox").css("top"),10);
// variable declaration
TextToSpeech tts;
// TextToSpeech initialization, must go within the onCreate method
tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Lenguage not supported");
}
} else {
Log.e("TTS", "Initialization failed");
}
}
});
// method call
public void buttonSpeak().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
speak();
}
});
}
private void speak() {
tts.speak("Text to Speech Test", TextToSpeech.QUEUE_ADD, null);
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
taken from: Text to Speech Youtube Tutorial
This is what I would use:
numbers = [float(x)/10 for x in range(10)]
rather than:
numbers = [x*0.1 for x in range(10)]
that would return :
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]
hope it helps.
Here is a quickly hacked up version of this using SVG I just did. Works well for me on my iPhone. Also works in a desktop browser using normal mouse events.
Well this is simple answer you want.
MaterialApp(
debugShowCheckedModeBanner: false
)
But if you want to go deep with app (Want a release apk (which don't have debug banner) and if you are using android studio then go to
Run -> Flutter Run 'main.dart' in Relese mode
The closest thing C does to "computing p" in a way that's directly visible to applications is acos(-1)
or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).
However, an interesting issue is that computing the trigonometric functions (sin
, cos
, and tan
) requires reduction of their argument modulo 2p. Since 2p is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x
is 1e12
, and 2*M_PI
differs from 2p by e, then fmod(x,2*M_PI)
differs from the correct value of 2p by up to 1e12*e/p times the correct value of x
mod 2p. That is to say, it's completely meaningless.
A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of p hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin
/cos
/tan
functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)
in your question, both buffer and byteArray seem to be byte[]. So:
ImageElement image = ImageElement.FromBinary(buffer);
Use the apache commons-lang3 lib
import org.apache.commons.lang3.exception.ExceptionUtils;
//...
String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));
CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
I'm normally the one of the very few Python experts who steadfastly defends regular expressions (they have quite a bad reputation in the Python community), but this is not one of those cases -- accepting (say) '333.444.555.666'
as an "IP address" is really bad, and if you need to do more checks after matching the RE, much of the point of using a RE is lost anyway. So, I second @Mark's recommendations heartily: IPy for generality and elegance (including support of IPv6 if you want!), string operations and int checks if you only need IPv4 (but, think twice about that limitation, and then think one more -- IPv6's time has way come!-):
def isgoodipv4(s):
pieces = s.split('.')
if len(pieces) != 4: return False
try: return all(0<=int(p)<256 for p in pieces)
except ValueError: return False
I'd far rather do that than a convoluted RE to match only numbers between 0 and 255!-)
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
Use EmailMultiAlternatives and render_to_string to make use of two alternative templates (one in plain text and one in html):
from django.core.mail import EmailMultiAlternatives
from django.template import Context
from django.template.loader import render_to_string
c = Context({'username': username})
text_content = render_to_string('mail/email.txt', c)
html_content = render_to_string('mail/email.html', c)
email = EmailMultiAlternatives('Subject', text_content)
email.attach_alternative(html_content, "text/html")
email.to = ['[email protected]']
email.send()
Before adding a class you should check if it already had class with .hasClass() method
For your specific question. You should be putting your stuff in Cascading Stylesheet. It's best practice to separate design and functionality.
so the proposed solution of adding and removing class names is best practice.
however when you are manipulating elements you don't control of how they are rendered. removeAttr('style') is BEST way to remove all inline styles.
This is a good use of a temporary table.
CREATE TEMPORARY TABLE patterns (
pattern VARCHAR(20)
);
INSERT INTO patterns VALUES ('ABC%'), ('XYZ%'), ('PQR%');
SELECT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
In the example patterns, there's no way col
could match more than one pattern, so you can be sure you'll see each row of tbl
at most once in the result. But if your patterns are such that col
could match more than one, you should use the DISTINCT
query modifier.
SELECT DISTINCT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
When we try to drop a column which is depended upon then we see this kind of error:
The object 'DF__*' is dependent on column ''.
drop the constraint which is dependent on that column with:
ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;
Example:
Msg 5074, Level 16, State 1, Line 1
The object 'DF__Employees__Colf__1273C1CD' is dependent on column 'Colf'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN Colf failed because one or more objects access this column.
Drop Constraint(DF__Employees__Colf__1273C1CD):
ALTER TABLE Employees DROP CONSTRAINT DF__Employees__Colf__1273C1CD;
Then you can Drop Column:
Alter Table TableName Drop column ColumnName
One option is strtok
example:
char name[20];
//pretend name is set to the value "My name"
You want to split it at the space between the two words
split=strtok(name," ");
while(split != NULL)
{
word=split;
split=strtok(NULL," ");
}
Do Graphically.
Database right click-->properties-->files-->select database owner-->select [sa]-- ok
i do it like this cover button and the middle image that
<button><img src="foldername/imagename" width="30px" height= "30px"></button>
For those that want it ISO 8601 compliant, since the other solutions do not have the T
separator nor the time offset (except Meistro's answer):
from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00
Note, I use fromtimestamp
because if I used utcfromtimestamp
I would need to chain on .astimezone(...)
anyway to get the offset.
If you don't want to go all the way to microseconds
you can choose a different unit with the
isoformat() method.
When executing DML statement , you should use executeUpdate
/execute
rather than executeQuery
.
Here is a brief comparison :
Create key value pairs on the phpsh commandline like this:
php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
[foo] => bar
[pyramid] => power
)
Get the count of key value pairs:
php> echo count($offerarray);
2
Get the keys as an array:
php> echo implode(array_keys($offerarray));
foopyramid
Filter out data in using a where clause so that you don't get 0 values.
This RegEx matches any Integer positive out of 0:
(?<!-)(?<!\d)[1-9][0-9]*
It works with two negative lookbehinds, which search for a minus before a number, which indicates it is a negative number. It also works for any negative number larger than -9 (e.g. -22).
When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.
When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used
versionlabel.Text = "Version " + Application.ProductVersion;
This approach requires a reference to System.Windows.Forms
.
You can achieve this with different methods:
(remember if an element is to be operated, better give it an id or class, rather than having it's parent element an id or class).
Here,
As the div has a class to target the select inside it, code will be:
$("div.id_100 select").val("val2");
or
$('div.id_100 option[value="val2"]').prop("selected", true);
If the class would have been given to select itself, code will be:
$(".id_100").val("val2");
or
$('.id_100 option[value=val2]').attr('selected','selected');
or
$('.id_100 option')
.removeAttr('selected')
.filter('[value=val1]')
.attr('selected', true);
To pass the value dynamically, code will be:
valu="val2";
$("div.id_100 select").val(valu);
$("div.id_100 > select > option[value=" + valu + "]").prop("selected",true);
If element is added through ajax,
You will have to give 'id' to your element and use
window.document.getElementById
else
You will have to give 'class' to your element and use
window.document.getElementById
You can also select value of select element by it's index number.
If you have given ID to your select element, code will be:
window.document.getElementById('select_element').selectedIndex = 4;
Remember when you change the select value as said above, change method is not called.
i.e. if you have written code to do some stuff on change of select the above methods will change the select value but will not trigger the change.
for to trigger the change function you have to add .change() at the end.
so the code will be:
$("#select_id").val("val2").change();
I had another problem, I did not want to encode data in gzip but to decode gzipped data. I am running javascript code outside of the browser so I need to decode it using pure javascript.
It took me some time but i found that in the JSXGraph library there is a way to read gzipped data.
Here is where I found the library: http://jsxgraph.uni-bayreuth.de/wp/2009/09/29/jsxcompressor-zlib-compressed-javascript-code/ There is even a standalone utility that can do that, JSXCompressor, and the code is LGPL licencied.
Just include the jsxcompressor.js file in your project and then you will be able to read a base 64 encoded gzipped data:
<!doctype html>
</head>
<title>Test gzip decompression page</title>
<script src="jsxcompressor.js"></script>
</head>
<body>
<script>
document.write(JXG.decompress('<?php
echo base64_encode(gzencode("Try not. Do, or do not. There is no try."));
?>'));
</script>
</html>
I understand it is not what you wanted but I still reply here because I suspect it will help some people.
For me it was due to insufficient disk space , and it was resolved after I freed up some disk space on my local drive.
You can also do:
array = numpy.append(array, value)
Note that the numpy.append()
method returns a new object, so if you want to modify your initial array, you have to write: array = ...
The below command line will give you the total memory used by the various process running on the Linux machine in MB:
ps -eo size,pid,user,command --sort -size | awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | awk '{total=total + $1} END {print total}'
Use a monospaced font like Lucida Console, which comes with Windows. If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.