bmjohns -> You are my life saviour. That is the only working solution (With the AppUtility struct)
I've created this class:
class Helper{
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
/// OPTIONAL Added method to adjust lock and rotate to the desired orientation
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
}
and followed your instructions, and everything works perfectly for Swift 3 -> xcode version 8.2.1
Or you could just use this..
window.addEventListener("orientationchange", function() {
if (window.orientation == "90" || window.orientation == "-90") {
//Do stuff
}
}, false);
It is now possible with the HTML5 webapp manifest. See below.
Original answer:
You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.
You can detect the device orientation with CSS3 media queries like this:
@media screen and (orientation:portrait) {
// CSS applied when the device is in portrait mode
}
@media screen and (orientation:landscape) {
// CSS applied when the device is in landscape mode
}
Or by binding a JavaScript orientation change event like this:
document.addEventListener("orientationchange", function(event){
switch(window.orientation)
{
case -90: case 90:
/* Device is in landscape mode */
break;
default:
/* Device is in portrait mode */
}
});
Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.
As explained on html5rocks.com, you can now force the orientation mode using a manifest.json
file.
You need to include those line into the json file:
{
"display": "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
"orientation": "landscape", /* Could be "landscape" or "portrait" */
...
}
And you need to include the manifest into your html file like this:
<link rel="manifest" href="manifest.json">
Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
If the number matches than I am checking it's occur first time or not with help of "indexOf()" if the number matches first time then print and save into in a string so, that when the next time same number matches then it's won't print because due to "indexOf()" condition will be false.
class Intersection
{
public static void main(String[] args)
{
String s="";
int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};
for (int i = 0; i < array1.length; i++)
{
for (int j = 0; j < array2.length; j++)
{
char c=(char)(array1[i]);
if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
{
System.out.println("Common element is : "+(array1[i]));
s+=c;
}
}
}
}
}
There is a simple way to do it. I tried it on my app and it worked pretty well.
Just type: $text = $row["text"]; echo nl2br($text);
Copied from the author's post:
Use the -t
option to git remote add
, e.g.:
git remote add -t remote-branch remote-name remote-url
You can use multiple -t branch
options to grab multiple branches.
For those working in Anaconda in Windows, I had the same problem. Notepad++ help me to solve it.
Open the file in Notepad++. In the bottom right it will tell you the current file encoding. In the top menu, next to "View" locate "Encoding". In "Encoding" go to "character sets" and there with patiente look for the enconding that you need. In my case the encoding "Windows-1252" was found under "Western European"
In my case clicking the checkbox for 'import project into workspace' fixed the error, even though the project was already in the workspace folder and didn't actually get moved their by eclipse.
The debugger should automatically attach to the browser with Visual Studio 2012. You can use the debugger
keyword to halt at a certain point in the application or use the breakpoints
directly inside VS.
You can also detatch the default debugger in Visual Studio and use the Developer Tools which come pre loaded with Internet Explorer or FireBug etc.
To do this goto Visual Studio
-> Debug
-> Detatch All
and then click Start debugging in Internet Explorer
. You can then set breakpoints at this level.
public class X { static {
System.out.println("Main not required to print this");
System.exit(0);
}}
Run from the cmdline with java X
.
That works too:
document.querySelector([attribute="value"]);
So:
document.querySelector([data-foo="bar"]);
Look carefully how many brackets does your array have. I met an example when function returned answer with extra bracket, like that:
>>>approx
array([[[1192, 391]],
[[1191, 409]],
[[1209, 438]],
[[1191, 409]]])
And this didn't work
>>> approx[1,1]
IndexError: index 1 is out of bounds for axis 1 with size 1
This could open the brackets:
>>> approx[:,0]
array([[1192, 391],
[1191, 409],
[1209, 438],
[1191, 409]])
Now it is possible to use an ordinary element access notation:
>>> approx[:,0][1,1]
409
The first bin in the FFT is DC (0 Hz), the second bin is Fs / N
, where Fs
is the sample rate and N
is the size of the FFT. The next bin is 2 * Fs / N
. To express this in general terms, the nth bin is n * Fs / N
.
So if your sample rate, Fs
is say 44.1 kHz and your FFT size, N
is 1024, then the FFT output bins are at:
0: 0 * 44100 / 1024 = 0.0 Hz
1: 1 * 44100 / 1024 = 43.1 Hz
2: 2 * 44100 / 1024 = 86.1 Hz
3: 3 * 44100 / 1024 = 129.2 Hz
4: ...
5: ...
...
511: 511 * 44100 / 1024 = 22006.9 Hz
Note that for a real input signal (imaginary parts all zero) the second half of the FFT (bins from N / 2 + 1
to N - 1
) contain no useful additional information (they have complex conjugate symmetry with the first N / 2 - 1
bins). The last useful bin (for practical aplications) is at N / 2 - 1
, which corresponds to 22006.9 Hz in the above example. The bin at N / 2
represents energy at the Nyquist frequency, i.e. Fs / 2
( = 22050 Hz in this example), but this is in general not of any practical use, since anti-aliasing filters will typically attenuate any signals at and above Fs / 2
.
src
folder which is immediately inside the project's folder.
Note the hollow 'J' in the image. That indicates that the file is not part of a project.
This is what I was looking for when googling this:
[{a: 1}, {b: 2}].reduce({}) { |h, v| h.merge v }
=> {:a=>1, :b=>2}
You might consider referencing the actual date/time in the source column for Quote_Month
, then you could transform your OR
into a couple of AND
s, something like (assuing the date's in something I've chosen to call Quote_Date
)
=SUMIFS(Quote_Value,"<=90",Quote_Date,">="&DATE(2013,11,1),Quote_Date,"<="&DATE(2013,12,31),Salesman,"=JBloggs",Days_To_Close)
(I moved the interesting conditions to the front).
This approach works here because that "OR" condition is actually specifying a date range - it might not work in other cases.
Usually in Linux you use crontab
for this kind of scduled tasks. But you have to specify the time when you "setup the timer" - so if you want it to be configurable in the file itself, you will have to create some mechanism to do that.
But in general, you would use for example:
30 1 * * 5 /path/to/script/script.sh
Would execute the script every Friday at 1:30 (AM) Here:
30
is minutes
1
is hour
next 2 *'s are day of month
and month
(in that order) and 5
is weekday
you may use the below code it works fine with swift 3
var preferredLanguage : String = Bundle.main.preferredLocalizations.first!
Did you try with strip() :
listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]
>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']
"before" by default implies before(:each)
. Ref The Rspec Book, copyright 2010, page 228.
before(scope = :each, options={}, &block)
I use before(:each)
to seed some data for each example group without having to call the let
method to create the data in the "it" block. Less code in the "it" block in this case.
I use let
if I want some data in some examples but not others.
Both before and let are great for DRYing up the "it" blocks.
To avoid any confusion, "let" is not the same as before(:all)
. "Let" re-evaluates its method and value for each example ("it"), but caches the value across multiple calls in the same example. You can read more about it here: https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let
This is adapted from CodesInChaos's extension method. The name is shorter (NotNull
) and more importantly, restricts the type (T
) to reference types with where T : class
.
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> source) where T : class
{
return source.Where(item => item != null);
}
White background is caused because of the Android starts while the app loads on memory, and it can be avoided if you just add this 2 line of code under SplashTheme.
<item name="android:windowDisablePreview">true</item>
<item name="android:windowIsTranslucent">true</item>
if you want the original style of your Ui to remain and the title bar to be removed with no effect on that, you have to remove the title bar in your activity rather than the manifest. leave the original theme style that you had in the manifest and in each activity that you want no title bar use this.requestWindowFeature(Window.FEATURE_NO_TITLE);
in the oncreate()
method before setcontentview()
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_signup);
...
}
You can do it server-side with nodejs.
Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!
The following example uses SES transport (Amazon SES):
let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
SES: new aws.SES({ apiVersion: "2010-12-01" })
});
Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.
It must be at least 64 bits. Other than that it's implementation defined.
Strictly speaking, unsigned long long
isn't standard in C++ until the C++0x standard. unsigned long long
is a 'simple-type-specifier' for the type unsigned long long int
(so they're synonyms).
The long long
set of types is also in C99 and was a common extension to C++ compilers even before being standardized.
Try gnuplot. It has very powerful graphing possibilities.
It can output to your terminal in the following way:
gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)
1 ++----------------**---------------+----**-----------+--------**-----++
+ *+ * + * * + sin(x) ****** +
0.8 ++ * * * * * * ++
| * * * * * * |
0.6 ++ * * * * * * ++
* * * * * * * |
0.4 +* * * * * * * ++
|* * * * * * * |
0.2 +* * * * * * * ++
| * * * * * * * |
0 ++* * * * * * *++
| * * * * * * *|
-0.2 ++ * * * * * * *+
| * * * * * * *|
-0.4 ++ * * * * * * *+
| * * * * * * *
-0.6 ++ * * * * * * ++
| * * * * * * |
-0.8 ++ * * * * * * ++
+ * * + * * + * * +
-1 ++-----**---------+----------**----+---------------**+---------------++
-10 -5 0 5 10
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
1 ) Copy the initialAdminPassword in Specified path.
2 ) Login with following Credentials
User Name : admin
Password : <da12906084fd405090a9fabfd66342f0>
3 ) Once you login into the jenkins application you can click on admin profile and reset the password.
You can go to jwt.io
, paste your token and read the contents. This is jarring for a lot of people initially.
The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.
The logical question is what is the motivation for not concerning itself with encrypted contents?
The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure
(is not transmitted via HTTP, only via HTTPS) and httpOnly
(can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.
This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).
JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.
It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.
Here's my adaptation of Ates Goral's answer using C++11. I've added the lambda in here, but the principle is that you could pass it in and thereby control what characters your string contains:
std::string random_string( size_t length )
{
auto randchar = []() -> char
{
const char charset[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[ rand() % max_index ];
};
std::string str(length,0);
std::generate_n( str.begin(), length, randchar );
return str;
}
Here is an example of passing in a lambda to the random string function: http://ideone.com/Ya8EKf
Why would you use C++11?
For example:
#include <iostream>
#include <vector>
#include <random>
#include <functional> //for std::function
#include <algorithm> //for std::generate_n
typedef std::vector<char> char_array;
char_array charset()
{
//Change this to suit
return char_array(
{'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E','F',
'G','H','I','J','K',
'L','M','N','O','P',
'Q','R','S','T','U',
'V','W','X','Y','Z',
'a','b','c','d','e','f',
'g','h','i','j','k',
'l','m','n','o','p',
'q','r','s','t','u',
'v','w','x','y','z'
});
};
// given a function that generates a random character,
// return a string of the requested length
std::string random_string( size_t length, std::function<char(void)> rand_char )
{
std::string str(length,0);
std::generate_n( str.begin(), length, rand_char );
return str;
}
int main()
{
//0) create the character set.
// yes, you can use an array here,
// but a function is cleaner and more flexible
const auto ch_set = charset();
//1) create a non-deterministic random number generator
std::default_random_engine rng(std::random_device{}());
//2) create a random number "shaper" that will give
// us uniformly distributed indices into the character set
std::uniform_int_distribution<> dist(0, ch_set.size()-1);
//3) create a function that ties them together, to get:
// a non-deterministic uniform distribution from the
// character set of your choice.
auto randchar = [ ch_set,&dist,&rng ](){return ch_set[ dist(rng) ];};
//4) set the length of the string you want and profit!
auto length = 5;
std::cout<<random_string(length,randchar)<<std::endl;
return 0;
}
The logic applies to many other objectives. And how to read .sh_history of each user from /home/ filesystem? What if there are thousand of them?
#!/bin/ksh
last |head -10|awk '{print $1}'|
while IFS= read -r line
do
su - "$line" -c 'tail .sh_history'
done
Here is the script https://github.com/imvieira/SysAdmin_DevOps_Scripts/blob/master/get_and_run.sh
Use Location Listener Method
@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}
My guess is that you've got something in method1
which wraps one exception in another, and uses the toString()
of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.
Here's a short but complete program which demonstrates RuntimeException.getMessage()
behaving correctly:
public class Test {
public static void main(String[] args) {
try {
failingMethod();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private static void failingMethod() {
throw new RuntimeException("Just the message");
}
}
Output:
Error: Just the message
As a quick and very scoped solution:
Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.
When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.
There are several options... assuming you found your TD by var td = document.getElementyById('myTD_ID');
you can do:
td.innerHTML = "mytext";
td.textContent= "mytext";
td.innerText= "mytext";
- this one may not work outside IE? Not sure
Use firstChild or children array as previous poster noted.
If it's just the text that needs to be changed, textContent is faster and less prone to XSS attacks (https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent)
Everything you need here can be found in this quickstart guide.
A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d
or [A-Za-z]{2}\d{6}
.
If you want to accept only capital letters then replace [A-Za-z]
with [A-Z]
.
I have been able to ping from VMs and the host by setting the VM's network settings to "Bridged" mode. This, in short, places them all on the same physical network. This coupled with your static IP addresses should do the trick.
I try this it solved.
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setCancelable(true);
builder.setTitle("Opss!!");
builder.setMessage("You Don't have anough coins to withdraw. ");
builder.setMessage("Please read the Withdraw rules.");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("OK",
(dialog, which) -> dialog.dismiss());
builder.create().show();
You can also write it like this:
let elem: any;
elem = $("div.printArea");
elem.printArea();
If you initialize both the parameters as float
, you will sure get actual divided value.
For example:
float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;
Ans:17.75.
From Typescript 3.7 on, you can also use nullish coalescing:
let x = foo ?? bar();
Which is the equivalent for checking for null or undefined:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
While not exactly the same, you could write your code as:
var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
In flutter if you want to do conditional rendering, you may do this:
Column(
children: <Widget>[
if (isCondition == true)
Text('The condition is true'),
],
);
But what if you want to use a tertiary (if-else) condition? when the child widget is multi-layered.
You can use this for its solution flutter_conditional_rendering a flutter package which enhances conditional rendering, supports if-else and switch conditions.
If-Else condition:
Column(
children: <Widget>[
Conditional.single(
context: context,
conditionBuilder: (BuildContext context) => someCondition == true,
widgetBuilder: (BuildContext context) => Text('The condition is true!'),
fallbackBuilder: (BuildContext context) => Text('The condition is false!'),
),
],
);
Switch condition:
Column(
children: <Widget>[
ConditionalSwitch.single<String>(
context: context,
valueBuilder: (BuildContext context) => 'A',
caseBuilders: {
'A': (BuildContext context) => Text('The value is A!'),
'B': (BuildContext context) => Text('The value is B!'),
},
fallbackBuilder: (BuildContext context) => Text('None of the cases matched!'),
),
],
);
If you want to conditionally render a list of widgets (List<Widget>)
instead of a single one. Use Conditional.list()
and ConditionalSwitch.list()!
System.out.println("I\nam\na\nboy");
System.out.println("I am a boy".replaceAll("\\s+","\n"));
System.out.println("I am a boy".replaceAll("\\s+",System.getProperty("line.separator"))); // portable way
for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked
s = "ABCD"
from array import array
a = array("B", s)
Why not do string suppression with triple quotes:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
The methods in some of the other answers that use a regular expression do not cover all cases, particularly:
The following method handles these cases:
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^$(){}|\[\]\/\\])/g, '\\$1'); }
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
This will return null
if the cookie is not found. It will return an empty string if the value of the cookie is empty.
Notes:
document.cookie
- When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn are name=value
pairs. There appears to be a single space after each semicolon.String.prototype.match()
- Returns null
when no match is found. Returns an array when a match is found, and the element at index [1]
is the value of the first matching group.Regular Expression Notes:
(?:xxxx)
- forms a non-matching group.^
- matches the start of the string.|
- separates alternative patterns for the group.;\\s*
- matches one semi-colon followed by zero or more whitespace characters.=
- matches one equal sign.(xxxx)
- forms a matching group.[^;]*
- matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.Try to re-import the Maven project. Also make sure that the project directory name is not excluded in Settings | File Types | Ignore Files and Folders
.
For Python2 WIN10 Users:
1.Uninstall python thoroughly ,include all folders.
2.Fetch and install the lastest python-2.7.msi (ver 2.7.15)
3.After step 2,you may find pip had been installed too.
4.Now ,if your system'env haven't been changed,you can use pip to install packages now.The "tlsv1 alert protocol version" will not appear.
There is more than one library for working in C++ in Android programming:
-- Step 1: Create temp table. create table Billing ( TAP_ID char(10), ACCT_NUM char(10));
SELECT * FROM BILLING;
-- Step 2: Create Control file.
load data infile IN_DATA.txt into table Billing fields terminated by ',' (TAP_ID, ACCT_NUM)
-- Step 3: Create input data file. IN_DATA.txt file content: 100,15678966
-- Step 4: Execute command from run: .. client\bin>sqlldr username@db-sis__id/password control='Billing.ctl'
I was having the same problem using Tomcat 6.0 and Eclipse and I tried out something which my friend suggested and it worked for me. The link for the question I asked and my reply commented can be found here:
JSTL Tomcat 6.0 Cannot find the taglib descriptor Error
Let me know if this solves your "Cannot find the taglibrary descriptor" problem.
While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:
for key, value in Dictionary.items():
print(key, value)
Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:
stringified_dictionary = {}
for key, value in Dictionary.items():
stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary
This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.
JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.
I had to replace new lines with br
string newString = oldString.Replace("\n", "<br />");
or if you use xml
<asp:Label ID="Label1" runat="server" Text='<%# ShowLineBreaks(Eval("Comments")) %>'></asp:Label>
Then in code behind
public string ShowLineBreaks(object text)
{
return (text.ToString().Replace("\n", "<br/>"));
}
There are many good answers here, so let me offer another way to look at it...
There is no overkill when you are coding. It doesn't cost you anything to type @override, but the savings can be immense if you misspelled a method name or got the signature slightly wrong.
Think about it this way: In the time you navigated here and typed this post, you pretty much used more time than you will spend typing @override for the rest of your life; but one error it prevents can save you hours.
Java does all it can to make sure you didn't make any mistakes at edit/compile time, this is a virtually free way to solve an entire class of mistakes that aren't preventable in any other way outside of comprehensive testing.
Could you come up with a better mechanism in Java to ensure that when the user intended to override a method, he actually did?
Another neat effect is that if you don't provide the annotation it will warn you at compile time that you accidentally overrode a parent method--something that could be significant if you didn't intend to do it.
Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:
polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)
Notes
The validity of this approach will depend on your objectives, the assumptions of optimize()
and AIC()
and if AIC is the criterion that you want to use,
polyfit()
may not have a single minimum. check this with something like:
for (i in 2:length(x)-1) print(polyfit(i))
I used the as.integer()
function because it is not clear to me how I would interpret a non-integer polynomial.
for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here
Update
Also see the stepAIC
function (in the MASS package) to automate model selection.
If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py
to get it recognized as a directory.
In your script, include import sys
and sys.path
, you will be able to see all the paths available to Python. You must be able to see your current working directory.
Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc
and now you can use the methods in that module.
As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction
. On the right my console shows that after execution of sys.path
, I can see my working directory.
I made a small script to see not only who is listening where but also to display established connections and to which countries. Works on OSX Siera
#!/bin/bash
printf "\nchecking established connections\n\n"
for i in $(sudo lsof -i -n -P | grep TCP | grep ESTABLISHED | grep -v IPv6 |
grep -v 127.0.0.1 | cut -d ">" -f2 | cut -d " " -f1 | cut -d ":" -f1); do
printf "$i : " & curl freegeoip.net/xml/$i -s -S | grep CountryName |
cut -d ">" -f2 | cut -d"<" -f1
done
printf "\ndisplaying listening ports\n\n"
sudo lsof -i -n -P | grep TCP | grep LISTEN | cut -d " " -f 1,32-35
#EOF
Sample output
checking established connections
107.178.244.155 : United States
17.188.136.186 : United States
17.252.76.19 : United States
17.252.76.19 : United States
17.188.136.186 : United States
5.45.62.118 : Netherlands
40.101.42.66 : Ireland
151.101.1.69 : United States
173.194.69.188 : United States
104.25.170.11 : United States
5.45.62.49 : Netherlands
198.252.206.25 : United States
151.101.1.69 : United States
34.198.53.220 : United States
198.252.206.25 : United States
151.101.129.69 : United States
91.225.248.133 : Ireland
216.58.212.234 : United States
displaying listening ports
mysqld TCP *:3306 (LISTEN)
com.avast TCP 127.0.0.1:12080 (LISTEN)
com.avast TCP [::1]:12080 (LISTEN)
com.avast TCP 127.0.0.1:12110 (LISTEN)
com.avast TCP [::1]:12110 (LISTEN)
com.avast TCP 127.0.0.1:12143 (LISTEN)
com.avast TCP [::1]:12143 (LISTEN)
com.avast TCP 127.0.0.1:12995 (LISTEN)
com.avast [::1]:12995 (LISTEN)
com.avast 127.0.0.1:12993 (LISTEN)
com.avast [::1]:12993 (LISTEN)
Google TCP 127.0.0.1:34013 (LISTEN)
This may be useful to check if you are connected to north-korea! ;-)
I had the same problem. The solution was to update IntelliJ to the newest version.
You can use finds null separated output option with read to iterate over directory structures safely.
#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file;
do echo "$file" ;
done
So for your case
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done
additionally
#!/bin/bash
while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done < <(find . -maxdepth 1 -type f -print0)
will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed
In his excellent answer, StuartLC cites an answer to a related question and mentions that placing newlines inside the {expression}
of an interpolated string "looks odd." Most would agree, but the unpleasant source code effect can be mitigated somewhat--and without any runtime consequences--by using dedicated {expression}
blocks which resolve to default(String)
, that is, null
(and specifically not String.Empty
).
The (albeit minor) point is to not mess-up or pollute your actual expression content, by instead using a dedicated token for this purpose. So if you declare a constant, for example:
const String more = null;
...then a line which might be too long to look at in source code, such as...
var s1 = $"one: {99 + 1} two: {99 + 2} three: {99 + 3} four: {99 + 4} five: {99 + 5} six: {99 + 6}";
...can be instead written like this.
var s2 = $@"{more
}one: {99 + 1} {more
}two: {99 + 2} {more
}three: {99 + 3} {more
}four: {99 + 4} {more
}five: {99 + 5} {more
}six: {99 + 6}";
Or perhaps you prefer a different "odd" approach to the same thing:
// elsewhere:
public const String ? = null; // Unicode '\u039E', Greek 'Capital Letter Xi'
// anywhere:
var s3 = $@"{
?}one: {99 + 1} {
?}two: {99 + 2} {
?}three: {99 + 3} {
?}four: {99 + 4} {
?}five: {99 + 5} {
?}six: {99 + 6}";
Actually, it looks like we can also do it without a continuation symbol:
var s4 = $@"one: {99 + 1
}two: {99 + 2
}three: {99 + 3
}four: {99 + 4
}five: {99 + 5
}six: {99 + 6}";
All four examples produce the same string
at runtime, which in this case is all on a single line:
one: 100 two: 101 three: 102 four: 103 five: 104 six: 105
As Stuart suggested, IL performance is preserved in both these examples by not using +
to concatenate strings. Although the longer format string in my new example is indeed stored in the IL, and thus your executable, the null placeholders it references are not initialized, and there are no excess concatenations or function calls at runtime. For comparison, here is the IL for the above two examples.
IL for first example
ldstr "one: {0} two: {1} three: {2} four: {3} five: {4} six: {5}"
ldc.i4.6
newarr object
dup
ldc.i4.0
ldc.i4.s 100
box int32
stelem.ref
dup
ldc.i4.1
ldc.i4.s 101
box int32
stelem.ref
dup
ldc.i4.2
ldc.i4.s 102
box int32
stelem.ref
dup
ldc.i4.3
ldc.i4.s 103
box int32
stelem.ref
dup
ldc.i4.4
ldc.i4.s 104
box int32
stelem.ref
dup
ldc.i4.5
ldc.i4.s 105
box int32
stelem.ref
call string string::Format(string, object[])
IL for second example
ldstr "{0}one: {1} {2}two: {3} {4}three: {5} {6}four: {7} {8}five: {9} {10}six: {11}"
ldc.i4.s 12
newarr object
dup
ldc.i4.1
ldc.i4.s 100
box int32
stelem.ref
dup
ldc.i4.3
ldc.i4.s 101
box int32
stelem.ref
dup
ldc.i4.5
ldc.i4.s 102
box int32
stelem.ref
dup
ldc.i4.7
ldc.i4.s 103
box int32
stelem.ref
dup
ldc.i4.s 9
ldc.i4.s 104
box int32
stelem.ref
dup
ldc.i4.s 11
ldc.i4.s 105
box int32
stelem.ref
call string string::Format(string, object[])
Floating it will reorganise the flow but position: absolute is the only way to completely remove it from the flow of the document.
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
instanceof is very efficient, so your performance is unlikely to suffer. However, using lots of instanceof suggests a design issue.
If you can use xClass == String.class, this is faster. Note: you don't need instanceof for final classes.
If you git stash pop
(with no conflicts) it will remove the stash after it is applied. But if you git stash apply
it will apply the patch without removing it from the stash list. Then you can revert the unwanted changes with git checkout -- files...
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
/* for chrome */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;}
/* for mozilla */
input[type=number] {-moz-appearance: textfield;}
Use a BOM to solve version issues.
you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.
To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>3.2.12.RELEASE</version>
<type>pom</type>
</dependency>
Can you provide more details about what you are trying to do? In general, if you have a unicode string, you can use encode to convert it into string with appropriate encoding. Eg:
>>> a = u"\u00E1"
>>> type(a)
<type 'unicode'>
>>> a.encode('utf-8')
'\xc3\xa1'
>>> a.encode('latin-1')
'\xe1'
(The approach of the better_enums library)
There is a way to do enum to string in current C++ that looks like this:
ENUM(Channel, char, Red = 1, Green, Blue)
// "Same as":
// enum class Channel : char { Red = 1, Green, Blue };
Usage:
Channel c = Channel::_from_string("Green"); // Channel::Green (2)
c._to_string(); // string "Green"
for (Channel c : Channel::_values())
std::cout << c << std::endl;
// And so on...
All operations can be made constexpr
. You can also implement the C++17 reflection proposal mentioned in the answer by @ecatmur.
#
) is the only way to convert a token to a string in current C++.constexpr
. It can also be made to work with C++98 + __VA_ARGS__
. It is definitely modern C++.The macro's definition is somewhat involved, so I'm answering this in several ways.
It is straightforward to extend this answer to the features of the library – nothing "important" is left out here. It is, however, quite tedious, and there are compiler portability concerns.
Disclaimer: I am the author of both the CodeProject article and the library.
You can try the code in this answer, the library, and the implementation of N4428 live online in Wandbox. The library documentation also contains an overview of how to use it as N4428, which explains the enums portion of that proposal.
The code below implements conversions between enums and strings. However, it can be extended to do other things as well, such as iteration. This answer wraps an enum in a struct
. You can also generate a traits struct
alongside an enum instead.
The strategy is to generate something like this:
struct Channel {
enum _enum : char { __VA_ARGS__ };
constexpr static const Channel _values[] = { __VA_ARGS__ };
constexpr static const char * const _names[] = { #__VA_ARGS__ };
static const char* _to_string(Channel v) { /* easy */ }
constexpr static Channel _from_string(const char *s) { /* easy */ }
};
The problems are:
{Red = 1, Green, Blue}
as the initializer for the values array. This is not valid C++, because Red
is not an assignable expression. This is solved by casting each constant to a type T
that has an assignment operator, but will drop the assignment: {(T)Red = 1, (T)Green, (T)Blue}
.{"Red = 1", "Green", "Blue"}
as the initializer for the names array. We will need to trim off the " = 1"
. I am not aware of a great way to do this at compile time, so we will defer this to run time. As a result, _to_string
won't be constexpr
, but _from_string
can still be constexpr
, because we can treat whitespace and equals signs as terminators when comparing with untrimmed strings.__VA_ARGS__
. This is pretty standard. This answer includes a simple version that can handle up to 8 elements.constexpr
(or just const
) arrays at namespace scope, or regular arrays in non-constexpr
static inline functions. The code in this answer is for C++11 and takes the former approach. The CodeProject article is for C++98 and takes the latter.#include <cstddef> // For size_t.
#include <cstring> // For strcspn, strncpy.
#include <stdexcept> // For runtime_error.
// A "typical" mapping macro. MAP(macro, a, b, c, ...) expands to
// macro(a) macro(b) macro(c) ...
// The helper macro COUNT(a, b, c, ...) expands to the number of
// arguments, and IDENTITY(x) is needed to control the order of
// expansion of __VA_ARGS__ on Visual C++ compilers.
#define MAP(macro, ...) \
IDENTITY( \
APPLY(CHOOSE_MAP_START, COUNT(__VA_ARGS__)) \
(macro, __VA_ARGS__))
#define CHOOSE_MAP_START(count) MAP ## count
#define APPLY(macro, ...) IDENTITY(macro(__VA_ARGS__))
#define IDENTITY(x) x
#define MAP1(m, x) m(x)
#define MAP2(m, x, ...) m(x) IDENTITY(MAP1(m, __VA_ARGS__))
#define MAP3(m, x, ...) m(x) IDENTITY(MAP2(m, __VA_ARGS__))
#define MAP4(m, x, ...) m(x) IDENTITY(MAP3(m, __VA_ARGS__))
#define MAP5(m, x, ...) m(x) IDENTITY(MAP4(m, __VA_ARGS__))
#define MAP6(m, x, ...) m(x) IDENTITY(MAP5(m, __VA_ARGS__))
#define MAP7(m, x, ...) m(x) IDENTITY(MAP6(m, __VA_ARGS__))
#define MAP8(m, x, ...) m(x) IDENTITY(MAP7(m, __VA_ARGS__))
#define EVALUATE_COUNT(_1, _2, _3, _4, _5, _6, _7, _8, count, ...) \
count
#define COUNT(...) \
IDENTITY(EVALUATE_COUNT(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1))
// The type "T" mentioned above that drops assignment operations.
template <typename U>
struct ignore_assign {
constexpr explicit ignore_assign(U value) : _value(value) { }
constexpr operator U() const { return _value; }
constexpr const ignore_assign& operator =(int dummy) const
{ return *this; }
U _value;
};
// Prepends "(ignore_assign<_underlying>)" to each argument.
#define IGNORE_ASSIGN_SINGLE(e) (ignore_assign<_underlying>)e,
#define IGNORE_ASSIGN(...) \
IDENTITY(MAP(IGNORE_ASSIGN_SINGLE, __VA_ARGS__))
// Stringizes each argument.
#define STRINGIZE_SINGLE(e) #e,
#define STRINGIZE(...) IDENTITY(MAP(STRINGIZE_SINGLE, __VA_ARGS__))
// Some helpers needed for _from_string.
constexpr const char terminators[] = " =\t\r\n";
// The size of terminators includes the implicit '\0'.
constexpr bool is_terminator(char c, size_t index = 0)
{
return
index >= sizeof(terminators) ? false :
c == terminators[index] ? true :
is_terminator(c, index + 1);
}
constexpr bool matches_untrimmed(const char *untrimmed, const char *s,
size_t index = 0)
{
return
is_terminator(untrimmed[index]) ? s[index] == '\0' :
s[index] != untrimmed[index] ? false :
matches_untrimmed(untrimmed, s, index + 1);
}
// The macro proper.
//
// There are several "simplifications" in this implementation, for the
// sake of brevity. First, we have only one viable option for declaring
// constexpr arrays: at namespace scope. This probably should be done
// two namespaces deep: one namespace that is likely to be unique for
// our little enum "library", then inside it a namespace whose name is
// based on the name of the enum to avoid collisions with other enums.
// I am using only one level of nesting.
//
// Declaring constexpr arrays inside the struct is not viable because
// they will need out-of-line definitions, which will result in
// duplicate symbols when linking. This can be solved with weak
// symbols, but that is compiler- and system-specific. It is not
// possible to declare constexpr arrays as static variables in
// constexpr functions due to the restrictions on such functions.
//
// Note that this prevents the use of this macro anywhere except at
// namespace scope. Ironically, the C++98 version of this, which can
// declare static arrays inside static member functions, is actually
// more flexible in this regard. It is shown in the CodeProject
// article.
//
// Second, for compilation performance reasons, it is best to separate
// the macro into a "parametric" portion, and the portion that depends
// on knowing __VA_ARGS__, and factor the former out into a template.
//
// Third, this code uses a default parameter in _from_string that may
// be better not exposed in the public interface.
#define ENUM(EnumName, Underlying, ...) \
namespace data_ ## EnumName { \
using _underlying = Underlying; \
enum { __VA_ARGS__ }; \
\
constexpr const size_t _size = \
IDENTITY(COUNT(__VA_ARGS__)); \
\
constexpr const _underlying _values[] = \
{ IDENTITY(IGNORE_ASSIGN(__VA_ARGS__)) }; \
\
constexpr const char * const _raw_names[] = \
{ IDENTITY(STRINGIZE(__VA_ARGS__)) }; \
} \
\
struct EnumName { \
using _underlying = Underlying; \
enum _enum : _underlying { __VA_ARGS__ }; \
\
const char * _to_string() const \
{ \
for (size_t index = 0; index < data_ ## EnumName::_size; \
++index) { \
\
if (data_ ## EnumName::_values[index] == _value) \
return _trimmed_names()[index]; \
} \
\
throw std::runtime_error("invalid value"); \
} \
\
constexpr static EnumName _from_string(const char *s, \
size_t index = 0) \
{ \
return \
index >= data_ ## EnumName::_size ? \
throw std::runtime_error("invalid identifier") : \
matches_untrimmed( \
data_ ## EnumName::_raw_names[index], s) ? \
(EnumName)(_enum)data_ ## EnumName::_values[ \
index] : \
_from_string(s, index + 1); \
} \
\
EnumName() = delete; \
constexpr EnumName(_enum value) : _value(value) { } \
constexpr operator _enum() const { return (_enum)_value; } \
\
private: \
_underlying _value; \
\
static const char * const * _trimmed_names() \
{ \
static char *the_names[data_ ## EnumName::_size]; \
static bool initialized = false; \
\
if (!initialized) { \
for (size_t index = 0; index < data_ ## EnumName::_size; \
++index) { \
\
size_t length = \
std::strcspn(data_ ## EnumName::_raw_names[index],\
terminators); \
\
the_names[index] = new char[length + 1]; \
\
std::strncpy(the_names[index], \
data_ ## EnumName::_raw_names[index], \
length); \
the_names[index][length] = '\0'; \
} \
\
initialized = true; \
} \
\
return the_names; \
} \
};
and
// The code above was a "header file". This is a program that uses it.
#include <iostream>
#include "the_file_above.h"
ENUM(Channel, char, Red = 1, Green, Blue)
constexpr Channel channel = Channel::_from_string("Red");
int main()
{
std::cout << channel._to_string() << std::endl;
switch (channel) {
case Channel::Red: return 0;
case Channel::Green: return 1;
case Channel::Blue: return 2;
}
}
static_assert(sizeof(Channel) == sizeof(char), "");
The program above prints Red
, as you would expect. There is a degree of type safety, since you can't create an enum without initializing it, and deleting one of the cases from the switch
will result in a warning from the compiler (depending on your compiler and flags). Also, note that "Red"
was converted to an enum during compilation.
It should work fine, are you wrapping the code in a $(document).ready()
call? If not use that or use live
i.e.
$('#fileupload1').live('change', function(){
alert("hola");
});
Here is a jsFiddle of this working against jQuery 1.4.4
Also had this issue, This array was out of range:
order: [1, 'asc'],
I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm
as well as specifying norm
as an argument to scatter
and colorbar
. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list
.
Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1
, e.g., has 9 easily distinguishable colors, and tab20
could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.
import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)
which produces the image below. The n
in the call to Set1
specifies
the first n
colors of that colormap, and the last n
in the call to from_list
specifies to construct a map with n
colors (the default being 256). In order to set cm
as the default colormap with plt.set_cmap
, I found it to be necessary to give it a name and register it, viz:
cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)
SqlConnection conn = new SqlConnection(@"Data Source=TOM-PC\sqlexpress;Initial Catalog=Northwind;User ID=sa;Password=xyz") ;
conn.Open();
SqlCommand sc = new SqlCommand("select customerid,contactname from customers", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("customerid", typeof(string));
dt.Columns.Add("contactname", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "customerid";
comboBox1.DisplayMember = "contactname";
comboBox1.DataSource = dt;
conn.Close();
Here's a version for knockout.js
based on the accepted answer:
Important: It does actually require jQuery too for the replacing, but I thought it may be useful to some.
ko.bindingHandlers.svgConvert =
{
'init': function ()
{
return { 'controlsDescendantBindings': true };
},
'update': function (element, valueAccessor, allBindings, viewModel, bindingContext)
{
var $img = $(element);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
$.get(imgURL, function (data)
{
// Get the SVG tag, ignore the rest
var $svg = $(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined')
{
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined')
{
$svg = $svg.attr('class', imgClass + ' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
}
};
Then just apply data-bind="svgConvert: true"
to your img tag.
This solution completely replaces the img
tag with a SVG and any additional bindings would not be respected.
<?php
function current_url()
{
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
return $validURL;
}
//echo "page URL is : ".current_url();
$offer_url = current_url();
?>
<?php
if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>
<?php
}
?>
You need to set up a local repository that will host such libraries. There are a number of projects that do exactly that. For example Artifactory.
myvariable = 4
mystring = str(myvariable) # '4'
also, alternatively try repr:
mystring = repr(myvariable) # '4'
This is called "conversion" in python, and is quite common.
As addition to other answers, one can write something else if variable is None like this:
{{ variable or '' }}
Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like
Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.
Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.
Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.
HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.
If we go into more detail, then answer to this question go longer. We can understand more from following posts:
Try:
<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>
Use the "Display" style attribute with your bool model attribute to define the div's visibility.
Download HAXM from SDK Manager
Open your SDK Manager from Android Studio, click the icon shown in the screen shot.
Click on "Launch Standalone SDK Manager" on the "Default Settings" Dialog.
Check node "Extras > Intel x86 Emulator Accelerator (HAXM installer)" and proceed with HAXM download.
Installing or Modifying HAXM
You can now access with installation (or modifying existing installtino) of HAXM by accessing the download location. Enter this path in "run"
%localappdata%\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager
and double click the file "intelhaxm-android.exe"
You can increase the size of memory allocated to HAXM while modifying existing HAXM install. I have a machine with 32 GB of RAM and would like to launch multiple AVDs at same time (for automated testing etc.) so I have allocated 8 GB to HAXM.
Caveat
If you are running one AVD of one 1 GB and allocated 2 GB to HAXM, you cannot run another AVD with RAM more than 1 GB. Please make sure that Android Device Monitor is not running when you are modifying or installing HAXM (just to avoid any suprises).
These steps are tested on Windows platform, but generally could be applied to other platforms too with slight modification.
Great answer Sohnee. Would like to add that if you have an array of objects and you wish to sort by key then its almost the same, this is an example of one that can sort by both date(number) or title(string):
if (sortBy === 'date') {
return n1.date - n2.date
} else {
if (n1.title > n2.title) {
return 1;
}
if (n1.title < n2.title) {
return -1;
}
return 0;
}
Could also make the values inside as variables n1[field] vs n2[field] if its more dynamic, just keep the diff between strings and numbers.
The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.
This is the answer that worked for me:
foreach (var x in jobj)
{
var key = ((JProperty) (x)).Name;
var jvalue = ((JProperty)(x)).Value ;
}
Seems like you could also do this:
__dirname=fs.realpathSync('.');
of course, dont forget fs=require('fs')
(it's not really global in node scripts exactly, its just defined on the module level)
I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1
let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)
In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by
let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)
And in VC2, when close the view controller, as usual we can use:
self.dismiss(animated: true, completion: nil)
To clear the SQL window you can use:
clear screen;
which can also be shortened to
cl scr;
If anyone is still looking for the easiest solution, set the following attribute to true
on your parent layout
android:focusableInTouchMode="true"
Example:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true">
.......
......
</android.support.constraint.ConstraintLayout>
As of 2016, you're supposed to use Array.findIndex
(an ES2015/ES6 standard) for this:
a = [_x000D_
{prop1:"abc",prop2:"qwe"},_x000D_
{prop1:"bnmb",prop2:"yutu"},_x000D_
{prop1:"zxvz",prop2:"qwrq"}];_x000D_
_x000D_
index = a.findIndex(x => x.prop2 ==="yutu");_x000D_
_x000D_
console.log(index);
_x000D_
It's supported in Google Chrome, Firefox and Edge. For Internet Explorer, there's a polyfill on the linked page.
Performance note
Function calls are expensive, therefore with really big arrays a simple loop will perform much better than findIndex
:
let test = [];_x000D_
_x000D_
for (let i = 0; i < 1e6; i++)_x000D_
test.push({prop: i});_x000D_
_x000D_
_x000D_
let search = test.length - 1;_x000D_
let count = 100;_x000D_
_x000D_
console.time('findIndex/predefined function');_x000D_
let fn = obj => obj.prop === search;_x000D_
_x000D_
for (let i = 0; i < count; i++)_x000D_
test.findIndex(fn);_x000D_
console.timeEnd('findIndex/predefined function');_x000D_
_x000D_
_x000D_
console.time('findIndex/dynamic function');_x000D_
for (let i = 0; i < count; i++)_x000D_
test.findIndex(obj => obj.prop === search);_x000D_
console.timeEnd('findIndex/dynamic function');_x000D_
_x000D_
_x000D_
console.time('loop');_x000D_
for (let i = 0; i < count; i++) {_x000D_
for (let index = 0; index < test.length; index++) {_x000D_
if (test[index].prop === search) {_x000D_
break;_x000D_
}_x000D_
}_x000D_
}_x000D_
console.timeEnd('loop');
_x000D_
As with most optimizations, this should be applied with care and only when actually needed.
&
is HTML for "Start of a character reference".
&
is the character reference for "An ampersand".
¤t;
is not a standard character reference and so is an error (browsers may try to perform error recovery but you should not depend on this).
If you used a character reference for a real character (e.g. ™
) then it (™) would appear in the URL instead of the string you wanted.
(Note that depending on the version of HTML you use, you may have to end a character reference with a ;
, which is why &trade=
will be treated as ™. HTML 4 allows it to be ommited if the next character is a non-word character (such as =
) but some browsers (Hello Internet Explorer) have issues with this).
Use the native PHP $_SERVER['HTTP_USER_AGENT']
variable instead.
You do not need to parse every single line and then concatenate them again...
Source.fromFile(path)(Codec.UTF8).mkString
I prefer to use this:
import scala.io.{BufferedSource, Codec, Source}
import scala.util.Try
def readFileUtf8(path: String): Try[String] = Try {
val source: BufferedSource = Source.fromFile(path)(Codec.UTF8)
val content = source.mkString
source.close()
content
}
There are various data structures which are optimized for adding elements at the first index. Mind though, that if you convert your collection to one of these, the conversation will probably need a time and space complexity of O(n)
The JDK includes the Deque
structure which offers methods like addFirst(e)
and offerFirst(e)
Deque<String> deque = new LinkedList<>();
deque.add("two");
deque.add("one");
deque.addFirst("three");
//prints "three", "two", "one"
Space and time complexity of insertion is with LinkedList
constant (O(1)
). See the Big-O cheatsheet.
A very easy but inefficient method is to use reverse:
Collections.reverse(list);
list.add(elementForTop);
Collections.reverse(list);
If you use Java 8 streams, this answer might interest you.
O(n)
O(1)
Looking at the JDK implementation this has a O(n)
time complexity so only suitable for very small lists.
I do it this way when there are many points to use...
public enum Status {
VALID("valid"), OLD("old");
private final String val;
Status(String val) {
this.val = val;
}
public String getStatus() {
return val;
}
public static void setRequestAttributes(HttpServletRequest request) {
Map<String,String> vals = new HashMap<String,String>();
for (Status val : Status.values()) {
vals.put(val.name(), val.value);
}
request.setAttribute("Status", vals);
}
}
JSP
<%@ page import="...Status" %>
<% Status.setRequestAttributes(request) %>
<c:when test="${dp.status eq Status.VALID}">
...
If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200
and have two icons in top row and two icon in bottom row. So, it's four quadrants.
.sprite-of-icons {
background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}
.sp-logo-1 { background-position: 0 0; }
/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }
Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.
Another handy SCSS mixin solution by Ryan Benhase.
/****************************
HIGH PPI DISPLAY BACKGROUNDS
*****************************/
@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {
$at1x_path: "#{$path}.#{$ext}";
$at2x_path: "#{$path}@2x.#{$ext}";
background-image: url("#{$at1x_path}");
background-size: $w $h;
background-position: $pos;
background-repeat: $repeat;
@media all and (-webkit-min-device-pixel-ratio : 1.5),
all and (-o-min-device-pixel-ratio: 3/2),
all and (min--moz-device-pixel-ratio: 1.5),
all and (min-device-pixel-ratio: 1.5) {
background-image: url("#{$at2x_path}");
}
}
div.background {
@include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}
For more info about above mixin READ HERE.
If you really have:
var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];
then simply:
var objs = $.map(s, $.parseJSON);
You only need to add .Returns(Task.FromResult(0));
after the Callback.
Example:
mock.Setup(arg => arg.DoSomethingAsync())
.Callback(() => { <my code here> })
.Returns(Task.FromResult(0));
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
I'm using webstorm on the deployed files
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.016427,72.571156),
map: map,
icon: 'images/map_marker_icon.png',
title: 'Hi..!'
});
apply local path on icon only
You don't need to instantiate an object, because yau are going to use a static variable: Console.WriteLine(Book.myInt);
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.
As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.
This isn't very well documented, but we can trigger any kinds of events very simply.
This example will trigger 50 double click on the button:
let theclick = new Event("dblclick")
for (let i = 0;i < 50;i++){
action.dispatchEvent(theclick)
}
_x000D_
<button id="action" ondblclick="out.innerHTML+='Wtf '">TEST</button>
<div id="out"></div>
_x000D_
The Event interface represents an event which takes place in the DOM.
An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the HTMLElement.click() method of an element, or by defining the event, then sending it to a specified target using EventTarget.dispatchEvent().
https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
The simplest way to achieve this is given below,
I)
Glide.with(context.getApplicationContext())
.load(Your Path)
.override(15, 15) // (change according to your wish)
.error(R.drawable.placeholder)
.into(image.score);
else you can follow the code below..
II)
1.Create a class.(Code is given below)
public class BlurTransformation extends BitmapTransformation {
private RenderScript rs;
public BlurTransformation(Context context) {
super( context );
rs = RenderScript.create( context );
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );
// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(
rs,
blurredBitmap,
Allocation.MipmapControl.MIPMAP_FULL,
Allocation.USAGE_SHARED
);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
script.setRadius(10);
// Start the ScriptIntrinisicBlur
script.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);
toTransform.recycle();
return blurredBitmap;
}
@Override
public String getId() {
return "blur";
}
}
2.Set image to ImageView using Glide.
eg:
Glide.with(this)
.load(expertViewDetailsModel.expert.image)
.asBitmap()
.transform(new BlurTransformation(this))
.into(ivBackground);
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
A simple readable version is
def find(lst, key, value):
for i, dic in enumerate(lst):
if dic[key] == value:
return i
return -1
Looking at your example, I think this is what you want:
var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
With Yglu Structural Templating, your example can be written:
foo: !()
!? $.propname:
type: number
default: !? $.default
bar:
!apply .foo:
propname: "some_prop"
default: "some default"
Disclaimer: I am the author or Yglu.
Yes there are two way to add a line feed:
Use the existing function from VBA vbCrLf
in the string you want to add a line feed, as such:
Dim text As String
text = "Hello" & vbCrLf & "World!"
Worksheets(1).Cells(1, 1) = text
Use the Chr()
function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:
Dim text As String
text = "Hello" & Chr(13) & Chr(10) & "World!"
Worksheets(1).Cells(1, 1) = text
In both cases, you will have the same output in cell (1,1) or A1.
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
Just change build tools version to 25.0.3.. and sync now I hope it will help..
npm config set registry "http://registry.npmjs.org"
Solved the issue for me. Note that it wouldn't accecpt a forward slash at the end of the url and it had to be entered exactly as shown above.
Or in C# 3.0 using System.Linq
you can skip the intermediate list:
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = from nv in nvPairs
select new InputProperty()
{
Name = "udf:" + nv.Name,
Val = nv.Value
};
update.Items = ip.ToArray();
return update;
}
That's funny how Stefan Gehrig his answer is actually the correct one. You don't need to convert a string into a "011010101" string to store it in BINARY field in a database. Anyway since this is the first answer that comes up when you google for "php convert string to binary string". Here is my contribution to this problem.
The most voted answer by Francois Deschenes goes wrong for long strings (either bytestrings or bitstrings) that is because
base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.
From: https://secure.php.net/manual/en/function.base-convert.php
To work around this limitation you can chop up the input string into chunks. The functions below implement this technique.
<?php
function bytesToBits(string $bytestring) {
if ($bytestring === '') return '';
$bitstring = '';
foreach (str_split($bytestring, 4) as $chunk) {
$bitstring .= str_pad(base_convert(unpack('H*', $chunk)[1], 16, 2), strlen($chunk) * 8, '0', STR_PAD_LEFT);
}
return $bitstring;
}
function bitsToBytes(string $bitstring) {
if ($bitstring === '') return '';
// We want all bits to be right-aligned
$bitstring_len = strlen($bitstring);
if ($bitstring_len % 8 > 0) {
$bitstring = str_pad($bitstring, intdiv($bitstring_len + 8, 8) * 8, '0', STR_PAD_LEFT);
}
$bytestring = '';
foreach (str_split($bitstring, 32) as $chunk) {
$bytestring .= pack('H*', str_pad(base_convert($chunk, 2, 16), strlen($chunk) / 4, '0', STR_PAD_LEFT));
}
return $bytestring;
}
for ($i = 0; $i < 10000; $i++) {
$bytestring_in = substr(hash('sha512', uniqid('', true)), 0, rand(0, 128));
$bits = bytesToBits($bytestring_in);
$bytestring_out = bitsToBytes($bits);
if ($bytestring_in !== $bytestring_out) {
printf("IN : %s\n", $bytestring_in);
printf("BITS: %s\n", $bits);
printf("OUT : %s\n", $bytestring_out);
var_dump($bytestring_in, $bytestring_out); // printf() doesn't show some characters ..
die('Error in functions [1].');
}
}
for ($i = 0; $i < 10000; $i++) {
$len = rand(0, 128);
$bitstring_in = '';
for ($j = 0; $j <= $len; $j++) {
$bitstring_in .= (string) rand(0,1);
}
$bytes = bitsToBytes($bitstring_in);
$bitstring_out = bytesToBits($bytes);
// since converting to byte we always have a multitude of 4, so we need to correct the bitstring_in to compare ..
$bitstring_in_old = $bitstring_in;
$bitstring_in_len = strlen($bitstring_in);
if ($bitstring_in_len % 8 > 0) {
$bitstring_in = str_pad($bitstring_in, intdiv($bitstring_in_len + 8, 8) * 8, '0', STR_PAD_LEFT);
}
if ($bitstring_in !== $bitstring_out) {
printf("IN1 : %s\n", $bitstring_in_old);
printf("IN2 : %s\n", $bitstring_in);
printf("BYTES: %s\n", $bytes);
printf("OUT : %s\n", $bitstring_out);
var_dump($bytes); // printf() doesn't show some characters ..
die('Error in functions [2].');
}
}
echo 'All ok!' . PHP_EOL;
Note that if you insert a bitstring that is not a multitude of 8 (example: "101") you will not be able to recover the original bitstring when you converted to bytestring. From the bytestring converting back, uyou will get "00000101" which is numerically the same (unsigned 8 bit integer) but has a different string length. Therefor if the bitstring length is important to you you should save the length in a separate variable and chop of the first part of the string after converting.
$bits_in = "101";
$bits_in_len = strlen($bits_in); // <-- keep track if input length
$bits_out = bytesToBits(bitsToBytes("101"));
var_dump($bits_in, $bits_out, substr($bits_out, - $bits_in_len)); // recover original length with substr
Take advantage of as.matrix
:
# keep the first column
names <- df.aree[,1]
# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))
# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names
Unless I'm mistaken, I'd say it's to write your own function.
function findIndexOfGreatest(array) {
var greatest;
var indexOfGreatest;
for (var i = 0; i < array.length; i++) {
if (!greatest || array[i] > greatest) {
greatest = array[i];
indexOfGreatest = i;
}
}
return indexOfGreatest;
}
Google Maps API v3:
I initialized Google Map and added markers to it. Later, I wanted to retrieve all markers and did it simply by accessing the map property "markers".
var map = new GMaps({
div: '#map',
lat: 40.730610,
lng: -73.935242,
});
var myMarkers = map.markers;
You can loop over it and access all Marker methods listed at Google Maps Reference.
You need to set the OFS
variable (output field separator) to be a tab:
echo "$line" |
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'
(make sure you quote the $line
variable in the echo statement)
The big difference is that the first example actually invokes the lambda f(x)
, while the second example doesn't.
Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)]
while your second example is equivalent to [f for x in range(10)]
.
You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –
module.exports = {
entry: {
home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
}
};
When debugging optimized programs (which may be necessary if the bug doesn't show up in debug builds), you often have to understand assembly compiler generated.
In your particular case, return value of cpnd_find_exact_ckptinfo
will be stored in the register which is used on your platform for return values. On ix86
, that would be %eax
. On x86_64
: %rax
, etc. You may need to google for '[your processor] procedure calling convention' if it's none of the above.
You can examine that register in GDB
and you can set it. E.g. on ix86
:
(gdb) p $eax
(gdb) set $eax = 0
Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.
http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds
I have not found a solution yet...
To summarize and complement the existing answers, as of Windows PowerShell v5.1 / PowerShell Core 7.0.0-preview.4:
David Mohundro's answer rightfully points that instead of [bool]
parameters you should use [switch]
parameters in PowerShell, where the presence vs. absence of the switch name (-Unify
specified vs. not specified) implies its value, which makes the original problem go away.
However, on occasion you may still need to pass the switch value explicitly, particularly if you're constructing a command line programmatically:
In PowerShell Core, the original problem (described in Emperor XLII's answer) has been fixed.
That is, to pass $true
explicitly to a [switch]
parameter named -Unify
you can now write:
pwsh -File .\RunScript.ps1 -Unify:$true # !! ":" separates name and value, no space
The following values can be used: $false
, false
, $true
, true
, but note that passing 0
or 1
does not work.
Note how the switch name is separated from the value with :
and there must be no whitespace between the two.
Note: If you declare a [bool]
parameter instead of a [switch]
(which you generally shouldn't), you must use the same syntax; even though -Unify $false
should work, it currently doesn't - see this GitHub issue.
In Windows PowerShell, the original problem persists, and - given that Windows PowerShell is no longer actively developed - is unlikely to get fixed.
The workaround suggested in LarsWA's answer - even though it is based on the official help topic as of this writing - does not work in v5.1
Using -Command
instead of -File
is the only effective workaround:
:: # From cmd.exe
powershell -Command "& .\RunScript.ps1 -Unify:$true"
With -Command
you're effectively passing a piece of PowerShell code, which is then evaluated as usual - and inside PowerShell passing $true
and $false
works (but not true
and false
, as now also accepted with -File
).
Caveats:
Using -Command
can result in additional interpretation of your arguments, such as if they contain $
chars. (with -File
, arguments are literals).
Using -Command
can result in a different exit code.
For details, see this answer and this answer.
The api will return the list in increments of 1000. Check the IsTruncated property to see if there are still more. If there are, you need to make another call and pass the last key that you got as the Marker property on the next call. You would then continue to loop like this until IsTruncated is false.
See this Amazon doc for more info: Iterating Through Multi-Page Results
It's as simple as following:
File logFile = new File(...);
ProcessBuilder pb = new ProcessBuilder()
.command("somecommand", "arg1", "arg2")
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(logFile);
by .redirectErrorStream(true) you tell process to merge error and output stream and then by .redirectOutput(file) you redirect merged output to a file.
Update:
I did manage to do this as follows:
public static void main(String[] args) {
// Async part
Runnable r = () -> {
ProcessBuilder pb = new ProcessBuilder().command("...");
// Merge System.err and System.out
pb.redirectErrorStream(true);
// Inherit System.out as redirect output stream
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
try {
pb.start();
} catch (IOException e) {
e.printStackTrace();
}
};
new Thread(r, "asyncOut").start();
// here goes your main part
}
Now you're able to see both outputs from main and asyncOut threads in System.out
=Replace(Format(CDate(Now()),"MM.dd.yyyy"), ".", "/")
I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda and pip work well together.
Just manage Conda from the command line. PyCharm will automatically notice changes once they happen, just like it does with pip.
Create a new Conda environment:
conda create --name foo pandas bokeh
This environment lives under conda_root/envs/foo
. Your python interpreter is conda_root/envs/foo/bin/pythonX.X
and your all your site-packages are in conda_root/envs/foo/lib/pythonX.X/site-packages
. This is same directory structure as in a pip virtual environement. PyCharm sees no difference.
Now to activate your new environment from PyCharm go to file > settings > project > interpreter, select Add local in the project interpreter field (the little gear wheel) and hunt down your python interpreter. Congratulations! You now have a Conda environment with pandas and bokeh!
Now install more packages:
conda install scikit-learn
OK... go back to your interpreter in settings. Magically, PyCharm now sees scikit-learn!
And the reverse is also true, i.e. when you pip install another package in PyCharm, Conda will automatically notice. Say you've installed requests. Now list the Conda packages in your current environment:
conda list
The list now includes requests and Conda has correctly detected (3rd column) that it was installed with pip.
This is definitely good news for people like myself who are trying to get away from the pip/virtualenv installation problems when packages are not pure python.
NB: I run PyCharm pro edition 4.5.3 on Linux. For Windows users, replace in command line with in the GUI (and forward slashes with backslashes). There's no reason it shouldn't work for you too.
EDIT: PyCharm5 is out with Conda support! In the community edition too.
Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()
i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.
To keep it basic, I used a loop and something like this to get you started (my index are datetimes):
import pandas as pd
import datetime as dt
#populate your dataframe: "df"
#...
df[df.index<(df.index[0]+dt.timedelta(hours=1))] #gives you a slice. you can then take .sum() .mean(), whatever
and then you can run functions on that slice. You can see how adding an iterator to make the start of the window something other than the first value in your dataframes index would then roll the window (you could use a > rule for the start as well for example).
Note, this may be less efficient for SUPER large data or very small increments as your slicing may become more strenuous (works for me well enough for hundreds of thousands of rows of data and several columns though for hourly windows across a few weeks)
import React, { useEffect, useRef } from 'react';
function Example() {
let inp = useRef();
useEffect(() => {
if (!inp && !inp.current) return;
inp.current.focus();
return () => inp = null;
});
const handleSubmit = () => {
//...
}
return (
<form
onSubmit={e => {
e.preventDefault();
handleSubmit(e);
}}
>
<input
name="fakename"
defaultValue="...."
ref={inp}
type="radio"
style={{
position: "absolute",
opacity: 0
}}
/>
<button type="submit">
submit
</button>
</form>
)
}
Enter code here sometimes in popups it would not work to binding just a form and passing the onSubmit to the form because form may not have any input.
In this case if you bind the event to the document by doing document.addEventListener
it will cause problem in another parts of the application.
For solving this issue we should wrap a form and should put a input with what is hidden by css, then you focus on that input by ref it will be work correctly.
You can use this
File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
try this
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
var this_input=$(this);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.attr('checked1','11')_x000D_
} else {_x000D_
this_input.attr('checked1','22')_x000D_
}_x000D_
$('.radio-button').prop('checked', false);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.prop('checked', false);_x000D_
this_input.attr('checked1','22')_x000D_
} else {_x000D_
this_input.prop('checked', true);_x000D_
this_input.attr('checked1','11')_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
Swift 3 UILabel extention
Tip: If you need some space between the image and the text just use a space or two before the labelText.
extension UILabel {
func addIconToLabel(imageName: String, labelText: String, bounds_x: Double, bounds_y: Double, boundsWidth: Double, boundsHeight: Double) {
let attachment = NSTextAttachment()
attachment.image = UIImage(named: imageName)
attachment.bounds = CGRect(x: bounds_x, y: bounds_y, width: boundsWidth, height: boundsHeight)
let attachmentStr = NSAttributedString(attachment: attachment)
let string = NSMutableAttributedString(string: "")
string.append(attachmentStr)
let string2 = NSMutableAttributedString(string: labelText)
string.append(string2)
self.attributedText = string
}
}
You need something like:
URL resource = this.getClass().getResource("/path/to/resource.res");
File is = null;
try {
is = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream input = new FileInputStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But it will work only within your IDE, not in runnable JAR. I had same problem explained here.
If you want a list of only the object columns you could do:
non_numerics = [x for x in df.columns \
if not (df[x].dtype == np.float64 \
or df[x].dtype == np.int64)]
and then if you want to get another list of only the numerics:
numerics = [x for x in df.columns if x not in non_numerics]
I think this would do it:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".divlink").click(function(){
$("#content").attr("src" , $(this).attr("ref"));
});
});
</script>
</head>
<body>
<iframe id="content"></iframe>
<a href="#" ref="page1.html" class="divlink" >Page 1</a><br />
<a href="#" ref="page2.html" class="divlink" >Page 2</a><br />
<a href="#" ref="page3.html" class="divlink" >Page 3</a><br />
<a href="#" ref="page4.html" class="divlink" >Page 4</a><br />
<a href="#" ref="page5.html" class="divlink" >Page 5</a><br />
<a href="#" ref="page6.html" class="divlink" >Page 6</a><br />
</body>
</html>
By the way if you can avoid Jquery, you can just use the target
attribute of <a>
element:
<html>
<body>
<iframe id="content" name="content"></iframe>
<a href="page1.html" target="content" >Page 1</a><br />
<a href="page2.html" target="content" >Page 2</a><br />
<a href="page3.html" target="content" >Page 3</a><br />
<a href="page4.html" target="content" >Page 4</a><br />
<a href="page5.html" target="content" >Page 5</a><br />
<a href="page6.html" target="content" >Page 6</a><br />
</body>
</html>
The Maven build lifecycle now includes the "integration-test" phase for running integration tests, which are run separately from the unit tests run during the "test" phase. It runs after "package", so if you run "mvn verify", "mvn install", or "mvn deploy", integration tests will be run along the way.
By default, integration-test runs test classes named **/IT*.java
, **/*IT.java
, and **/*ITCase.java
, but this can be configured.
For details on how to wire this all up, see the Failsafe plugin, the Failsafe usage page (not correctly linked from the previous page as I write this), and also check out this Sonatype blog post.
table {
border-collapse:collapse;
}
Two options I can think of (though neither of them is programatically detecting porn):
Give this a go:
var distinct_list
= data.DATA.map(function (d) {return d[x];}).filter((v, i, a) => a.indexOf(v) === i)
For those who would like to use developer powershell. Here are the lines to add to your settings.json:
"terminal.integrated.automationShell.windows": "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shellArgs.windows": [
"-noe",
"-c",
" &{Import-Module 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell b7c50c8d} ",
],
Maybe you are using:
$(document).ready(function(){
// Your code here
});
Try this instead:
window.onload = function(){ }
it happened for me when I deleted the jdk and installed new one somehow the project kept seeing the old one as invalid but couldn't change, so right click on your module -> Open Module Settings -> and choose Compile Sdk Version.
For trouble-shooting on existing Windows Service program, use 'Debugger.Break()' as other guys suggested.
For new Windows Service program, I would suggest using James Michael Hare's method http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx
That's because endOf
mutates the original value.
Relevant quote:
Mutates the original moment by setting it to the end of a unit of time.
Here's an example function that gives you the output you want:
function getMonthDateRange(year, month) {
var moment = require('moment');
// month in moment is 0 based, so 9 is actually october, subtract 1 to compensate
// array is 'year', 'month', 'day', etc
var startDate = moment([year, month - 1]);
// Clone the value before .endOf()
var endDate = moment(startDate).endOf('month');
// just for demonstration:
console.log(startDate.toDate());
console.log(endDate.toDate());
// make sure to call toDate() for plain JavaScript date type
return { start: startDate, end: endDate };
}
References:
When you install this nuget package Microsoft.AspNet.WebPages they can be find in C:\Program Files (x86)\Microsoft Visual Studio\Shared\Packages\Microsoft.AspNet.WebPages.x.x.x\lib\net45
@Pedram, your old solution works actually fine in lollipop too (and better than new one since it's usable everywhere, including in remote views) just change your circular_progress_bar.xml
code to this:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp"
android:useLevel="true"> <!-- Just add this line -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Partial Class _Default
Inherits System.Web.UI.Page
Dim str As String
Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed
str += "PAGE DISPOSED" & "<br />"
End Sub
Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
str += "PAGE ERROR " & "<br />"
End Sub
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
str += "PAGE INIT " & "<br />"
End Sub
Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
str += "INIT Complte " & "<br />"
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
str += "PAGE LOAD " & "<br />"
End Sub
Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
str += "PAGE LOAD Complete " & "<br />"
End Sub
Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
str = ""
str += "PAGE PRE INIT" & "<br />"
End Sub
Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
str += "PAGE PRE LOAD " & "<br />"
End Sub
Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
str += "PAGE PRE RENDER " & "<br />"
End Sub
Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
str += "PAGE PRE RENDER COMPLETE " & "<br />"
End Sub
Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
str += "PAGE SAVE STATE COMPLTE " & "<br />"
lbl.Text = str
End Sub
Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
'Response.Write("PAGE UN LOAD\n")
End Sub
End Class
This can be solved by using https://twitter.com/intent/tweet
instead of http://www.twitter.com/share
. Using the intent/tweet
function, you simply URL encode your entire URL and it works like a charm.
Just add this to your AndroidManifest.xml
<activity android:screenOrientation="landscape">
I mean, there is an activity tag, add this as another parameter. In case if you need portrait orientation, change landscape to portrait. Hope this helps.
You can do this conversion with the OpenSSL library
Windows binaries can be found here:
http://www.slproweb.com/products/Win32OpenSSL.html
Once you have the library installed, the command you need to issue is:
openssl x509 -in mycert.crt -out mycert.pem -outform PEM
You can also return false after processing your jquery.
Eg.
$(".clickableAnchor").live(
"click",
function(){
//your code
return false; //<- prevents redirect to href address
}
);
You will need to create a virtual device that runs on ARM. Virtual devices running on X86 require an Intel processor. AMD support as specified by Android is only available for Linux systems. If you want a better experience when creating your Virtual Device, use "Store a snapshot for faster startup" instead of the default "Use Host GPU".
The only difference is that CHARACTER VARYING is more human friendly than VARCHAR
Microsoft has an article about this issue. It goes through it all step by step.
In short it involves starting up the instance of sqlserver with -m
like all the other answers suggest. However Microsoft provides slightly more detailed instructions.
From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)
In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.
Close Management Studio.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)
Click OK, and after the message to restart, right-click your server name, and then click Restart.
After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.
On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)
Note
For earlier versions of Windows, the Run as administrator option appears as a sub-menu.
In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.
a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.
b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.
CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS; ALTER SERVER ROLE sysadmin ADD MEMBER [CONTOSO\PatK];
c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.
CREATE LOGIN TempLogin WITH PASSWORD = '************'; ALTER SERVER ROLE sysadmin ADD MEMBER TempLogin;
Warning:
Replace ************ with a strong password.
d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.
ALTER LOGIN sa WITH PASSWORD = '************'; Warning
Replace ************ with a strong password.
The following steps now change SQL Server back to multi-user mode. Close SSMS.
In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.
On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.
Note
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.
Right-click your server name, and then click Restart.
Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.
exec
is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:
exec('print(5)') # prints 5.
# exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)') # prints 5{newline}6.
exec('if True: print(6)') # prints 6.
exec('5') # does nothing and returns nothing.
eval
is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:
x = eval('5') # x <- 5
x = eval('%d + 6' % x) # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5') # INVALID; assignment is not an expression.
x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
compile
is a lower level version of exec
and eval
. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:
compile(string, '', 'eval')
returns the code object that would have been executed had you done eval(string)
. Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec')
returns the code object that would have been executed had you done exec(string)
. You can use any number of statements here.
compile(string, '', 'single')
is like the exec
mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')
I had this issue after converting my Write-Host
cmdlets to Write-Information
and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.
Write-Host this is a good idea $here
Write-Information this is a good idea $here
<=BAD
This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...
Write-Information ("this is a good idea $here")
<=GOOD
I've got the same issue, my model is binding from another form, I've added ng-change
and ng-model
and it still doesn't work:
<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>
<ng-dropzone
dropzone="dropzone"
dropzone-config="dropzoneButtonCfg"
model="pdfUrl">
</ng-dropzone>
An input #pdf-url
gets data from dropzone (two ways binding), however, ng-change
doesn't work in this case. $scope.$watch
is a solution for me:
$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
if (newPdfUrl !== oldPdfUrl) {
// It's updated - Do something you want here.
}
});
Hope this help.
float
stores floating-point values, that is, values that have potential decimal placesint
only stores integral values, that is, whole numbersSo while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float
.
Dissecting them both a little further:
In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.
In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:
M × 2E
(There is more to it, but this should suffice for the purpose of this discussion)
The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.
Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float
is around 3.4 × 1038 whereas int
only allows values up to 2.1 × 109.
But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int
can store), that at the larger end of float
's numeric range the numbers are spaced wider apart (since there cannot be more unique float
numbers than there are unique int
numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float
of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float
is using there.
Similarly, you can also represent very small numbers (between 0 and 1) in a float
but regardless of whether the numbers are very large or very small, float
only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float
cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...
You can download language pack and use "Install or Uninstall display languages" wizard. To do this:
Win+R
, paste lpksetup
and press Enter
Install display languages
buttonBrowse
and pick the *.cab file of the MUI language you downloadedIn my case it was an improperly named XML file that caused my R file not to rebuild. This did not show up in the package explorer, but it was shown in the LogCat. Look out for any warnings there about your res files. No matter how many times you clean your project, the R file will not rebuild until those errors are taken care of.
I had the same problem. It turns out that, compiling a project I got from someone else, I haven't set the correct StartUp project (right click on the desired startup project in the solution explorer and pick "set as StartUp Project"). Maybe this will help, cheers.
Try using
git reset --hard <commit id>
Please Note : Here commit id will the id of the commit you want to go to but not the id you want to reset. this was the only point where i also got stucked.
then push
git push -f <remote> <branch>
Simple: e.g. if div id 'mydiv'
jQuery.fancybox.open({href: "#mydiv"});
This also makes JS code functional which is inside div.
I believe you're looking for the @filename
syntax, e.g.:
strip new lines
curl --data "@/path/to/filename" http://...
keep new lines
curl --data-binary "@/path/to/filename" http://...
curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary
in place of --data
In my case reducing Xmx1024m to something smaller e.g Xmx512m make it works. So from all the responses (above and in similar other sites), it seems that you may try to massage/reduce the memory size.
You can use Programmatic Navigation.In order to go back, you use this:
router.go(n)
Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:
<a @click="$router.go(-1)">back</a>
In layman's terms:
JDBC is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS
, etc. Data sets can be returned which you can handle in your app, and you can do all the usual things like INSERT
, DELETE
, run stored procedures, etc. It is one of the underlying technologies behind most Java database access (including JPA providers).
One of the issues with traditional JDBC apps is that you can often have some crappy code where lots of mapping between data sets and objects occur, logic is mixed in with SQL, etc.
JPA is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. Mostly, XML mapping files or annotations on getters and setters can be used to tell the JPA provider which fields on your object map to which fields in the DB. The most famous JPA provider is Hibernate, so it's a good place to start for concrete examples.
Other examples include OpenJPA, toplink, etc.
Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write from and to the DB.
Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.
include('front.inc');
global $name;
function foo() {
echo $name;
}
function bar() {
echo $name;
}
foo();
bar();
will only show errors. The correct way to do that would be:
include('front.inc');
function foo() {
global $name;
echo $name;
}
function bar() {
global $name;
echo $name;
}
foo();
bar();
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
You can do it easily by Assertion using Selenium Testng framework.
Steps:
1.Create Firefox browser session
2.Initialize expected title name.
3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.
4.Get the actual title name using "driver.getTitle()" and store it in String variable.
5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;
public class PageTitleVerification
{
private static WebDriver driver = new FirefoxDriver();
@Test
public void test01_GooglePageTitleVerify()
{
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";
Utility.waitForElementInDOM(driver, "Google Search", 15);
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);
//Verify expected page title and actual page title is same
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle
),"Page title not matched or Problem in loading url page");
}
}
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Utility {
/*Wait for an element to be present in DOM before specified time (in seconds ) has
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier,
long timeOutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier)));
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
}
}
In scala, you can:
abstract class Tree
case class Node(a:Int, left:Tree, right:Tree) extends Tree
case class Leaf(a:Int) extends Tree
def lca(tree:Tree, a:Int, b:Int):Tree = {
tree match {
case Node(ab,l,r) => {
if(ab==a || ab ==b) tree else {
val temp = lca(l,a,b);
val temp2 = lca(r,a,b);
if(temp!=null && temp2 !=null)
tree
else if (temp==null && temp2==null)
null
else if (temp==null) r else l
}
}
case Leaf(ab) => if(ab==a || ab ==b) tree else null
}
}
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
Since I want my project to compile to a stand-alone EXE file, I linked the UnitTest project to the function.obj file generated from function.cpp and it works.
Right click on the 'UnitTest1' project ? Configuration Properties ? Linker ? Input ? Additional Dependencies ? add "..\MyProjectTest\Debug\function.obj".
Use utf8_encode()
Man page can be found here http://php.net/manual/en/function.utf8-encode.php
Also read this article from Joel on Software. It provides an excellent explanation if what Unicode is and how it works. http://www.joelonsoftware.com/articles/Unicode.html
There is no error message associated with the mail()
function. There is only a true
or false
returned on whether the email was accepted for delivery. Not whether it ultimately gets delivered, but basically whether the domain exists and the address is a validly formatted email address.
Firefox does not support the MPEG H.264 (mp4) format at this time, due to a philosophical disagreement with the closed-source nature of the format.
To play videos in all browsers without using plugins, you will need to host multiple copies of each video, in different formats. You will also need to use an alternate form of the video
tag, as seen in the JSFiddle from @TimHayes above, reproduced below. Mozilla claims that only mp4 and WebM are necessary to ensure complete coverage of all major browsers, but you may wish to consult the Video Formats and Browser Support heading on W3C's HTML5 Video page to see which browser supports what formats.
Additionally, it's worth checking out the HTML5 Video page on Wikipedia for a basic comparison of the major file formats.
Below is the appropriate video
tag (you will need to re-encode your video in WebM or OGG formats as well as your existing mp4):
<video id="video" controls='controls'>
<source src="videos/clip.mp4" type="video/mp4"/>
<source src="videos/clip.webm" type="video/webm"/>
<source src="videos/clip.ogv" type="video/ogg"/>
Your browser doesn't seem to support the video tag.
</video>
Updated Nov. 8, 2013
Network infrastructure giant Cisco has announced plans to open-source an implementation of the H.264 codec, removing the licensing fees that have so far proved a barrier to use by Mozilla. Without getting too deep into the politics of it (see following link for that) this will allow Firefox to support H.264 starting in "early 2014". However, as noted in that link, this still comes with a caveat. The H.264 codec is merely for video, and in the MPEG-4 container it is most commonly paired with the closed-source AAC audio codec. Because of this, playback of H.264 video will work, but audio will depend on whether the end-user has the AAC codec already present on their machine.
The long and short of this is that progress is being made, but you still can't avoid using multiple encodings without using a plugin.
As noticed in comments start with sent_tokenize(), because word_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8').
from nltk.tokenize import word_tokenize, sent_tokenize
text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)
If the attribute is matching f.text_field
in form use string, if it is matching f.text_area
use text.
You can use this for direct find value via params name.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
although Response::json()
is not getting popular of recent, that does not stop you and Me from using it.
In fact you don't need any facade to use it,
instead of:
$response = Response::json($messages, 200);
Use this:
$response = \Response::json($messages, 200);
with the slash, you are sure good to go.
Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.
Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".
In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.
Step1: recognize the Arduino device unplug your Arduino and list /dev files:
#ls -l /dev
plug your Arduino and go and list /dev files
#ls -l /dev
Find the new file (device) that was not before plugging, for example:
ttyACM0 or ttyUSB1
Read this properties:
ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0
the first c mean that Arduino is a character device.
user owner: root
group owner: dialout
mayor number: 166
minor number: 0
Step2: set your user as group owner.
If you do:
groups <yourUser>
And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:
usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>
restart the pc, and set /dev/<yourDeviceFile>
as your serial port before upload.
Supposedly you have a component:
product-list.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'pm-products',
templateUrl: './product-list.component.html'
})
export class ProductListComponent {
pageTitle: string = 'product list';
}
And you get this error:
ERROR in src/app/app.component.ts:6:3 - error NG8001: 'pm-products' is not a known element:
- If 'pm-products' is an Angular component, then verify that it is part of this module.
app.component.ts:
import { Component } from "@angular/core";
@Component({
selector: 'pm-root', // 'pm-root'
template: `
<div><h1>{{pageTitle}}</h1>
<pm-products></pm-products> // not a known element ?
</div>
`
})
export class AppComponent {
pageTitle: string = 'Acme Product Management';
}
Make sure you import the component:
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// --> add this import (you can click on the light bulb in the squiggly line in VS Code)
import { ProductListComponent } from './products/product-list.component';
@NgModule({
declarations: [
AppComponent,
ProductListComponent // --> Add this line here
],
imports: [
BrowserModule
],
bootstrap: [AppComponent],
})
export class AppModule { }
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
That loads all the DLLs present in your executable's folder.
In my case I was trying to use Reflection
to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.
EDIT: I timed it, and it only seems to load them the first time.
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
stopwatch.Restart();
foreach (var f in Directory.GetFiles(".", "*.dll"))
Assembly.LoadFrom(f);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
Output: 34 0 0 0
So one could potentially run that code before any Reflection searches just in case.
I had a similar issue when deploying from OSx on my local to my Linux live site.
It ran fine on OSx, but on Linux I was getting:
An Error Was Encountered
Unable to load the requested class: Ckeditor
The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".
I also changed my load call to match the capitalization:
$this->load->library('CKEditor');
Here is the simple version
#one
a = [[0]*10]*10
#two
row, col = 10, 10
a = [[0]*row]*col
simple way you can do this by adding this css So, you just added this to CSS:
.modal-body {
position: relative;
padding: 20px;
height: 200px;
overflow-y: scroll;
}
and it's working!
There's two ways to say "don't match": character ranges, and zero-width negative lookahead/lookbehind.
The former: don't match a
, b
, c
or 0
: [^a-c0]
The latter: match any three-letter string except foo
and bar
:
(?!foo|bar).{3}
or
.{3}(?<!foo|bar)
Also, a correction for you: *
, ?
and +
do not actually match anything. They are repetition operators, and always follow a matching operator. Thus, a+
means match one or more of a
, [a-c0]+
means match one or more of a
, b
, c
or 0
, while [^a-c0]+
would match one or more of anything that wasn't a
, b
, c
or 0
.
Cast from string using float()
:
>>> float('NaN')
nan
>>> float('Inf')
inf
>>> -float('Inf')
-inf
>>> float('Inf') == float('Inf')
True
>>> float('Inf') == 1
False
To copy formatting:
Range("F10").Select
Selection.Copy
Range("I10:J10").Select ' note that we select the whole merged cell
Selection.PasteSpecial Paste:=xlPasteFormats
copying the formatting will break the merged cells, so you can use this to put the cell back together
Range("I10:J10").Select
Selection.Merge
To copy a cell value, without copying anything else (and not using copy/paste), you can address the cells directly
Range("I10").Value = Range("F10").Value
other properties (font, color, etc ) can also be copied by addressing the range object properties directly in the same way
There are 2 ways to declare a variable as global:
1. assign variable inside functions and use global line
def declare_a_global_variable():
global global_variable_1
global_variable_1 = 1
# Note to use the function to global variables
declare_a_global_variable()
2. assign variable outside functions:
global_variable_2 = 2
Now we can use these declared global variables in the other functions:
def declare_a_global_variable():
global global_variable_1
global_variable_1 = 1
# Note to use the function to global variables
declare_a_global_variable()
global_variable_2 = 2
def print_variables():
print(global_variable_1)
print(global_variable_2)
print_variables() # prints 1 & 2
Note 1:
If you want to change a global variable inside another function like update_variables()
you should use global line in that function before assigning the variable:
global_variable_1 = 1
global_variable_2 = 2
def update_variables():
global global_variable_1
global_variable_1 = 11
global_variable_2 = 12 # will update just locally for this function
update_variables()
print(global_variable_1) # prints 11
print(global_variable_2) # prints 2
Note 2:
There is a exception for note 1 for list and dictionary variables while not using global line inside a function:
# declaring some global variables
variable = 'peter'
list_variable_1 = ['a','b']
list_variable_2 = ['c','d']
def update_global_variables():
"""without using global line"""
variable = 'PETER' # won't update in global scope
list_variable_1 = ['A','B'] # won't update in global scope
list_variable_2[0] = 'C' # updated in global scope surprisingly this way
list_variable_2[1] = 'D' # updated in global scope surprisingly this way
update_global_variables()
print('variable is: %s'%variable) # prints peter
print('list_variable_1 is: %s'%list_variable_1) # prints ['a', 'b']
print('list_variable_2 is: %s'%list_variable_2) # prints ['C', 'D']
Judging from what you've posted, and assuming it's not a typo, Eclipse is looking in C:\s\platform-tools...
If that's the case, then you should check Eclipse's Window/Preferences/Android option for the SDK Location. Maybe yours is set to "C:\s". You can't edit it to be a value such as that without causing an error, but maybe it's got corrupted somehow.
I think that if you put a span style after the <a>
tag with text-decoration:none
it will work in the majority of the browsers / email clients.
As in:
<a href="" style="text-decoration:underline">
<span style="color:#0b92ce; text-decoration:none">BANANA</span>
</a>
You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.
using(SqlConnection openCon=new SqlConnection("your_connection_String"))
{
string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";
using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
{
querySaveStaff.Connection=openCon;
querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
.....
openCon.Open();
querySaveStaff.ExecuteNonQuery();
}
}