This should handle issue:
SPOOL_FILE=${LOG_DIR}/${LOG_FILE_NAME}.spool
SQLPLUS_OUTPUT=`sqlplus -s "$SFDC_WE_CORE" <<EOF
SET HEAD OFF
SET AUTOPRINT OFF
SET TERMOUT OFF
SET SERVEROUTPUT ON
SPOOL ${SPOOL_FILE}
WHENEVER SQLERROR EXIT SQL.SQLCODE
DECLARE
BEGIN
foooo
--rollback;
END;
/
EOF`
RC=$?
if [[ $RC != 0 ]] ; then
echo " RDBMS exit code : $RC " | tee -a ${LOG_FILE}
cat ${SPOOL_FILE} | tee -a ${LOG_FILE}
cat ${LOG_FILE} | mail -s "Script ${INIT_EXE} failed on $SFDC_ENV" $SUPPORT_LIST
exit 3
fi
Use the Counter.most_common()
method, it'll sort the items for you:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq
is used instead of a straight sort:
>>> x.most_common(1)
[('c', 7)]
Outside of counters, sorting can always be adjusted based on a key
function; .sort()
and sorted()
both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True)
would give you the same sorting as x.most_common()
, but only return the keys, for example:
>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
or you can sort on only the value given (key, value)
pairs:
>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
See the Python sorting howto for more information.
A URL that starts with the URL scheme and scheme specific part (http://
, https://
, ftp://
, etc.) is an absolute URL.
Any other URL is a relative URL and needs a base URL the relative URL is resolved from (and thus depend on) that is the URL of the resource the reference is used in if not declared otherwise.
Take a look at RFC 2396 – Appendix C for examples of resolving relative URLs.
In my case php-fpm outputs 500 error without any logging because of missing php-mysql module. I moved joomla installation to another server and forgot about it. So apt-get install php-mysql
and service restart solved it.
I started with trying to fix broken logging without success. Finally with strace
i found fail message after db-related system calls. Though my case is not directly related to op's question, I hope it could be useful.
I had FB never being defined. Turned out that I was prototyping functions into the Object class called "merge" and another called "toArray". Both of these screwed up Facebook, no error messages but it wouldn't load.
I changed the names of my prototypes, it works now. Hey, if Facebook is going to prototype Object, shouldn't I be allowed to prototype it?
1 - You need to have Tesseract OCR installed on your computer.
get it from here. https://github.com/UB-Mannheim/tesseract/wiki
Download the suitable version.
2 - Add Tesseract path to your System Environment. i.e. Edit system variables.
3 - Run pip install pytesseract
and pip install tesseract
4 - Add this line to your python script every time
pytesseract.pytesseract.tesseract_cmd = 'C:/OCR/Tesseract-OCR/tesseract.exe' # your path may be different
5 - Run the code.
Try "ssh-add" which worked for me.
For any one having this issue with Flurry framework. This is what fixed my issue. For me the issue was that i had imported the following files but never used them. "libFlurryTVOS_9.2.3" "libFlurryWatch_9.2.3"
So all I had to do was go to project target settings and remove these 2 files from the "Linked framework and libraries" section and the problem was solved.
I prefer to use "await" command and async functions to get rid of confusions of promises,
In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :
async function SubFunction(output){
// Call to database , returns a promise, like an Ajax call etc :
const response = await axios.get( GetApiHost() + '/api/some_endpoint')
// Return :
return response;
}
and then I would call this function from main function :
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
Noting that I returned both main function and sub function to async functions here.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
If you wish a full domain origin, you can use this:
document.location.origin
And if you wish to get only the domain, use can you just this:
document.location.hostname
But you have other options, take a look at the properties in:
document.location
I would try any(byte[].class)
Try this command:
cat /proc/stat
This will be something like this:
cpu 55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0
More details:
http://www.mail-archive.com/[email protected]/msg01690.html http://www.linuxhowtos.org/System/procstat.htm
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
From the Python glossary:
It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a
__path__
attribute is considered a package.
Python files with a dash in the name, like my-file.py
, cannot be imported with a simple import
statement. Code-wise, import my-file
is the same as import my - file
which will raise an exception. Such files are better characterized as scripts whereas importable files are modules.
UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.
By using JOINs, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how SQL should use data from one table to select the rows in another table.
The UNION operation is different from using JOINs that combine columns from two tables.
UNION Example:
SELECT 1 AS [Column1], 2 AS [Column2]
UNION
SELECT 3 AS [Column1], 4 AS [Column2]
Output:
Column1 Column2
-------------------
1 2
3 4
JOIN Example:
SELECT a.Column1, b.Column2 FROM TableA a INNER JOIN TableB b ON a.Id = b.AFKId
This will output all the rows from both the tables for which the condition a.Id = b.AFKId
is true.
You should avoid using nested selects and I would go as far to say you should never use them in the actual select part of your statement. You will be running that select for each row that is returned. This is a really expensive operation. Rather use joins. It is much more readable and the performance is much better.
In your case the query below should help. Note the cases statement is still there, but now it is a simple compare operation.
select
p.product_id,
p.type_id,
p.product_name,
p.type,
case p.type_id when 10 then (CONCAT_WS(' ' , first_name, middle_name, last_name )) else (null) end artistC
from
Product p
inner join Product_Type pt on
pt.type_id = p.type_id
left join Product_ArtistAuthor paa on
paa.artist_id = p.artist_id
where
p.product_id = $pid
I used a left join since I don't know the business logic.
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
I'll echo what Dmitriy said, but adding on a point.
I worked on a batch billing system that needed to insert large sets of rows on 30+ tables. We weren't allowed to do a data pump (Oracle) so we had to do bulk inserts. Those tables had foreign keys on them, but we had already ensured that they were not breaking any relationships.
Before insert, we disable the foreign key constraints so that Oracle doesn't take forever doing the inserts. After the insert is successful, we re-enable the constraints.
PS: In a large database with many foreign keys and child row data for a single record, sometimes foreign keys can be bad, and you may want to disallow cascading deletes. For us in the billing system, it would take too long and be too taxing on the database if we did cascading deletes, so we just mark the record as bad with a field on the main driver (parent) table.
If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:
import csv
csv.register_dialect('skip_space', skipinitialspace=True)
with open(my_file, 'r') as f:
reader=csv.reader(f , delimiter=' ', dialect='skip_space')
for item in reader:
print(item)
The Array.prototype
property represents the prototype for the Array
constructor and allows you to add new properties
and methods
to all Array
objects. we can create a prototype for this purpose
Array.prototype.has_element = function(element) {
return $.inArray( element, this) !== -1;
};
And then use it like this
var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false
See the Demo below
Array.prototype.has_element = function(element) {_x000D_
return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
You can use std::set
instead of std::map
.
You can store both key and value in std::pair
and the type of container will look like this:
std::set< std::pair<int, std::string> > items;
std::set
will sort it's values both by original keys and values that were stored in std::map
.
I was looking to use this method for signatures as well, i found a sample on http://codetheory.in/.
I've added the below code to a jsfiddle
Html:
<div id="sketch">
<canvas id="paint"></canvas>
</div>
Javascript:
(function() {
var canvas = document.querySelector('#paint');
var ctx = canvas.getContext('2d');
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var mouse = {x: 0, y: 0};
var last_mouse = {x: 0, y: 0};
/* Mouse Capturing Work */
canvas.addEventListener('mousemove', function(e) {
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
/* Drawing on Paint App */
ctx.lineWidth = 5;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'blue';
canvas.addEventListener('mousedown', function(e) {
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
};
}());
This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.
Some possible alternatives:
Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.
Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.
If you have @oneToOne
mapping set to FetchType.LAZY
and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.
Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.
Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects
As @Agent_9191 and @partick mentioned you should use
$('tbody :visible').highlight(myArray[i]); // works for all children of tbody that are visible
or
$('tbody:visible').highlight(myArray[i]); // works for all visible tbodys
Additionally, since you seem to be applying a class to the highlighted words, instead of using jquery to alter the background for all matched highlights, just create a css rule with the background color you need and it gets applied directly once you assign the class.
.highlight { background-color: #FFFF88; }
The disapproval of tail
here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n
, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1] 1 2 3 4 5 6 7 8 9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
# only 0's may be mixed with negative subscripts
Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.
--Kotlin Version
package com.ps.salestrackingapp.Services
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log
class LocationService : Service() {
private var mLocationManager: LocationManager? = null
var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER), LocationListener(LocationManager.NETWORK_PROVIDER))
class LocationListener(provider: String) : android.location.LocationListener {
internal var mLastLocation: Location
init {
Log.e(TAG, "LocationListener $provider")
mLastLocation = Location(provider)
}
override fun onLocationChanged(location: Location) {
Log.e(TAG, "onLocationChanged: $location")
mLastLocation.set(location)
Log.v("LastLocation", mLastLocation.latitude.toString() +" " + mLastLocation.longitude.toString())
}
override fun onProviderDisabled(provider: String) {
Log.e(TAG, "onProviderDisabled: $provider")
}
override fun onProviderEnabled(provider: String) {
Log.e(TAG, "onProviderEnabled: $provider")
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
Log.e(TAG, "onStatusChanged: $provider")
}
}
override fun onBind(arg0: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG, "onStartCommand")
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onCreate() {
Log.e(TAG, "onCreate")
initializeLocationManager()
try {
mLocationManager!!.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
mLocationListeners[1])
} catch (ex: java.lang.SecurityException) {
Log.i(TAG, "fail to request location update, ignore", ex)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "network provider does not exist, " + ex.message)
}
try {
mLocationManager!!.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
mLocationListeners[0])
} catch (ex: java.lang.SecurityException) {
Log.i(TAG, "fail to request location update, ignore", ex)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "gps provider does not exist " + ex.message)
}
}
override fun onDestroy() {
Log.e(TAG, "onDestroy")
super.onDestroy()
if (mLocationManager != null) {
for (i in mLocationListeners.indices) {
try {
mLocationManager!!.removeUpdates(mLocationListeners[i])
} catch (ex: Exception) {
Log.i(TAG, "fail to remove location listners, ignore", ex)
}
}
}
}
private fun initializeLocationManager() {
Log.e(TAG, "initializeLocationManager")
if (mLocationManager == null) {
mLocationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
}
companion object {
private val TAG = "BOOMBOOMTESTGPS"
private val LOCATION_INTERVAL = 1000
private val LOCATION_DISTANCE = 0f
}
}
It's simple:
array = []
will set array
to be an empty list. (They're called lists in Python, by the way, not arrays)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
I am not sure I understand what you want, but based on what I understood
the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"
you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")
worked for me, see the picture
I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code
print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";
package Changed;
{
my $test = 10;
my $test1 = 11;
print "trying to print local vars from a closed block: $test, $test1\n";
}
&Check_global;
sub Check_global {
print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package: $test\n";
print "trying to print local var outside the block $test1\n";
Will Output this:
package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block
In case using "use strict" will get this failure while attempting to run the script:
Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.
in MySQL schema is synonym of database. Its quite confusing for beginner people who jump to MySQL and very first day find the word schema, so guys nothing to worry as both are same.
When you are starting MySQL for the first time you need to create a database (like any other database system) to work with so you can CREATE SCHEMA which is nothing but CREATE DATABASE
In some other database system schema represents a part of database or a collection of Tables, and collection of schema is a database.
For the Java programming language, there is no difference between the two. Java has two types of comments: traditional comments (/* ... */
) and end-of-line comments (// ...
). See the Java Language Specification. So, for the Java programming language, both /* ... */
and /** ... */
are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).
However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular, /** ... */
comments are interpreted by the Javadoc tool, which is included in the Java platform and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between /** ... */
as documentation.
This is similar to tags like FIXME
and TODO
: if you include a comment like // TODO: fix this
or // FIXME: do that
, most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.
You can approach it from either an "allow list" or a "block list" way:
// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);
// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);
If it's reusable business logic, you can partial it out as well:
// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);
// and later
var result = clean(credentials);
A similar approach can be achieved without Lodash:
const transform = (obj, predicate) => {
return Object.keys(obj).reduce((memo, key) => {
if(predicate(obj[key], key)) {
memo[key] = obj[key]
}
return memo
}, {})
}
const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))
const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))
// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])
// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])
// "App"
const credentials = {
fname:"xyz",
lname:"abc",
age:23
}
const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)
You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.
It happens to me also.
It is because when we edit the
.env
file we need to restart the server. Just stop the currentphp artisan serve
and start it once again. This will work for sure.
If still not worked try doing php artisan config:cache
const
applies for variables, and prevents them from being modified in your code.
constexpr
tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const
variables, etc. The link given by Oli has a lot of excellent examples.
Basically they are 2 different concepts altogether, and can (and should) be used together.
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
Here is what you do in Excel 2003:
Here is what you do in Excel 2007:
Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?
If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.
Put the image — let's say it's width is 140px — inside of a link:
<a><img src='image link' style='width: 140px'></a>
Next, put the caption in a and give it a width less than your image, while centering it:
<a>
<img src='image link' style='width: 140px'>
<div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>
Next, in the link tag, style the link so that it no longer looks like a link. You can give it any color you want, but just remove any text decoration your links may carry.
<a style='text-decoration: none; color: orange;'>
<img src='image link' style='width: 140px'>
<div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>
I wrapped the image with it's caption in a link so that no text could push the caption out of the way: The caption is tied to the picture by the link. Here's an example: http://www.alphaeducational.com/p/okay.html
I had this problem and did not want to mess things up using sudo
. When investigating, I tried to get some info :
docker info
Surprinsingly, I had the following error :
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http:///var/run/docker.sock/v1.38/info: dial unix /var/run/docker.sock: connect: permission denied
For some reason I did not have enough privileges, the following command solved my problem :
sudo chown $USER /var/run/docker.sock
Et voilà !
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
@if(session('success'))
<h1>{{session('success')}}</h1>
@endif
Try command + t
.
It works for me.
The LEFT OUTER JOIN will return all records from the LEFT table joined with the RIGHT table where possible.
If there are matches though, it will still return all rows that match, therefore, one row in LEFT that matches two rows in RIGHT will return as two ROWS, just like an INNER JOIN.
EDIT: In response to your edit, I've just had a further look at your query and it looks like you are only returning data from the LEFT table. Therefore, if you only want data from the LEFT table, and you only want one row returned for each row in the LEFT table, then you have no need to perform a JOIN at all and can just do a SELECT directly from the LEFT table.
In case anyone looking for commonly supported formats by server
3g2|3gp|3gp2|3gpp|aac|aaf|aca|accdb|accde|accdt|acx|adt|adts|afm|ai|aif|aifc|aiff|appcache|application|art|asd|asf|asi|asm|asr|asx|atom|au|avi|axs|bas|bcpio|bin|bmp|c|cab|calx|cat|cdf|chm|class|clp|cmx|cnf|cod|cpio|cpp|crd|crl|crt|csh|css|csv|cur|dcr|deploy|der|dib|dir|disco|dll|dllconfig|dlm|doc|docm|docx|dot|dotm|dotx|dsp|dtd|dvi|dvr-ms|dwf|dwp|dxr|eml|emz|eot|eps|esd|etx|evy|exe|execonfig|fdf|fif|fla|flr|flv|gif|gtar|gz|h|hdf|hdml|hhc|hhk|hhp|hlp|hqx|hta|htc|htm|html|htt|hxt|ico|ics|ief|iii|inf|ins|isp|IVF|jar|java|jck|jcz|jfif|jpb|jpe|jpeg|jpg|js|json|jsonld|jsx|latex|less|lit|lpk|lsf|lsx|lzh|m13|m14|m1v|m2ts|m3u|m4a|m4v|man|manifest|map|mdb|mdp|me|mht|mhtml|mid|midi|mix|mmf|mno|mny|mov|movie|mp2|mp3|mp4|mp4v|mpa|mpe|mpeg|mpg|mpp|mpv2|ms|msi|mso|mvb|mvc|nc|nsc|nws|ocx|oda|odc|ods|oga|ogg|ogv|one|onea|onepkg|onetmp|onetoc|onetoc2|osdx|otf|p10|p12|p7b|p7c|p7m|p7r|p7s|pbm|pcx|pcz|pdf|pfb|pfm|pfx|pgm|pko|pma|pmc|pml|pmr|pmw|png|pnm|pnz|pot|potm|potx|ppam|ppm|pps|ppsm|ppsx|ppt|pptm|pptx|prf|prm|prx|ps|psd|psm|psp|pub|qt|qtl|qxd|ra|ram|rar|ras|rf|rgb|rm|rmi|roff|rpm|rtf|rtx|scd|sct|sea|setpay|setreg|sgml|sh|shar|sit|sldm|sldx|smd|smi|smx|smz|snd|snp|spc|spl|spx|src|ssm|sst|stl|sv4cpio|sv4crc|svg|svgz|swf|t|tar|tcl|tex|texi|texinfo|tgz|thmx|thn|tif|tiff|toc|tr|trm|ts|tsv|ttf|tts|txt|u32|uls|ustar|vbs|vcf|vcs|vdx|vml|vsd|vss|vst|vsto|vsw|vsx|vtx|wav|wax|wbmp|wcm|wdb|webm|wks|wm|wma|wmd|wmf|wml|wmlc|wmls|wmlsc|wmp|wmv|wmx|wmz|woff|woff2|wps|wri|wrl|wrz|wsdl|wtv|wvx|x|xaf|xaml|xap|xbap|xbm|xdr|xht|xhtml|xla|xlam|xlc|xlm|xls|xlsb|xlsm|xlsx|xlt|xltm|xltx|xlw|xml|xof|xpm|xps|xsd|xsf|xsl|xslt|xsn|xtp|xwd|z|zip
Use properties of window.location
var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;
You can see more properties at https://developer.mozilla.org/en/DOM/window.location
You're already prepending the hash sign in your showDialog()
function, and you're missing single quotes in your second code snippet. You should also return false
from the handler to prevent a postback from occurring. Try:
<asp:Button ID="ButtonAdd" runat="server" Text="Add"
OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />
As mentioned originally in this answer by SoBeRich, and in my own answer, as of git 2.4.x
git push --atomic origin <branch name> <tag>
(Note: this actually work with HTTPS only with Git 2.24)
As of git 2.4.1, you can do
git config --global push.followTags true
If set to true enable --follow-tags option by default.
You may override this configuration at time of push by specifying --no-follow-tags.
As noted in this thread by Matt Rogers answering Wes Hurd:
--follow-tags
only pushes annotated tags.
git tag -a -m "I'm an annotation" <tagname>
That would be pushed (as opposed to git tag <tagname>
, a lightweight tag, which would not be pushed, as I mentioned here)
Since git 1.8.3 (April 22d, 2013), you no longer have to do 2 commands to push branches, and then to push tags:
The new "
--follow-tags
" option tells "git push
" to push relevant annotated tags when pushing branches out.
You can now try, when pushing new commits:
git push --follow-tags
That won't push all the local tags though, only the one referenced by commits which are pushed with the git push
.
Git 2.4.1+ (Q2 2015) will introduce the option push.followTags
: see "How to make “git push
” include tags within a branch?".
The nuclear option would be git push --mirror
, which will push all refs under refs/
.
You can also push just one tag with your current branch commit:
git push origin : v1.0.0
You can combine the --tags
option with a refspec like:
git push origin --tags :
(since --tags
means: All refs under refs/tags
are pushed, in addition to refspecs explicitly listed on the command line)
You also have this entry "Pushing branches and tags with a single "git push" invocation"
A handy tip was just posted to the Git mailing list by Zoltán Füzesi:
I use
.git/config
to solve this:
[remote "origin"]
url = ...
fetch = +refs/heads/*:refs/remotes/origin/*
push = +refs/heads/*
push = +refs/tags/*
With these lines added
git push origin
will upload all your branches and tags. If you want to upload only some of them, you can enumerate them.
Haven't tried it myself yet, but it looks like it might be useful until some other way of pushing branches and tags at the same time is added to git push.
On the other hand, I don't mind typing:
$ git push && git push --tags
Beware, as commented by Aseem Kishore
push = +refs/heads/*
will force-pushes all your branches.
This bit me just now, so FYI.
René Scheibe adds this interesting comment:
The
--follow-tags
parameter is misleading as only tags under.git/refs/tags
are considered.
Ifgit gc
is run, tags are moved from.git/refs/tags
to.git/packed-refs
. Afterwardsgit push --follow-tags ...
does not work as expected anymore.
Or as a single command:
git push -u origin master:my_test
Pushes the commits from your local master branch to a (possibly new) remote branch my_test
and sets up master
to track origin/my_test
.
The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:
<h2 style="text-align:center; font-family:tahoma">TITLE</h2>
I never suggest using Textboxes or Inputboxes to accept dates. So many things can go wrong. I cannot even suggest using the Calendar Control or the Date Picker as for that you need to register the mscal.ocx or mscomct2.ocx and that is very painful as they are not freely distributable files.
Here is what I recommend. You can use this custom made calendar to accept dates from the user
PROS:
CONS:
Ummm...Ummm... Can't think of any...
HOW TO USE IT (File missing from my dropbox. Please refer to the bottom of the post for an upgraded version of the calendar)
Userform1.frm
and Userform1.frx
from here.Userform1.frm
as shown in the image below.Importing the form
RUNNING IT
You can call it in any procedure. For example
Sub Sample()
UserForm1.Show
End Sub
SCREEN SHOTS IN ACTION
NOTE: You may also want to see Taking Calendar to new level
I think u want to change the default settings of android studio. Whenever a layout or Activity in created u want to create "RelativeLayout" by default. In that case, flow the step below
you are done
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
The CSS class that can be changed to add a image to the JQuery slider handle is called ".ui-slider-horizontal .ui-slider-handle".
The following code shows a demo:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>
<style type="text/css">
.ui-slider-horizontal .ui-state-default {background: white url(http://stackoverflow.com/content/img/so/vote-arrow-down.png) no-repeat scroll 50% 50%;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#slider").slider();
});
</script>
</head>
<body>
<div id="slider"></div>
</body>
</html>
I think registering a handle option was the old way of doing it and no longer supported in JQuery-ui 1.7.2?
There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps
This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.
javascript it a rather timtoady language )
Short version: use
pre_allocated_list = [None] * size
to preallocate a list (that is, to be able to address 'size' elements of the list instead of gradually forming the list by appending). This operation is very fast, even on big lists. Allocating new objects that will be later assigned to list elements will take much longer and will be the bottleneck in your program, performance-wise.
Long version:
I think that initialization time should be taken into account.
Since in Python everything is a reference, it doesn't matter whether you set each element into None or some string - either way it's only a reference. Though it will take longer if you want to create a new object for each element to reference.
For Python 3.2:
import time
import copy
def print_timing (func):
def wrapper (*arg):
t1 = time.time()
res = func (*arg)
t2 = time.time ()
print ("{} took {} ms".format (func.__name__, (t2 - t1) * 1000.0))
return res
return wrapper
@print_timing
def prealloc_array (size, init = None, cp = True, cpmethod = copy.deepcopy, cpargs = (), use_num = False):
result = [None] * size
if init is not None:
if cp:
for i in range (size):
result[i] = init
else:
if use_num:
for i in range (size):
result[i] = cpmethod (i)
else:
for i in range (size):
result[i] = cpmethod (cpargs)
return result
@print_timing
def prealloc_array_by_appending (size):
result = []
for i in range (size):
result.append (None)
return result
@print_timing
def prealloc_array_by_extending (size):
result = []
none_list = [None]
for i in range (size):
result.extend (none_list)
return result
def main ():
n = 1000000
x = prealloc_array_by_appending(n)
y = prealloc_array_by_extending(n)
a = prealloc_array(n, None)
b = prealloc_array(n, "content", True)
c = prealloc_array(n, "content", False, "some object {}".format, ("blah"), False)
d = prealloc_array(n, "content", False, "some object {}".format, None, True)
e = prealloc_array(n, "content", False, copy.deepcopy, "a", False)
f = prealloc_array(n, "content", False, copy.deepcopy, (), False)
g = prealloc_array(n, "content", False, copy.deepcopy, [], False)
print ("x[5] = {}".format (x[5]))
print ("y[5] = {}".format (y[5]))
print ("a[5] = {}".format (a[5]))
print ("b[5] = {}".format (b[5]))
print ("c[5] = {}".format (c[5]))
print ("d[5] = {}".format (d[5]))
print ("e[5] = {}".format (e[5]))
print ("f[5] = {}".format (f[5]))
print ("g[5] = {}".format (g[5]))
if __name__ == '__main__':
main()
Evaluation:
prealloc_array_by_appending took 118.00003051757812 ms
prealloc_array_by_extending took 102.99992561340332 ms
prealloc_array took 3.000020980834961 ms
prealloc_array took 49.00002479553223 ms
prealloc_array took 316.9999122619629 ms
prealloc_array took 473.00004959106445 ms
prealloc_array took 1677.9999732971191 ms
prealloc_array took 2729.999780654907 ms
prealloc_array took 3001.999855041504 ms
x[5] = None
y[5] = None
a[5] = None
b[5] = content
c[5] = some object blah
d[5] = some object 5
e[5] = a
f[5] = []
g[5] = ()
As you can see, just making a big list of references to the same None object takes very little time.
Prepending or extending takes longer (I didn't average anything, but after running this a few times I can tell you that extending and appending take roughly the same time).
Allocating new object for each element - that is what takes the most time. And S.Lott's answer does that - formats a new string every time. Which is not strictly required - if you want to preallocate some space, just make a list of None, then assign data to list elements at will. Either way it takes more time to generate data than to append/extend a list, whether you generate it while creating the list, or after that. But if you want a sparsely-populated list, then starting with a list of None is definitely faster.
If you need to prepend a text at the beginning of each line that has a certain string, try following. In the following example, I am adding # at the beginning of each line that has the word "rock" in it.
sed -i -e 's/^.*rock.*/#&/' file_name
In Swift 2.0,
My solution to the problem is a combination of a couple of answers on this question. The problem I faced in @Phil's answer was that I couldn't change the position of the icon, and it always appeared in right the corner. And the one answer from @anatoliy_v, I couldn't resize the icon size I want to append to the string.
To make it work for me, I first did a pod 'SMIconLabel'
and then created this function:
func drawTextWithIcon(labelName: SMIconLabel, imageName: String, labelText: String!, width: Int, height: Int) {
let newSize = CGSize(width: width, height: height)
let image = UIImage(named: imageName)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let imageResized = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
labelName.text = " \(labelText)"
labelName.icon = imageResized
labelName.iconPosition = .Left
}
This solution will not only help you place the image but will also allow you to make necessary changes to the icon size and other attributes.
Thank You.
On a Mac, you need to use this command:
STATIC_DEPS=true sudo pip install lxml
According to Documentation
git diff Shows changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, changes resulting from a merge, changes between two blob objects, or changes between two files on disk.
In git diff
- There's a significant difference between two dots ..
and 3 dots ...
in the way we compare branches or pull requests in our repository. I'll give you an easy example which demonstrates it easily.
Example: Let's assume we're checking out new branch from master and pushing some code in.
G---H---I feature (Branch)
/
A---B---C---D master (Branch)
Two dots - If we want to show the diffs between all changes happened in the current time on both sides, We would use the git diff origin/master..feature
or just git diff origin/master
,output: ( H, I
against A, B, C, D
)
Three dots - If we want to show the diffs between the last common ancestor (A
), aka the check point we started our new branch ,we use git diff origin/master...feature
,output: (H, I
against A
).
I'd rather use the 3 dots in most circumstances.
It's quite simple.
All you need to do is:
You need to set the flags after the project
command in your CMakeLists.txt.
Also, if you're calling include(${QT_USE_FILE})
or add_definitions(${QT_DEFINITIONS})
, you should include these set
commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g.
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")
One case where namespaces may not be so useful for achieving "static classes" is when using these classes to achieve composition over inheritance. Namespaces cannot be friends of classes and so cannot access private members of a class.
class Class {
public:
void foo() { Static::bar(*this); }
private:
int member{0};
friend class Static;
};
class Static {
public:
template <typename T>
static void bar(T& t) {
t.member = 1;
}
};
Promise
A Promise handles a single event when an async operation completes or fails.
Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.
Observable
An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.
SMS Push uses SMS as a carrier, WAP uses download via WAP.
Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...
Need to convert it in base64.
JS have btoa() function for it.
For example:
var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);
But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.
Update:
Need to write simple hex to base64 converter:
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
And use it:
img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');
See working example with your hex data on jsfiddle
In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.
glutSolidSphere
is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?
#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>
// your framework of choice here
class SolidSphere
{
protected:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
public:
SolidSphere(float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = x;
*n++ = y;
*n++ = z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
}
}
void draw(GLfloat x, GLfloat y, GLfloat z)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,z);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();
}
};
SolidSphere sphere(1, 12, 24);
void display()
{
int const win_width = …; // retrieve window dimensions from
int const win_height = …; // framework of choice here
float const win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#ifdef DRAW_WIREFRAME
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
sphere.draw(0, 0, -5);
swapBuffers();
}
int main(int argc, char *argv[])
{
// initialize and register your framework of choice here
return 0;
}
This error is because you selected a target rather than a project name, so please, at the left side of general in Xcode you will find your project name. Click on it and change it from target to project section.
More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):
from datetime import datetime
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
time2 = datetime.strftime('19 01 2021', '%d %m %Y')
difference = time2 - time1
difference_in_seconds = difference.total_seconds()
One way, using regular expressions:
>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup 20 99 That s ridiculous '
\w
will match alphanumeric characters and underscores
[^\w]
will match anything that's not alphanumeric or underscore
Since react-native eject is depreciated in 60.3 and I was getting diff errors trying to upgrade form 60.1 to 60.3 regenerating the android folder was not working.
I had to
rm -R node_modules
Then update react-native in package.json to 59.1 (remove package-lock.json)
Run
npm install
react-native eject
This will regenerate your android and ios folders Finally upgrade back to 60.3
react-native upgrade
react-native upgrade while back and 59.1 did not regenerate my android folder so the eject was necessary.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
final RelativeLayout relativeLayout = new RelativeLayout(this);
final TextView tv1 = new TextView(this);
tv1.setText("tv1 is here");
// Setting an ID is mandatory.
tv1.setId(View.generateViewId());
relativeLayout.addView(tv1);
final TextView tv2 = new TextView(this);
tv2.setText("tv2 is here");
// We are defining layout params for tv2 which will be added to its parent relativelayout.
// The type of the LayoutParams depends on the parent type.
RelativeLayout.LayoutParams tv2LayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
//Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams.
tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId());
//Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2.
relativeLayout.addView(tv2);
tv2.setLayoutParams(tv2LayoutParams);
//Or we can combined the above two steps in one line of code
//relativeLayout.addView(tv2, tv2LayoutParams);
this.setContentView(relativeLayout);
}
}
length of an array(type int) with sizeof: sizeof(array)/sizeof(int)
WITH UPD AS (UPDATE TEST_TABLE SET SOME_DATA = 'Joe' WHERE ID = 2
RETURNING ID),
INS AS (SELECT '2', 'Joe' WHERE NOT EXISTS (SELECT * FROM UPD))
INSERT INTO TEST_TABLE(ID, SOME_DATA) SELECT * FROM INS
Tested on Postgresql 9.3
Extended from : user3777549
Multi-value filter on one set of data(reference to title key only)
HTML
<div *ngFor='let item of items | filtermulti: [{title:["mr","ms"]},{first:["john"]}]' >
Hello {{item.first}} !
</div>
filterMultiple
args.forEach(function (filterobj) {
console.log(filterobj)
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (!filtervalue.some(x=>x==objectToFilter[filterkey]) && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
With JavaScript you can create a link 'on the fly' using something like:
var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();
This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.
Use the preprocessor #
operator:
#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
String s = "1";
try {
long l = Long.parseLong(s);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
I'm assuming as a developer, you have some degree of administrative control over your machine. If so, from the command line, run msconfig.exe. You can remove many processes from even starting, thereby eliminating the need to kill them with the above mentioned solutions.
You could achieve this with a simple for
loop:
var min = 12,
max = 100,
select = document.getElementById('selectElementId');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.
Edited in response to comment from OP:
[How] do [I] apply this to more than one element?
function populateSelect(target, min, max){
if (!target){
return false;
}
else {
var min = min || 0,
max = max || min + 100;
select = document.getElementById(target);
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);
// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');
// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);
And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement
in order to chain the populate()
function, as a method, to the DOM node:
HTMLSelectElement.prototype.populate = function (opts) {
var settings = {};
settings.min = 0;
settings.max = settings.min + 100;
for (var userOpt in opts) {
if (opts.hasOwnProperty(userOpt)) {
settings[userOpt] = opts[userOpt];
}
}
for (var i = settings.min; i <= settings.max; i++) {
this.appendChild(new Option(i, i));
}
};
document.getElementById('selectElementId').populate({
'min': 12,
'max': 40
});
References:
require('url').parse('/status?name=ryan', {parseQueryString: true}).query
returns
{ name: 'ryan' }
Ran into the same issue with Web API and .Net Core Web API. Worked fine in VS 2017 while debugging, but returned 404 when published to IIS 7.5. Solution for me was to change the way I created the site. Instead of publishing to the root of a Web Site (created by right clicking Sites...Add Web Site), I had to create an Application (created by right clicking a Web Site...Add Application) and publish to that folder. Note that for the Core version, I had to change the Application Pool .NET Framework Version setting to "No Managed Code".
To get the actual full path file names of the desired files using the find command, use it with the pwd command:
find $(pwd) -name \*.txt -print
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV
directive, but the subsequent instruction RUN export $PATH
There's no need to export the environment variables, once you have declared them via ENV
in your Dockerfile.
As soon as the RUN export ...
lines were removed, my image was built successfully
If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon
Xcode 8.X , Swift 3.X
Easy Use;
let params:NSMutableDictionary? = [
"IdQuiz" : 102,
"IdUser" : "iosclient",
"User" : "iosclient",
"List": [
[
"IdQuestion" : 5,
"IdProposition": 2,
"Time" : 32
],
[
"IdQuestion" : 4,
"IdProposition": 3,
"Time" : 9
]
]
];
let ulr = NSURL(string:"http://myserver.com" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.
Just add:
export {};
at the top of your code.
Credit to EUGENE MURAVITSKY
$: rails g migration RenameHashedPasswordColumn
invoke active_record
create db/migrate/20160323054656_rename_hashed_password_column.rb
Open that migration file and modify that file as below(Do enter your original table_name
)
class RenameHashedPasswordColumn < ActiveRecord::Migration
def change
rename_column :table_name, :hased_password, :hashed_password
end
end
If you are using NodeJs for your server side, just add these to your route and you will be Ok
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Your route will then look somehow like this
router.post('/odin', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.json({Name: req.body.name, Phone: req.body.phone});
});
Client side for Ajax call
var sendingData = {
name: "Odinfono Emmanuel",
phone: "1234567890"
}
<script>
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1:3000/odin',
method: 'POST',
type: 'json',
data: sendingData,
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>
You should have something like this in your browser console as response
{ name: "Odinfono Emmanuel", phone: "1234567890"}
Enjoy coding....
>>> points = {'a': (3, 4), 'c': (5, 5), 'b': (1, 2), 'd': (3, 3)}
>>> dict(filter(lambda x: (x[1][0], x[1][1]) < (5, 5), points.items()))
{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}
Set data to this:
data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.
<form style="display: none" action="postUrl" method="post">_x000D_
<button type="submit" id="button_to_link"> </button>_x000D_
</form>_x000D_
<label style="text-decoration: underline" for="button_to_link"> link that posts </label>
_x000D_
Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);
"range" will now be the occupied cell range
Put it in as a background on the list element:
<ul id="nav">
<li><a><img /></a></li>
...
<li><a><img /></a></li>
</ul>
#nav li{background: url(/images/separator.gif) no-repeat left; padding-left:20px;}
/* left padding creates a gap between links */
Next, I recommend a different markup for accessibility:
Rather than embedding the images inline, put text in as text, surround each with a span, apply the image as a background the the , and then hide the text with display:none -- this gives much more styling flexibilty, and allows you to use tiling with a 1px wide bg image, saves bandwidth, and you can embed it in a CSS sprite, which saves HTTP calls:
HTML:
<ul id="nav">
<li><a><span>link text</span></a></li>
...
<li><a><span>link text</span></a></li>
</ul
CSS:
#nav li{background: url(/images/separator.gif) no-repeat left; padding-left:20px;}
#nav a{background: url(/images/nav-bg.gif) repeat-x;}
#nav a span{display:none;}
UPDATE OK, I see others got similar answer in before me -- and I note that John also includes a means for keeping the separator from appearing before the first element, by using the li + li selector -- which means any li coming after another li.
Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:
Just adding this in the hope to be of help to someone.
Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.
The process to do so is as follows:
Reference to Office Support Page where this solution was first posted. https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US
As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread
, as now the sleep functions are public:
Static Public Members
QThread * currentThread()
Qt::HANDLE currentThreadId()
int idealThreadCount()
void msleep(unsigned long msecs)
void sleep(unsigned long secs)
void usleep(unsigned long usecs)
void yieldCurrentThread()
cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
Create file .dockerignore
in your docker build context directory (so in this case, most likely a directory that is a parent to node_modules) with one line in it:
**/node_modules
although you probably just want:
node_modules
Info about dockerignore: https://docs.docker.com/engine/reference/builder/#dockerignore-file
Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.
Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/>
simply factories a java.util.Properties instance that you can inject.
In Spring 3.1 (not 3.0...) you can do something like this:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:
@Value("${ds.user}") private String user;
If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Note that the PPC is defined using a static
bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor
- it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.
You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().
Syntax will be like this:
select c.*
from comments c
join (
values
(1,1),
(3,2),
(2,3),
(4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering
I used this code:
This is worked for me successfully.
"C:\Program Files\Java\jdk1.6.0_26\bin\keytool.exe" -exportcert -alias sociallisting -
keystore "D:\keystore\SocialListing" | "C:\cygwin\bin\openssl.exe" sha1 -binary |
"C:\cygwin\bin\openssl.exe" base64
From command prompt as admin run:
netsh interface ip delete destinationcache
Works on Win7.
By using the List
property.
ListBox1.AddItem "foo"
ListBox1.List(ListBox1.ListCount - 1, 1) = "bar"
I know I am late to the party, but hopefully this will be useful for someone else. If you are using backbone v0.9.9+, you could use, listenTo
and stopListening
initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
}
stopListening
is called automatically by remove
. You can read more here and here
Sounds like you're looking for the time_ago_in_words
method (or distance_of_time_in_words
), from ActiveSupport. Call it like this:
<%= time_ago_in_words(timestamp) %>
<script src="JavascriptLibrary/jquery-1.4.2.js"></script>
<script>
var $i = jQuery.noConflict();
// alert($i.fn.jquery);
</script>
<script src="JavascriptLibrary/jquery-1.8.3.js"></script>
<script>
var $j = jQuery.noConflict();
//alert($j.fn.jquery);
</script>
<script src="JavascriptLibrary/jquery.colorbox.js"></script>
<script src="Js/jquery-1.12.3.js"></script>
<script>
var $NJS = jQuery.noConflict();
</script>
You can do it like this:
<script>
$i.alert('hi i am jquery-1.4.2.js alert function');
$j.alert('hi i am jquery-1.8.3.js alert function');
</script>
From the first search result on google:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
JavaScriptSerializer Class
Provides serialization and deserialization functionality for AJAX-enabled applications.
Inheritance Hierarchy
System.Object
System.Web.Script.Serialization.JavaScriptSerializer
Namespace: System.Web.Script.Serialization
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)
So, include System.Web.Extensions.dll
as a reference.
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
It's weird that the Swing toolkit doesn't include this functionality, but here's the best answer to your question:
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit to 3 characters
e.consume();
}
});
I use this in a fun guessing game example in my Udemy.com course "Learn Java Like a Kid". Cheers - Bryson
I found a workaround a week ago. You can use direct commands with "ExecuteCommand
":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand
statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.
Have you tried calling TcpClient.Dispose() explicitly?
And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?
The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.
Well, in my case it was definitely the USER Objects that were out of control. I looked in the Windows Task Manager and sure enough, the USER Objects count was at 10'000 exactly.
I am dynamically embedding property and list sheets in Tab Pages by setting the Parent property of the property or list sheet's container panel to that of the Tab Page. I am conditionally recycling or re-creating the property and list sheet forms depending on the type of collection being listed or class type of the object being inspected.
NB: In Delphi, all controls had an Owner and a Parent property. Even if one changed the Parent property of a control, it would still be disposed by its owner when the owning control got destroyed.
In C# it seems that if a control e.g. a Panel is programmatically reassigned from, say, a Form to a Tab Page by changing the Panel.Parent property, calling Dispose() on the Form won't dispose the Panel, neither will calling Controls.Clear() on the Tab Page. Even a direct call Panel.Dispose() won't actually dispose it, unless its Parent is manually set to null beforehand.
<Window x:Class="HTA.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
Width="1024" Height="768"
WindowState="Maximized" WindowStyle="None">
Window state to Maximized and window style to None
Essentially the same as Gringo Suave's answer, but with a generator:
from datetime import datetime, timedelta
def datetime_range(start=None, end=None):
span = end - start
for i in xrange(span.days + 1):
yield start + timedelta(days=i)
Then you can use it as follows:
In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out:
[datetime.datetime(2014, 1, 1, 0, 0),
datetime.datetime(2014, 1, 2, 0, 0),
datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 1, 4, 0, 0),
datetime.datetime(2014, 1, 5, 0, 0)]
Or like this:
In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
...: print date
...:
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
When I tried to select the development provisioning profile in Code Signing Identity is would say "profile doesn't match any valid certificate". So when I followed the two step process below it worked:
1) Under "Code Signing Identity" for Development change to "Don't Code Sign".
2) Then Under "Code Signing Identity" for Development you will be able to select your provisioning profile for Development.
Drove me nuts, but stumbled upon the solution.
Another option, for incrementing the versionCode
and the versionName
, is using a timestamp.
defaultConfig {
versionName "${getVersionNameTimestamp()}"
versionCode getVersionCodeTimestamp()
}
def getVersionNameTimestamp() {
return new Date().format('yy.MM.ddHHmm')
}
def getVersionCodeTimestamp() {
def date = new Date()
def formattedDate = date.format('yyMMddHHmm')
def code = formattedDate.toInteger()
println sprintf("VersionCode: %d", code)
return code
}
Starting on January,1 2022 formattedDate = date.format('yyMMddHHmm') exceeds the capacity of Integers
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.
If you are using Eclipse: How to add dependent libraries in Eclipse
If you are using command line include the path to the driver jar using the -cp parameter of java.
java -cp C:\lib\* Main
Try adding $(document).ready(function(){
to the beginning of your script, and then });
. Also, does the div
have the id in it properly, i.e., as an id, not a class, etc.?
Android Device Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To start the standalone Device Monitor application in Android Studio 3.1 and lower you can run android-sdk/tools/monitor.bat
I struggled for a while about this. Stupid rule for __init__
. It is two "_" together to be "__"
I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.
For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:
x86
Open C:\Windows\SysWOW64\cmd.exe Run the command: powershell Set-ExecutionPolicy RemoteSigned
x64
Open C:\Windows\system32\cmd.exe Run the command powershell Set-ExecutionPolicy RemoteSigned
You can check mode using
In CMD: echo %PROCESSOR_ARCHITECTURE% In Powershell: [Environment]::Is64BitProcess
I hope this help you.
Another approach in spark 2.1.0
is to use --conf spark.driver.userClassPathFirst=true
during spark-submit which changes the priority of dependency load, and thus the behavior of the spark-job, by giving priority to the jars the user is adding to the class-path with the --jars
option.
org.apache.jasper.JasperException: Unable to compile class for JSP:
The method has been renamed to findById(…)
returning an Optional
so that you have to handle absence yourself:
Optional<Foo> result = repository.findById(…);
result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before
One possible way to count lines of code in Eclipse:
using the Search / File... menu, select File Search tab, specify \n[\s]* for Containing text (this will not count empty lines), and tick Regular expression.
Hat tip: www.monblocnotes.com/node/2030
You could try using a $_SESSION
variable to make sure that a request was made from a browser. Otherwise, you could have the request sent through a database or file [server-side].
I had some pain with this, using a dynamically generated list items - WordPress Stack.
Added this and it worked:
$(document).ready(function () {
$(".current-menu-item").addClass("active");
});
Will do it on the fly.
You're looking for:
.is(':visible')
Although you should probably change your selector to use jQuery considering you're using it in other places anyway:
if($('#testElement').is(':visible')) {
// Code
}
It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible')
on the child will return false
(which makes sense).
:visible
has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible
):
Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!
Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.
Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle()
:
function toggleTestElement() {
$('#testElement').fadeToggle('fast');
}
log x to base b = y
is the inverse of b^y = x
If you have an M-ary tree of depth d and size n, then:
traversing the whole tree ~ O(M^d) = O(n)
Walking a single path in the tree ~ O(d) = O(log n to base M)
For .net core 2.1 console application, the following approaches worked for me:
1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):
dotnet appName.dll
2 - from Visual Studio
R.C solution and click publish
'Target location' -> 'configure' ->
'Deployment Mode' = 'Self-Contained'
'Target Runtime' = 'win-x64 or win-x86 depending on the OS'
References:
For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:
I had the same problem, however using Codeblocks. Because of this problem i quited programming because everytime i just wanted to throw my computer out of the window.
I want to thank user963228 whos answer is really a solution to that. You have to put Application Experience on Manual startup(you can do it by searching services in windows 7 start menu, and then find Application Experience and click properties).
This problem happens when people want to tweak theyr windows 7 machine, and they decide to disable some pointless services, so they google some tweaking guide and most of those guides say that Application Experience is safe to disable.
I think this problem should be linked to windows 7 problem not VS problem and it should be more visible - it took me long time to find this solution.
Thanks again!
import java.util.Scanner; import javax.swing.JOptionPane;
public class javaCalculator {
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
Strings, by C
definition, are terminated by '\0'
. You have no "C strings"
in your program.
Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.
To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).
You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C
sense of the word.
If you run your program with input redirection, the EOF
is the actual end of file, not a make belief one
./a.out < source.c
Oracle
WHERE ROWNUM <= 10 and whatever_else ;
ROWNUM
is a magic variable which contains each row's sequence number 1..n.
https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial
Please follow this link.
import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
header=1, sep='\t', quotechar='"')
#traffic_station_df['Address'] = 'address'
#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)
You can Use Playlist
Right click on the test method -> Add to playlist -> New playlist
the execution order will be as you add them to the playlist but if you want to change it you have the file
Use asymptote instead!
This is what it can look like:
https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.html
This is the code: https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.asy
Asymptote can also read in data files.
And the full gallery: https://asymptote.sourceforge.io/gallery/index.html
To use asymptote from within Python:
https://ctan.org/tex-archive/graphics/asymptote/base/asymptote.py
include.prepload.js file will have a line something like below. probably as the last line.
//# sourceMappingURL=include.prepload.js.map
Delete it and the error will go away.
That looks like you tried to add the libraries servlet.jar
or servlet-api.jar
into your project /lib/
folder, but Tomcat already should provide you with those libraries. Remove them from your project and classpath. Search for that anywhere in your project or classpath and remove it.
var string = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked:
if(arr[i] === ' '){
console.log(i);
}
I know regex can do the trick too!
You're setting the Content-Type
to be multipart/form-data
, but then using JSON.stringify
on the body data, which returns application/json
. You have a content type mismatch.
You will need to encode your data as multipart/form-data
instead of json
. Usually multipart/form-data
is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded
(which is the default for HTML forms).
The specification for multipart/form-data
can be found in RFC 1867.
For a guide on how to submit that kind of data via javascript, see here.
The basic idea is to use the FormData object (not supported in IE < 10):
async function sendData(url, data) {
const formData = new FormData();
for(const name in data) {
formData.append(name, data[name]);
}
const response = await fetch(url, {
method: 'POST',
body: formData
});
// ...
}
Per this article make sure not to set the Content-Type
header. The browser will set it for you, including the boundary
parameter.
Let me provide complete code for execution protected methods via reflection. It supports any types of params including generics, autoboxed params and null values
@SuppressWarnings("unchecked")
public static <T> T executeSuperMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass().getSuperclass(), instance, methodName, params);
}
public static <T> T executeMethod(Object instance, String methodName, Object... params) throws Exception {
return executeMethod(instance.getClass(), instance, methodName, params);
}
@SuppressWarnings("unchecked")
public static <T> T executeMethod(Class clazz, Object instance, String methodName, Object... params) throws Exception {
Method[] allMethods = clazz.getDeclaredMethods();
if (allMethods != null && allMethods.length > 0) {
Class[] paramClasses = Arrays.stream(params).map(p -> p != null ? p.getClass() : null).toArray(Class[]::new);
for (Method method : allMethods) {
String currentMethodName = method.getName();
if (!currentMethodName.equals(methodName)) {
continue;
}
Type[] pTypes = method.getParameterTypes();
if (pTypes.length == paramClasses.length) {
boolean goodMethod = true;
int i = 0;
for (Type pType : pTypes) {
if (!ClassUtils.isAssignable(paramClasses[i++], (Class<?>) pType)) {
goodMethod = false;
break;
}
}
if (goodMethod) {
method.setAccessible(true);
return (T) method.invoke(instance, params);
}
}
}
throw new MethodNotFoundException("There are no methods found with name " + methodName + " and params " +
Arrays.toString(paramClasses));
}
throw new MethodNotFoundException("There are no methods found with name " + methodName);
}
Method uses apache ClassUtils for checking compatibility of autoboxed params
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during the
contentWindow
property of theiframe
object. Most other browsers uses thecontentDocument
property and that is the reason why we proof this property first in this OR condition. If it is not set trycontentWindow.document
.
Select elements in iframe
Then you can usually use getElementById()
or even querySelectorAll()
to select the DOM-Element from the iframeDocument
:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window
element from iframe
to call some global functions, variables or whole libraries (e.g. jQuery
):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
have you tried using <pre>
tag.
I like using the following to prevent things being outside my div
elements. It helps with CSS rollovers too.
.marquee{
overflow:hidden;
}
this will hide anything that moves/is outside of the div which will prevent the browser expanding and causing a scroll bar to appear.
You can do it by using name attibute, class, id or just universal checkbox; If you want to count only checked number of checkbox.
By the class name :
var countChk = $('checkbox.myclassboxName:checked').length;
By name attribute :
var countByName= $('checkbox[name=myAllcheckBoxName]:checked').length;
$('checkbox.className').blur(function() {
//count only checked checkbox
$('checkbox[name=myAllcheckBoxName]:checked').length;
});
Simply put, don't use DateTime.MinVaue
as a default value.
There are a couple of different MinValues
out there, depending which environment you are in.
I once had a project, where I was implementing a Windows CE project, I was using the Framework's DateTime.MinValue
(year 0001), the database MinValue
(1753) and a UI control DateTimePicker
(i think it was 1970). So there were at least 3 different MinValues that were leading to strange behavior and unexpected results. (And I believe that there was even a fourth (!) version, I just do not recall where it came from.).
Use a nullable database field and change your value into a Nullable<DateTime>
instead. Where there is no valid value in your code, there should not be a value in the database as well. :-)
Found this to work well cross browser and mobile back_button_override.js .
(Added a timer for safari 5.0)
// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("back", null, null);
window.onpopstate = function () {
history.pushState('back', null, null);
if(count == 1){window.location = 'your url';}
};
}
}
setTimeout(function(){count = 1;},200);
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
Am I getting it because the act of calling it via e.extractAll("th") also passes in self as an argument?
Yes, that's precisely it. If you like, the first parameter is the object name, e
that you are calling it with.
And if so, by removing the self in the call, would I be making it some kind of class method that can be called like Extractor.extractAll("th")?
Not quite. A classmethod needs the @classmethod
decorator, and that accepts the class as the first paramater (usually referenced as cls
). The only sort of method that is given no automatic parameter at all is known as a staticmethod, and that again needs a decorator (unsurprisingly, it's @staticmethod
). A classmethod is used when it's an operation that needs to refer to the class itself: perhaps instantiating objects of the class; a staticmethod is used when the code belongs in the class logically, but requires no access to class or instance.
But yes, both staticmethods and classmethods can be called by referencing the classname as you describe: Extractor.extractAll("th")
.
DateTime start1 = DateTime.Parse(txtDate.Text);
SELECT *
FROM dbo.March2010 A
WHERE A.Date >= start1;
First convert TexBox into the Datetime then....use that variable into the Query
If you want to normalize n dimensional feature vectors stored in a 3D tensor, you could also use PyTorch:
import numpy as np
from torch import FloatTensor
from torch.nn.functional import normalize
vecs = np.random.rand(3, 16, 16, 16)
norm_vecs = normalize(FloatTensor(vecs), dim=0, eps=1e-16).numpy()
If you don't want to add/edit .vimrc, you can start with
vi "+set number" /path/to/file
Use the command dir
to list all the directories and files in a directory; ls
is a unix command.
Remove last occurrence or all occurrences, or first occurrence?
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Remove this line to remove all occurrences
}
}
or
var array = [2, 5, 9, 5];
// Remove first occurrence
for (var i = 0; array.length; i++) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Do not remove this line
}
}
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;
/**
*
* @author shivshankar pal
*
* this code is working properly. doing proper encription and decription
note:- it will work only with jdk8
*
*
*/
public class TDes {
private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00 };
public static String encode(String args) {
System.out.println("plain data==> " + args);
byte[] encoding;
try {
encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));
System.out.println("Base64.encodeBase64==>" + new String(encoding));
byte[] str5 = des3EncodeCBC(key, keyiv, encoding);
System.out.println("des3EncodeCBC==> " + new String(str5));
byte[] encoding1 = Base64.getEncoder().encode(str5);
System.out.println("Base64.encodeBase64==> " + new String(encoding1));
return new String(encoding1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decode(String args) {
try {
System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));
byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));
byte[] str6 = des3DecodeCBC(key, keyiv, decode);
System.out.println("des3DecodeCBC==>" + new String(str6));
String data=new String(str6);
byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
System.out.println("plaintext==> " + new String(decode1));
return new String(decode1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "u mistaken in try block";
}
private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
}
Try it:
<input type="button" value="Dont show this again! " onClick="fbLikeDump();WriteCookie();" />
Or also
<script>
function clickEvent(){
fbLikeDump();
WriteCookie();
}
</script>
<input type="button" value="Dont show this again! " onClick="clickEvent();" />
Usefull script which you can delete all data in all tables of a database , replace tt with you databse name :
declare @tablename nvarchar(100)
declare c1 cursor for
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG='tt' AND TABLE_TYPE='BASE TABLE'
open c1
fetch next from c1 into @tablename
while @@FETCH_STATUS = 0
begin
print @t1
exec('alter table ' + @tablename + ' nocheck constraint all')
exec('delete from ' + @tablename)
exec ('alter table ' + @tablename + ' check constraint all')
fetch next from c1 into @tablename
end
close c1
DEALLOCATE c1
On Django 1.9, I tried django-admin runserver
and got the same error, but when I used python manage.py runserver
I got the intended result. This may solve this error for a lot of people!
You should use the Time.IsZero() function instead:
func (Time) IsZero
func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
cout<<"File can not open.\n";
return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
dataFile >> name;
test.push_back(name);
}
dataFile.close();
}
try this
background-image: url("/yourimagefolder/yourimage.jpg");
I had the same problem when I used background-image: url("yourimagefolder/yourimage.jpg");
Notice the slash that made the difference. The level of the folder was the reason why I could not load the image. I guess you also encountered the same issue
4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.
Before starting jvm just check how much RAM is available and then set memory accordingly.
The arrow is a border.
You need to change for each arrow the color corresponding.
.tooltip.top .tooltip-arrow {
border-top-color: @color;
}
.tooltip.top-left .tooltip-arrow {
border-top-color: @color;
}
.tooltip.top-right .tooltip-arrow {
border-top-color:@color;
}
.tooltip.right .tooltip-arrow {
border-right-color: @color;
}
.tooltip.left .tooltip-arrow {
border-left-color: @color;
}
.tooltip.bottom .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip.bottom-left .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip.bottom-right .tooltip-arrow {
border-bottom-color: @color;
}
.tooltip > .tooltip-inner {
background-color: @color;
font-size: @font-size-small;
}
However If i want to add a class to change the color (like in the fiddle with '.class + .tooltip...' it doesn't work (bootstrap 3).
If someone know how to handle that ?!?
Yes, it's
use Illuminate\Support\Facades\Redirect;
return Redirect::to('http://heera.it');
Update: Redirect::away('url')
(For external link, Laravel Version 4.19):
public function away($path, $status = 302, $headers = array())
{
return $this->createRedirect($path, $status, $headers);
}
You could take the average buffer gets per execution during a period of activity of the instance:
SELECT username,
buffer_gets,
disk_reads,
executions,
buffer_get_per_exec,
parse_calls,
sorts,
rows_processed,
hit_ratio,
module,
sql_text
-- elapsed_time, cpu_time, user_io_wait_time, ,
FROM (SELECT sql_text,
b.username,
a.disk_reads,
a.buffer_gets,
trunc(a.buffer_gets / a.executions) buffer_get_per_exec,
a.parse_calls,
a.sorts,
a.executions,
a.rows_processed,
100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,
module
-- cpu_time, elapsed_time, user_io_wait_time
FROM v$sqlarea a, dba_users b
WHERE a.parsing_user_id = b.user_id
AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')
AND a.buffer_gets > 10000
ORDER BY buffer_get_per_exec DESC)
WHERE ROWNUM <= 20
Use .val()
instead of .innerHTML
for getting value of selected option
Use .text()
for getting text of selected option
Thanks for correcting :)
It's an old post but I none of this solution worked for me so I'm posting my solution if anyone find this helpful.
I just had the same problem.
In my case the control I needed to disable was a user control with child dropdowns which I could disable in IE but not in chrome.
my solution was to disable each child object, not just the usercontrol, with that code:
$('#controlName').find('*').each(function () { $(this).attr("disabled", true); })
It's working for me in chrome now.
For me the fix was:
git remote set-url origin https://some_url/some_repo
Then:
git push
One way is to use the code Gamlet posted in his answer:
Save it as curl.php
Then in your file:
require 'curl.php';
$photo="https://graph.facebook.com/me/picture?access_token=" . $session['access_token'];
$sample = new sfFacebookPhoto;
$thephotoURL = $sample->getRealUrl($photo);
echo $thephotoURL;
I thought I would post this, because it took me a bit of time to figure out the particulars... Even though profile pictures are public, you still need to have an access token in there to get it when you curl it.
I also fixed this issue by running
aspnet_regiis -i
using the visual studio command line tools as an administrator
<div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>
you can use the ng-if directive as above.
You can list breakpoints with:
info break
This will list all breakpoints. Then a breakpoint can be deleted by its corresponding number:
del 3
For example:
(gdb) info b
Num Type Disp Enb Address What
3 breakpoint keep y 0x004018c3 in timeCorrect at my3.c:215
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
(gdb) del 3
(gdb) info b
Num Type Disp Enb Address What
4 breakpoint keep y 0x004295b0 in avi_write_packet atlibavformat/avienc.c:513
Solution (not the best, but still working for some cases) for non-dinamic text with fixed width.Usefull for situations when there are a little space to "stretch" text to the end of the penultimate line. Make some symbols in the end of the paragraph (experiment with their length) and hide it; apply to the paragraph absolute position or just correct free space with padding/marging.
Good compabitity/crossbrowser way for center-justifying text.
Example (paragraph before):
.paragraph {_x000D_
width:455px;_x000D_
text-align:justify;_x000D_
}_x000D_
_x000D_
.center{_x000D_
display:block;_x000D_
text-align:center;_x000D_
margin-top:-17px;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna,<br><center>vel scelerisque nisl consectetur et.</center></div>
_x000D_
And after the fix:
.paragraph {_x000D_
width:455px;_x000D_
text-align:justify;_x000D_
position:relative;_x000D_
}_x000D_
.center{_x000D_
display:block;_x000D_
text-align:center;_x000D_
margin-top:-17px;_x000D_
}_x000D_
.paragraph b{_x000D_
opacity:0;_x000D_
_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0);_x000D_
-moz-opacity: 0;_x000D_
-khtml-opacity: 0;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, <b>__</b><br><div class="center">vel scelerisque nisl consectetur et.</div></div>
_x000D_
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
You need to use linecolor instead of lc, like:
set style line 1 lt 1 lw 3 pt 3 linecolor rgb "red"
"help set style line" gives you more info.
Add this to the your code:
import pyspark
def spark_shape(self):
return (self.count(), len(self.columns))
pyspark.sql.dataframe.DataFrame.shape = spark_shape
Then you can do
>>> df.shape()
(10000, 10)
But just remind you that .count()
can be very slow for very large table that has not been persisted.
It's my solution to save local data to txt file.
function export2txt() {_x000D_
const originalData = {_x000D_
members: [{_x000D_
name: "cliff",_x000D_
age: "34"_x000D_
},_x000D_
{_x000D_
name: "ted",_x000D_
age: "42"_x000D_
},_x000D_
{_x000D_
name: "bob",_x000D_
age: "12"_x000D_
}_x000D_
]_x000D_
};_x000D_
_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {_x000D_
type: "text/plain"_x000D_
}));_x000D_
a.setAttribute("download", "data.txt");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2txt()">Export data to local txt file</button>
_x000D_
As of Java 7:
System.lineSeparator()
Java API : System.lineSeparator
Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
As an aside, under Windows, ProcessExplorer is fantastic for observing the existing TCP/IP connections for each process.
Linked list is guaranteed to act in sequential order.
From the documentation
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
iterator() Returns an iterator over the elements in this list in proper sequence.
I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:
#
# script to register Python 2.0 or later for use with
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html
import sys
from _winreg import *
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
installpath, installpath, installpath
)
def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print "*** Unable to register!"
return
print "--- Python", version, "is now registered!"
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register!"
print "*** You probably have another Python installation!"
if __name__ == "__main__":
RegisterPy()
Create a file named .gitignore
in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):
dir_to_ignore/
More information is here.
A slightly different (simpler) version of the accepted answer:
Have a component registered on the parent instance:
export default {
components: { 'my-component': myComponent }
}
Render the component in template/html with a reference:
<my-component ref="foo"></my-component>
Access the component method:
<script>
this.$refs.foo.doSomething();
</script>
If all you need is toggle comments I'd rather go with commentary.vim by tpope.
Pathogen:
cd ~/.vim/bundle
git clone git://github.com/tpope/vim-commentary.git
vim-plug:
Plug 'tpope/vim-commentary'
Vundle:
Plugin 'tpope/vim-commentary'
Add this to your .vimrc file: noremap <leader>/ :Commentary<cr>
You can now toggle comments by pressing Leader
+/
, just like Sublime and Atom.
BhupeshC and murat , this is what I was looking for. However @SQL varchar(4000) wasn't big enough. So, small change
DECLARE @cmd varchar(4000)
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
select 'ALTER TABLE ['+s.name+'].['+t.name+'] DROP CONSTRAINT [' + RTRIM(f.name) +'];' FROM sys.Tables t INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id INNER JOIN sys.schemas s ON s.schema_id = f.schema_id
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @cmd
WHILE @@FETCH_STATUS = 0
BEGIN
-- EXEC (@cmd)
PRINT @cmd
FETCH NEXT FROM MY_CURSOR INTO @cmd
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
GO
What you'll see sometimes is the following:
class Abstract1( object ):
"""Some description that tells you it's abstract,
often listing the methods you're expected to supply."""
def aMethod( self ):
raise NotImplementedError( "Should have implemented this" )
Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.
And the difference between abstract and interface is a hairsplitting thing when you have duck typing.
Java uses interfaces because it doesn't have multiple inheritance.
Because Python has multiple inheritance, you may also see something like this
class SomeAbstraction( object ):
pass # lots of stuff - but missing something
class Mixin1( object ):
def something( self ):
pass # one implementation
class Mixin2( object ):
def something( self ):
pass # another
class Concrete1( SomeAbstraction, Mixin1 ):
pass
class Concrete2( SomeAbstraction, Mixin2 ):
pass
This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.
String LastId = "id";
database.execSQL("ALTER TABLE " + PhraseContract.TABLE_NAME + " RENAME TO " + PhraseContract.TABLE_NAME + "old");
database.execSQL("CREATE TABLE " + PhraseContract.TABLE_NAME
+"("
+ PhraseContract.COLUMN_ID + " INTEGER PRIMARY KEY,"
+ PhraseContract.COLUMN_PHRASE + " text ,"
+ PhraseContract.COLUMN_ORDER + " text ,"
+ PhraseContract.COLUMN_FROM_A_LANG + " text"
+")"
);
database.execSQL("INSERT INTO " +
PhraseContract.TABLE_NAME + "("+ PhraseContract.COLUMN_ID +" , "+ PhraseContract.COLUMN_PHRASE + " , "+ PhraseContract.COLUMN_ORDER +" , "+ PhraseContract.COLUMN_FROM_A_LANG +")" +
" SELECT " + LastId +" , "+ PhraseContract.COLUMN_PHRASE + " , "+ PhraseContract.COLUMN_ORDER +" , "+ PhraseContract.COLUMN_FROM_A_LANG +
" FROM " + PhraseContract.TABLE_NAME + "old");
database.execSQL("DROP TABLE " + PhraseContract.TABLE_NAME + "old");
pack_forget
and grid_forget
will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy
method.
To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.
Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.