For Swift: Here is a simple extension to UIImage:
//ImageRotation.swift
import UIKit
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let radiansToDegrees: (CGFloat) -> CGFloat = {
return $0 * (180.0 / CGFloat(M_PI))
}
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip){
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
(Source)
Use it with:
rotatedPhoto = rotatedPhoto?.imageRotatedByDegrees(90, flip: false)
The former will rotate an image and flip it if flip is set to true.
If you are using Oracle, consider specifying cache size for the sequence. If you are routinely create objects in batches of 5K, you can just set it to a 1000 or 5000. We did it for the sequence used for the surrogate primary key and were amazed that execution times for an ETL process hand-written in Java dropped in half.
I could not paste formatted code into comment. Here's the sequence DDL:
create sequence seq_mytable_sid
minvalue 1
maxvalue 999999999999999999999999999
increment by 1
start with 1
cache 1000
order
nocycle;
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas
library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.
Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all')
. With Pandas 0.23.4, you get the following:
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)
warnings.warn(d.msg, FutureWarning)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
warnings.warn(d.msg, FutureWarning)
>>>
Following the @bdiamante's advice, you use the warnings
library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In fact, disabling all warnings produces the same output:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn
on the warning messages shows that the pandas
warning system is implemented in core/config_init.py
:
$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead
Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!
Please try jQuery UI dialog
Here is the forms demo
For mobile use, have a look at jQuery Mobile - Creating dialogs
Just change
import android.widget.Toolbar;
To
import android.support.v7.widget.Toolbar;
You can get the number of elements in the list by calling list.size()
, however some of the elements may be duplicates or null
(if your list implementation allows null
).
If you want the number of unique items and your items implement equals
and hashCode
correctly you can put them all in a set and call size
on that, like this:
new HashSet<>(list).size()
If you want the number of items with a distinct itemId
you can do this:
list.stream().map(i -> i.itemId).distinct().count()
Assuming that the type of itemId
correctly implements equals
and hashCode
(which String
in the question does, unless you want to do something like ignore case, in which case you could do map(i -> i.itemId.toLowerCase())
).
You may need to handle null
elements by either filtering them before the call to map
: filter(Objects::nonNull)
or by providing a default itemId for them in the map
call: map(i -> i == null ? null : i.itemId)
.
Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.
Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).
Orginal Posted on Github: Link
Slightly off-topic to your question, but it's probably worth mentioning anyway:
Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.
I also agree that you should use the @Override
annotation whenever you're overriding equals (or any other method).
• Debug: fine-grained statements concerning program state, typically used for debugging;
• Info: informational statements concerning program state, representing program events or behavior tracking;
• Warn: statements that describe potentially harmful events or states in the program;
• Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;
• Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.
Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx
You need to create an alias for the mother.kind
. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();
Use the following syntax:
$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05
Disclaimer: Leading zeros only work in >=bash-4
.
If you want to use printf
, nothing prevents you from putting its result in a variable for further use:
$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05
you can also just run it with a shell, for example:
bash example.txt
sh example.txt
import math
math.sqrt( x )
It is a trivial addition to the answer chain. However since the Subject is very common google hit, this deserves to be added, I believe.
just to add some clarity, you need to stage changes with git add
, then amend last commit:
git add /path/to/modified/files
git commit --amend --no-edit
This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.
if the data is the result of a formula, then it will never be empty (even if you set it to ""
), as having a formula is not the same as an empty cell
There are 2 methods, depending on how static the data is.
The easiest fix is to clear the cells that return empty strings, but that means you will have to fix things if data changes
the other fix involves a little editing of the formula, so instead of setting it equal to ""
, you set it equal to NA()
.
For example, if you have =IF(A1=0,"",B1/A1)
, you would change that to =IF(A1=0,NA(),B1/A1)
.
This will create the gaps you desire, and will also reflect updates to the data so you don't have to keep fixing it every time
If you can ping the FQDN, look at how DNS devolution is set up the PC.
Winsock API which MS ping will automatically use the FQDN of the client PC if append primary and connection specific DNS suffix is checked in TCP/IP advanced DNS settings. If the host is in another domain, the client must perform DNS devolution.
Under XP TCP/IP advanced properties DNS, make sure append parent suffixes is checked so that the ping request traverses the domain back to the parent.
From personal experience, the System.Diagnostics.Stopwatch
class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!
Consider the following example:
Stopwatch sw;
for(int index = 0; index < 10; index++)
{
sw = Stopwatch.StartNew();
DoSomething();
Console.WriteLine(sw.ElapsedMilliseconds);
}
sw.Stop();
Example results
132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms
Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"
The answer is that Stopwatch
does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.
What you should really be looking for absolute accuracy is Performance Profiling!
Take a look at the following:
RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling
Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?
I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET
In case the script is having multiple arguments
#!/usr/bin/python
import subprocess
output = subprocess.call(["./test.sh","xyz","1234"])
print output
Output will give the status code. If script runs successfully it will give 0 otherwise non-zero integer.
podname=xyz serial=1234
0
Below is the test.sh shell script.
#!/bin/bash
podname=$1
serial=$2
echo "podname=$podname serial=$serial"
[a-z]
matches a single char between a and z. So, if your string was just "d"
, for example, then it would have matched and been printed out.
You need to change your regex to [a-z]+
to match one or more chars.
I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?
Forget the mouse. To remove 5 lines, either:
Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?
As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.
I suggest spending some time with the Vim Tutor (run vimtutor
) to get more familiar with Vim in a very didactic way.
This is an extension (excuse the pun) of elclanrs' solution to include detail on instance methods, as well as taking an extensible approach to that aspect of the question; I fully acknowledge that this is put together thanks to David Flanagan's "JavaScript: The Definitive Guide" (partially adjusted for this context). Note that this is clearly more verbose than other solutions, but would probably benefit in the long-term.
First we use David's simple "extend" function, which copies properties to a specified object:
function extend(o,p) {
for (var prop in p) {
o[prop] = p[prop];
}
return o;
}
Then we implement his Subclass definition utility:
function defineSubclass(superclass, // Constructor of our superclass
constructor, // Constructor of our new subclass
methods, // Instance methods
statics) { // Class properties
// Set up the prototype object of the subclass
constructor.prototype = Object.create(superclass.prototype);
constructor.prototype.constructor = constructor;
if (methods) extend(constructor.prototype, methods);
if (statics) extend(constructor, statics);
return constructor;
}
For the last bit of preparation we enhance our Function prototype with David's new jiggery-pokery:
Function.prototype.extend = function(constructor, methods, statics) {
return defineSubclass(this, constructor, methods, statics);
};
After defining our Monster class, we do the following (which is re-usable for any new Classes we want to extend/inherit):
var Monkey = Monster.extend(
// constructor
function Monkey() {
this.bananaCount = 5;
Monster.apply(this, arguments); // Superclass()
},
// methods added to prototype
{
eatBanana: function () {
this.bananaCount--;
this.health++;
this.growl();
}
}
);
Some time this happens when your Java folder get updated.
Open Eclipse folder and search file eclipse.ini. Open the eclipse.ini file and check whether jre version is same as jre available in your java folder.
I faced same problem when my jre got changed from jre1.8.0_101 to jre1.8.0_111.
C:\Program Files\Java\jre1.8.0_101\bin to C:\Program Files\Java\jre1.8.0_111\bin
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
def foo():
global bar
bar = 32
I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
You can imitate open source Dockerfile, for example:
Node: node12-github
RUN groupadd --gid 1000 node \
&& useradd --uid 1000 --gid node --shell /bin/bash --create-home node
superset: superset-github
RUN useradd --user-group --create-home --no-log-init --shell /bin/bash
superset
I think it's a good way to follow open source.
I made a blog post about NetBeans' new and upcoming support for Django. When paired with its already fantastic Python, JavaScript, HTML and CSS support, it's a strong candidate in my mind!
I'm running MacOS Mojave (10.14.6) and to get MySQL to recognize my config file, I had to place it in /usr/local/mysql-5.7.26-macos10.14-x86_64/etc/my.cnf. Also I have a symbolic link pointing to it from /usr/local/@mysql/etc/my.cnf .
I was trying to turn off sql_mode=only_full_group_by and setting that option in the config file was the only way I could get the setting to persist across sessions. The contents of the config file are:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION
I'm using the native install of MySQL, not the Homebrew set up.
If you just want to append data to the Url You can do so by using HttpUrlConnection since HttpClient is now deprecated. A better way would be to use a library like-
Volley Retrofit
We can post data to the php script and fetch result and display it by using this code performed Through AsyncTask class.
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
String data ="";
int sizeData = 0;
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
Dialog.setCancelable(false);
Dialog.setCanceledOnTouchOutside(false);
try{
// Set Request parameter
data +="&" + URLEncoder.encode("username", "UTF-8") + "="+edittext.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);//define connection timeout
conn.setReadTimeout(5000);//define read timeout
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(),"Error encountered",Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject jsonRootObject = new JSONObject(Content);
JSONObject json2 =jsonRootObject.getJSONObject("jsonkey");//pass jsonkey here
String id =json2.optString("id").toString();//parse json to string through parameters
//the result is stored in string id. you can display it now
} catch (JSONException e) {e.printStackTrace();}
}
}
}
But using libraries such as volley or retrofit is much better option because Asynctask class and HttpurlConnection is slower compared to libraries. Also the library will fetch everything and is faster as well.
You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.
https://en.wikipedia.org/wiki/SQL_injection
I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.
In my scenario, I want to update the status of status based on his id
student_obj = StudentStatus.objects.get(student_id=101)
student_obj.status= 'Enrolled'
student_obj.save()
Or If you want the last id from Student_Info table you can use the following.
student_obj = StudentStatus.objects.get(student_id=StudentInfo.objects.last().id)
student_obj.status= 'Enrolled'
student_obj.save()
This helped me to get remote branch before merging it into other:
git fetch repo xyz:xyz
git checkout xyz
Have you tried the import text function.
xCode 6 allows you to right click on the provisioning profile under account -> detail (the screen shot you have there) & shows a popup "show in finder".
For me it didn't work after doing all of the steps suggested in the question and in the top answer. Initially the import didn't work, and then when I restarted IntelliJ, I got these messages from the Gradle Plugin:
Gradle DSL method not found: 'annotationProcessor()'
Possible causes:<ul><li>The project 'wq-handler-service' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Upgrade plugin to version 2.3.2 and sync project</li><li>The project 'wq-handler-service' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin.
Apply Gradle plugin</li>
This was weird because I don't develop for Android, just using IntelliJ for Mac OS.
To be fair, my build.gradle
file had these lines in the dependencies
section, which I copied from a colleague:
compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
After checking versions, the only thing that completely solved my problem was adding the below to the plugins
section of build.gradle
, which I found on this page:
id 'net.ltgt.apt' version '0.15'
Looks like it's a
Gradle plugin making it easier/safer to use Java annotation processors
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * @year + @month - 22801, @day - 1)
You can test if bool is defined in c99 stdbool.h with
#ifndef __bool_true_false_are_defined || __bool_true_false_are_defined == 0
//typedef or define here
#endif
This worked for me:
Rename-Item -Path A_Package.nupkg -NewName A_Package.zip
Expand-Archive -Path A_Package.zip -DestinationPath C:\Reference
Add this to your dependencies in build.gradle
:
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
...
The latest version can be found here
Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project
Take a look at your libraries folder, the library you just added should be in there.
Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard
(or some variation of that name) which is usually symlinked to to a directory in /storage
like /storage/sdcard0
or /storage/0
sometimes the emulated storage is mounted to /sdcard
and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard
git config information will stored in ~/.gitconfig
in unix platform.
In Windows it will be stored in C:/users/<NAME>/.gitconfig.
You can edit it manually by opening this files and deleting the fields which you are interested.
Depends on what your target browsers are. In newer ones it's as simple as:
-moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
box-shadow: 0 0 5px #fff;
For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.
▐▐ is HTML and is made with this code: ▐▐
.
I ended up here when trying to figure this out. With the version that's up there right now you can drag and drop a folder into it and it works, even though it doesn't allow you to select a folder when you open the upload dialogue.
Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N
for the S/U and U/S contention, as in No Conflict.
As for the HOLDLOCK hint the documentation states:
HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.
...
SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...
and the Transaction Isolation Level topic explains what SERIALIZABLE means:
No other transactions can modify data that has been read by the current transaction until the current transaction completes.
Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Therefore the behavior you see is perfectly explained by the product documentation:
SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...
After OP edit:
I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.
The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.
in Angular-9 if you want to disable/enable on button click here is a simple solution if you are using reactive forms.
define a function in component.ts file
//enable example you can use the same approach for disable with .disable()
toggleEnable() {
this.yourFormName.controls.formFieldName.enable();
console.log("Clicked")
}
Call it from your component.html
e.g
<button type="button" data-toggle="form-control" class="bg-primary text-white btn-
reset" style="width:100%"(click)="toggleEnable()">
I had the same issue but when i deleted the cached items from Temp folder the build failed.
In order to make the build work again I had to close the project and reopen it.
You're looking for the FromBase64Transform
class, used with the CryptoStream
class.
If you have a string, you can also call Convert.FromBase64String
.
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.
For more information read this.
Hope it helps.
I had the same problem, caused by a clash between the graphicx
package and an inclusion of the epsfig
package that survived the ages...
Please check that there is no inclusion of epsfig
, it is deprecated.
Look at this method to see which fields are supported. You will find for LocalDateTime
:
•NANO_OF_SECOND
•NANO_OF_DAY
•MICRO_OF_SECOND
•MICRO_OF_DAY
•MILLI_OF_SECOND
•MILLI_OF_DAY
•SECOND_OF_MINUTE
•SECOND_OF_DAY
•MINUTE_OF_HOUR
•MINUTE_OF_DAY
•HOUR_OF_AMPM
•CLOCK_HOUR_OF_AMPM
•HOUR_OF_DAY
•CLOCK_HOUR_OF_DAY
•AMPM_OF_DAY
•DAY_OF_WEEK
•ALIGNED_DAY_OF_WEEK_IN_MONTH
•ALIGNED_DAY_OF_WEEK_IN_YEAR
•DAY_OF_MONTH
•DAY_OF_YEAR
•EPOCH_DAY
•ALIGNED_WEEK_OF_MONTH
•ALIGNED_WEEK_OF_YEAR
•MONTH_OF_YEAR
•PROLEPTIC_MONTH
•YEAR_OF_ERA
•YEAR
•ERA
The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime
cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate
(with even less supported fields).
If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.
Coming back to your question and the numbers in your code:
The result 1605 is correct
=> (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1
16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).
UPDATE after given timezone info:
local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861
As JSR-310-code with two equivalent approaches:
long secondsSinceUnixEpoch1 =
LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();
long secondsSinceUnixEpoch2 =
LocalDate
.of(2014, 2, 4)
.atTime(19, 51, 1)
.atZone(ZoneId.of("Europe/Oslo"))
.toEpochSecond();
Although you could certainly use the compareTo
method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.
Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:
if (count > 0) { }
And the Integer
instance count
gets automatically converted to an int
for the comparison.
If you're having trouble understanding this, check out the link above, or imagine it's doing this:
if (count.intValue() > 0) { }
There's a few useful functions for dealing with errno
s. (Just to make it clear, these are built-in to libc
-- I'm just providing sample implementations because some people find reading code clearer than reading English.)
#include <string.h>
char *strerror(int errnum);
/* you can think of it as being implemented like this: */
static char strerror_buf[1024];
const char *sys_errlist[] = {
[EPERM] = "Operation not permitted",
[ENOENT] = "No such file or directory",
[ESRCH] = "No such process",
[EINTR] = "Interrupted system call",
[EIO] = "I/O error",
[ENXIO] = "No such device or address",
[E2BIG] = "Argument list too long",
/* etc. */
};
int sys_nerr = sizeof(sys_errlist) / sizeof(char *);
char *strerror(int errnum) {
if (0 <= errnum && errnum < sys_nerr && sys_errlist[errnum])
strcpy(strerror_buf, sys_errlist[errnum]);
else
sprintf(strerror_buf, "Unknown error %d", errnum);
return strerror_buf;
}
strerror
returns a string describing the error number you've passed to it. Caution, this is not thread- or interrupt-safe; it is free to rewrite the string and return the same pointer on the next invocation. Use strerror_r
if you need to worry about that.
#include <stdio.h>
void perror(const char *s);
/* you can think of it as being implemented like this: */
void perror(const char *s) {
fprintf(stderr, "%s: %s\n", s, strerror(errno));
}
perror
prints out the message you give it, plus a string describing the current errno
, to standard error.
That's the other way around. You should write:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
click: function() {
// Handle click...
}
}, "td");
<mat-icon style="-webkit-text-fill-color:blue">face</mat-icon>
If you want to find elapsed time, this method will work as long as you don't reboot the computer between the start and end.
In Windows, use GetTickCount(). Here's how:
DWORD dwStart = GetTickCount();
...
... process you want to measure elapsed time for
...
DWORD dwElapsed = GetTickCount() - dwStart;
dwElapsed is now the number of elapsed milliseconds.
In Linux, use clock() and CLOCKS_PER_SEC to do about the same thing.
If you need timestamps that last through reboots or across PCs (which would need quite good syncronization indeed), then use the other methods (gettimeofday()).
Also, in Windows at least you can get much better than standard time resolution. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:
timeBeginPeriod(1);
at the beginning of your program or process and a:
timeEndPeriod(1);
at the end, then the quantum will change to 1 ms, and you will get much better time resolution on the GetTickCount() call. However, this does make a subtle change to how your entire computer runs processes, so keep that in mind. However, Windows Media Player and many other things do this routinely anyway, so I don't worry too much about it.
I'm sure there's probably some way to do the same in Linux (probably with much better control, or maybe with sub-millisecond quantums) but I haven't needed to do that yet in Linux.
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
Bash one-liner
echo -n "5a" | while read -N2 code; do printf "\x$code"; done
Some awk
version.
awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'
When pattern found, set c=5
If c
is true, print and decrease number of c
Following worked for me
git pull
Then checkout the required branch
If you have Local Values overriding master values, you won't change its values in php.ini take a look for those variables in a .htaccess or in the virtual-host config file.
...
php_admin_value display_errors On
php_admin_value error_reporting E_ALL
</VirtualHost>
If you edit vhost, restart apache,
$ sudo service apache2 restart
.htaccess edits don't need apache to restart
There's now a simpler way with .NET Standard
or .NET Core
:
var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());
NOTE: In order to use the JsonMediaTypeFormatter
class, you will need to install the Microsoft.AspNet.WebApi.Client
NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App
.
Using this signature of HttpClient.PostAsync
, you can pass in any object and the JsonMediaTypeFormatter
will automatically take care of serialization etc.
With the response, you can use HttpContent.ReadAsAsync<T>
to deserialize the response content to the type that you are expecting:
var responseObject = await response.Content.ReadAsAsync<MyResponseType>();
Type mysql --version
to see if it is installed.
To find location use find -name mysql
.
The problem with other answers here is that they use position: absolute;
This makes it difficult to layout the element itself in relation to the ::before
pseudo-element. For example, if you wish to show an image before a link like this:
Here's how I was able to achieve the layout in the picture:
a::before {_x000D_
content: "";_x000D_
float: left;_x000D_
width: 16px;_x000D_
height: 16px;_x000D_
margin-right: 5px;_x000D_
background: url(../../lhsMenu/images/internal_link.png) no-repeat 0 0;_x000D_
background-size: 80%;_x000D_
}
_x000D_
Note that this method allows you to scale the background image, as well as keep the ability to use margins and padding for layout.
Use the write()-Method of the Popup's document to put your markup there:
$.post(url, function (data) {
var w = window.open('about:blank');
w.document.open();
w.document.write(data);
w.document.close();
});
You could set your SVG as a mask. That way setting a background-color would act as your fill color.
HTML
<div class="logo"></div>
CSS
.logo {
background-color: red;
-webkit-mask: url(logo.svg) no-repeat center;
mask: url(logo.svg) no-repeat center;
}
JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/mask
Please check whether your browser supports this feature: https://caniuse.com/#search=mask
Deleting the file will also remove the content. See remove file.
$country_code = trim(file_get_contents("http://ipinfo.io/{$ip_address}/country"))
will get you the country code.
If you just want an outer border, the easiest way is to put it in a Border control:
<Border BorderBrush="Black" BorderThickness="2">
<Grid>
<!-- Grid contents here -->
</Grid>
</Border>
The reason you're seeing the border completely fill your control is that, by default, it's HorizontalAlignment and VerticalAlignment are set to Stretch. Try the following:
<Grid>
<Border HorizontalAlignment="Left" VerticalAlignment="Top" BorderBrush="Black" BorderThickness="2">
<Grid Height="166" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" Width="479" Background="#FFF2F2F2" />
</Border>
</Grid>
This should get you what you're after (though you may want to put a margin on all 4 sides, not just 2...)
You can also use a while loop:
while (true) {
//your code
}
I live in uk was keep on trying for 'us-west-2'region. So redirected to 'eu-west-2'. The correct region for S3 is 'eu-west-2'
I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.
example:
linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));
see definition: http://man7.org/linux/man-pages/man7/socket.7.html
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger
structure.
struct linger {
int l_onoff; /* linger active */
int l_linger; /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.
The reason you need to use Thread.currentThread()
in order to call interrupt()
is that interrupt()
is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.
I know the competition is closed for some years. …
Nonetheless this is my suggestion for a pure python prime sieve, based on omitting the multiples of 2, 3 and 5 by using appropriate steps while processing the sieve forward. Nonetheless it is actually slower for N<10^9 than @Robert William Hanks superior solutions rwh_primes2 and rwh_primes1. By using a ctypes.c_ushort sieve array above 1.5* 10^8 it is somehow adaptive to memory limits.
10^6
$ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.primeSieveSeq(1000000)" 10 loops, best of 3: 46.7 msec per loop
to compare:$ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes1(1000000)" 10 loops, best of 3: 43.2 msec per loop to compare: $ python -m timeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes2(1000000)" 10 loops, best of 3: 34.5 msec per loop
10^7
$ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.primeSieveSeq(10000000)" 10 loops, best of 3: 530 msec per loop
to compare:$ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes1(10000000)" 10 loops, best of 3: 494 msec per loop to compare: $ python -m timeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes2(10000000)" 10 loops, best of 3: 375 msec per loop
10^8
$ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.primeSieveSeq(100000000)" 10 loops, best of 3: 5.55 sec per loop
to compare: $ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes1(100000000)" 10 loops, best of 3: 5.33 sec per loop to compare: $ python -m timeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes2(100000000)" 10 loops, best of 3: 3.95 sec per loop
10^9
$ python -mtimeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.primeSieveSeq(1000000000)" 10 loops, best of 3: 61.2 sec per loop
to compare: $ python -mtimeit -n 3 -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes1(1000000000)" 3 loops, best of 3: 97.8 sec per loop
to compare: $ python -m timeit -s"import primeSieveSpeedComp" "primeSieveSpeedComp.rwh_primes2(1000000000)" 10 loops, best of 3: 41.9 sec per loop
You may copy the code below into ubuntus primeSieveSpeedComp to review this tests.
def primeSieveSeq(MAX_Int):
if MAX_Int > 5*10**8:
import ctypes
int16Array = ctypes.c_ushort * (MAX_Int >> 1)
sieve = int16Array()
#print 'uses ctypes "unsigned short int Array"'
else:
sieve = (MAX_Int >> 1) * [False]
#print 'uses python list() of long long int'
if MAX_Int < 10**8:
sieve[4::3] = [True]*((MAX_Int - 8)/6+1)
sieve[12::5] = [True]*((MAX_Int - 24)/10+1)
r = [2, 3, 5]
n = 0
for i in xrange(int(MAX_Int**0.5)/30+1):
n += 3
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 2
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 1
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 2
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 1
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 2
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 3
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
n += 1
if not sieve[n]:
n2 = (n << 1) + 1
r.append(n2)
n2q = (n2**2) >> 1
sieve[n2q::n2] = [True]*(((MAX_Int >> 1) - n2q - 1) / n2 + 1)
if MAX_Int < 10**8:
return [2, 3, 5]+[(p << 1) + 1 for p in [n for n in xrange(3, MAX_Int >> 1) if not sieve[n]]]
n = n >> 1
try:
for i in xrange((MAX_Int-2*n)/30 + 1):
n += 3
if not sieve[n]:
r.append((n << 1) + 1)
n += 2
if not sieve[n]:
r.append((n << 1) + 1)
n += 1
if not sieve[n]:
r.append((n << 1) + 1)
n += 2
if not sieve[n]:
r.append((n << 1) + 1)
n += 1
if not sieve[n]:
r.append((n << 1) + 1)
n += 2
if not sieve[n]:
r.append((n << 1) + 1)
n += 3
if not sieve[n]:
r.append((n << 1) + 1)
n += 1
if not sieve[n]:
r.append((n << 1) + 1)
except:
pass
return r
I use this alias
git config --global alias.track '!f() { ([ $# -eq 2 ] && ( echo "Setting tracking for branch " $1 " -> " $2;git branch --set-upstream $1 $2; ) || ( git for-each-ref --format="local: %(refname:short) <--sync--> remote: %(upstream:short)" refs/heads && echo --Remotes && git remote -v)); }; f'
then
git track
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
-webkit-transition: all 1s ease; /* Safari and Chrome */
-moz-transition: all 1s ease; /* Firefox */
-ms-transition: all 1s ease; /* IE 9 */
-o-transition: all 1s ease; /* Opera */
transition: all 1s ease;
just want to make a note on the above transitions only need
-webkit-transition: all 1s ease; /* Safari and Chrome */
transition: all 1s ease;
and -ms- certainly doenst work for IE 9 i dont know where you got that idea from.
It would help to have sample information about your output. Recursively using rbind
on bigger and bigger things is not recommended. My first guess at something that would help you:
z <- list(1:3,4:6,7:9)
do.call(rbind,z)
See a related question for more efficiency, if needed.
You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example
ALTER SEQUENCE mysequence INCREMENT BY 100;
select mysequence.nextval from dual;
ALTER SEQUENCE mysequence INCREMENT BY 1;
replace the query inside your model function with this
$query = $this->db->query("SELECT id FROM home");
in view:
echo $query->num_rows();
input
elementvar getInputValueWidth = (function(){
// https://stackoverflow.com/a/49982135/104380
function copyNodeStyle(sourceNode, targetNode) {
var computedStyle = window.getComputedStyle(sourceNode);
Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
}
function createInputMeassureElm( inputelm ){
// create a dummy input element for measurements
var meassureElm = document.createElement('span');
// copy the read input's styles to the dummy input
copyNodeStyle(inputelm, meassureElm);
// set hard-coded styles needed for propper meassuring
meassureElm.style.width = 'auto';
meassureElm.style.position = 'absolute';
meassureElm.style.left = '-9999px';
meassureElm.style.top = '-9999px';
meassureElm.style.whiteSpace = 'pre';
meassureElm.textContent = inputelm.value || '';
// add the meassure element to the body
document.body.appendChild(meassureElm);
return meassureElm;
}
return function(){
return createInputMeassureElm(this).offsetWidth;
}
})();
// delegated event binding
document.body.addEventListener('input', onInputDelegate)
function onInputDelegate(e){
if( e.target.classList.contains('autoSize') )
e.target.style.width = getInputValueWidth.call(e.target) + 'px';
}
_x000D_
input{
font-size:1.3em;
padding:5px;
margin-bottom: 1em;
}
input.type2{
font-size: 2.5em;
letter-spacing: 4px;
font-style: italic;
}
_x000D_
<input class='autoSize' value="type something">
<br>
<input class='autoSize type2' value="here too">
_x000D_
all features of jwt.io doesn't support all languages. In NodeJs you can use
var decoded = jwt.decode(token);
my working clean solution (2017)
function loaderScript(scriptUrl){
return new Promise(function (res, rej) {
let script = document.createElement('script');
script.src = scriptUrl;
script.type = 'text/javascript';
script.onError = rej;
script.async = true;
script.onload = res;
script.addEventListener('error',rej);
script.addEventListener('load',res);
document.head.appendChild(script);
})
}
As Martin pointed, used like that:
const event = loaderScript("myscript.js")
.then(() => { console.log("loaded"); })
.catch(() => { console.log("error"); });
OR
try{
await loaderScript("myscript.js")
console.log("loaded");
}catch{
console.log("error");
}
I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.
Hope this helps.
this will set your session to keep everything till the browser is closed
session.setMaxinactiveinterval(-1);
and this should set it for 1 day
session.setMaxInactiveInterval(60*60*24);
I suspect the problem is that you've put the "-D" after the -jar
. Try this:
java -Dtest="true" -jar myApplication.jar
From the command line help:
java [-options] -jar jarfile [args...]
In other words, the way you've got it at the moment will treat -Dtest="true"
as one of the arguments to pass to main
instead of as a JVM argument.
(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.)
As per the above this will fix server side validation of an Email Address:
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
However...
If you are using JQuery client side validation you should know that the Email validates differently server side (model validation) to client side (JQuery validation). In that test@example (a top level domain email address) would fail server side but would validate fine on the client side.
To fix this disparity you can override the default client side email validation as follows:
$.validator.methods.email = function (value, element) {
return this.optional(element) || /^[a-z0-9._]+@[a-z]+\.[a-z.]+/.test(value);
}
what about this :
git log --pretty="%h %cD %cn %s"
it shows someting like :
674cd0d Wed, 20 Nov 2019 12:15:38 +0000 Bob commit message
see the pretty format documentation enter link description here
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
I have a hell of a time using virtualenv
on windows with git bash, I usually end up specifying the python binary explicitly.
If my environment is in say .env
I'll call python via ./.env/Scripts/python.exe …
, or in a shebang line #!./.env/Scripts/python.exe
;
Both assuming your working directory contains your virtualenv (.env
).
Below is code to break a loop in a simple way
import scala.util.control.Breaks.break
object RecurringCharacter {
def main(args: Array[String]) {
val str = "nileshshinde";
for (i <- 0 to str.length() - 1) {
for (j <- i + 1 to str.length() - 1) {
if (str(i) == str(j)) {
println("First Repeted Character " + str(i))
break() //break method will exit the loop with an Exception "Exception in thread "main" scala.util.control.BreakControl"
}
}
}
}
}
For 4th highest salary:
select min(salary) from (select distinct salary from hibernatepractice.employee e order by salary desc limit 4) as e1;
For n th highest salary:
select min(salary) from (select distinct salary from hibernatepractice.employee e order by salary desc limit n) as e1;
Remember to use the server's local name, not the domain name, when resolving the name
IIS AppPool\DefaultAppPool
(just a reminder because this tripped me up for a bit):
I don't think that anybody has mentioned this, but alloca also has some serious security issues not necessarily present with malloc (though these issues also arise with any stack based arrays, dynamic or not). Since the memory is allocated on the stack, buffer overflows/underflows have much more serious consequences than with just malloc.
In particular, the return address for a function is stored on the stack. If this value gets corrupted, your code could be made to go to any executable region of memory. Compilers go to great lengths to make this difficult (in particular by randomizing address layout). However, this is clearly worse than just a stack overflow since the best case is a SEGFAULT if the return value is corrupted, but it could also start executing a random piece of memory or in the worst case some region of memory which compromises your program's security.
If you want to access a property from inside a class you should:
private $classNumber = 8;
Using refs
is not best practice because it reads the DOM directly, it's better to use React's state
instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.
You can use setState
together with an onChange
event listener to render the component again every time the input field changes:
// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />
// Button is disabled when input state is empty.
<button disabled={!this.state.value} />
Here's a working example:
class AddItem extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = { value: '' };_x000D_
this.onChange = this.onChange.bind(this);_x000D_
this.add = this.add.bind(this);_x000D_
}_x000D_
_x000D_
add() {_x000D_
this.props.onButtonClick(this.state.value);_x000D_
this.setState({ value: '' });_x000D_
}_x000D_
_x000D_
onChange(e) {_x000D_
this.setState({ value: e.target.value });_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div className="add-item">_x000D_
<input_x000D_
type="text"_x000D_
className="add-item__input"_x000D_
value={this.state.value}_x000D_
onChange={this.onChange}_x000D_
placeholder={this.props.placeholder}_x000D_
/>_x000D_
<button_x000D_
disabled={!this.state.value}_x000D_
className="add-item__button"_x000D_
onClick={this.add}_x000D_
>_x000D_
Add_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,_x000D_
document.getElementById('View')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id='View'></div>
_x000D_
I found something else. Android uses the /libs
directory for JAR files. I have seen the "Conversion to Dalvik format failed with error 1" error numerous times, always when I made a mistake in my JAR files.
Now I upgraded Roboguice to a newer version, by putting the new JAR file in the /libs
directory and switching the class path to the new version. That caused the Dalvik error.
When I removed one of the Roboguice JAR files from the /libs
folder, the error disappeared. Apparently, Android picks up all JAR files from /libs
, regardless of which ones you specify in the Java build path. I don't remember exactly, but I think Android started using /libs
by default starting with Android 4.0 (Ice Cream Sandwich, ICS).
ul {
text-align: center;
list-style: inside;
}
If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes
The backslash escapes the #, interpreting it as its literal character instead of a comment character.
Are you sure the Start
method returns before the child process starts? I was always under the impression that Start
starts the child process synchronously.
If you want to wait until your child process finishes some sort of initialization then you need inter-process communication - see Interprocess communication for Windows in C# (.NET 2.0).
The answer is right in the MYSQL manual itself.
"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
To create a test case template:
"New" -> "JUnit Test Case" -> Select "Class under test" -> Select "Available methods". I think the wizard is quite easy for you.
List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2"),
new KeyValuePair<string, string>("Key3", "Value3"),
};
kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));
Using this code:
foreach (KeyValuePair<string, string> kvp in kvpList)
{
Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}
the expected output should be:
Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3
The same will work with a KeyValuePair or whatever other type you want to use..
Edit -
To lookup by the key, you can do the following:
var result = stringList.Where(s => s == "Lookup");
You could do this with a KeyValuePair by doing the following:
var result = kvpList.Where (kvp => kvp.Value == "Lookup");
Last edit -
Made the answer specific to KeyValuePair rather than string.
Although this answer is a bit verbose it does allow you to create a single commit branch by doing a single merge with another branch. (No rebasing/squashing/merging individual commits).
Since we don't care about the in-between commits we can use a simple solution:
# Merge and resolve conflicts
git merge origin/master
# Soft reset and create a HEAD with the version you want
git reset --soft origin/master
git commit -m "Commit message"
git push origin your-branch -f
... then to remove the history...
# Get the most up-to-date master
git checkout master
git reset --hard
# Create a temporary branch
git checkout -b temp-branch
# Retrieve the diff between master and your-branch and commit with a single commit
git checkout origin/your-branch
git commit -m "Feature commit"
# Force push to the feature branch
git push origin temp-branch:your-branch -f
# Clean up
git checkout your-branch
git branch -D temp-branch
This can all be put into a bash function with 3 params like so squashall --their master --mine your-branch --msg "Feature commit"
and it will work as long as you have the correct version of files locally.
Change it to this:
var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
This is a regular expression literal that is passed the i
flag which means to be case insensitive.
Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.
A faster / alternative way to change the height and/or width of a UIView
is by setting its width/height through frame.size
:
let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight
def listToStringWithoutBrackets(list1):
return str(list1).replace('[','').replace(']','')
You want to replace the values in a dataset column, but you're getting an error like this:
invalid factor level, NA generated
Try this instead:
levels(dataframe$column)[levels(dataframe$column)=='old_value'] <- 'new_value'
Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:
<ol type="A">
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
</ol>
Then in the stylesheet:
ol {font-weight: bold;}
ol li span.label {font-weight:normal;}
And it bolded the A
, B
, C
etc and not the text.
(Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)
To prevent division by zero you could pre-initialize the output 'out' where the div0 error happens, eg np.where
does not cut it since the complete line is evaluated regardless of condition.
example with pre-initialization:
a = np.arange(10).reshape(2,5)
a[1,3] = 0
print(a) #[[0 1 2 3 4], [5 6 7 0 9]]
a[0]/a[1] # errors at 3/0
out = np.ones( (5) ) #preinit
np.divide(a[0],a[1], out=out, where=a[1]!=0) #only divide nonzeros else 1
Install below NuGet Package will solve your issue
Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.SqlServer
You could also use the coalesce function. I tested this in PostgreSQL, but it should also work for MySQL or MS SQL server.
INNER JOIN x ON coalesce(x.qid, -1) = coalesce(y.qid, -1)
This will replace NULL
with -1
before evaluating it. Hence there must be no -1
in qid
.
Since you can never depend on exact comparisons when dealing with floating point computations (such as these ways of calculating the square root), a less error-prone implementation would be
import math
def is_square(integer):
root = math.sqrt(integer)
return integer == int(root + 0.5) ** 2
Imagine integer
is 9
. math.sqrt(9)
could be 3.0
, but it could also be something like 2.99999
or 3.00001
, so squaring the result right off isn't reliable. Knowing that int
takes the floor value, increasing the float value by 0.5
first means we'll get the value we're looking for if we're in a range where float
still has a fine enough resolution to represent numbers near the one for which we are looking.
Getting the second largest number from an array is pretty easy in python, I have done with simple steps and put various ways of test cases and it gave the right answer every time. PS. I know it's for c but I just gave a simple solution to the question if done in python
n = int(input()) #taking number of elements in array
arr = map(int, input().split()) #taking differet elements
l=[]
s=set()
for i in arr: #putting all the elemnents in set to remove any duplicate number
s.add(i)
for j in s: #putting all element from the set in the list to sort and get the second largest number
l.append(j)
l.sort()
c=len(l)
print(l[c-2]) #printing second largest number
var result = from cx in CustomerList
group cx by cx.GroupID into cxGroup
orderby cxGroup.Key
select cxGroup;
foreach (var cxGroup in result) {
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key));
foreach (var cx in cxGroup) {
Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}",
new object[] { cx.ID, cx.Name, cx.GroupID }));
}
}
If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix yourscript.sh
. Then, run the script.
As of 2019, it looks like you can get toLocaleDateString to return only certain parts and then you can join them as you wish:
var date = new Date();
console.log(date.toLocaleDateString("en-US", { day: 'numeric' })
+ "-"+ date.toLocaleDateString("en-US", { month: 'short' })
+ "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> 16-Nov-2019
console.log(date.toLocaleDateString("en-US", { month: 'long' })
+ " " + date.toLocaleDateString("en-US", { day: 'numeric' })
+ ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> November 16, 2019
I'm assuming windows here. So, you'll need to use WMI to get that information. Check out The Scripting Guy's archives for a lot of examples on how to use WMI from a script.
You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).
If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).
I had a similar use case, except I wanted to checkout only the commit for a tag and prune the directories. Using --depth 1
makes it really sparse and can really speed things up.
mkdir myrepo
cd myrepo
git init
git config core.sparseCheckout true
git remote add origin <url> # Note: no -f option
echo "path/within_repo/to/subdir/" > .git/info/sparse-checkout
git fetch --depth 1 origin tag <tagname>
git checkout <tagname>
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
Do you have the right permissions to write to SD card in your manifest ? Look for WRITE_EXTERNAL_STORAGE at http://developer.android.com/reference/android/Manifest.permission.html
In addition to the other answers, I'd like to improve the removal, to something more generic:
$(this).closest('tr').remove();
This would be much better than using $(this).parent().parent().remove();
, because it doesn't depend on the depth of the element. So, the structure of the row becomes much more flexible.
$post = Post::select(DB::raw('count(*) as user_count, category_id'))
->groupBy('category_id')
->get();
This is an example which results count of post by category.
You can't. Javascript runs client side, C# runs server side.
In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.
To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
If I understand correctly then it would be easier if you gave your image a transparent background and set the background container's background-color property without having to use filters and so on.
http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html
Shows you how to use filters in IE. Maybe if you leverage something from that. Not very cross-browser compatible though. Another option might be to have two images and use them as background-images (rather than img tags), swap one out after another using the :hover pseudo selector.
SELECT text
FROM all_source
where name = 'FGETALGOGROUPKEY'
order by line
alternatively:
select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
from dual;
We can do a nested loop to visit all the elements of elements in your list:
for (Gun g: gunList) {
System.out.print(g.toString() + "\n ");
for(Bullet b : g.getBullet() {
System.out.print(g);
}
System.out.println();
}
Best Approach
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class OrderByValue {
public static void main(String a[]){
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("java", 20);
map.put("C++", 45);
map.put("Unix", 67);
map.put("MAC", 26);
map.put("Why this kolavari", 93);
Set<Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
{
return (o1.getValue()).compareTo( o2.getValue() );//Ascending order
//return (o2.getValue()).compareTo( o1.getValue() );//Descending order
}
} );
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}}
Output
java ==== 20
MAC ==== 26
C++ ==== 45
Unix ==== 67
Why this kolavari ==== 93
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.
Say, you have an object:
{foo: [1, 4, 7, 10], bar: "baz"}
serializing into JSON will convert it into a string:
'{"foo":[1,4,7,10],"bar":"baz"}'
which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}
.
Sounds like you need to install the devel package for zlib, probably want to do something like sudo apt-get install zlib1g-dev
(I don't use ubuntu so you'll want to double-check the package). Instead of using python-brew you might want to consider just compiling by hand, it's not very hard. Just download the source, and configure
, make
, make install
. You'll want to at least set --prefix
to somewhere, so it'll get installed where you want.
./configure --prefix=/opt/python2.7 + other options
make
make install
You can check what configuration options are available with ./configure --help
and see what your system python was compiled with by doing:
python -c "import sysconfig; print sysconfig.get_config_var('CONFIG_ARGS')"
The key is to make sure you have the development packages installed for your system, so that Python will be able to build the zlib
, sqlite3
, etc modules. The python docs cover the build process in more detail: http://docs.python.org/using/unix.html#building-python.
As of ruby 2.3.0
class Check
def self.first_method
second_method
end
private
def self.second_method
puts "well I executed"
end
end
Check.first_method
#=> well I executed
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
What you want cannot be done, because plt.legend()
places a legend in the current axes, in your case in the last one.
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.
use this
byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);
use the
innerHTML
property and access the td
using getElementById()
as always.
Maybe
if (inventory.contains("bread") && !inventory.contains("water"))
Or
if (inventory.contains("bread")) {
if (!inventory.contains("water")) {
// do something here
}
}
Try the cex
argument:
?par
cex
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
In both languages (Java and C#) int
is 4-byte signed integer.
Unlike Java, C# Provides both signed and unsigned integer values. As Java and C# are object object-oriented, some operations in these languages do not map directly onto instructions provided by the run time and so needs to be defined as part of an object of some type.
C# provides System.Int32
which is a value type using a part of memory that belongs to the reference type on the heap.
java provides java.lang.Integer
which is a reference type operating on int
. The methods in Integer
can't be compiled directly to run time instructions.So we box an int value to convert it into an instance of Integer and use the methods which expects instance of some type (like toString()
, parseInt()
, valueOf()
etc).
In C# variable int refers to System.Int32.Any
4-byte value in memory can be interpreted as a primitive int, that can be manipulated by instance of System.Int32.So int is an alias for System.Int32.When
using integer-related methods like int.Parse()
, int.ToString()
etc. Integer is compiled into the FCL System.Int32
struct calling the respective methods like Int32.Parse()
, Int32.ToString()
.
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
The same issue with 7.1
apt-get install php7.1-json
sudo nano /etc/php/7.1/mods-available/json.ini
If you want to know if a string is a number, you could always try parsing it:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Note that TryParse
returns a bool
, which you can use to check if your parsing succeeded.
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED - TESTED SCRIPT
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
<script>
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
alert(cellVal);
}
}
</script>
All of the previous answers have one or more problems. The accepted answer allows ip numbers like 999.999.999.999. The currently second most upvoted answer requires prefixing with 0 such as 127.000.000.001 or 008.008.008.008 instead of 127.0.0.1 or 8.8.8.8. Apama has it almost right, but that expression requires that the ipnumber is the only thing on the line, no leading or trailing space allowed, nor can it select ip's from the middle of a line.
I think the correct regex can be found on http://www.regextester.com/22
So if you want to extract all ip-adresses from a file use:
grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" file.txt
If you don't want duplicates use:
grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" file.txt | sort | uniq
Please comment if there still are problems in this regex. It easy to find many wrong regex for this problem, I hope this one has no real issues.
The ASCIIfication of 3 is "\x33"
not "\x03"
!
That is what python does for str(3)
but it would be totally wrong for bytes, as they should be considered arrays of binary data and not be abused as strings.
The most easy way to achieve what you want is bytes((3,))
, which is better than bytes([3])
because initializing a list is much more expensive, so never use lists when you can use tuples. You can convert bigger integers by using int.to_bytes(3, "little")
.
Initializing bytes with a given length makes sense and is the most useful, as they are often used to create some type of buffer for which you need some memory of given size allocated. I often use this when initializing arrays or expanding some file by writing zeros to it.
Date is not in any time zone (it is a millisecond office from a defined moment in time same for everyone), but underlying (R)DBs generally store timestamps in political format (year, month, day, hour, minute, second, ...) that is time-zone sensitive.
To be serious, Hibernate MUST be allow being told within some form of mapping that the DB date is in such-and-such timezone so that when it loads or stores it it does not assume its own...
To limit what you run as sudo, you could run
python non_sudo_stuff.py
sudo -E python -c "import os; os.system('sudo echo 1')"
without needing to store the password. The -E
parameter passes your current user's env to the process. Note that your shell will have sudo priveleges after the second command, so use with caution!
newVal exists in the entire scope of the switch but is only initialised if the VAL limb is hit. If you create a block around the code in VAL it should be OK.
I just went through this issue and none of the suggestions solved my problem. While I was unable to start MySQL on boot and found the same message in the logs ("Another MySQL daemon already running with the same unix socket"), I was able to start the service once I arrived at the console.
In my configuration file, I found the following line: bind-address=xx.x.x.x
. I randomly decided to comment it out, and the error on boot disappeared. Because the bind address provides security, in a way, I decided to explore it further. I was using the machine's IP address, rather than the IPv4 loopback address - 127.0.0.1
.
In short, by using 127.0.0.1
as the bind-address
, I was able to fix this error. I hope this helps those who have this problem, but are unable to resolve it using the answers detailed above.
If you want make a border in a shape xml. You need to use:
For the external border,you need to use:
<stroke/>
For the internal background,you need to use:
<solid/>
If you want to set corners,you need to use:
<corners/>
If you want a padding betwen border and the internal elements,you need to use:
<padding/>
Here is a shape xml example using the above items. It works for me
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#D0CFCC" />
<solid android:color="#F8F7F5" />
<corners android:radius="10dp" />
<padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>
How about
...
C() : arr{ {1,2,3} }
{}
...
?
Compiles fine on g++ 4.8
If you are trying to do it on android 6 request the permission and use the code of the answer of this question
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
return;
}
Once it is granted
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_RC) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted start reading or writing database
} else {
Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
}
}
}
with assuming below setting in .config file:
<configuration>
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
</configuration>
try this:
public class myController : Controller
{
NameValueCollection myKeys = ConfigurationManager.AppSettings;
public void MyMethod()
{
var myUsername = myKeys["PFUserName"];
var myPassword = myKeys["PFPassWord"];
}
}
Add into ~/.Rprofile
local({r <- getOption("repos")
r["CRAN"] <- "mirror_site" #for example, https://mirrors.ustc.edu.cn/CRAN/
options(repos=r)
options(BioC_mirror="bioc_mirror_site") #if using biocLite
})
I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.
There is no need to invoke PHP for this. Just put it directly into the HTML:
<a href="http://www.example.com/">...
our version: it also cleans the empty strings and nil values
class Hash
def compact
delete_if{|k, v|
(v.is_a?(Hash) and v.respond_to?('empty?') and v.compact.empty?) or
(v.nil?) or
(v.is_a?(String) and v.empty?)
}
end
end
input[type=checkbox]
{
/* Double-sized Checkboxes */
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
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.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
you can use this script
# git mv a folder and sub folders in windows
function Move-GitFolder {
param (
$target,
$destination
)
Get-ChildItem $target -recurse |
Where-Object { ! $_.PSIsContainer } |
ForEach-Object {
$fullTargetFolder = [System.IO.Path]::GetFullPath((Join-Path (Get-Location) $target))
$fullDestinationFolder = [System.IO.Path]::GetFullPath((Join-Path (Get-Location) $destination))
$fileDestination = $_.Directory.FullName.Replace($fullTargetFolder.TrimEnd('\'), $fullDestinationFolder.TrimEnd('\'))
New-Item -ItemType Directory -Force -Path $fileDestination | Out-Null
$filePath = Join-Path $fileDestination $_.Name
git mv $_.FullName $filePath
}
}
Usage
Move-GitFolder <Target folder> <Destination folder>
the advantage of this solution over other solutions is that it move folders and files recursively in a folder and even create the folder structure if it doesn't exist
These lines Worked for me.
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
//My Stuff
});
To delete untracked on *nix without the purge extension you can use
hg pull
hg update -r MY_BRANCH -C
hg status -un|xargs rm
Which is using
update -r --rev REV revision
update -C --clean discard uncommitted changes (no backup)
status -u --unknown show only unknown (not tracked) files
status -n --no-status hide status prefix
One of the reason I found was why it doesn't find a jar from repository might be because the .pom file for that particular jar might be missing or corrupt. Just correct it and try to load from local repository.
"So does it mean definition equals declaration plus initialization."
Not necessarily, your declaration might be without any variable being initialized like:
void helloWorld(); //declaration or Prototype.
void helloWorld()
{
std::cout << "Hello World\n";
}
I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html
His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.
For following Error:
ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.
Run following NPM command:
$ npm install [email protected]
Source Link
Lambdas are purely a call-site construct: the recipient of the lambda does not need to know that a Lambda is involved, instead it accepts an Interface with the appropriate method.
In other words, you define or use a functional interface (i.e. an interface with a single method) that accepts and returns exactly what you want.
For this Java 8 comes with a set of commonly-used interface types in java.util.function
(thanks to Maurice Naftalin for the hint about the JavaDoc).
For this specific use case there's java.util.function.IntBinaryOperator
with a single int applyAsInt(int left, int right)
method, so you could write your method
like this:
static int method(IntBinaryOperator op){
return op.applyAsInt(5, 10);
}
But you can just as well define your own interface and use it like this:
public interface TwoArgIntOperator {
public int op(int a, int b);
}
//elsewhere:
static int method(TwoArgIntOperator operator) {
return operator.op(5, 10);
}
Using your own interface has the advantage that you can have names that more clearly indicate the intent.
git init
git add .
git commit -m "Initial commit"
After this, make a new GitHub repository and follow on-screen instructions.
If you want a simple visual comparison on Windows such as you can get in Visual SourceSafe or Team Foundation Server (TFS), try this:
Note: After upgrading to Windows 10 I have lost the Git context menu options. However, you can achieve the same thing using 'gitk' or 'gitk filename' in a command window.
Once you call 'Git History', the Git GUI tool will start, with a history of the file in the top left pane. Select one of the versions you would like to compare. Then right-click on the second version and choose either
Diff this -> selected
or
Diff selected -> this
Colour-coded differences will appear in the lower left-hand pane.
In your compare
method, o1
and o2
are already elements in the movieItems
list. So, you should do something like this:
Collections.sort(movieItems, new Comparator<Movie>() {
public int compare(Movie m1, Movie m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
I was searching for a fix on this and the folder i was ADD or COPY'ing was not in the build folder, multiple directories above or referenced from /
Moving the folder from outside the build folder into the build folder fixed my issue.
I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.
var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");
require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
console.log(err);
});
new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.
As mentioned in the comments, req.rawBody
is no longer a thing. If you are using express
/connect
then you should use the bodyParser()
middleware and use req.body
, and if you are doing this using standard Node then you need to aggregate the incoming data
event Buffer
objects and do this image data parsing in the end
callback.
Without external variables:
$('.element').bind('mousewheel', function(e, d) {
if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
|| (this.scrollTop === 0 && d > 0)) {
e.preventDefault();
}
});
FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).
For more information try this link.
... or just resultlist.RemoveAt(1)
if you know exactly the index.
Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)
var source = "afskfsd33j"
var result = source.match(/a(.*)j/);
result: ["afskfsd33j", "fskfsd33"]
The reason why you received this exact result is following:
First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".
Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".
If you want to get rid of second value in array you may define pattern like this:
/a(?:.*)j/
where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.
Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:
/a.*j/
If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:
var result = /a.*j/.test(source);
The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml
I am posting this as an answer not because it's the correct answer to your question, but because it's a solution to the same problem, but using attributes instead. Otherwise Vikas Gujjar's answer is correct.
Quite oftern your data could be in attributes, but it's quite hard to find any working examples using XStream to do this, so here's one:
Sample data:
<settings>
<property name="prop1" value="foo"/>
<property name="prop2" /> <!-- NOTE:
The example supports null elements as
the backing object is a HashMap.
A Properties object would be handled
by a PropertiesConverter which wouldn't
allow you null values. -->
<property name="prop3" value="1"/>
</settings>
Implementation of MapEntryConverter (slightly re-worked @Vikas Gujjar's implementation to use attributes instead):
public class MapEntryConverter
implements Converter
{
public boolean canConvert(Class clazz)
{
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(Object value,
HierarchicalStreamWriter writer,
MarshallingContext context)
{
//noinspection unchecked
AbstractMap<String, String> map = (AbstractMap<String, String>) value;
for (Map.Entry<String, String> entry : map.entrySet())
{
//noinspection RedundantStringToString
writer.startNode(entry.getKey().toString());
//noinspection RedundantStringToString
writer.setValue(entry.getValue().toString());
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context)
{
Map<String, String> map = new HashMap<String, String>();
while (reader.hasMoreChildren())
{
reader.moveDown();
map.put(reader.getAttribute("name"), reader.getAttribute("value"));
reader.moveUp();
}
return map;
}
}
XStream instance setup, parsing and storing:
XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
xstream.alias("settings", HashMap.class);
xstream.registerConverter(new MapEntryConverter());
...
// Parse:
YourObject yourObject = (YourObject) xstream.fromXML(is);
// Store:
xstream.toXML(yourObject);
...
do you mean something like this?
new_list = [ seq[0] for seq in yourlist ]
What you actually have is a list of tuple
objects, not a list of sets (as your original question implied). If it is actually a list of sets, then there is no first element because sets have no order.
Here I've created a flat list because generally that seems more useful than creating a list of 1 element tuples. However, you can easily create a list of 1 element tuples by just replacing seq[0]
with (seq[0],)
.
Although adequate answers have already been given, I'd like to propose a less verbose solution, that can be used without the helper methods available in an MVC controller class. Using a third party library called "RazorEngine" you can use .Net file IO to get the contents of the razor file and call
string html = Razor.Parse(razorViewContentString, modelObject);
Get the third party library here.
After several month without real solution for this problem, I suppose that the best solution is to upgrade the application to .NET framework 4.0, which is supported by Windows 8, Windows 10 and Windows 2012 Server by default and it is still available as offline installation for Windows XP.
This worked for me:
sonar.exclusions=src/**/wwwroot/**/*.js,src/**/wwwroot/**/*.css
It excludes any .js and .css files under any of the sub directories of a folder "wwwroot" appearing as one of the sub directories of the "src" folder (project root).
The error shows that com.bd.service.ArticleService
is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:
<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>
Alternatively, if you want to include all subpackages in com.bd
:
<context:component-scan base-package="com.bd">
<context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>
As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan
annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration
.
@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {
@Autowired
ArticleService articleService;
...
}
You might find this Spring in depth section on Autowiring useful.
Here's some code that I use. I found that if I set any cookie from my site, then cookies magically work in the iframe from then on.
http://developsocialapps.com/foundations-of-a-facebook-app-framework/
if (isset($_GET['setdefaultcookie'])) {
// top level page, set default cookie then redirect back to canvas page
setcookie ('default',"1",0,"/");
$url = substr($_SERVER['REQUEST_URI'],strrpos($_SERVER['REQUEST_URI'],"/")+1);
$url = str_replace("setdefaultcookie","defaultcookieset",$url);
$url = $facebookapp->getCanvasUrl($url);
echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>";
exit();
} else if ((!isset($_COOKIE['default'])) && (!isset($_GET['defaultcookieset']))) {
// no default cookie, so we need to redirect to top level and set
$url = $_SERVER['REQUEST_URI'];
if (strpos($url,"?") === false) $url .= "?";
else $url .= "&";
$url .= "setdefaultcookie=1";
echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>";
exit();
}
For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window.
Follow this article -> http://developer.android.com/google/play-services/setup.html
You should to choose Using Android Studio
Example Gradle file:
Note: Open the build.gradle file inside your application module directory.
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "{applicationId}"
minSdkVersion 14
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:20.+'
compile 'com.google.android.gms:play-services:6.1.+'
}
You can find latest version of Google Play Services here: https://developer.android.com/google/play-services/index.html
Just set offset for UIBarButtonItem appearance.
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000)
forBarMetrics:UIBarMetricsDefault];
It depends. If you want to distinguish between no parameter passed in at all, and an empty string passed in, you could use None.
The first column actually refers to Text Field:
// Add the pet to our listview
ListViewItem lvi = new ListViewItem();
lvi.text = pet.Name;
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);
Or you can use the Constructor
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
....
use
struct arg_struct *args = (struct arg_struct *)arguments;
in place of
struct arg_struct *args = (struct arg_struct *)args;
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client