I encountered the same issue when trying to use Cordova. Turns out I already had brew, try which brew
, but it was outdated. So, I had to update it first:
brew update
brew install ant
import java.io.*;
Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
Consider the following if you run into any further problems, but I'm guessing that the above will work for you:
You can use the title attribute, e.g. if you want to have a Tooltip over a text, just make:
<span title="This is a Tooltip">This is a text</span>
_x000D_
C++ Implementation (not by me) here. Note that when your bytes are over 65535, you need to shift with a long value as shown here.
Use rename
(aka prename
) which is a Perl script which may be on your system already. Do it in two steps:
find -name "* *" -type d | rename 's/ /_/g' # do the directories first
find -name "* *" -type f | rename 's/ /_/g'
Based on Jürgen's answer and able to handle multiple layers of files and directories in a single bound using the "Revision 1.5 1998/12/18 16:16:31 rmb1" version of /usr/bin/rename
(a Perl script):
find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;
Use FileInfo.Exists
Property:
DirectoryInfo di = new DirectoryInfo(ProcessingDirectory);
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
log.Info("no files present")
}
foreach (var fi in TXTFiles)
log.Info(fi.Exists);
or File.Exists
Method:
string curFile = @"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
I had a similar problem.
I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.
About half-way down is an answer by "Robert P" with some extension functions I found useful.
don't they both keep a value for another request?
Yes they do, but when the first one is void
, the second one returns and object
:
public void Keep(string key)
{
_retainedKeys.Add(key); // just adds the key to the collection for retention
}
public object Peek(string key)
{
object value;
_data.TryGetValue(key, out value);
return value; // returns an object without marking it for deletion
}
I ended up just downloading my pdf using below code
function downloadPdfDocument(fileName){
var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";
req.onload = function (event) {
var blob = req.response;
//for IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
};
req.send();
}
In order to get the device token use following code but you can get the device token only using physical device. If you have mandatory to send the device token then while using simulator you can put the below condition.
if(!(TARGET_IPHONE_SIMULATOR))
{
[infoDict setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"DeviceToken"] forKey:@"device_id"];
}
else
{
[infoDict setValue:@"e79c2b66222a956ce04625b22e3cad3a63e91f34b1a21213a458fadb2b459385" forKey:@"device_id"];
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(@"My token is: %@", deviceToken);
NSString * deviceTokenString = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"the generated device token string is : %@",deviceTokenString);
[[NSUserDefaults standardUserDefaults] setObject:deviceTokenString forKey:@"DeviceToken"];
}
beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:
$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
NO
$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
NO
$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
YES
I solved such problem with such shell/awk function:
# get version of GNU tool
toolversion() {
local prog="$1" operator="$2" value="$3" version
version=$($prog --version | awk '{print $NF; exit}')
awk -vv1="$version" -vv2="$value" 'BEGIN {
split(v1, a, /\./); split(v2, b, /\./);
if (a[1] == b[1]) {
exit (a[2] '$operator' b[2]) ? 0 : 1
}
else {
exit (a[1] '$operator' b[1]) ? 0 : 1
}
}'
}
if toolversion grep '>=' 2.6; then
# do something awesome
fi
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
I published the vue-unique-id Vue plugin for this on npm.
None of the other solutions address the requirement of having more than one form element in your component. Here's my take on a plugin that builds on previously given answers:
Vue.use((Vue) => {
// Assign a unique id to each component
let uuid = 0;
Vue.mixin({
beforeCreate: function() {
this.uuid = uuid.toString();
uuid += 1;
},
});
// Generate a component-scoped id
Vue.prototype.$id = function(id) {
return "uid-" + this.uuid + "-" + id;
};
});
This doesn't rely on the internal _uid
property which is reserved for internal use.
Use it like this in your component:
<label :for="$id('field1')">Field 1</label>
<input :id="$id('field1')" type="text" />
<label :for="$id('field2')">Field 2</label>
<input :id="$id('field2')" type="text" />
To produce something like this:
<label for="uid-42-field1">Field 1</label>
<input id="uid-42-field1" type="text" />
<label for="uid-42-field2">Field 2</label>
<input id="uid-42-field2" type="text" />
You can create an autofield. Here is the documentation for the same
Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.
Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.
There's one more difference. class can be used to define type properties of computed type only. If you need a stored type property use static instead.
Class :- reference type
struct :- value type
The ally.js accessibility library provides an unofficial, test-based list here:
https://allyjs.io/data-tables/focusable.html
(NB: Their page doesn't say how often tests were performed.)
You can do that using replace
and len
.
Count number of x
characters in str
:
len(str) - len(replace(str, 'x', ''))
Supervised learning is when the data you feed your algorithm with is "tagged" or "labelled", to help your logic make decisions.
Example: Bayes spam filtering, where you have to flag an item as spam to refine the results.
Unsupervised learning are types of algorithms that try to find correlations without any external inputs other than the raw data.
Example: data mining clustering algorithms.
Here's a simple example using reduce. It runs serially, maintains insertion order, and does not require Bluebird.
/**
*
* @param items An array of items.
* @param fn A function that accepts an item from the array and returns a promise.
* @returns {Promise}
*/
function forEachPromise(items, fn) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item);
});
}, Promise.resolve());
}
And use it like this:
var items = ['a', 'b', 'c'];
function logItem(item) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
resolve();
})
});
}
forEachPromise(items, logItem).then(() => {
console.log('done');
});
We have found it useful to send an optional context into loop. The context is optional and shared by all iterations.
function forEachPromise(items, fn, context) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item, context);
});
}, Promise.resolve());
}
Your promise function would look like this:
function logItem(item, context) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
context.itemCount++;
resolve();
})
});
}
byte b = (byte)0xC8;
int v1 = b; // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)
Most of the time v2 is the way you really need.
maybe your script tab has some problem.
if you set type, must type="application/javascript".
<!DOCTYPE html>
<html>
<head>
<title>
Hello
</title>
</head>
<body>
<div onclick="showMsg('Hello')">
Click me show message
</div>
<script type="application/javascript">
function showMsg(item) {
alert(item);
}
</script>
</body>
</html>
You can use a formula like:
(weekday + 5) % 7 + 1
If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want.
addition: for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula is :
(weekday + @@DATEFIRST + 5) % 7 + 1
You cannot use WHILE
like that; see: mysql DECLARE WHILE outside stored procedure how?
You have to put your code in a stored procedure. Example:
CREATE PROCEDURE myproc()
BEGIN
DECLARE i int DEFAULT 237692001;
WHILE i <= 237692004 DO
INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
SET i = i + 1;
END WHILE;
END
Fiddle: http://sqlfiddle.com/#!2/a4f92/1
Alternatively, generate a list of INSERT
statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:
for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done
By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.
For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant
. There's a tutorial, or you could just dive straight in:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>
PyEnchant
comes with a few dictionaries (en_GB, en_US, de_DE, fr_FR), but can use any of the OpenOffice ones if you want more languages.
There appears to be a pluralisation library called inflect
, but I've no idea whether it's any good.
When using sp_rename which works like in above answers, check also which objects are affected after renaming, that reference that table, because you need to change those too
I took a code example for table dependencies at Pinal Dave's blog here
USE AdventureWorks
GO
SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE
referenced_entity_name = 'Customer'
So, all these dependent objects needs to be updated also
Or use some add-in if you can, some of them have feature to rename object, and all depend,ent objects too
There isn't any in printf
- the two are synonyms.
You have used '/0'
instead of '\0'
. This is incorrect: the '\0'
is a null character, while '/0'
is a multicharacter literal.
Moreover, in C it is OK to skip a zero in your condition:
while (*(forward++)) {
...
}
is a valid way to check character, integer, pointer, etc. for being zero.
To be a little more concrete about how RSA uses properties of prime numbers, the RSA algorithm depends critically upon Euler's Theorem, which states that for relatively prime numbers "a" and "N", a^e is congruent to 1 modulo N, where e is the Euler's totient function of N.
Where do primes come into that? To compute the Euler's totient function of N efficiently requires knowing the prime factorization of N. In the case of the RSA algorithm, where N = pq for some primes "p" and "q", then e = (p - 1)(q - 1) = N - p - q + 1. But without knowing p and q, computation of e is very difficult.
More abstractly, many crypotgraphic protocols use various trapdoor functions, functions which are easy to compute but difficult to invert. Number theory is a rich source of such trapdoor functions (such as multiplication of large prime numbers), and prime numbers are absolutely central to number theory.
JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/
helps when embedding JSON in a <script>
tag, which doesn't allow </
inside strings, like Seb points out.
Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/"
. (Yuck)
You can use JavaScript as well, in case the textfield is dithered.
WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);
SWIFT 5
If you don't have a ViewController set as the initial ViewController in storyboard, you need to do 2 things:
Finally, you can now add your code in SceneDelegate:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
// Make sure you set an Storyboard ID for the view controller you want to instantiate
window?.rootViewController = storyboard.instantiateViewController(withIdentifier: identifier)
window?.makeKeyAndVisible()
}
Have you considered using span
instead of div
? It is the in-line version of div
.
I had the same error using an UpdateView
I had this:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url())
and I solved just doing:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))
You need to call ignoring
with exception to ignore while the WebDriver
will wait.
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class);
See the documentation of FluentWait for more info. But beware that this condition is already implemented in ExpectedConditions so you should use
WebElement element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
*Update for newer versions of Selenium:
withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)
So the code will look as such:
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30)
.pollingEvery(Duration.ofMillis(200)
.ignoring(NoSuchElementException.class);
Basic tutorial for waiting can be found here.
The difference between a data flow diagram (DFD) and a flow chart (FC) are that a data flow diagram typically describes the data flow within a system and the flow chart usually describes the detailed logic of a business process.
What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon
In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.
You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc
:
int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
buf[i] = (int*) malloc(N * sizeof(int));
and then you can reference buf[3][5]
or whatever.
Add this at the top of your file:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
DANGEROUS This disables HTTPS / SSL / TLS checking across your entire node.js environment. Please see the solution using an https agent below.
Try using SweetAlert its just simply the best . You will get a lot of customization and flexibility.
sweetAlert(
{
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!"
},
deleteIt()
);
my sample code
wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen
Use in XML:
android:src="@drawable/image"
Source use:
imageView.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.your_image));
This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
I have struggled on this same issue for several days. It can be solved by modifying the security user access properties of the file system folder on which your site is mapped. But IIS_IUSRS is not the only account you must authorize.
OR
You can achieve it like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>
This should be in your page's <head>
and any jQuery ready event handlers should be in the <body>
to avoid errors (although it's not fool-proof!).
One more reason to not use Google-hosted jQuery is that in some countries, Google's domain name is banned.
If you want to present a new view in the same storyboard,
In CurrentViewController.m,
#import "YourViewController.h"
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];
To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.
You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.
ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz
FOREIGN KEY (xyz)
REFERENCES ChildTable (xyz) ON DELETE CASCADE
-vm
C:\Program Files\Java\jdk1.5.0_06\bin\javaw.exe
Remember, no quotes, no matter if your path has spaces (as opposed to command line execution).
See here: Find the JRE for Eclipse
npm i -g npm
This is what i get promped on my console from npm when new update/bug-fix are released:
Following solution will drop specific default constraint of a column from the table
Declare @Const NVARCHAR(256)
SET @Const = (
SELECT TOP 1 'ALTER TABLE' + YOUR TABLE NAME +' DROP CONSTRAINT '+name
FROM Sys.default_constraints A
JOIN sysconstraints B on A.parent_object_id = B.id
WHERE id = OBJECT_ID('YOUR TABLE NAME')
AND COL_NAME(id, colid)='COLUMN NAME'
AND OBJECTPROPERTY(constid,'IsDefaultCnst')=1
)
EXEC (@Const)
Writing this middleware might help !
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
for details visit http://enable-cors.org/server_expressjs.html
Just backgrounding your script (./myscript &
) will not daemonize it. See http://www.faqs.org/faqs/unix-faq/programmer/faq/, section 1.7, which describes what's necessary to become a daemon. You must disconnect it from the terminal so that SIGHUP
does not kill it. You can take a shortcut to make a script appear to act like a daemon;
nohup ./myscript 0<&- &>/dev/null &
will do the job. Or, to capture both stderr and stdout to a file:
nohup ./myscript 0<&- &> my.admin.log.file &
However, there may be further important aspects that you need to consider. For example:
chdir("/")
(or cd /
inside your script), and fork so that the parent exits, and thus the original descriptor is closed.umask 0
. You may not want to depend on the umask of the caller of the daemon.For an example of a script that takes all of these aspects into account, see Mike S' answer.
An easy fix to this question is to add '[' in the start of your json file, and ending it with a ']'. This solved it for me.
In my case, I used Angular forms with contenteditable
elements like div
and had similar problems before.
I wrote ng-contenteditable module to resolve this problem.
You need to stop the submission if an error occured:
HTML
<form name ="myform" onsubmit="return validation();">
JS
if (document.myform.username.value == "") {
document.getElementById('errors').innerHTML="*Please enter a username*";
return false;
}
Based on the clarifying comment by @user2989027, I think a good solution is the following:
definition = ['apple', 'ball']
data = {'orange':1, 'pear':2, 'apple':3, 'ball':4}
my_data = {}
for k in definition:
try:
my_data[k]=data[k]
except KeyError:
pass
print my_data
I tried not to do anything fancy here. I setup my data and an empty dictionary. I then loop through a list of strings that represent potential keys in my data dictionary. I copy each value from data to my_data, but consider the case where data may not have the key that I want.
If you have a staging server that has directory listing enabled, then you can copy the index.html
to the production server.
For example:
wget https://staging/dir/index.html
# do any additional processing on index.html
scp index.html prod/dir
I believe this error is caused because the local server and live server are running different versions of MySQL. To solve this:
utf8mb4_unicode_520_ci
with utf8mb4_unicode_ci
Hope that helps
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
To make a function available on jQuery objects you add it to the jQuery prototype (fn is a shortcut for prototype in jQuery) like this:
jQuery.fn.myFunction = function() {
// Usually iterate over the items and return for chainability
// 'this' is the elements returns by the selector
return this.each(function() {
// do something to each item matching the selector
}
}
This is usually called a jQuery plugin.
Example - http://jsfiddle.net/VwPrm/
I agree this code works, to size an ImageIcon from a file for display while keeping the aspect ratio I have used the below.
/*
* source File of image, maxHeight pixels of height available, maxWidth pixels of width available
* @return an ImageIcon for adding to a label
*/
public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth)
{
int newHeight = 0, newWidth = 0; // Variables for the new height and width
int priorHeight = 0, priorWidth = 0;
BufferedImage image = null;
ImageIcon sizeImage;
try {
image = ImageIO.read(source); // get the image
} catch (Exception e) {
e.printStackTrace();
System.out.println("Picture upload attempted & failed");
}
sizeImage = new ImageIcon(image);
if(sizeImage != null)
{
priorHeight = sizeImage.getIconHeight();
priorWidth = sizeImage.getIconWidth();
}
// Calculate the correct new height and width
if((float)priorHeight/(float)priorWidth > (float)maxHeight/(float)maxWidth)
{
newHeight = maxHeight;
newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight);
}
else
{
newWidth = maxWidth;
newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth);
}
// Resize the image
// 1. Create a new Buffered Image and Graphic2D object
BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
// 2. Use the Graphic object to draw a new image to the image in the buffer
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, 0, 0, newWidth, newHeight, null);
g2.dispose();
// 3. Convert the buffered image into an ImageIcon for return
return (new ImageIcon(resizedImg));
}
I prefer use a pure MySQL syntax to get last auto_increment id of the table I want.
php mysql_insert_id() and mysql last_insert_id() give only last transaction ID.
If you want last auto_incremented ID of any table in your schema (not only last transaction one), you can use this query
SELECT AUTO_INCREMENT FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'my_database'
AND TABLE_NAME = 'my_table_name';
That's it.
Just add the following line to the <head>
section of your HTML file:
<link rel="icon" href="data:,">
Features of this solution:
href="#"
)In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.
Thanks & Regards Vengat Maran
Use git reset:
git reset --hard "Version 1.0 Revision 1.5"
(assuming that the specified string is the tag).
This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:
ModelStateException
that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)HandleModelStateExceptionAttribute
that catches custom exception and returns HTTP error status with model state error in the bodyThis provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success
and error
handlers.
$.ajax({
type: "POST",
url: "some/url",
success: function(data, status, xhr) {
// handle success
},
error: function(xhr, status, error) {
// handle error
}
});
[HandleModelStateException]
public ActionResult Create(User user)
{
if (!this.ModelState.IsValid)
{
throw new ModelStateException(this.ModelState);
}
// create new user because validation was successful
}
The whole problem is detailed in this blog post where you can find all the code to run this in your application.
To anyone developing for Android, you can use android.util.Pair. :)
Right-click folder -> TortiseGit -> Clean up.. -> click OK
None of the above solutions worked for me but this one did.
I believe the flag --force
is what you are really looking for. Just use git branch -d --force <branch_name>
to delete the branch forcibly.
My solution is:
import threading, time
def a():
t = threading.currentThread()
while getattr(t, "do_run", True):
print('Do something')
time.sleep(1)
def getThreadByName(name):
threads = threading.enumerate() #Threads list
for thread in threads:
if thread.name == name:
return thread
threading.Thread(target=a, name='228').start() #Init thread
t = getThreadByName('228') #Get thread by name
time.sleep(5)
t.do_run = False #Signal to stop thread
t.join()
Based on drspaceboo's solution, with Kotlin you can use an extension to convert Float
to dips more easily.
fun Float.toDips() =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, resources.displayMetrics);
Usage:
(65f).toDips()
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
I wanted a solution with the following properties:
Both requirements were not provided in the other answers, so here's how to read stdin while doing everything on the command line:
grep special_string -r | sort | python3 <(cat <<EOF
import sys
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 4:
print("%-45s %7.3f %s %s" % (tokens[0], float(tokens[1]), tokens[2], tokens[3]))
EOF
)
I think you are not asking the right question--
A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer.
Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying:
try:
mystring.decode('ascii')
except UnicodeDecodeError:
print "it was not a ascii-encoded unicode string"
else:
print "It may have been an ascii-encoded unicode string"
Might just be for Visual Studio '15, if you right-click on source code, there's an option for insert comment
This puts summary
tags around your comment section, but it does give the indentation that you want.
subprocess.call
expects the same arguments as subprocess.Popen
- that is a list of strings (the argv
in C) rather than a single string.
It's quite possible that your child process attempted to run "s" with the parameters "o", "m", "e", ...
Those "anchors" that exist solely to provide a click event, but do not actually link to other content, should really be button elements because that's what they really are.
It can be styled like so:
<button style="border:none; background:transparent; cursor: pointer;">Click me</button>
And of course click events can be attached to buttons without worry of the browser jumping to the top, and without adding extraneous javascript such as onclick="return false;" or event.preventDefault() .
Using Spring Framework , you can add many attachments :
package com.mkyong.common;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail
{
private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String dear, String content) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(
simpleMailMessage.getText(), dear, content));
FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
helper.addAttachment(file.getFilename(), file);
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
To know how to configure your project to deal with this code , complete reading this tutorial .
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
Another option that may be suitable in this situation is using XML
The XML option to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.
The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).
Vertical expansion
Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.
Horizontal expansion
Unlike the PIVOT, newly added documents can be displayed without altering the script.
Performance breakdown
In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.
You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/
Error: 10060 Adding a timeout parameter to request solved the issue for me.
import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)
A similar error also occurred while I was making a GET request. Again, passing a timeout
parameter solved the 10060 Error.
response = requests.get(param_url, timeout=20)
You might consider writing an iterator instead, which allows you to use normal 'for' loop syntax like '++'. I searched and found a similar question answered here on StackOverflow which gives pointers on making DateTime iterable.
function handle_change(
evt: React.ChangeEvent<HTMLInputElement>
): string {
evt.persist(); // This is needed so you can actually get the currentTarget
const inputValue = evt.currentTarget.value;
return inputValue
}
And make sure you have "lib": ["dom"]
in your tsconfig
.
The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.
It uses strftime()
, which works with struct timespec
just as well as with struct timeval
because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.
Example output: 2021-01-19T04:50:01.435561072Z
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int utc_system_timestamp(char[]);
int main(void) {
char buf[31];
utc_system_timestamp(buf);
printf("%s\n", buf);
}
// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
const int bufsize = 31;
struct timespec now;
struct tm tm;
int retval = clock_gettime(CLOCK_REALTIME, &now);
gmtime_r(&now.tv_sec, &tm);
strftime(buf, bufsize, "%Y-%m-%dT%H:%M:%S.", &tm);
sprintf(buf, "%s%09luZ", buf, now.tv_nsec);
return retval;
}
According to question Matplotlib (pyplot) savefig outputs blank image.
One thing should note: if you use plt.show
and it should after plt.savefig
, or you will give a blank image.
A detailed example:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
I searched for a similar issue,
Wanted to throw away local commits:
So did the below:
git reset --hard origin/dev
Check:
git status
On branch dev
Your branch is up-to-date with 'origin/dev'.
nothing to commit, working tree clean
now local commits are lost, back to the initial cloned state, point 1 above.
A common trick is to check like this:
trim(TextBox1.Value & vbnullstring) = vbnullstring
this will work for spaces, empty strings, and genuine null values
First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.
You can also change the default color cycle in your matplotlibrc
file.
If you don't know where that file is, do the following in python:
import matplotlib
matplotlib.matplotlib_fname()
This will show you the path to your currently used matplotlibrc file.
In that file you will find amongst many other settings also the one for axes.color.cycle
. Just put in your desired sequence of colors and you will find it in every plot you make.
Note that you can also use all valid html color names in matplotlib.
Here a little array solution within a two line function. It checks also if the leading zeros are less than the length of the number string.
function pad(num, z) {
if (z < (num = num + '').length) return num;
return Array(++z - num.length).join('0') + num;
}
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'
__del__()
gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.__init__()
raises an exception then the object is assumed to be incomplete and __del__()
won't be invoked.If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
In my case, it was due to Same Origin policies. To explain it further, MDN states the following:
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.
Wrote a tutorial so that you can animate your activity's in and out,
Enjoy:
The solution for the configuration provided by the angular team itself can be found here.
Here is all the relevant code:
1) app.config.ts
import { OpaqueToken } from "@angular/core";
export let APP_CONFIG = new OpaqueToken("app.config");
export interface IAppConfig {
apiEndpoint: string;
}
export const AppConfig: IAppConfig = {
apiEndpoint: "http://localhost:15422/api/"
};
2) app.module.ts
import { APP_CONFIG, AppConfig } from './app.config';
@NgModule({
providers: [
{ provide: APP_CONFIG, useValue: AppConfig }
]
})
3) your.service.ts
import { APP_CONFIG, IAppConfig } from './app.config';
@Injectable()
export class YourService {
constructor(@Inject(APP_CONFIG) private config: IAppConfig) {
// You can use config.apiEndpoint now
}
}
Now you can inject the config everywhere without using the string names and with the use of your interface for static checks.
You can of course separate the Interface and the constant further to be able to supply different values in production and development e.g.
I was having the same issue with ghost and heroku.
heroku config:set NODE_ENV=production
solved it!
Check your config and env that the server is running on.
just do it like this
x=zeros(100,200);
for i=1:100
for j=1:200
x(i,j)=input('enter the number');
end
end
Hadoop is essentially providing a mechanism to perform something similar to what @Ivella is suggesting.
Hadoop's HDFS (Distributed file system) is going to take your 20GB file and save it across the cluster in blocks of a fixed size. Lets say you configure the block size to be 128MB, the file would be split into 20x8x128MB blocks.
You would then run a map reduce program over this data, essentially counting the lines for each block (in the map stage) and then reducing these block line counts into a final line count for the entire file.
As for performance, in general the bigger your cluster, the better the performance (more wc's running in parallel, over more independent disks), but there is some overhead in job orchestration that means that running the job on smaller files will not actually yield quicker throughput than running a local wc
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:
https://pathcopycopy.github.io/
Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:
If you're only replacing single characters, you should use strtr()
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
The fleqn
option in the document class will apply left aligning setting in all equations of the document. You can instead use \begin{flalign}
. This will align only the desired equations.
Tom's answer is quite detailed and exhaustive but you may also be interested in this simple study about Parquet vs Avro done at Allstate Insurance, summarized here:
"Overall, Parquet showed either similar or better results on every test [than Avro]. The query-performance differences on the larger datasets in Parquet’s favor are partly due to the compression results; when querying the wide dataset, Spark had to read 3.5x less data for Parquet than Avro. Avro did not perform well when processing the entire dataset, as suspected."
I'm just giving my real time example:
In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".
document.querySelectorAll("[id^='select2-qownerName_select-result']");
When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.
$("[id^='select2-qownerName_select-result']")
You can supply a function argument to scale
, and ggplot will use
that function to calculate the tick locations.
library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))
number_ticks <- function(n) {function(limits) pretty(limits, n)}
ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks=number_ticks(10)) +
scale_y_continuous(breaks=number_ticks(10))
Example 1:
This is how the and operator works.
x and y => if x is false, then x, else y
So in other words, since mylist1
is not False
, the result of the expression is mylist2
. (Only empty lists evaluate to False
.)
Example 2:
The &
operator is for a bitwise and, as you mention. Bitwise operations only work on numbers. The result of a & b is a number composed of 1s in bits that are 1 in both a and b. For example:
>>> 3 & 1
1
It's easier to see what's happening using a binary literal (same numbers as above):
>>> 0b0011 & 0b0001
0b0001
Bitwise operations are similar in concept to boolean (truth) operations, but they work only on bits.
So, given a couple statements about my car
The logical "and" of these two statements is:
(is my car red?) and (does car have wheels?) => logical true of false value
Both of which are true, for my car at least. So the value of the statement as a whole is logically true.
The bitwise "and" of these two statements is a little more nebulous:
(the numeric value of the statement 'my car is red') & (the numeric value of the statement 'my car has wheels') => number
If python knows how to convert the statements to numeric values, then it will do so and compute the bitwise-and of the two values. This may lead you to believe that &
is interchangeable with and
, but as with the above example they are different things. Also, for the objects that can't be converted, you'll just get a TypeError
.
Example 3 and 4:
Numpy implements arithmetic operations for arrays:
Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.
But does not implement logical operations for arrays, because you can't overload logical operators in python. That's why example three doesn't work, but example four does.
So to answer your and
vs &
question: Use and
.
The bitwise operations are used for examining the structure of a number (which bits are set, which bits aren't set). This kind of information is mostly used in low-level operating system interfaces (unix permission bits, for example). Most python programs won't need to know that.
The logical operations (and
, or
, not
), however, are used all the time.
Commenting just so people can have a solution to the intended question.
You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.
In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.
The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.
I like Alex FTPS Client which is written by a Microsoft MVP name Alex Pilotti. It's a C# library you can use in Console apps, Windows Forms, PowerShell, ASP.NET (in any .NET language). If you have a multithreaded app you will have to configure the library to run syncronously, but overall a good client that will most likely get you what you need.
You can also use the sqldf
package which performs selects on R data frames as :
df1 <- sqldf("select A, B, E from df")
This gives as the output a data frame df1
with columns: A, B ,E.
You can use, pathlib also
from pathlib import Path
fl = Path("file_name")
fl.chmod(0o444)
You can just simply add the following code;
<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>
I have been working with Swift 3.0 and wanted to contribute an answer for the updated syntax. Additionally, and possibly more importantly, I am using the PropertyListSerialization object to do the heavy lifting, which is a lot more flexible than just using the NSDictionary as it allows for an Array as the root type of the plist.
Below is a screenshot of the plist I am using. It is a little complicated, so as to show the power available, but this will work for any allowable combination of plist types.
As you can see I am using an Array of String:String dictionaries to store a list of website names and their corresponding URL.
I am using the PropertyListSerialization object, as mentioned above, to do the heavy lifting for me. Additionally, Swift 3.0 has become more "Swifty" so all of the object names have lost the "NS" prefix.
let path = Bundle.main().pathForResource("DefaultSiteList", ofType: "plist")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil)
After the above code runs plist
will be of type Array<AnyObject>
, but we know what type it really is so we can cast it to the correct type:
let dictArray = plist as! [[String:String]]
// [[String:String]] is equivalent to Array< Dictionary<String, String> >
And now we can access the various properties of our Array of String:String Dictionaries in a natural way. Hopefully to convert them into actual strongly typed structs or classes ;)
print(dictArray[0]["Name"])
Take a look at the Python tutorial section 4.7.3 and 4.7.4. It talks about passing tuples as arguments.
I would also consider using named parameters (and passing a dictionary) instead of using a tuple and passing a sequence. I find the use of positional arguments to be a bad practice when the positions are not intuitive or there are multiple parameters.
If your ID is unique identifier type or your id in table is not sorted you must do like this below.
select * from
(select ROW_NUMBER() OVER (ORDER BY (select 0)) AS RowNumber,* from table1) a
where a.RowNumber between 2 and 5
The code will be
select * from limit 2,5
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']").each(function(){ ...
or
$("input:checkbox[name='ProductCode']").each(function(){ ...
It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName
method which will be used to select elements and be much faster than selecting by the name
attribute
To anyone still struggling to get the os.environ
solution to work as I was, check that this is placed before you import tensorflow
in your script, just like mwweb's answer:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import tensorflow as tf
Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length
of the array:
> AssocArray.length
0
What is often referred to as "associative array" is actually just an object in JS:
var AssocArray = {}; // <- initialize an object, not an array
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a
is the same as AssocArray['a']
.
Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.
More info: https://stackoverflow.com/a/26630862/4154438
The plus operator converts operands to int first and then does the addition. So the result is the int. You need to cast it back to short explicitly because conversions from a "longer" type to "shorter" type a made explicit, so that you don't loose data accidentally with an implicit cast.
As to why int16 is cast to int, the answer is, because this is what is defined in C# spec. And C# is this way is because it was designed to closely match to the way how CLR works, and CLR has only 32/64 bit arithmetic and not 16 bit. Other languages on top of CLR may choose to expose this differently.
You need to specify the domain:
$('.button1').click(function() {
window.location = 'www.example.com/index.php?id=' + this.id;
});
In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:
class A : public B
{
public:
A(int a, int b, int c);
private:
int b_, c_;
};
Then, assuming B has a constructor which takes an int, A's constructor may look like this:
A::A(int a, int b, int c)
: B(a), b_(b), c_(c) // initialization list
{
// do something
}
As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.
Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.
Another issue is that your database may be in a "non-trusted" location. Go to the trust center settings and add your database location to the trusted locations list.
Create a Date
object using the diffence between your times as a constructor,
then use Calendar methods to get values ..
Date diff = new Date(d2.getTime() - d1.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(diff);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation
This fiddle should work like what you need, but will not for now.
Unfortunately, it's still a draft, and isn't fully implemented on major browsers.
It does work for content
on pseudo-elements, though.
urllib2 provides some extra functionality, namely the urlopen()
function can allow you to specify headers (normally you'd have had to use httplib in the past, which is far more verbose.) More importantly though, urllib2 provides the Request
class, which allows for a more declarative approach to doing a request:
r = Request(url='http://www.mysite.com')
r.add_header('User-Agent', 'awesome fetcher')
r.add_data(urllib.urlencode({'foo': 'bar'})
response = urlopen(r)
Note that urlencode()
is only in urllib, not urllib2.
There are also handlers for implementing more advanced URL support in urllib2. The short answer is, unless you're working with legacy code, you probably want to use the URL opener from urllib2, but you still need to import into urllib for some of the utility functions.
Bonus answer With Google App Engine, you can use any of httplib, urllib or urllib2, but all of them are just wrappers for Google's URL Fetch API. That is, you are still subject to the same limitations such as ports, protocols, and the length of the response allowed. You can use the core of the libraries as you would expect for retrieving HTTP URLs, though.
/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";
/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
return _globalValue;
}
set
{
_globalValue = value;
}
}
/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}
You can grab the demo source code from here: http://abhinavsingh.com/blog/2008/05/gmail-type-attachment-how-to-make-one/
It is ready to use, or you can modify to suit your application needs. Hope it helps :)
You can set border
properties on a tr
element, but according to the CSS 2.1 specification, such properties have no effect in the separated borders model, which tends to be the default in browsers. Ref.: 17.6.1 The separated borders model. (The initial value of border-collapse
is separate
according to CSS 2.1, and some browsers also set it as default value for table
. The net effect anyway is that you get separated border on almost all browsers unless you explicitly specifi collapse
.)
Thus, you need to use collapsing borders. Example:
<style>
table { border-collapse: collapse; }
tr:nth-child(3) { border: solid thin; }
</style>
you can use decoration like this :
Container(
width: 60,
height: 60,
child: Icon(CustomIcons.option, size: 20,),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFFe0f2f1)),
)
Now you have circle shape and Icon on it.
You could simply use XmlHttp
(AJAX) to hit the required URL and the HTML response from the URL will be available in the responseText
property. If it's not the same domain, your users will receive a browser alert saying something like "This page is trying to access a different domain. Do you want to allow this?"
Use this code in Swift
imageView.image=UIImage(data: NSData(contentsOfURL: NSURL(string: "http://myURL/ios8.png")!)!
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
I've written a one linear for this:
[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);
I feel however I can spend more time to make a JSON.parse(JSON.stringify())
-free version which is used for cloning here.
Btw, have a look at my another answer here.
With simple parameter types (i.e. not refcursors etc.) you can do something like this:
SET serveroutput on;
DECLARE
InParam1 number;
InParam2 number;
OutParam1 varchar2(100);
OutParam2 varchar2(100);
OutParam3 varchar2(100);
OutParam4 number;
BEGIN
/* Assign values to IN parameters */
InParam1 := 33;
InParam2 := 89;
/* Call procedure within package, identifying schema if necessary */
schema.package.procedure(InParam1, InParam2,
OutParam1, OutParam2, OutParam3, OutParam4);
/* Display OUT parameters */
dbms_output.put_line('OutParam1: ' || OutParam1);
dbms_output.put_line('OutParam2: ' || OutParam2);
dbms_output.put_line('OutParam3: ' || OutParam3);
dbms_output.put_line('OutParam4: ' || OutParam4);
END;
/
:var
bind variables:
var InParam1 number;
var InParam2 number;
var OutParam1 varchar2(100);
var OutParam2 varchar2(100);
var OutParam3 varchar2(100);
var OutParam4 number;
BEGIN
/* Assign values to IN parameters */
:InParam1 := 33;
:InParam2 := 89;
/* Call procedure within package, identifying schema if necessary */
schema.package.procedure(:InParam1, :InParam2,
:OutParam1, :OutParam2, :OutParam3, :OutParam4);
END;
/
-- Display OUT parameters
print :OutParam1;
print :OutParam2;
print :OutParam3;
print :OutParam4;
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).
To enable Push Notification for your iOS app, you will need to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.
(Updated version with updated screen shots Here)
Step 1: Login to iOS Provisioning Portal, click "Certificates" on the left navigation bar. Then, click "+" button.
Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click "Continue" button.
Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click "Continue" to go to next step.
Step 4: Follow the steps "About Creating a Certificate Signing Request (CSR)" to create a Certificate Signing Request.
To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:
Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.
Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.
Step 5: Upload the ".certSigningRequest" file which is generated in Step 4, then click "Generate" button.
Step 6: Click "Done" to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:
Then Click "Download" button to download the certificate (.cer file) you've created just now. - Double click the downloaded file to install the certificate into Keychain Access on your Mac.
Step 7: On your Mac, go to "Keychain", look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with "Apple Production IOS Push Services:" followed by your app's bundle ID.
Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the "Select" key on your keyboard, right click (or cmd-click if you use a single button mouse), choose "Export 2 items", like Below:
Then save the p12 file with name "pushcert.p12" to your Desktop - now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.
Step 9: Now the most difficult part - open "Terminal" on your Mac, and run the following commands:
cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts
Step 10: Remove pushcert.p12 from Desktop to avoid mis-uploading it to Build Your Own area. Open "Terminal" on your Mac, and run the following commands:
cd
cd Desktop
rm pushcert.p12
Step 11 - NEW AWS UPDATE: Create new pushcert.p12
to submit to AWS SNS. Double click on the new pushcert.pem
, then export the one highlighed on the green only.
Credit: AWS new update
Now you have successfully created an Apple Push Notification Certificate (.p12 file)! You will need to upload this file to our Build Your Own area later on. :)
You will get the un passed argument value as undefined. But in your case you have to pass at least null value in the first argument.
Or you have to change the method definition like
my_function = function(options, content) { action }
I encountered this problem too.
and here is my old doesn't work code
if(data.access == 'private'){
Jbookaccess.removeProp("checked") ;
//I also have tried : Jbookaccess.removeAttr("checked") ;
}else{
Jbookaccess.prop("checked", true)
}
here is my new code which is worked now:
if(data.access == 'private'){
Jbookaccess.prop("checked",false) ;
}else{
Jbookaccess.prop("checked", true)
}
so,the key point is before it worked ,make sure the checked property does exist and does not been removed.
If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.
Paste this in your custom css file:
@media (min-width:992px)
{
.container{width:960px}
}
@media (min-width:1200px)
{
.container{width:960px}
}
I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
<form class="form-inline">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">
</div>
<button type="submit" class="btn btn-default">Sign in</button>
</form>
Here is my suggestion - it's quite simple as that:
[^-]*
Whenever you encounter an error with this message use my_string.encode()
.
(where my_string
is the string you're passing to a function/method).
The encode
method of str
objects returns the encoded version of the string as a bytes
object which you can then use.
In this specific instance, socket methods such as .send
expect a bytes object as the data to be sent, not a string object.
Since you have an object of type str
and you're passing it to a function/method that expects an object of type bytes
, an error is raised that clearly explains that:
TypeError: a bytes-like object is required, not 'str'
So the encode
method of strings is needed, applied on a str
value and returning a bytes
value:
>>> s = "Hello world"
>>> print(type(s))
<class 'str'>
>>> byte_s = s.encode()
>>> print(type(byte_s))
<class 'bytes'>
>>> print(byte_s)
b"Hello world"
Here the prefix b
in b'Hello world'
denotes that this is indeed a bytes object. You can then pass it to whatever function is expecting it in order for it to run smoothly.
Well any Javascript object functions sort-of like a "map"
randomObject['hello'] = 'world';
Typically people build simple objects for the purpose:
var myMap = {};
// ...
myMap[newKey] = newValue;
edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.
13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.
There are couple of ways to pass parameter in event handlers, some are following.
You can use an arrow function to wrap around an event handler and pass parameters:
<button onClick={() => this.handleClick(id)} />
above example is equivalent to calling .bind
or you can explicitly call bind.
<button onClick={this.handleClick.bind(this, id)} />
Apart from these two approaches, you can also pass arguments to a function that is defined as a curry function.
handleClick = (id) => () => {
console.log("Hello, your ticket number is", id)
};
<button onClick={this.handleClick(id)} />
1) Note that it is considered insecure to have the .htpasswd
file below the server root.
2) The docs say this about relative paths, so it looks you're out of luck:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the ServerRoot.
3) While the answers recommending the use of environment variables work perfectly fine, I would prefer to put a placeholder in the .htaccess
file, or have different versions in my codebase, and have the deployment process set it all up (i. e. replace placeholders or rename / move the appropriate file).
On Java projects, I use Maven to do this type of work, on, say, PHP projects, I like to have a build.sh and / or install.sh shell script that tunes the deployed files to their environment. This decouples your codebase from the specifics of its target environment (i. e. its environment variables and configuration parameters). In general, the application should adapt to the environment, if you do it the other way around, you might run into problems once the environment also has to cater for different applications, or for completely unrelated, system-specific requirements.
By default, Java only supports AES 128 bit (16 bytes) key sizes for encryption. If you do not need more than default supported, you can trim the key to the proper size before using Cipher
. See javadoc for default supported keys.
This is an example of generating a key that would work with any JVM version without modifying the policy files. Use at your own discretion.
Here is a good article on whether key 128 to 256 key sizes matter on AgileBits Blog
SecretKeySpec getKey() {
final pass = "47e7717f0f37ee72cb226278279aebef".getBytes("UTF-8");
final sha = MessageDigest.getInstance("SHA-256");
def key = sha.digest(pass);
// use only first 128 bit (16 bytes). By default Java only supports AES 128 bit key sizes for encryption.
// Updated jvm policies are required for 256 bit.
key = Arrays.copyOf(key, 16);
return new SecretKeySpec(key, AES);
}
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Or even this
<?php
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
Using Playframework 2.6, the Json library found in the java api can also be used to simply parse the string. The string can either be a json element of json array. Since the returned value is not of importance here we just catch the parse error to determine that the string is a correct json string or not.
import play.libs.Json;
public static Boolean isValidJson(String value) {
try{
Json.parse(value);
return true;
} catch(final Exception e){
return false;
}
}
You should inspect full trace very carefully,
I've a server socket application and fixed a java.net.SocketException: Connection reset
case.
In my case it happens while reading from a clientSocket Socket
object which is closed its connection because of some reason. (Network lost,firewall or application crash or intended close)
Actually I was re-establishing connection when I got an error while reading from this Socket object.
Socket clientSocket = ServerSocket.accept();
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
int readed = is.read(); // WHERE ERROR STARTS !!!
The interesting thing is for my JAVA Socket
if a client connects to my ServerSocket
and close its connection without sending anything is.read()
is being called repeatedly.It seems because of being in an infinite while loop for reading from this socket you try to read from a closed connection.
If you use something like below for read operation;
while(true)
{
Receive();
}
Then you get a stackTrace something like below on and on
java.net.SocketException: Socket is closed
at java.net.ServerSocket.accept(ServerSocket.java:494)
What I did is just closing ServerSocket and renewing my connection and waiting for further incoming client connections
String Receive() throws Exception
{
try {
int readed = is.read();
....
}catch(Exception e)
{
tryReConnect();
logit(); //etc
}
//...
}
This reestablises my connection for unknown client socket losts
private void tryReConnect()
{
try
{
ServerSocket.close();
//empty my old lost connection and let it get by garbage col. immediately
clientSocket=null;
System.gc();
//Wait a new client Socket connection and address this to my local variable
clientSocket= ServerSocket.accept(); // Waiting for another Connection
System.out.println("Connection established...");
}catch (Exception e) {
String message="ReConnect not successful "+e.getMessage();
logit();//etc...
}
}
I couldn't find another way because as you see from below image you can't understand whether connection is lost or not without a try and catch
,because everything seems right . I got this snapshot while I was getting Connection reset
continuously.
The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.
If you can, make the fields final.
How about this?
var http = require('http'),
fs = require('fs'),
options;
options = {
host: 'www.google.com' ,
port: 80,
path: '/images/logos/ps_logo2.png'
}
var request = http.get(options, function(res){
//var imagedata = ''
//res.setEncoding('binary')
var chunks = [];
res.on('data', function(chunk){
//imagedata += chunk
chunks.push(chunk)
})
res.on('end', function(){
//fs.writeFile('logo.png', imagedata, 'binary', function(err){
var buffer = Buffer.concat(chunks)
fs.writeFile('logo.png', buffer, function(err){
if (err) throw err
console.log('File saved.')
})
})
What if you are using this to determine the current selector to find its children
so this holds: <ol>
then there is <li>
s under how to write a selector
var count = $(this+"> li").length;
wont work..
both of them works
<%= f.submit class: "btn btn-primary" %>
and
<%= f.submit "Name of Button", class: "btn btn-primary "%>
If you have installed mongodb community server via homebrew, then you can do:
brew services list
This will list the current services as below:
Name Status User Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
redis stopped
Then you can restart mongodb by first stopping and restart:
brew services stop mongodb
brew services start mongodb
Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.
This will work:
>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
... title, sequence = match.groups()
... title = title.strip()
... sequence = rx_blanks.sub("",sequence)
... print "Title:",title
... print "Sequence:",sequence
... print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK
Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW
Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)
^
) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).(.+?)\n\n
means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.[A-Z]+\n
means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.((?:
textline)+)
means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.\n
in the regular expression if you want to enforce a double newline at the end.\n
or \r
or \r\n
) then just fix the regular expression by replacing every occurrence of \n
by (?:\n|\r\n?)
.Other words printf absent in python... I'm surprised! Best code is
def printf(format, *args):
sys.stdout.write(format % args)
Because of this form allows not to print \n. All others no. That's why print is bad operator. And also you need write args in special form. There is no disadvantages in function above. It's a standard usual form of printf function.
#define USER_IS(c0,c1,c2,c3,c4,c5,c6,c7,c8,c9)\
ch0==c0 && ch1==c1 && ch2==c2 && ch3==c3 && ch4==c4 && ch5==c5 && ch6==c6 && ch7==c7 ;
#define ch0 'j'
#define ch1 'a'
#define ch2 'c'
#define ch3 'k'
#if USER_IS('j','a','c','k',0,0,0,0)
#define USER_VS "queen"
#elif USER_IS('q','u','e','e','n',0,0,0)
#define USER_VS "jack"
#endif
it basically a fixed length static char array initialized manually instead of a variable length static char array initialized automatically always ending with a terminating null char
The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.
awk '{ print substr($0, index($0,$3)) }'
solution found here:
http://www.linuxquestions.org/questions/linux-newbie-8/awk-print-field-to-end-and-character-count-179078/
I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.
I know I am late to answer this question but I would like to add something to answer of @Ethan, the highest voted and accepted answer.
We can use yargs
to get the command line parameter and with that we can also add our own alias for some parameters like follow.
var args = require('yargs')
.alias('r', 'release')
.alias('d', 'develop')
.default('release', false)
.argv;
Kindly refer this link for more details. https://github.com/yargs/yargs/blob/HEAD/docs/api.md
Following is use of alias as per given in documentation of yargs
. We can also find more yargs
function there and can make the command line passing experience even better.
.alias(key, alias)
Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
Optionally .alias() can take an object that maps keys to aliases. Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.
Looks to me like you need to set the yellow
on #doc3
and then get rid of the white
that is called out on the #yui-main
(which is covering up the color of the #doc3
). This gets you yellow between header and footer.
Moreover you should have clear understanding about the following concepts:
Screen size:
Actual physical size, measured as the screen's diagonal. For simplicity, Android groups all actual screen sizes into four generalized sizes: small, normal, large, and extra large.
Screen density:
The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen. For simplicity, Android groups all actual screen densities into four generalized densities: low, medium, high, and extra high.
Orientation:
The orientation of the screen from the user's point of view. This is either landscape or portrait, meaning that the screen's aspect ratio is either wide or tall, respectively. Be aware that not only do different devices operate in different orientations by default, but the orientation can change at runtime when the user rotates the device.
Resolution:
The total number of physical pixels on a screen. When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.
Density-independent pixel (dp):
A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.
Reference: Android developers site
I also had the same problem and I resolved by adding the reference in one of my projects which didn't had the mentioned reference. If you have 2-3 projects in your solution, then check by adding this reference to the other projects.
Would appreciate any thoughts on the situation with 3 data sets. Say a logistic regression model is fitted yielding the following accuracy (Gini): Train: 70%; Test 58% and Out-of-time validation: 66%.
Actually all the possible combinations of predictors bring the same results with quite a huge drop between train and test data sets. The sample size is around 8k divided into train and test 70/30. OOT sample contains a few thousands of cases. Regularization, ensembles didn't help in solving this.
I doubt whether this is something I should concern if OOT performance is acceptable and close to train sample performance?
This only results in null
if obj2
was already null
before the cast, so your problem is earlier than you think. (Also, you need not construct a new ArrayList to initialize al1
if you're going to assign to it immediately. Just say ArrayList al1 = (ArrayList) obj2;
.)
I get your problem, I faced the same problem in my Application. I was calling registerReceiver() multiple time within the application.
A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.
public class YourApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
//register your Broadcast receiver here
IntentFilter intentFilter = new IntentFilter("MANUAL_BROADCAST_RECIEVER");
registerReceiver(new BroadcastReciever(), intentFilter);
}
}
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
You need to sample the load average for several seconds and calculate the CPU utilization from that. If unsure what to you, get the sources of "top" and read it.
The problem is in this method:
public static byte[] encrypt(String toEncrypt) throws Exception{
This is the method signature which pretty much says:
In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".
....
concatURL = padString(concatURL, ' ', 16);
byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
String encryptedString = bytesToHex(encrypted);
content.removeAll();
......
So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.
The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.
Try this:
public static byte[] encrypt(String toEncrypt) {
try{
String plaintext = toEncrypt;
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
} catch ( NoSuchAlgorithmException nsae ) {
// What can you do if the algorithm doesn't exists??
// this usually won't happen because you would test
// your code before shipping.
// So in this case is ok to transform to another kind
throw new IllegalStateException( nsae );
} catch ( NoSuchPaddingException nspe ) {
// What can you do when there is no such padding ( whatever that means ) ??
// I guess not much, in either case you won't be able to encrypt the given string
throw new IllegalStateException( nsae );
}
// line 109 won't say it needs a return anymore.
}
Basically in this particular case you should make sure the cryptography package is available in the system.
Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.
In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.
The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.
try {
// risky code ...
} catch( Exception e ) {
// a bomb has just exploited
// you should NOT ignore it
}
// The code continues here, but what should it do???
If the code is to fail, it is better to Fail fast
Here are some related answers:
UPDATE: The latest version of Android studio (2.x) made major improvements to the bundled emulator. It's responsive and has a whole bunch of features.
For those still interested: Try using Genymotion. You can download a version for Windows/Mac OS X/Linux after registering. A plugin for Eclipse is also available:
The installation of the plugin can be done by launching Eclipse and going to "Help / Install New Software" menu, then just add a new Update Site with the following URL: http://plugins.genymotion.com/eclipse. Follow the steps indicated by Eclipse.
This emulator is fast and responsive.
GenyMotion allows you to control various sensors of your device including the battery level, signal strength, and GPS. The latest version now also contains camera tools.
matching empty string or email
(^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)
matching empty string or email but also matching any amount of whitespace
(^\s*$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$)
see more about the email matching regex itself:
I changed the header and footer of the PEM file to
-----BEGIN RSA PRIVATE KEY-----
and
-----END RSA PRIVATE KEY-----
Finally, it works!
jQuery Core doesn't have anything special, but you can read on jQuery Mobile Events page about different touch events, which also work on other than iOS devices as well.
They are:
Notice also, that during scroll events (based on touch on mobile devices) iOS devices freezes DOM manipulation while scrolling.
Well I did not read correctly the man echo
page for this.
echo had 2 options that could do this if I added a 3rd escape character.
The 2 options are -n
and -e
.
-n
will not output the trailing newline. So that saves me from going to a new line each time I echo something.
-e
will allow me to interpret backslash escape symbols.
Guess what escape symbol I want to use for this: \r
. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.
So the echo line would look like this:
echo -ne "Movie $movies - $dir ADDED!"\\r
I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \
symbols in there.
As mentioned by William, printf
can also do similar (and even more extensive) tasks like this.
You should put the image in webview and work with that. Zoom in / out controls are available in webview.
You mention that there are date duplicates, but it appears they're quite unique down to the precision of seconds.
Can you clarify what precision of date you start considering dates duplicate - day, hour, minute?
In any case, you'll probably want to floor your datetime field. You didn't indicate which field is preferred when removing duplicates, so this query will prefer the last name in alphabetical order.
SELECT MAX(owner_name),
--floored to the second
dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') AS StartDate
From MyTable
GROUP BY dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01')
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
change to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Egypt (free software)
KcacheGrind (GPL)
Graphviz (CPL)
CodeViz (GPL)
Find any files whose name is ".kube/config
", and content include eks_use1d
:
locate ".kube/config" | xargs -i sh -c 'echo \\n{};cat {} | grep eks_use1d'
Easy.
(as of 2021)
Click your app, click App Information in the left side menu, scroll all the way down to the Additional Information section, click Remove App.
Boom. done.
It is due to OS
In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:
"scripts": {
"start": "node app.js",
"dev": "nodemon server.js",
"prod": "NODE_ENV=production & nodemon app.js"
}
For windows
Also set up your .env file variable having NODE_ENV=development
If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)
const dotenv = require('dotenv'); dotenv.config({ path: './config/config.env' });
Take the number 123.456789
Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..
you can simply write:
for item,i in zip(your_list, range(len(your_list)):
if type(item) == list:
print(f"{item} at index {i} is a list")
Check for any recusive calls for methods. Mainly it is caused when there is recursive call for a method. A simple example is
public static void main(String... args) {
Main main = new Main();
main.testMethod(1);
}
public void testMethod(int i) {
testMethod(i);
System.out.println(i);
}
Here the System.out.println(i); will be repeatedly pushed to stack when the testMethod is called.
The best way its add:
<ImageView
android:id="@+id/ivBack"
style="?attr/actionButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:src="@drawable/ic_back_arrow_black"
android:tint="@color/white" />
Try this after curl_exec to see what's the problem:
print curl_error($ch);
If it's print something like 'malformed' then check your URL format.
You can set the figure size if you explicitly create the figure with
plt.figure(figsize=(3,4))
You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff
No. You have 2 options:
DateTime date = DateTime.MinValue;
This works when you need to do something every X amount of time (since you will always be over MinValue
) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue
) if you are not careful.
And you can use Nullable
:
DateTime? date = null;
Which is nice and avoids most issues while introducing only 1 or 2.
It really depends on what you are trying to achieve.
When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware
and InitializingBean
. If they are found, the methods are invoked. E.g. (very simplified)
Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(ctx);
}
Note that in newer version it may be better to use annotations, rather than implementing spring-specific interfaces. Now you can simply use:
@Inject // or @Autowired
private ApplicationContext ctx;
If it helps anyone, here is what I got working in Python using the Python Requests library instead of CURL.
As explained by @staypuftman above, you will need your API Key and List ID from MailChimp and make sure your API Key suffix and URL prefix (i.e. us5) match.
Python:
#########################################################################################
# To add a single contact to MailChimp (using MailChimp v3.0 API), requires:
# + MailChimp API Key
# + MailChimp List Id for specific list
# + MailChimp API URL for adding a single new contact
#
# Note: the API URL has a 3/4 character location subdomain at the front of the URL string.
# It can vary depending on where you are in the world. To determine yours, check the last
# 3/4 characters of your API key. The API URL location subdomain must match API Key
# suffix e.g. us5, us13, us19 etc. but in this example, us5.
# (suggest you put the following 3 values in 'settings' or 'secrets' file)
#########################################################################################
MAILCHIMP_API_KEY = 'your-api-key-here-us5'
MAILCHIMP_LIST_ID = 'your-list-id-here'
MAILCHIMP_ADD_CONTACT_TO_LIST_URL = 'https://us5.api.mailchimp.com/3.0/lists/' + MAILCHIMP_LIST_ID + '/members/'
# Create new contact data and convert into JSON as this is what MailChimp expects in the API
# I've hardcoded some test data but use what you get from your form as appropriate
new_contact_data_dict = {
"email_address": "[email protected]", # 'email_address' is a mandatory field
"status": "subscribed", # 'status' is a mandatory field
"merge_fields": { # 'merge_fields' are optional:
"FNAME": "John",
"LNAME": "Smith"
}
}
new_contact_data_json = json.dumps(new_contact_data_dict)
# Create the new contact using MailChimp API using Python 'Requests' library
req = requests.post(
MAILCHIMP_ADD_CONTACT_TO_LIST_URL,
data=new_contact_data_json,
auth=('user', MAILCHIMP_API_KEY),
headers={"content-type": "application/json"}
)
# debug info if required - .text and .json also list the 'merge_fields' names for use in contact JSON above
# print req.status_code
# print req.text
# print req.json()
if req.status_code == 200:
# success - do anything you need to do
else:
# fail - do anything you need to do - but here is a useful debug message
mailchimp_fail = 'MailChimp call failed calling this URL: {0}\n' \
'Returned this HTTP status code: {1}\n' \
'Returned this response text: {2}' \
.format(req.url, str(req.status_code), req.text)
quux00's answer only tells about comparing basic types.
If you need to compare types you defined, you shouldn't use reflect.TypeOf(xxx)
. Instead, use reflect.TypeOf(xxx).Kind()
.
There are two categories of types:
Here is a full example:
type MyFloat float64
type Vertex struct {
X, Y float64
}
type EmptyInterface interface {}
type Abser interface {
Abs() float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (f MyFloat) Abs() float64 {
return math.Abs(float64(f))
}
var ia, ib Abser
ia = Vertex{1, 2}
ib = MyFloat(1)
fmt.Println(reflect.TypeOf(ia))
fmt.Println(reflect.TypeOf(ia).Kind())
fmt.Println(reflect.TypeOf(ib))
fmt.Println(reflect.TypeOf(ib).Kind())
if reflect.TypeOf(ia) != reflect.TypeOf(ib) {
fmt.Println("Not equal typeOf")
}
if reflect.TypeOf(ia).Kind() != reflect.TypeOf(ib).Kind() {
fmt.Println("Not equal kind")
}
ib = Vertex{3, 4}
if reflect.TypeOf(ia) == reflect.TypeOf(ib) {
fmt.Println("Equal typeOf")
}
if reflect.TypeOf(ia).Kind() == reflect.TypeOf(ib).Kind() {
fmt.Println("Equal kind")
}
The output would be:
main.Vertex
struct
main.MyFloat
float64
Not equal typeOf
Not equal kind
Equal typeOf
Equal kind
As you can see, reflect.TypeOf(xxx)
returns the direct types which you might want to use, while reflect.TypeOf(xxx).Kind()
returns the basic types.
Here's the conclusion. If you need to compare with basic types, use reflect.TypeOf(xxx).Kind()
; and if you need to compare with self-defined types, use reflect.TypeOf(xxx)
.
if reflect.TypeOf(ia) == reflect.TypeOf(Vertex{}) {
fmt.Println("self-defined")
} else if reflect.TypeOf(ia).Kind() == reflect.Float64 {
fmt.Println("basic types")
}