I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).
Setting 'clang' as the compiler configure should use worked for me:
export CC=clang
pip install --no-clean pycrypto
I was struggle with this behavior too. I wanted to change div class in jinja based on counter. I was surprised that pythonic way did not work. Following code was reseting my counter on each iteration, so I had only red class.
{% if sloupec3: %}
{% set counter = 1 %}
{% for row in sloupec3: %}
{% if counter == 3 %}
{% set counter = 1 %}
{% endif %}
{% if counter == 1: %}
<div class="red"> some red div </div>
{% endif %}
{% if counter == 2: %}
<div class="gray"> some gray div </div>
{% endif %}
{% set counter = counter + 1 %}
{% endfor %}
{% endif %}
I used loop.index like this and it works:
{% if sloupec3: %}
{% for row in sloupec3: %}
{% if loop.index % 2 == 1: %}
<div class="red"> some red div </div>
{% endif %}
{% if loop.index % 2 == 0: %}
<div class="gray"> some gray div </div>
{% endif %}
{% endfor %}
{% endif %}
The @Nadun's version did not work for me, sizing wasn't working well. Removed the direction="column"
or changing it to row
, helps with building vertical login forms with responsive sizing.
<Grid
container
spacing={0}
alignItems="center"
justify="center"
style={{ minHeight: "100vh" }}
>
<Grid item xs={6}></Grid>
</Grid>;
This is a project for getting IP address of any website , it's usefull and so easy to make.
import java.net.InetAddress;
import java.net.UnkownHostExceptiin;
public class Main{
public static void main(String[]args){
try{
InetAddress addr = InetAddresd.getByName("www.yahoo.com");
System.out.println(addr.getHostAddress());
}catch(UnknownHostException e){
e.printStrackTrace();
}
}
}
For your iframe
give an outer div
with style
display:inline-block
, And for your paragraph div
also give display:inline-block
HTML
<div class="side">
<iframe></iframe>
</div>
<div class="side">
<p></p>
</div>
CSS
.side {
display:inline-block;
}
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
Here is my solution and it's also working, when element shows into the viewport
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
var firEvent = false,
objectPosTop = $('.go-counterTeaser').offset().top;
//when element shows at bottom
var elementViewInBottom = objectPosTop - winHeight;
$(window).on('scroll', function() {
var currentPosition = $(document).scrollTop();
//when element position starting in viewport
if (currentPosition > elementViewInBottom && firEvent === false) {
firEvent = true;
animationCounter();
}
});
}
//counter function will animate by using external js also add seprator "."
function animationCounter(){
$('.numberBlock h2').each(function () {
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator('.');
var counterValv = $(this).text();
$(this).animateNumber(
{
number: counterValv,
numberStep: comma_separator_number_step
}
);
});
}
https://jsfiddle.net/uosahmed/frLoxm34/9/
In my experience, I've found it best to go with the GPS fix unless it's not available. I don't know much about other location providers, but I know that for GPS there are a few tricks that can be used to give a bit of a ghetto precision measure. The altitude is often a sign, so you could check for ridiculous values. There is the accuracy measure on Android location fixes. Also if you can see the number of satellites used, this can also indicate the precision.
An interesting way of getting a better idea of the accuracy could be to ask for a set of fixes very rapidly, like ~1/sec for 10 seconds and then sleep for a minute or two. One talk I've been to has led to believe that some android devices will do this anyway. You would then weed out the outliers (I've heard Kalman filter mentioned here) and use some kind of centering strategy to get a single fix.
Obviously the depth you get to here depends on how hard your requirements are. If you have particularly strict requirement to get THE BEST location possible, I think you'll find that GPS and network location are as similar as apples and oranges. Also GPS can be wildly different from device to device.
CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find
command. To search for files within the current directory:
find -name "filename"
You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:
find / -name "filename"
will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:
find /home/username -name *.java
There are many more options to the find command and you should do a:
man find
to learn more about it.
One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:
find / -name 'filename' 2>/dev/null
That just redirects the stderr to /dev/null.
Use Instant
, replacement for java.util.Date
.
Instant.now() // Capture current moment as seen in UTC.
If you must have a Date
, convert.
java.util.Date.from( Instant.now() )
The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.
The java.time classes tend to use static factory methods rather than constructors for instantiating objects.
To get the current moment in UTC time zone:
Instant instant = Instant.now();
To get the current moment in a particular time zone:
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );
If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant
.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Posting here as I think it may be useful for people using Flask
with pymongo
. This is my current "best practice" setup for allowing flask to marshall pymongo bson data types.
mongoflask.py
from datetime import datetime, date
import isodate as iso
from bson import ObjectId
from flask.json import JSONEncoder
from werkzeug.routing import BaseConverter
class MongoJSONEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, (datetime, date)):
return iso.datetime_isoformat(o)
if isinstance(o, ObjectId):
return str(o)
else:
return super().default(o)
class ObjectIdConverter(BaseConverter):
def to_python(self, value):
return ObjectId(value)
def to_url(self, value):
return str(value)
app.py
from .mongoflask import MongoJSONEncoder, ObjectIdConverter
def create_app():
app = Flask(__name__)
app.json_encoder = MongoJSONEncoder
app.url_map.converters['objectid'] = ObjectIdConverter
# Client sends their string, we interpret it as an ObjectId
@app.route('/users/<objectid:user_id>')
def show_user(user_id):
# setup not shown, pretend this gets us a pymongo db object
db = get_db()
# user_id is a bson.ObjectId ready to use with pymongo!
result = db.users.find_one({'_id': user_id})
# And jsonify returns normal looking json!
# {"_id": "5b6b6959828619572d48a9da",
# "name": "Will",
# "birthday": "1990-03-17T00:00:00Z"}
return jsonify(result)
return app
Why do this instead of serving BSON or mongod extended JSON?
I think serving mongo special JSON puts a burden on client applications. Most client apps will not care using mongo objects in any complex way. If I serve extended json, now I have to use it server side, and the client side. ObjectId
and Timestamp
are easier to work with as strings and this keeps all this mongo marshalling madness quarantined to the server.
{
"_id": "5b6b6959828619572d48a9da",
"created_at": "2018-08-08T22:06:17Z"
}
I think this is less onerous to work with for most applications than.
{
"_id": {"$oid": "5b6b6959828619572d48a9da"},
"created_at": {"$date": 1533837843000}
}
A better way to solve it is to start small.
Let's start with 1 bit. Which can either be 1
or 0
. That's 2 values, or 10
in binary.
Now 2 bits, which can either be 00
, 01
, 10
or 11
That's 4 values, or 100
in binary... See the pattern?
You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".
Sometimes npm uninstall -g packageName
doesn’t work.
In this case you can delete package manually.
On Mac, go to folder /usr/local/lib/node_modules
and delete the folder with the package you want. That's it. Check your list of globally installed packages with this command:
npm list -g --depth=0
Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.
I looked around for an answer to this and the best way I found was to use Flex and inline styling on different components.
For example, to make two paper components divide my full screen in 2 vertical components (in ration of 1:4), the following code works fine.
const styles = {
div:{
display: 'flex',
flexDirection: 'row wrap',
padding: 20,
width: '100%'
},
paperLeft:{
flex: 1,
height: '100%',
margin: 10,
textAlign: 'center',
padding: 10
},
paperRight:{
height: 600,
flex: 4,
margin: 10,
textAlign: 'center',
}
};
class ExampleComponent extends React.Component {
render() {
return (
<div>
<div style={styles.div}>
<Paper zDepth={3} style={styles.paperLeft}>
<h4>First Vertical component</h4>
</Paper>
<Paper zDepth={3} style={styles.paperRight}>
<h4>Second Vertical component</h4>
</Paper>
</div>
</div>
)
}
}
Now, with some more calculations, you can easily divide your components on a page.
The followin example shows how to capture and process video frames in HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Capturing & Processing Video in HTML5</title>
</head>
<body>
<div>
<h2>Camera Preview</h2>
<video id="cameraPreview" width="240" height="180" autoplay></video>
<p>
<button id="startButton" onclick="startCapture();">Start Capture</button>
<button id="stopButton" onclick="stopCapture();">Stop Capture</button>
</p>
</div>
<div>
<h2>Processing Preview</h2>
<canvas id="processingPreview" width="240" height="180"></canvas>
</div>
<div>
<h2>Recording Preview</h2>
<video id="recordingPreview" width="240" height="180" autoplay controls></video>
<p>
<a id="downloadButton">Download</a>
</p>
</div>
<script>
const ROI_X = 250;
const ROI_Y = 150;
const ROI_WIDTH = 240;
const ROI_HEIGHT = 180;
const FPS = 25;
let cameraStream = null;
let processingStream = null;
let mediaRecorder = null;
let mediaChunks = null;
let processingPreviewIntervalId = null;
function processFrame() {
let cameraPreview = document.getElementById("cameraPreview");
processingPreview
.getContext('2d')
.drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
}
function generateRecordingPreview() {
let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
let mediaBlobUrl = URL.createObjectURL(mediaBlob);
let recordingPreview = document.getElementById("recordingPreview");
recordingPreview.src = mediaBlobUrl;
let downloadButton = document.getElementById("downloadButton");
downloadButton.href = mediaBlobUrl;
downloadButton.download = "RecordedVideo.webm";
}
function startCapture() {
const constraints = { video: true, audio: false };
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
cameraStream = stream;
let processingPreview = document.getElementById("processingPreview");
processingStream = processingPreview.captureStream(FPS);
mediaRecorder = new MediaRecorder(processingStream);
mediaChunks = []
mediaRecorder.ondataavailable = function(event) {
mediaChunks.push(event.data);
if(mediaRecorder.state == "inactive") {
generateRecordingPreview();
}
};
mediaRecorder.start();
let cameraPreview = document.getElementById("cameraPreview");
cameraPreview.srcObject = stream;
processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
})
.catch((err) => {
alert("No media device found!");
});
};
function stopCapture() {
if(cameraStream != null) {
cameraStream.getTracks().forEach(function(track) {
track.stop();
});
}
if(processingStream != null) {
processingStream.getTracks().forEach(function(track) {
track.stop();
});
}
if(mediaRecorder != null) {
if(mediaRecorder.state == "recording") {
mediaRecorder.stop();
}
}
if(processingPreviewIntervalId != null) {
clearInterval(processingPreviewIntervalId);
processingPreviewIntervalId = null;
}
};
</script>
</body>
</html>
_x000D_
Press Ctrl+Alt+Shift+S in android studio or go to File > Project Structure... Select app on left side and select falvors tab on right side on default config change version code , name and etc...
Retrieve the ID of the current item in the WordPress Loop.
echo get_the_ID();
hence works for the product id too. #tested #woo-commerce
I have found an excellent and relatively short explanation here.
A multipart request is a REST request containing several packed REST requests inside its entity.
Just update @angular/material from 7 to 9,
npm uninstall @angular/material --save
npm install @angular/material@^7.1.0 --save
ng update @angular/material
Just wait and see Angular doing the Migration alone,
Hope it helps someone :)
Have you start by reading the information on this on Wikipedia - Block cipher modes of operation? Then follow the reference link on Wikipedia to NIST: Recommendation for Block Cipher Modes of Operation.
.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.
To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.
jdk is necessary to compile to code and convert java code to byte codes while jre is necessary for executing the byte codes.
Try this
rails destroy model Rating
It will remove model, migration, tests and fixtures
This may help you ;D
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
float Stukprijs;
float Aantal;
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
}
private void button1_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
errorProvider2.Clear();
if (float.TryParse(textBox1.Text, out Stukprijs))
{
if (float.TryParse(textBox2.Text, out Aantal))
{
float Totaal = Stukprijs * Aantal;
string Output = Totaal.ToString();
textBox3.Text = Output;
if (Totaal >= 100)
{
float korting = Totaal - 100;
float korting2 = korting / 100 * 15;
string Output2 = korting2.ToString();
textBox4.Text = Output2;
if (korting2 >= 10)
{
textBox4.BackColor = Color.LightGreen;
}
else
{
textBox4.BackColor = SystemColors.Control;
}
}
else
{
textBox4.Text = "0";
textBox4.BackColor = SystemColors.Control;
}
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
else
{
errorProvider1.SetError(textBox1, "Bedrag plz!");
if (float.TryParse(textBox2.Text, out Aantal))
{
}
else
{
errorProvider2.SetError(textBox2, "Aantal plz!");
}
}
}
private void BTNwissel_Click(object sender, EventArgs e)
{
//LL, LU, LR, LD.
Color c = LL.BackColor;
LL.BackColor = LU.BackColor;
LU.BackColor = LR.BackColor;
LR.BackColor = LD.BackColor;
LD.BackColor = c;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
}
}
}
Combining the multiple ways browsers are using to store the user's language, you get this function :
const getNavigatorLanguage = () => {
if (navigator.languages && navigator.languages.length) {
return navigator.languages[0];
} else {
return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
}
}
We first check the navigator.languages
array for its first element.
Then we get either navigator.userLanguage
or navigator.language
.
If this fails we get navigator.browserLanguage
.
Finally, we set it to 'en'
if everything else failed.
And here's the sexy one-liner :
const getNavigatorLanguage = () => (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
Use orderBy:
df.orderBy('column_name', ascending=False)
Complete answer:
group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)
http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html
I see great answers up here but what I miss were some diagrams and since I had to work with Spring Framework I came across their explanation.
I find the following diagrams very useful. They illustrate the difference in communication between parties with OAuth2 and OAuth1.
Change status bar color when you are not using
AppBar
First Import this
import 'package:flutter/services.dart';
Now use below code to change status bar color in your application when you are not using the AppBar
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
statusBarColor: AppColors.statusBarColor,/* set Status bar color in Android devices. */
statusBarIconBrightness: Brightness.dark,/* set Status bar icons color in Android devices.*/
statusBarBrightness: Brightness.dark)/* set Status bar icon color in iOS. */
);
To change the status bar color in
iOS
when you are usingSafeArea
Scaffold(
body: Container(
color: Colors.red, /* Set your status bar color here */
child: SafeArea(child: Container(
/* Add your Widget here */
)),
),
);
Take a look at permatswap()
in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.
mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
This gives:
R> out$perm[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 1
[2,] 0 1 0 1 0
[3,] 0 0 0 1 1
[4,] 1 0 0 0 1
R> out$perm[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 1 1
[2,] 0 0 0 1 1
[3,] 1 0 0 1 0
[4,] 0 0 1 0 1
To explain the call:
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
times
is the number of randomised matrices you want, here 99burnin
is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matricesthin
says only take a random draw every thin
swapsmtype = "prab"
says treat the matrix as presence/absence, i.e. binary 0/1 data.A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin
is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.
Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.
Acording with the documentation, the method getEntity in Jax rs 2.0 return a InputStream. If you need to convert to InputStream to String with JSON format, you need to cast the two formats. For example in my case, I implemented the next method:
private String processResponse(Response response) {
if (response.getEntity() != null) {
try {
InputStream salida = (InputStream) response.getEntity();
StringWriter writer = new StringWriter();
IOUtils.copy(salida, writer, "UTF-8");
return writer.toString();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
return null;
}
why I implemented this method. Because a read in differets blogs that many developers they have the same problem whit the version in jaxrs using the next methods
String output = response.readEntity(String.class)
and
String output = response.getEntity(String.class)
The first works using jersey-client from com.sun.jersey library and the second found using the jersey-client from org.glassfish.jersey.core.
This is the error that was being presented to me: org.glassfish.jersey.client.internal.HttpUrlConnector$2 cannot be cast to java.lang.String
I use the following maven dependency:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>
What I do not know is why the readEntity method does not work.I hope you can use the solution.
Carlos Cepeda
Emacs is an IDE.
edit: OK, I'll elaborate. What is an IDE?
As a starting point, let's expand the acronym: Integrated Development Environment. To analyze this, I start from the end.
An environment is, generally speaking, the part of the world that surrounds the point of view. In this case, it is what we see on our monitor (perhaps hear from our speakers) and manipulate through our keyboard (and perhaps a mouse).
Development is what we want to do in this environment, its purpose, if you want. We use the environment to develop software. This defines what subparts we need: an editor, an interface to the REPL, resp. the compiler, an interface to the debugger, and access to online documentation (this list may not be exhaustive).
Integrated means that all parts of the environment are somehow under a uniform surface. In an IDE, we can access and use the different subparts with a minimum of switching; we don't have to leave our defined environment. This integration lets the different subparts interact better. For example, the editor can know about what language we write in, and give us symbol autocompletion, jump-to-definition, auto-indentation, syntax highlighting, etc.. It can get information from the compiler, automatically jump to errors, and highlight them. In most, if not all IDEs, the editor is naturally at the heart of the development process.
Emacs does all this, it does it with a wide range of languages and tasks, and it does it with excellence, since it is seamlessly expandable by the user wherever he misses anything.
Counterexample: you could develop using something like Notepad, access documentation through Firefox and XPdf, and steer the compiler and debugger from a shell. This would be a Development Environment, but it would not be integrated.
Your query execution will return list of Object[]
.
List result_source = LoadSource.list();
for(Object[] objA : result_source) {
// read it all
}
The best way to do it without any headache is to use the
\tablefootnote
command from the tablefootnote
package. Add the following to your preamble:
\usepackage{tablefootnote}
It just works without the need of additional tricks.
This solved the issue for me:
pip install -I --upgrade psutil --force
Afterwards just uninstall psutil with the new version and hop you can suddenly install the older version (:
hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]]
Enumerable#collect
takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.
The Enumerable
module is pretty awesome. Knowing it well can save you lots of time and lots of code.
$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);
If you want to retrieve the package's root path from any of its modules, the following works (tested on Python 3.6):
from . import __path__ as ROOT_PATH
print(ROOT_PATH)
The main __init__.py
path can also be referenced by using __file__
instead.
Hope this helps!
Although this is an old thread I want to share my solution and hopefully get some feedback on this. Be warned that I only tested this solution with my local database in some JUnit testcase. So this is not a productive feature so far.
I solved that issue for my by introducing a custom annotation called Sequence with no property. It's just a marker for fields that should be assigned a value from an incremented sequence.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sequence
{
}
Using this annotation i marked my entities.
public class Area extends BaseEntity implements ClientAware, IssuerAware
{
@Column(name = "areaNumber", updatable = false)
@Sequence
private Integer areaNumber;
....
}
To keep things database independent I introduced an entity called SequenceNumber which holds the sequence current value and the increment size. I chose the className as unique key so each entity class wil get its own sequence.
@Entity
@Table(name = "SequenceNumber", uniqueConstraints = { @UniqueConstraint(columnNames = { "className" }) })
public class SequenceNumber
{
@Id
@Column(name = "className", updatable = false)
private String className;
@Column(name = "nextValue")
private Integer nextValue = 1;
@Column(name = "incrementValue")
private Integer incrementValue = 10;
... some getters and setters ....
}
The last step and the most difficult is a PreInsertListener that handles the sequence number assignment. Note that I used spring as bean container.
@Component
public class SequenceListener implements PreInsertEventListener
{
private static final long serialVersionUID = 7946581162328559098L;
private final static Logger log = Logger.getLogger(SequenceListener.class);
@Autowired
private SessionFactoryImplementor sessionFactoryImpl;
private final Map<String, CacheEntry> cache = new HashMap<>();
@PostConstruct
public void selfRegister()
{
// As you might expect, an EventListenerRegistry is the place with which event listeners are registered
// It is a service so we look it up using the service registry
final EventListenerRegistry eventListenerRegistry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);
// add the listener to the end of the listener chain
eventListenerRegistry.appendListeners(EventType.PRE_INSERT, this);
}
@Override
public boolean onPreInsert(PreInsertEvent p_event)
{
updateSequenceValue(p_event.getEntity(), p_event.getState(), p_event.getPersister().getPropertyNames());
return false;
}
private void updateSequenceValue(Object p_entity, Object[] p_state, String[] p_propertyNames)
{
try
{
List<Field> fields = ReflectUtil.getFields(p_entity.getClass(), null, Sequence.class);
if (!fields.isEmpty())
{
if (log.isDebugEnabled())
{
log.debug("Intercepted custom sequence entity.");
}
for (Field field : fields)
{
Integer value = getSequenceNumber(p_entity.getClass().getName());
field.setAccessible(true);
field.set(p_entity, value);
setPropertyState(p_state, p_propertyNames, field.getName(), value);
if (log.isDebugEnabled())
{
LogMF.debug(log, "Set {0} property to {1}.", new Object[] { field, value });
}
}
}
}
catch (Exception e)
{
log.error("Failed to set sequence property.", e);
}
}
private Integer getSequenceNumber(String p_className)
{
synchronized (cache)
{
CacheEntry current = cache.get(p_className);
// not in cache yet => load from database
if ((current == null) || current.isEmpty())
{
boolean insert = false;
StatelessSession session = sessionFactoryImpl.openStatelessSession();
session.beginTransaction();
SequenceNumber sequenceNumber = (SequenceNumber) session.get(SequenceNumber.class, p_className);
// not in database yet => create new sequence
if (sequenceNumber == null)
{
sequenceNumber = new SequenceNumber();
sequenceNumber.setClassName(p_className);
insert = true;
}
current = new CacheEntry(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue(), sequenceNumber.getNextValue());
cache.put(p_className, current);
sequenceNumber.setNextValue(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue());
if (insert)
{
session.insert(sequenceNumber);
}
else
{
session.update(sequenceNumber);
}
session.getTransaction().commit();
session.close();
}
return current.next();
}
}
private void setPropertyState(Object[] propertyStates, String[] propertyNames, String propertyName, Object propertyState)
{
for (int i = 0; i < propertyNames.length; i++)
{
if (propertyName.equals(propertyNames[i]))
{
propertyStates[i] = propertyState;
return;
}
}
}
private static class CacheEntry
{
private int current;
private final int limit;
public CacheEntry(final int p_limit, final int p_current)
{
current = p_current;
limit = p_limit;
}
public Integer next()
{
return current++;
}
public boolean isEmpty()
{
return current >= limit;
}
}
}
As you can see from the above code the listener used one SequenceNumber instance per entity class and reserves a couple of sequence numbers defined by the incrementValue of the SequenceNumber entity. If it runs out of sequence numbers it loads the SequenceNumber entity for the target class and reserves incrementValue values for the next calls. This way I do not need to query the database each time a sequence value is needed. Note the StatelessSession that is being opened for reserving the next set of sequence numbers. You cannot use the same session the target entity is currently persisted since this would lead to a ConcurrentModificationException in the EntityPersister.
Hope this helps someone.
$http_name_of_the_header_key
i.e if you have origin = domain.com
in header, you can use $http_origin
to get "domain.com"
In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores
Reference doc here: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_
For your example the variable would be $http_my_custom_header
.
there is another technique
use
background-size:cover
That is it full set of css is
body {
background: url('images/body-bg.jpg') no-repeat center center fixed;
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Latest browsers support the default property.
If you don't mind changing your HTML, you can use the data-toggle
attribute on <button>
s. See the Single toggle section of the button examples:
<button type="button" class="btn btn-primary" data-toggle="button">
Single toggle
</button>
All the answers are great for situations where you cannot use NumPy. If you can, here is another approach:
def cosine(x, y):
dot_products = np.dot(x, y.T)
norm_products = np.linalg.norm(x) * np.linalg.norm(y)
return dot_products / (norm_products + EPSILON)
Also bear in mind about EPSILON = 1e-07
to secure the division.
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
$http.post(url, parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file
.
Instead of
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
Use
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
It will install any missing headers. It solved my issue
To give an alternative answer (Who needs 5 equal answers?):
list.Add(5);
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now
Keep in mind that all other references to the old list have not been cleared (depending on the situation, this might be what you want). Also, in terms of performance, it is usually a bit slower.
To include all files and directories:
archive.bulk([
{
expand: true,
cwd: "temp/freewheel-bvi-120",
src: ["**/*"],
dot: true
}
]);
It uses node-glob(https://github.com/isaacs/node-glob) underneath, so any matching expression compatible with that will work.
MSDN Documentation Here
To add a bit of context to M.Ali's Answer you can convert a string to a uniqueidentifier using the following code
SELECT CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E')
If that doesn't work check to make sure you have entered a valid GUID
This is a further optimisation.
\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)
\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*(\d{1,2})$
(i) allows for valid international prefixes
(ii) followed by 9 or 10 digits, with any type or placing of delimeters (except between the last two digits)
This will match:
+1-234-567-8901
+61-234-567-89-01
+46-234 5678901
+1 (234) 56 89 901
+1 (234) 56-89 901
+46.234.567.8901
+1/234/567/8901
I had the same problem and tried all of the above without any success, then I found out what it was:
I'd created a folder called "System" in one of my projects and then created a class in it. The problem seems to stem from having a namespace called "System" when the .cs file is created, even if it is in a namespace of "MyProject.System".
Looking back I can understand why this would cause problems. It really stumped me at first as the error messages don't initially seem to relate to the problem.
Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.
Downgrade Froala to v3.0.
Something in v3.1 broke our Create React App build process.
We discovered that there was an issue between React Scripts 3.2 and Froala 3.1.
Updating to React Scripts v3.3 allowed us to upgrade to Froala 3.1.
In addition to already suggested p
and puts
— well, actually in most cases you do can write logger.info "blah"
just as you suggested yourself. It works in console too, not only in server mode.
But if all you want is console debugging, puts
and p
are much shorter to write, anyway.
Here is a simple way to do it:
#include <iostream>
using namespace std;
int main()
{
cout.flush(); // Flush the output stream
system("clear"); // Clear the console with the "system" function
}
Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.
The matrix representation of the general 2D transformation looks like this:
x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)
where (x,y) are the components of the original vector and (x', y') are the transformed components.
If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:
x' = -y
y' = +x
Same result as given earlier, but with a little more explanation as to where it comes from.
If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.
If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.
What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:
#ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
#else
# define LIBRARY_API __declspec(dllimport)
#endif
Then on a function that you want to be exported you use LIBRARY_API
:
LIBRARY_API int GetCoolInteger();
In your library build project create a define LIBRARY_EXPORTS
this will cause your functions to be exported for your DLL build.
Since LIBRARY_EXPORTS
will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.
If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:
#ifdef _WIN32
# ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
# else
# define LIBRARY_API __declspec(dllimport)
# endif
#elif
# define LIBRARY_API
#endif
When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.
If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C"
inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:
The Code:
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT int getEngineVersion() {
return 1;
}
EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
K.getGraphicsServer().addGraphicsDriver(
auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
);
}
And here's what the exports look like with Dumpbin /exports:
Dump of file opengl_plugin.dll
File Type: DLL
Section contains the following exports for opengl_plugin.dll
00000000 characteristics
49866068 time date stamp Sun Feb 01 19:54:32 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
2 1 00011028 registerPlugin = @ILT+35(_registerPlugin)
So this code works fine:
m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");
m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
::GetProcAddress(m_hDLL, "registerPlugin")
);
Have you tried something like:
//a[contains(@prop, "Foo")]
I've never used the contains function before but suspect that it should work as advertised...
Add an id column to the csv file and leave it blank:
id,Name,Address
,name1,addr test 1
,name2,addr test 2
Remove KEEPIDENTITY keyword from query:
BULK INSERT Employee FROM 'path\tempFile.csv '
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');
The id identity field will be auto-incremented.
If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.
=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))
Will return the answer you want and also remove the #N/A
result that would appear if you couldn't find a result due to it not appearing in your lookup list.
Ross
An inner class is a friend of the class it is defined within.
So, yes; an object of type Outer::Inner
can access the member variable var
of an object of type Outer
.
Unlike Java though, there is no correlation between an object of type Outer::Inner
and an object of the parent class. You have to make the parent child relationship manually.
#include <string>
#include <iostream>
class Outer
{
class Inner
{
public:
Inner(Outer& x): parent(x) {}
void func()
{
std::string a = "myconst1";
std::cout << parent.var << std::endl;
if (a == MYCONST)
{ std::cout << "string same" << std::endl;
}
else
{ std::cout << "string not same" << std::endl;
}
}
private:
Outer& parent;
};
public:
Outer()
:i(*this)
,var(4)
{}
Outer(Outer& other)
:i(other)
,var(22)
{}
void func()
{
i.func();
}
private:
static const char* const MYCONST;
Inner i;
int var;
};
const char* const Outer::MYCONST = "myconst";
int main()
{
Outer o1;
Outer o2(o1);
o1.func();
o2.func();
}
In my case error message displaed in Windows Event Viewer -> Windows Logs -> Application was "The Module DLL C:\Windows\system32\inetsrv\rewrite.dll failed to load. The data is the error." Uninstalling rewrite module via installer solved the problem. I wasn't using any rewrite rules so I uninstalled rewrite module. Reinstalling the module may help the problem as well.
As mentioned here, this feature is not currently supported.
private void addContact(String name, String number){
Uri addContactsUri = ContactsContract.Data.CONTENT_URI;
long rowContactId = getRawContactId();
String displayName = name;
insertContactDisplayName(addContactsUri, rowContactId, displayName);
String phoneNumber = number;
String phoneTypeStr = "Mobile";//work,home etc
insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);
}
private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
// Put contact display name value.
contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);
activity.getContentResolver().insert(addContactsUri, contentValues);
}
private long getRawContactId()
{
// Inser an empty contact.
ContentValues contentValues = new ContentValues();
Uri rawContactUri = activity.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
// Get the newly created contact raw id.
long ret = ContentUris.parseId(rawContactUri);
return ret;
}
private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr) {
// Create a ContentValues object.
ContentValues contentValues = new ContentValues();
// Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
// Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
// Put phone number value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
// Calculate phone type by user selection.
int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
if ("home".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
} else if ("mobile".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
} else if ("work".equalsIgnoreCase(phoneTypeStr)) {
phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
}
// Put phone type value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);
// Insert new contact data into phone contact list.
activity.getContentResolver().insert(addContactsUri, contentValues);
}
(since I ran into this today)
Be careful when using ES2015 fat arrow syntax:
This will fail :
it('accesses the network', done => {
this.timeout(500); // will not work
// *this* binding refers to parent function scope in fat arrow functions!
// i.e. the *this* object of the describe function
done();
});
EDIT: Why it fails:
As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.
Bottom line: Don't use arrow functions for functions that need an increased timeout.
Edit: this information is for visualvm specifically, not for any other java app
As mentioned by others, you need to modify the visualvm.conf
For the latest version of JvisualVM 1.3.6 on Mac, the install directories have changed.
It is currently in /Applications/VisualVM.app/Contents/Resources/visualvm/etc/visualvm.conf.
However this may depend on where you have installed VisualVM. The easiest way to find where your VisualVM is to start it, and then look at the process using:
ps -ef | grep VisualVM
You will see something like:
... -Dnetbeans.dirs=/Applications/VisualVM.app/Contents/Resources/visualvm/visualvm...
You want to take the netbeans.dir property and look up a directory and you will find the etc folder.
Uncomment this line in the visualvm.conf and change the path to the jdk
visualvm_jdkhome="/path/to/jdk"
Additionally, if you are having slowness with your visualvm and you have a lot of memory, I would suggest greatly increasing the amount of memory available and running it in server mode:
visualvm_default_options="-J-XX:MaxPermSize=96m -J-Xmx2048m -J-Xms2048m -J-server -J-XX:+UseCompressedOops -J-XX:+UseConcMarkSweepGC -J-XX:+UseParNewGC -J-XX:NewRatio=2 -J-Dnetbeans.accept_license_class=com.sun.tools.visualvm.modules.startup.AcceptLicense -J-Dsun.jvmstat.perdata.syncWaitMs=10000 -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.d3d=false"
Use grep:
grep -wE "string1|String2|...." file_name
Or you can use:
echo string | grep -wE "string1|String2|...."
This is old, but what about ASC?
You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.
SoapUI can do many things though!
Do you even need MSDTC? The escalation you're experiencing is often caused by creating multiple connections within a single TransactionScope.
If you do need it then you need to enable it as outlined in the error message. On XP:
TL;DR MacOS is probably blocking VirtualBox. Go to
System Preferences > Security & Privacy
Then hit the "Allow".
Solution:
Go to System Preferences > Security & Privacy
Then hit the "Allow" button to let Oracle (VirtualBox) load.
MacOS by default can block kexts from loading. You must click the "allow" button before executing the VirtualBoxStartup.sh script.
Then run:
sudo "/Library/Application Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh" restart
like the answer above.
(This article provides more clarity to MacOS kernel extension loading)
If you'd like to know what is the numeric version of FireFox you can use the following snippet:
var match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
var ver = match ? parseInt(match[1]) : 0;
You could try something like:
var Title = $('<textarea />').html("Chris' corner").text();_x000D_
console.log(Title);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
A more interactive version:
$('form').submit(function() {_x000D_
var theString = $('#string').val();_x000D_
var varTitle = $('<textarea />').html(theString).text();_x000D_
$('#output').text(varTitle);_x000D_
return false;_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="#" method="post">_x000D_
<fieldset>_x000D_
<label for="string">Enter a html-encoded string to decode</label>_x000D_
<input type="text" name="string" id="string" />_x000D_
</fieldset>_x000D_
<fieldset>_x000D_
<input type="submit" value="decode" />_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
<div id="output"></div>
_x000D_
You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is even or odd");
System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));
}
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
Here is my modular solution:
var final_style = document.createElement('style');
final_style.type = 'text/css';
function addNewStyle(selector, style){
final_style.innerHTML += selector + '{ ' + style + ' } \n';
};
function submitNewStyle(){
document.getElementsByTagName('head')[0].appendChild(final_style);
final_style = document.createElement('style');
final_style.type = 'text/css';
};
function submitNewStyleWithMedia(mediaSelector){
final_style.innerHTML = '@media(' + mediaSelector + '){\n' + final_style.innerHTML + '\n};';
submitNewStyle();
};
You basically anywhere in your code do:
addNewStyle('body', 'color: ' + color1);
, where color1
is defined variable.
When you want to "post" the current CSS file you simply do submitNewStyle()
,
and then you can still add more CSS later.
If you want to add it with "media queries", you have the option.
After "addingNewStyles" you simply use submitNewStyleWithMedia('min-width: 1280px');
.
It was pretty useful for my use-case, as I was changing CSS of public (not mine) website according to current time. I submit one CSS file before using "active" scripts, and the rest afterwards (makes the site look kinda-like it should before accessing elements through querySelector
).
I have Samsung Galaxy S3 and it was not showing in the "Remote devices" tab nor in chrome://inspect. The device did show in Windows's Device Manager as GT-I9300, though. What worked for me was:
cmd.exe
cd "C:\Program Files (x86)\ClockworkMod\Universal Adb Driver"
adb devices
I'm not sure if it affected the whole flow somehow, but at some point I've installed, and later uninstalled the drivers from Samsung: http://www.samsung.com/us/support/downloads/ > Mobile > Phones > Galaxy S > S III > Unlocked > http://www.samsung.com/us/support/owners/product/galaxy-s-iii-unlocked#downloads
Also you can take a look into StringUtils library. It has a bunch of cool stuff.
You should first pull
the changes from the develop
branch and only then merge them to your branch:
git checkout develop
git pull
git checkout branch-x
git rebase develop
Or, when on branch-x
:
git fetch && git rebase origin/develop
I have an alias that saves me a lot of time. Add to your ~/.gitconfig
:
[alias]
fr = "!f() { git fetch && git rebase origin/"$1"; }; f"
Now, all that you have to do is:
git fr develop
max-height
.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}
.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}
Turned out there was some extra code in the AppModel that was messing things up:
in beforeFind
and afterFind
:
App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");
I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.
Go to this link and wait for a while to load.
http://www.java.com/en/download/testjava.jsp
You will see the below image:
You can alternatively open command window and type java -version
I haven't used Cassandra, but I have used MongoDB and think it's awesome.
If you're after simple setup, this is it: You simply untar MongoDB and run the mongod daemon and that's it ... it's running.
Obviously that's only a starter, but to get you started it's easy.
Try to install the missing module.
npm install 'module-name'
you can also use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT
A BLOB type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. MEDIUMBLOB can store up to 16,777,213 bytes, and LONGBLOB can store up to 4,294,967,292 bytes.
Don't forget to contact your system administrator.
Because in my case I had every thing rightly configured(SSH also added) but I got the same error
repository access denied. fatal: Could not read from remote repository.
the reason was I only had read access to that repository. Therefore with out wasting your valuable time please check that as the first thing. Thank you.
There is another way without using $watch, using angular.copy:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var service = {
FirstName: '',
setFirstName: function(name) {
// this is the trick to sync the data
// so no need for a $watch function
// call this from anywhere when you need to update FirstName
angular.copy(name, service.FirstName);
}
};
return service;
});
// Step 1 Controller
myApp.controller('FirstCtrl', function( $scope, Data ){
});
// Step 2 Controller
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.FirstName = Data.FirstName;
});
You may also try this, anaconda http://continuum.io/downloads
But you need to modify your environment variable PATH, so that the anaconda folder is before the original Python folder.
You can truncate the date
SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')
Look at the SQL Fiddle for more examples.
I was also getting same error because of using &
character directly in layout xml.
So, please be careful about using html entities in your project.
In SQL Server, you would say:
Select name from users
UNION [ALL]
SELECT 'JASON'
In Oracle, you would say
Select name from user
UNION [ALL]
Select 'JASON' from DUAL
This condition happens to me every 6-months or so. I think it happens when closing NetBeans under very low memory conditions. I discovered that it could be easily corrected by (1) Rename your project, including its folder name using right-click on project explorer's project name---I put a simple suffix on the original name ("_damaged"). (2) Try BUILD. If that is successful, which it is for me, give three cheers. (3) Repeat step (1) to restore the original project name. BUILD and RUN should start without trouble. I guess that the 'rename the project and folder' process causes a special rediscovery of the applications main location.
I start with the following template, which is derived from numerous printings of Itzik Ben-Gan's routine:
;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
select Number from Tally where Number <= 1000000
The "WHERE N<= 1000000" clause limits the output to 1 to 1 million, and can easily be adjusted to your desired range.
Since this is a WITH clause, it can be worked into an INSERT... SELECT... like so:
-- Sample use: create one million rows
CREATE TABLE dbo.Example (ExampleId int not null)
DECLARE @RowsToCreate int
SET @RowsToCreate = 1000000
-- "Table of numbers" data generator, as per Itzik Ben-Gan (from multiple sources)
;WITH
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
INSERT Example (ExampleId)
select Number
from Tally
where Number <= @RowsToCreate
Indexing the table after it's built will be the fastest way to index it.
Oh, and I'd refer to it as a "Tally" table. I think this is a common term, and you can find loads of tricks and examples by Googling it.
It doesn't look like it's possible to not have the certificate error any more. I'm on Windows XP with IE 8. Group Policy had installed a self-signed certificate as a trusted root certificate for access to an internal site. When I look at MMC with the certificate snap-in I can see the certificate there OK.
When I look at:
Internet Options => Content => certificates
It isn't there!
This behaviour in IE started since our admins let loose with the last lot of Patch-Tuesday updates which installed on my machine on 10th Dec 2009. Prior to that it was quite happy to accept the certificate as valid.
You can use this command: git branch -D $(printf "%s\n" $(git branch) | grep '3.2')
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject
, then first get a String
from the result
:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject
:
JSONObject jsonObject = new JSONObject(jsonString);
Here is another solution based on vh
, or viewpoint height
, for details visit CSS units. It is based on this solution, which uses flex instead.
* {_x000D_
/* personal preference */_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
html {_x000D_
/* make sure we use up the whole viewport */_x000D_
width: 100%;_x000D_
min-height: 100vh;_x000D_
/* for debugging, a red background lets us see any seams */_x000D_
background-color: red;_x000D_
}_x000D_
body {_x000D_
/* make sure we use the full width but allow for more height */_x000D_
width: 100%;_x000D_
min-height: 100vh; /* this helps with the sticky footer */_x000D_
}_x000D_
main {_x000D_
/* for debugging, a blue background lets us see the content */_x000D_
background-color: skyblue;_x000D_
min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */_x000D_
}_x000D_
footer {_x000D_
/* for debugging, a gray background lets us see the footer */_x000D_
background-color: gray;_x000D_
min-height:2.5em;_x000D_
}
_x000D_
<main>_x000D_
<p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
<p>This is the content.</p>_x000D_
</main>_x000D_
<footer>_x000D_
<p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>_x000D_
<p>This is the footer.</p>_x000D_
</footer>
_x000D_
The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.
You may find more information here:
Specifically:
1vw (viewport width) = 1% of viewport width 1vh (viewport height) = 1% of viewport height 1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest 1vmax (viewport minimum) = 1vw or 1vh, whatever is largest
Solutions above don't work with websites with cloudflare protection, example: https://paxful.com/fr/buy-bitcoin
.
Modify agent as follows: options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36")
Fix found here: What is the difference in accessing Cloudflare website using ChromeDriver/Chrome in normal/headless mode through Selenium Python
Assuming you mean the letters of the English alphabet...
for ( int i = 0; i < 26; i++ )
{
Console.WriteLine( Convert.ToChar( i + 65 ) );
}
Console.WriteLine( "Press any key to continue." );
Console.ReadKey();
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
If you want to access folder you specified using Anaconda Prompt, try typing
cd C:\Users\u354590
select 1 from table
will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:
if exists(select 1 from table where some_column = 'some_value')
What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:
1) performance & you might retrieve more data than you actually need.
2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.
This will help you. :) Follow the next steps,
Copy Paste the Following code as it is,it will create the Function which convert the String to Int
CREATE FUNCTION dbo.SplitInts
(
@List VARCHAR(MAX),
@Delimiter VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT Item = CONVERT(INT, Item) FROM
( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
Create the Following stored procedure
CREATE PROCEDURE dbo.sp_DeleteMultipleId
@List VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM TableName WHERE Id IN( SELECT Id = Item FROM dbo.SplitInts(@List, ','));
END
GO
Execute this SP Using exec sp_DeleteId '1,2,3,12'
this is a string of Id's which you want to delete,
You convert your array to string in C# and pass it as a Stored Procedure parameter
int[] intarray = { 1, 2, 3, 4, 5 };
string[] result = intarray.Select(x=>x.ToString()).ToArray();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "sp_DeleteMultipleId";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Id",SqlDbType.VARCHAR).Value=result ;
This will delete multiple rows, All the best
One possibility might be:
an easy way with out much redundancy.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
Fileout.Write "your string goes here"
Fileout.Close
for me ,with JDK11 and IntelliJ 2016.3 , I kept getting the same message so I decided to uninstall JDK11 and installed JDK8 instead and it immediately worked!
This worked for me.
If we want to just add an additional field in ModelSerializer
, we can
do it like below, and also the field can be assigned some val after
some calculations of lookup. Or in some cases, if we want to send the
parameters in API response.
In model.py
class Foo(models.Model):
"""Model Foo"""
name = models.CharField(max_length=30, help_text="Customer Name")
In serializer.py
class FooSerializer(serializers.ModelSerializer):
retrieved_time = serializers.SerializerMethodField()
@classmethod
def get_retrieved_time(self, object):
"""getter method to add field retrieved_time"""
return None
class Meta:
model = Foo
fields = ('id', 'name', 'retrieved_time ')
Hope this could help someone.
I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.
show timezone;
But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone;
will return that value instead of "localtime".
So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".
Tips:
You can try to use
ctx.getSystemService("phone_msim")
instead of
ctx.getSystemService(Context.TELEPHONY_SERVICE)
If you have already tried Vaibhav's answer and telephony.getClass().getMethod()
fails, above is what works for my Qualcomm mobile.
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
The MAC address (the low-level local network interface address) does not survive hops through IP routers. You can't find the client MAC address from a remote server.
In a local subnet, the MAC addresses are mapped to IP addresses through the ARP system. Interfaces on the local net know how to map IP addresses to MAC addresses. However, when your packets have been routed on the local subnet to (and through) the gateway out to the "real" Internet, the originating MAC address is lost. Simplistically, each subnet-to-subnet hop of your packets involve the same sort of IP-to-MAC mapping for local routing in each subnet.
It is just this:
if 'errormessage' in kwargs:
print("yeah it's here")
You need to check, if the key is in the dictionary. The syntax for that is some_key in some_dict
(where some_key
is something hashable, not necessarily a string).
The ideas you have linked (these ideas) contained examples for checking if specific key existed in dictionaries returned by locals()
and globals()
. Your example is similar, because you are checking existence of specific key in kwargs
dictionary (the dictionary containing keyword arguments).
You can manually call the method invoked by PostBack from the Page_Load
event:
public void Page_Load(object sender, EventArgs e)
{
MyPostBackMethod(sender, e);
}
But if you mean if you can have the Page.IsPostBack
property set to true
without real post back, then the answer is no.
<script type="text/JavaScript">
function validate()
{
if( document.form1.quali.value == "-1" )
{
alert( "Please select qualification!" );
return false;
}
}
</script>
<form name="form1" method="post" action="" onsubmit="return validate(this);">
<select name="quali" id="quali" ">
<option value="-1" selected="selected">select</option>
<option value="1">Graduate</option>
<option value="2">Post Graduate</option>
</select>
</form>
// this code works 110% tested by me after many complex jquery method validation but it is simple javascript method plz try this if u fail in drop down required validation//
If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):
# 1) Get back to the main body page
driver.switch_to.default_content()
# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js:
# 3) Read the jquery from a file
jquery = jquery_js.read()
# 4) Load jquery lib
driver.execute_script(jquery)
# 5) Execute your command
driver.execute_script('$("#myId").click()')
It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx
Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke
method of the control which you want to update.
The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.
Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:
Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.
Easiest way is to use System.Linq as previously described
using System.Linq;
public int GetHighestValue(List<MyTypes> list)
{
return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}
This is also possible with a Dictionary
using System.Linq;
public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}
Your script is blocked from executing due to the execution policy.
You need to run PowerShell as administrator and set it on the client PC to Unrestricted. You can do that by calling Invoke with:
Set-ExecutionPolicy Unrestricted
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I'm using jQuery 3.3.1
and I received the same error, in my case, the URL was an Object
vs a string.
What happened was, that I took URL = window.location
- which returned an object. Once I've changed it into window.location.href
- it worked w/o the e.indexOf
error.
Peter's answer with an additional check! Of course, not 100% guaranteed!
var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
outPutValue = JSON.stringify(jsonToCheck);
try{
JSON.parse(outPutValue);
isJson = true;
}catch(err){
isJson = false;
}
}
if(isJson){
alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
alert("Is other!");
}
If the above solution does not work for you, try this:
#1.1 Do NOT ignore file pattern in any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php
##########################
# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php
For this problem, I do a help function like this:
const char* name(Id id) {
struct Entry {
Id id;
const char* name;
};
static const Entry entries[] = {
{ ErrorA, "ErrorA" },
{ ErrorB, "ErrorB" },
{ 0, 0 }
}
for (int it = 0; it < gui::SiCount; ++it) {
if (entries[it].id == id) {
return entries[it].name;
}
}
return 0;
}
Linear search is usually more efficient than std::map
for small collections like this.
If you're looking for a solution that seems to be more "by the book" and methodologically designed (using a BroadcastReceiver), you better have a look at the following link: http://www.hrupin.com/2011/10/how-to-finish-all-activities-in-your-android-application-through-simple-call.
A slight change is required in the proposed implementation that appears in that link - you should use the sendStickyBroadcast(Intent) method (don't forget to add the BROADCAST_STICKY permission to your manifest) rather than sendBroadcast(Intent), in order to enable your paused activities to be able to receive the broadcast and process it, and this means that you should also remove that sticky broadcast while restarting your application by calling the removeStickyBroadcast(Intent) method in your opening Activity's onCreate() method.
Although the above mentioned startActivity(...) based solutions, at first glance - seem to be very nice, elegant, short, fast and easy to implement - they feel a bit "wrong" (to start an activity - with all the possible overhead and resources that may be required and involved in it, just in order to kill it?...)
Another way: add windowNoTitle
and windowFullscreen
attributes directly to the theme (you can find styles.xml
file in res/values/
directory):
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
in the manifest file, in application
specify your theme
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
I'm using the Hadoop Mincemeat module. I think this is a great example to take a note of:
import mincemeat
def mapfn(k,v):
for w in v:
yield 'sum',w
#yield 'count',1
def reducefn(k,v):
r1=sum(v)
r2=len(v)
print r2
m=r1/r2
std=0
for i in range(r2):
std+=pow(abs(v[i]-m),2)
res=pow((std/r2),0.5)
return r1,r2,res
Here the generator gets numbers out of a text file (as big as 15GB) and applies simple math on those numbers using Hadoop's map-reduce. If I had not used the yield function, but instead a list comprehension, it would have taken a much longer time calculating the sums and average (not to mention the space complexity).
Hadoop is a great example for using all the advantages of Generators.
Here's a dplyr
option:
library(dplyr)
# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))
# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))
Use "in" or "where".
Its gonna be something like this:
db.mycollection.find( { $where : function() {
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );
If I remember correctly, the gen stands for generation, as in a generational garbage collector (that treats younger objects differently than mid-life and "permanent" objects). Principle of locality suggests that recently created objects will be wiped out first.
PHP also has money_format().
Here's an example:
echo money_format('$%i', 3.4); // echos '$3.40'
This function actually has tons of options, go to the documentation I linked to to see them.
Note: money_format is undefined in Windows.
UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php
WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.
Instead, look into NumberFormatter::formatCurrency.
$number = "123.45";
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($number, 'USD');
I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:
#
# script to register Python 2.0 or later for use with
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/[email protected]/msg10512.html
import sys
from _winreg import *
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
installpath, installpath, installpath
)
def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print "*** Unable to register!"
return
print "--- Python", version, "is now registered!"
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register!"
print "*** You probably have another Python installation!"
if __name__ == "__main__":
RegisterPy()
There are two things that could be happening:
READ_EXTERNAL_STORAGE
permission to your AndroidManifest.xml
Fileformat.info is a pretty good reference for this stuff. In your case, it's already in hex, so the hex value is f066
. So you'd do:
content: "\f066";
If you try using:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
and receive an error :
"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"
This means the DATE_FIELD
is not specified in seconds.
In my case, it was milli seconds - EPOCH time
.
The conversion worked using below:
df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
I came up with this:
int counter = 0;
bool checkPrime(int x) {
for (int y = x; y > 0; y--){
if (x%y == 0) {
counter++;
}
}
if (counter == 2) {
counter = 0; //resets counter for next input
return true; //if its only divisible by two numbers (itself and one) its a prime
}
else counter = 0;
return false;
}
You can also have a look at FLTK (C++ and not plain C though)
FLTK (pronounced "fulltick") is a cross-platform C++ GUI toolkit for UNIX®/Linux® (X11), Microsoft® Windows®, and MacOS® X. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via OpenGL® and its built-in GLUT emulation.
FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.
Here are some quickstart screencasts
[Happy New Year!]
You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()
TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);
Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).
I've developed a small vagrant-address plugin for that. It's simple, cross-platform, cross-provider, and does not require scripting.
If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).
If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL.
Here an example: (I used a procedure instead of a function, like @Thilo did)
create or replace procedure myprocedure(retval in out sys_refcursor) is
begin
open retval for
select TABLE_NAME from user_tables;
end myprocedure;
declare
myrefcur sys_refcursor;
tablename user_tables.TABLE_NAME%type;
begin
myprocedure(myrefcur);
loop
fetch myrefcur into tablename;
exit when myrefcur%notfound;
dbms_output.put_line(tablename);
end loop;
close myrefcur;
end;
using remove() method you can able to remove.
getLogout(data){
return this.sessionModel
.remove({session_id: data.sid})
.exec()
.then(data =>{
return "signup successfully"
})
}
Thx guys, I finally found the solution, a really basic one.. In my controller I have
$scope.mySplit = function(string, nb) {
var array = string.split(',');
return array[nb];
}
and in my view
{{mySplit(string,0)}}
You can use extend
method in list operations as well.
>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
right click on console.. click save as.. its this simple.. you'll get an output text file
please Find below one it helps me a lot to set data function
$('#datepicker').datepicker({dateFormat: 'yy-mm-dd'}).datepicker('setDate', '2010-07-25');
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
For me the solution was to override/correct the data directory in /etc/my/cnf.
I built MySQL 5.5.27 from source with the directions provided in the readme file:
# Preconfiguration setup
shell> groupadd mysql
shell> useradd -r -g mysql mysql
# Beginning of source-build specific instructions
shell> tar zxvf mysql-VERSION.tar.gz
shell> cd mysql-VERSION
shell> cmake .
shell> make
shell> make install
# End of source-build specific instructions
# Postinstallation setup
shell> cd /usr/local/mysql
shell> chown -R mysql .
shell> chgrp -R mysql .
shell> scripts/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql data
# Next command is optional
shell> cp support-files/my-medium.cnf /etc/my.cnf
shell> bin/mysqld_safe --user=mysql &
# Next command is optional
shell> cp support-files/mysql.server /etc/init.d/mysql.server
mysqld_safe terminated itself without explanation. running /etc/init.d/mysql.server start
resulted in the error:
"The server quit without updating PID file"
I noticed something odd in the installation instructions though. It has ownership changed to mysql for the directory "data", but not to "var"; this is unusual because for years I have had to ensure that var directory was mysql writable. So I manually ran chown -R mysql /usr/local/mysql/var
and then attempted to start it again. Still no luck. But worse, no .err file in the var dir - it was in the "data" dir! so scripts/mysql_install_db sets up camp in /usr/local/mysql/var, but the rest of the application seems to want to do its work in /usr/local/mysql/data!
So I just edited /etc/my.cnf and under the section [mysqld] I added a directive to explicitly point mysql's data directory to var (as I normally expect it to be any how), and after doing so, mysqld starts up just fine. The directive to add looks like this:
datadir = /usr/local/mysql/var
Worked for me. Hope it helps for you.
Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable
aListOfObjects.Sort((x, y) =>
{
int result = x.A.CompareTo(y.A);
return result != 0 ? result : x.B.CompareTo(y.B);
});
Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.
Typically these are development related libraries and the most common use of these tools is for developers working on osx.
They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.
xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).
macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.
One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.
homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.
macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects
Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in
/opt/local
Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.
Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:
We really don’t like dupes in Homebrew/homebrew
However, we do like dupes in the tap!
Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:
- Duplicate libraries regularly break builds
- Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
- We want you to try harder to make your formula work with what OS X comes with
You can optionally overwrite the macosx supplied versions of utilities with homebrew.
You need to use ==
or ===
for comparison. =
assigns a new value.
Besides that, using ==
is pointless when dealing with booleans only. Just use if(foo)
instead of if(foo == true)
.
It's possible to some extent but won't be really accurate, the idea is load image with a known file size then in its onload
event measure how much time passed until that event was triggered, and divide this time in the image file size.
Example can be found here: Calculate speed using javascript
Test case applying the fix suggested there:
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!_x000D_
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg"; _x000D_
var downloadSize = 4995374; //bytes_x000D_
_x000D_
function ShowProgressMessage(msg) {_x000D_
if (console) {_x000D_
if (typeof msg == "string") {_x000D_
console.log(msg);_x000D_
} else {_x000D_
for (var i = 0; i < msg.length; i++) {_x000D_
console.log(msg[i]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var oProgress = document.getElementById("progress");_x000D_
if (oProgress) {_x000D_
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");_x000D_
oProgress.innerHTML = actualHTML;_x000D_
}_x000D_
}_x000D_
_x000D_
function InitiateSpeedDetection() {_x000D_
ShowProgressMessage("Loading the image, please wait...");_x000D_
window.setTimeout(MeasureConnectionSpeed, 1);_x000D_
}; _x000D_
_x000D_
if (window.addEventListener) {_x000D_
window.addEventListener('load', InitiateSpeedDetection, false);_x000D_
} else if (window.attachEvent) {_x000D_
window.attachEvent('onload', InitiateSpeedDetection);_x000D_
}_x000D_
_x000D_
function MeasureConnectionSpeed() {_x000D_
var startTime, endTime;_x000D_
var download = new Image();_x000D_
download.onload = function () {_x000D_
endTime = (new Date()).getTime();_x000D_
showResults();_x000D_
}_x000D_
_x000D_
download.onerror = function (err, msg) {_x000D_
ShowProgressMessage("Invalid image, or error downloading");_x000D_
}_x000D_
_x000D_
startTime = (new Date()).getTime();_x000D_
var cacheBuster = "?nnn=" + startTime;_x000D_
download.src = imageAddr + cacheBuster;_x000D_
_x000D_
function showResults() {_x000D_
var duration = (endTime - startTime) / 1000;_x000D_
var bitsLoaded = downloadSize * 8;_x000D_
var speedBps = (bitsLoaded / duration).toFixed(2);_x000D_
var speedKbps = (speedBps / 1024).toFixed(2);_x000D_
var speedMbps = (speedKbps / 1024).toFixed(2);_x000D_
ShowProgressMessage([_x000D_
"Your connection speed is:", _x000D_
speedBps + " bps", _x000D_
speedKbps + " kbps", _x000D_
speedMbps + " Mbps"_x000D_
]);_x000D_
}_x000D_
}
_x000D_
<h1 id="progress">JavaScript is turned off, or your browser is realllllly slow</h1>
_x000D_
Quick comparison with "real" speed test service showed small difference of 0.12 Mbps when using big picture.
To ensure the integrity of the test, you can run the code with Chrome dev tool throttling enabled and then see if the result matches the limitation. (credit goes to user284130 :))
Important things to keep in mind:
The image being used should be properly optimized and compressed. If it isn't, then default compression on connections by the web server might show speed bigger than it actually is. Another option is using uncompressible file format, e.g. jpg. (thanks Rauli Rajande for pointing this out and Fluxine for reminding me)
The cache buster mechanism described above might not work with some CDN servers, which can be configured to ignore query string parameters, hence better setting cache control headers on the image itself. (thanks orcaman for pointing this out))
You can set max value for your seekbar by using this code:
sb1.setMax(100);
This will set the max value for your seekbar.
But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.
For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.
You can get more info via this link.
$ cat x.mak all: echo $(OPTION) $ make -f x.mak 'OPTION=-DPASSTOC=42' echo -DPASSTOC=42 -DPASSTOC=42
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
Try using now.date()
to get a Date
object rather than a DateTime
.
If that doesn't work, then converting that to a string should work:
now = datetime.datetime(2009,5,5)
str_now = now.date().isoformat()
cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))
I had the same problem using rvm
on Ubuntu
, was fixed by setting the source
on my terminal as a short-term solution:
source $HOME/.rvm/scripts/rvm
or
source /home/$USER/.rvm/scripts/rvm
and configure a default Ruby Version, 2.3.3
in my case.
rvm use 2.3.3 --default
And a long-term Solution is to add your source
to your .bashrc
file to permanently make Ubuntu look in .rvm
for all the Ruby files.
Add:
source .rvm/scripts/rvm
into
$HOME/.bashrc
file.
undo git rm
git rm file # delete file & update index
git checkout HEAD file # restore file & index from HEAD
undo git rm -r
git rm -r dir # delete tracked files in dir & update index
git checkout HEAD dir # restore file & index from HEAD
undo git rm -rf
git rm -r dir # delete tracked files & delete uncommitted changes
not possible # `uncommitted changes` can not be restored.
Uncommitted changes
includes not staged changes
, staged changes but not committed
.
Simple assigning to window.location
or window.location.href
should be fine:
window.location = newUrl;
However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:
Use the URL hash. For example, you can go from example.com
to example.com#foo
without loading a new page. You can simply set window.location.hash
to make this easy. Then, you should listen to the HTML5 hashchange
event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.
You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo
to example.com/bar
. Using this is easy:
window.history.pushState("example.com/foo");
When the user presses "back", you'll receive the window's popstate
event, which you can easily listen to (jQuery):
$(window).bind("popstate", function(e) { alert("location changed"); });
Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.
There are a couple of differences between the &
and &&
operators. The same differences apply to |
and ||
. The most important thing to keep in mind is that &&
is a logical operator that only applies to boolean operands, while &
is a bitwise operator that applies to integer types as well as booleans.
With a logical operation, you can do short circuiting because in certain cases (like the first operand of &&
being false
, or the first operand of ||
being true
), you do not need to evaluate the rest of the expression. This is very useful for doing things like checking for null
before accessing a filed or method, and checking for potential zeros before dividing by them. For a complex expression, each part of the expression is evaluated recursively in the same manner. For example, in the following case:
(7 == 8) || ((1 == 3) && (4 == 4))
Only the emphasized portions will evaluated. To compute the ||
, first check if 7 == 8
is true
. If it were, the right hand side would be skipped entirely. The right hand side only checks if 1 == 3
is false
. Since it is, 4 == 4
does not need to be checked, and the whole expression evaluates to false
. If the left hand side were true
, e.g. 7 == 7
instead of 7 == 8
, the entire right hand side would be skipped because the whole ||
expression would be true
regardless.
With a bitwise operation, you need to evaluate all the operands because you are really just combining the bits. Booleans are effectively a one-bit integer in Java (regardless of how the internals work out), and it is just a coincidence that you can do short circuiting for bitwise operators in that one special case. The reason that you can not short-circuit a general integer &
or |
operation is that some bits may be on and some may be off in either operand. Something like 1 & 2
yields zero, but you have no way of knowing that without evaluating both operands.
... using org.apache.http api. ...
You need to include SOAPAction
as a header in the request. As you have httpPost
and requestWrapper
handles, there are three ways adding the header.
1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );
Only difference is that addHeader
allows multiple values with same header name and setHeader
allows unique header names only. setHeader(...
over writes first header with the same name.
You can go with any of these on your requirement.
AGE
is defined as "42"
so the line:
str += "Do you feel " + AGE + " years old?";
is converted to:
str += "Do you feel " + "42" + " years old?";
Which isn't valid since "Do you feel "
and "42"
are both const char[]
. To solve this, you can make one a std::string
, or just remove the +
:
// 1.
str += std::string("Do you feel ") + AGE + " years old?";
// 2.
str += "Do you feel " AGE " years old?";
In class file you can either use:
module.exports = class ClassNameHere {
print() {
console.log('In print function');
}
}
or you can use this syntax
class ClassNameHere{
print(){
console.log('In print function');
}
}
module.exports = ClassNameHere;
On the other hand to use this class in any other file you need to do these steps.
First require that file using this syntax:
const anyVariableNameHere = require('filePathHere');
Then create an object
const classObject = new anyVariableNameHere();
After this you can use classObject
to access the actual class variables
There are several problems in your code.
First the big ones:
You are creating a new figure and a new axes in every iteration of your loop ?
put fig = plt.figure
and ax = fig.add_subplot(1,1,1)
outside of the loop.
Don't use the Locators. Call the functions ax.set_xticks()
and ax.grid()
with the correct keywords.
With plt.axes()
you are creating a new axes again. Use ax.set_aspect('equal')
.
The minor things:
You should not mix the MATLAB-like syntax like plt.axis()
with the objective syntax.
Use ax.set_xlim(a,b)
and ax.set_ylim(a,b)
This should be a working minimal example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
# And a corresponding grid
ax.grid(which='both')
# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
plt.show()
Output is this:
Generally, I am using the following method:
>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]
If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.
Source code:
public class Example extends JFrame{
MarvinImagePlugin prewitt = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
MarvinImagePlugin errorDiffusion = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
MarvinImagePlugin emboss = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");
public Example(){
super("Example");
// Layout
setLayout(new GridLayout(2,2));
// Load images
MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());
// Image Processing plug-ins
errorDiffusion.process(img1, img2);
prewitt.process(img1, img3);
emboss.process(img1, img4);
// Set panels
addPanel(img1);
addPanel(img2);
addPanel(img3);
addPanel(img4);
setSize(560,380);
setVisible(true);
}
public void addPanel(MarvinImage image){
MarvinImagePanel imagePanel = new MarvinImagePanel();
imagePanel.setImage(image);
add(imagePanel);
}
public static void main(String[] args) {
new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
You can find a point on a infinite line that is nearest to circle center by projecting vector AC onto vector AB. Calculate the distance between that point and circle center. If it is greater that R, there is no intersection. If the distance is equal to R, line is a tangent of the circle and the point nearest to circle center is actually the intersection point. If distance less that R, then there are 2 intersection points. They lie at the same distance from the point nearest to circle center. That distance can easily be calculated using Pythagorean theorem. Here's algorithm in pseudocode:
{
dX = bX - aX;
dY = bY - aY;
if ((dX == 0) && (dY == 0))
{
// A and B are the same points, no way to calculate intersection
return;
}
dl = (dX * dX + dY * dY);
t = ((cX - aX) * dX + (cY - aY) * dY) / dl;
// point on a line nearest to circle center
nearestX = aX + t * dX;
nearestY = aY + t * dY;
dist = point_dist(nearestX, nearestY, cX, cY);
if (dist == R)
{
// line segment touches circle; one intersection point
iX = nearestX;
iY = nearestY;
if (t < 0 || t > 1)
{
// intersection point is not actually within line segment
}
}
else if (dist < R)
{
// two possible intersection points
dt = sqrt(R * R - dist * dist) / sqrt(dl);
// intersection point nearest to A
t1 = t - dt;
i1X = aX + t1 * dX;
i1Y = aY + t1 * dY;
if (t1 < 0 || t1 > 1)
{
// intersection point is not actually within line segment
}
// intersection point farthest from A
t2 = t + dt;
i2X = aX + t2 * dX;
i2Y = aY + t2 * dY;
if (t2 < 0 || t2 > 1)
{
// intersection point is not actually within line segment
}
}
else
{
// no intersection
}
}
EDIT: added code to check whether found intersection points actually are within line segment.
All these answers doesn't work from M - to - Android"O" - 8, Due to Dozer mode that restrict the service - whatever service or any background operation that requires discrete things in background would be no longer able to run.
So the approach would be listening to the system FusedLocationApiClient through BroadCastReciever that always listening the location and work even in Doze mode.
Posting the link would be pointless, please search FusedLocation with Broadcast receiver.
Thanks
private void ClearFolder(string FolderName)
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach (FileInfo fi in dir.GetFiles())
{
fi.IsReadOnly = false;
fi.Delete();
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
di.Delete();
}
}
You need to add some arguments. Also, instancing and opening can be put in one line:
fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
Here's another approach using json and rouge:
require 'json'
require 'rouge'
formatter = Rouge::Formatters::Terminal256.new
json_lexer = Rouge::Lexers::JSON.new
puts formatter.format(json_lexer.lex(JSON.pretty_generate(JSON.parse(response))))
(parses response from e.g. RestClient
)
I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.
For example, consider a generic Field
class that has an ID number, a type code and a field name. If I want to search a vector
of these Field
s by either ID number or name, I might construct a functor to do so:
class Field
{
public:
unsigned id_;
string name_;
unsigned type_;
class match : public std::unary_function<bool, Field>
{
public:
match(const string& name) : name_(name), has_name_(true) {};
match(unsigned id) : id_(id), has_id_(true) {};
bool operator()(const Field& rhs) const
{
bool ret = true;
if( ret && has_id_ ) ret = id_ == rhs.id_;
if( ret && has_name_ ) ret = name_ == rhs.name_;
return ret;
};
private:
unsigned id_;
bool has_id_;
string name_;
bool has_name_;
};
};
Then code that needs to search for these Field
s can use the match
scoped within the Field
class itself:
vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));
Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
You have to use GetThumbnailImage
method in the Image
class:
https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx
Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.
Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));
It is in the System.Drawing namespace (in System.Drawing.dll).
Behavior:
If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.
Important: the remarks section of the Microsoft link above warns of certain potential problems:
The
GetThumbnailImage
method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the
DrawImage
method.
You must analyse the actual HTML output, for the hint.
By giving the path like this means "from current location", on the other hand if you start with a /
that would mean "from the context".
A scripting language is a programming language that is used to manipulate, customise, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language. A scripting language is intended for use by both professional and non-professional programmers.
reference
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
In Java, we say this keyword refers to the state of the current object of the application.
Similarly, in an alternate we have Context
in Android Development.
This can be defined either explicitly or implicitly,
Context con = this;
getApplicationContext();
getBaseContext();
getContext();
I have solved a similar problem using external native lib dependencies that are packaged inside of jar files. Sometimes these architecture dependend libraries are packaged alltogether inside one jar, sometimes they are split up into several jar files. so i wrote some buildscript to scan the jar dependencies for native libs and sort them into the correct android lib folders. Additionally this also provides a way to download dependencies that not found in maven repos which is currently usefull to get JNA working on android because not all native jars are published in public maven repos.
android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
lintOptions {
abortOnError false
}
defaultConfig {
applicationId "myappid"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
}
}
}
def urlFile = { url, name ->
File file = new File("$buildDir/download/${name}.jar")
file.parentFile.mkdirs()
if (!file.exists()) {
new URL(url).withInputStream { downloadStream ->
file.withOutputStream { fileOut ->
fileOut << downloadStream
}
}
}
files(file.absolutePath)
}
dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'net.java.dev.jna:jna:4.2.0'
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-arm.jar?raw=true', 'jna-android-arm')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-armv7.jar?raw=true', 'jna-android-armv7')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-aarch64.jar?raw=true', 'jna-android-aarch64')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86.jar?raw=true', 'jna-android-x86')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86-64.jar?raw=true', 'jna-android-x86_64')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips.jar?raw=true', 'jna-android-mips')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips64.jar?raw=true', 'jna-android-mips64')
}
def safeCopy = { src, dst ->
File fdst = new File(dst)
fdst.parentFile.mkdirs()
fdst.bytes = new File(src).bytes
}
def archFromName = { name ->
switch (name) {
case ~/.*android-(x86-64|x86_64|amd64).*/:
return "x86_64"
case ~/.*android-(i386|i686|x86).*/:
return "x86"
case ~/.*android-(arm64|aarch64).*/:
return "arm64-v8a"
case ~/.*android-(armhf|armv7|arm-v7|armeabi-v7).*/:
return "armeabi-v7a"
case ~/.*android-(arm).*/:
return "armeabi"
case ~/.*android-(mips).*/:
return "mips"
case ~/.*android-(mips64).*/:
return "mips64"
default:
return null
}
}
task extractNatives << {
project.configurations.compile.each { dep ->
println "Scanning ${dep.name} for native libs"
if (!dep.name.endsWith(".jar"))
return
zipTree(dep).visit { zDetail ->
if (!zDetail.name.endsWith(".so"))
return
print "\tFound ${zDetail.name}"
String arch = archFromName(zDetail.toString())
if(arch != null){
println " -> $arch"
safeCopy(zDetail.file.absolutePath,
"$buildDir/native-libs/$arch/${zDetail.file.name}")
} else {
println " -> No valid arch"
}
}
}
}
preBuild.dependsOn(['extractNatives'])
I'm using maven deploy file.
mvn deploy:deploy-file -DgroupId=my.group.id \
-DartifactId=my-artifact-id \
-Dversion=1.0.0.1 \
-Dpackaging=jar \
-Dfile=foo.jar \
-DgeneratePom=true \
-DrepositoryId=my-repo \
-Durl=http://my-nexus-server.com:8081/repository/maven-releases/
UPDATE:
As stated in comments using quotes in url cause NoSuchElementException
But I have add server config in my maven (~/.m2/settings.xml).
<servers>
<server>
<id>my-repo</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
References:
A UNIX guy probably told you that. :)
You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret_cast of the builder. IMO the simplest thing is just to use Solutions.
To resolve this issue, you have to delete the .snap
file located in the directory:
<workspace-directory>\.metadata\.plugins\org.eclipse.core.resources
After deleting this file, you could start Eclipse with no problem.
The prompt:
Password for 'https://[email protected]':
suggests, that you are using https not ssh. SSH urls start with git@, for example:
[email protected]:beginninggit/alias.git
Even if you work alone, with a single repo that you own, the operation:
git push
will cause:
Password for 'https://[email protected]':
if the remote origin starts with https
.
Check your remote with:
git remote -v
The remote depends on git clone
. If you want to use ssh clone the repo using its ssh url, for example:
git clone [email protected]:user/repo.git
I suggest you to start with git push
and git pull
for your private repo.
If that works, you have two joices suggested by Lazy Badger:
Normally, ViewState should be decryptable if you have the machine-key, right? After all, ASP.net needs to decrypt it, and that is certainly not a black box.
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
This is what worked for me on iOS 6 (very slight adaptation of rmarscher's answer):
<script>
(function(document,navigator,standalone) {
if (standalone in navigator && navigator[standalone]) {
var curnode,location=document.location,stop=/^(a|html)$/i;
document.addEventListener("click", function(e) {
curnode=e.target;
while (!stop.test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if ("href" in curnode && (curnode.href.indexOf("http") || ~curnode.href.indexOf(location.host)) && curnode.target == false) {
e.preventDefault();
location.href=curnode.href
}
},false);
}
})(document,window.navigator,"standalone")
</script>
You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }
So
http://stack_overflow.com/~foo%20bar#link
would be
http://stack\_overflow.com/\~foo\%20bar\#link
I found the following working solution to pass onClick function argument from child to the parent component:
Version with passing a method()
//ChildB component
class ChildB extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (<div><button onClick={() => handleToUpdate('someVar')}>
Push me
</button>
</div>)
}
}
//ParentA component
class ParentA extends React.Component {
constructor(props) {
super(props);
var handleToUpdate = this.handleToUpdate.bind(this);
var arg1 = '';
}
handleToUpdate(someArg){
alert('We pass argument from Child to Parent: ' + someArg);
this.setState({arg1:someArg});
}
render() {
var handleToUpdate = this.handleToUpdate;
return (<div>
<ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
}
}
if(document.querySelector("#demo")){
ReactDOM.render(
<ParentA />,
document.querySelector("#demo")
);
}
Version with passing an Arrow function
//ChildB component
class ChildB extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (<div>
<button onClick={() => handleToUpdate('someVar')}>
Push me
</button>
</div>)
}
}
//ParentA component
class ParentA extends React.Component {
constructor(props) {
super(props);
}
handleToUpdate = (someArg) => {
alert('We pass argument from Child to Parent: ' + someArg);
}
render() {
return (<div>
<ChildB handleToUpdate = {this.handleToUpdate} /></div>)
}
}
if(document.querySelector("#demo")){
ReactDOM.render(
<ParentA />,
document.querySelector("#demo")
);
}
Try the following:
foo(*values)
This can be found in the Python docs as Unpacking Argument Lists.
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.
Try this SQLite Database Browser
See full document here. This is very simple and fast database browser for SQLite.
Here's one way:
df.join(pd.DataFrame(s).T).fillna(method='ffill')
To break down what happens here...
pd.DataFrame(s).T
creates a one-row DataFrame from s
which looks like this:
s1 s2
0 5 6
Next, join
concatenates this new frame with df
:
a b s1 s2
0 1 3 5 6
1 2 4 NaN NaN
Lastly, the NaN
values at index 1 are filled with the previous values in the column using fillna
with the forward-fill (ffill
) argument:
a b s1 s2
0 1 3 5 6
1 2 4 5 6
To avoid using fillna
, it's possible to use pd.concat
to repeat the rows of the DataFrame constructed from s
. In this case, the general solution is:
df.join(pd.concat([pd.DataFrame(s).T] * len(df), ignore_index=True))
Here's another solution to address the indexing challenge posed in the edited question:
df.join(pd.DataFrame(s.repeat(len(df)).values.reshape((len(df), -1), order='F'),
columns=s.index,
index=df.index))
s
is transformed into a DataFrame by repeating the values and reshaping (specifying 'Fortran' order), and also passing in the appropriate column names and index. This new DataFrame is then joined to df
.
Caveats: this answer only allows exports color settings.
iTerm => Preferences => Profiles => Colors => Load Presets => Export
Import shall be similar.
Use Ctrl+0 to change focus to the sidebar.
The answer of delfuego is the simplest way to solve the certificate problem. But, in my case, one of our third party url (using https), updated their certificate every 2 months automatically. It means that I have to import the cert to our Java trust store manually every 2 months as well. Sometimes it caused production problems.
So, I made a method to solve it with SecureRestClientTrustManager to be able to consume https url without importing the cert file. Here is the method:
public static String doPostSecureWithHeader(String url, String body, Map headers) throws Exception { log.info("start doPostSecureWithHeader " + url + " with param " + body); long startTime; long endTime; startTime = System.currentTimeMillis(); Client client; client = Client.create(); WebResource webResource; webResource = null; String output = null; try{ SSLContext sslContext = null; SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); sslContext = SSLContext.getInstance("SSL"); sslContext .init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); defaultClientConfig .getProperties() .put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties( getHostnameVerifier(), sslContext)); client = Client.create(defaultClientConfig); webResource = client.resource(url); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ webResource.setProperty(entry.getKey(), entry.getValue()); } } WebResource.Builder builder = webResource.accept("application/json"); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ builder.header(entry.getKey(), entry.getValue()); } } ClientResponse response = builder .post(ClientResponse.class, body); output = response.getEntity(String.class); } catch(Exception e){ log.error(e.getMessage(),e); if(e.toString().contains("One or more of query value parameters are null")){ output="-1"; } if(e.toString().contains("401 Unauthorized")){ throw e; } } finally { if (client!= null) { client.destroy(); } } endTime = System.currentTimeMillis(); log.info("time hit "+ url +" selama "+ (endTime - startTime) + " milliseconds dengan output = "+output); return output; }
You could also use FilenameUtils from Apache. It provides you at least the following features for the example C:\dev\project\file.txt:
I wouldn't bother doing it in Linq2SQL. Create a stored Procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.