Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.
More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html
(source: avajava.com)
If you can't put value on buttons. I have just a rough solution. Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked.
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '\n')
{
lines++;
}
}
But please note: Why is “while ( !feof (file) )” always wrong?.
Use chr (13) for carriage return and chr (10) for new line
echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo chr (13). chr (10);
for Team Profile, simple in Prereference --> Account--->select the corret account-->detail-->click the left bottom 'refresh' button. the profile will be renewed.
One alternative for IE7+ and other browsers may be to use :first-child
instead, and invert your styles.
For example, if you're setting the margin on each li
:
ul li {
margin-bottom: 1em;
}
ul li:last-child {
margin-bottom: 0;
}
You could replace it with this:
ul li {
margin-top: 1em;
}
ul li:first-child {
margin-top: 0;
}
This will work well for some other cases like borders.
According to sitepoint, :first-child
buggy, but only to the extent that it will select some root elements (the doctype or html), and may not change styles if other elements are inserted.
In a few words: The constructor is called first, then any @FXML
annotated fields are populated, then initialize()
is called.
This means the constructor does not have access to @FXML
fields referring to components defined in the .fxml file, while initialize()
does have access to them.
Quoting from the Introduction to FXML:
[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.
Try this in the CSS of the div:
display: table-cell;
vertical-align: middle;
You can call more of 1 function filters in the same ng-repeat filter
<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
You do this by adding a usage key to your app’s Info.plist together with a purpose string. NSCameraUsageDescription Specifies the reason for your app to access the device’s camera
You had better use find_library command instead of link_directories. Concretely speaking there are two ways:
designate the path within the command
find_library(NAMES gtest PATHS path1 path2 ... pathN)
set the variable CMAKE_LIBRARY_PATH
set(CMAKE_LIBRARY_PATH path1 path2)
find_library(NAMES gtest)
the reason is as flowings:
Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).
Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).
If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.
It will merger two array and remove duplicate
<?php
$first = 'your first array';
$second = 'your second array';
$result = array_merge($first,$second);
print_r($result);
$result1= array_unique($result);
print_r($result1);
?>
Try this link link1
Put your if condition inside resize
function:
var windowsize = $(window).width();
$(window).resize(function() {
windowsize = $(window).width();
if (windowsize > 440) {
//if the window is greater than 440px wide then turn on jScrollPane..
$('#pane1').jScrollPane({
scrollbarWidth:15,
scrollbarMargin:52
});
}
});
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
Add the following namespace,
using System.IO;
and use the Directory
class to reach on the specific folder:
string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
File.Delete(fileName);
In Python 2.7.3:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
print type(e) #not catch
except socket.timeout as e:
print type(e) #catched
raise MyException("There was an error: %r" % e)
Following two steps worked perfectly fine for me:
Comment out the bind address from the file /etc/mysql/my.cnf
:
#bind-address = 127.0.0.1
Run following query in phpMyAdmin:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'; FLUSH PRIVILEGES;
if you execute
mvn eclipse:clean
followed by
mvn eclipse:eclipse
if will prepare the eclipse .classpath
file for you. That is, these commands are run against maven from the command line i.e. outside of eclipse.
This should format a field in an SQL query:
SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
From Java 8 onwards we have CompletableFuture
.
On your case, you may use the method supplyAsync
to get the result after execution.
Please find some reference here.
CompletableFuture<Integer> completableFuture
= CompletableFuture.supplyAsync(() -> yourMethod());
completableFuture.get() //gives you the value
Try sorting the array first. Then after it's sorted, if the array has an even amount of elements the mean of the middle two is the median, if it has a odd number, the middle element is the median.
You could hide controls using CSS Pseudo Selectors like Demo: https://jsfiddle.net/g1rsasa3
//For Firefox we have to handle it in JavaScript _x000D_
var vids = $("video"); _x000D_
$.each(vids, function(){_x000D_
this.controls = false; _x000D_
}); _x000D_
//Loop though all Video tags and set Controls as false_x000D_
_x000D_
$("video").click(function() {_x000D_
//console.log(this); _x000D_
if (this.paused) {_x000D_
this.play();_x000D_
} else {_x000D_
this.pause();_x000D_
}_x000D_
});
_x000D_
video::-webkit-media-controls {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
/* Could Use thise as well for Individual Controls */_x000D_
video::-webkit-media-controls-play-button {}_x000D_
_x000D_
video::-webkit-media-controls-volume-slider {}_x000D_
_x000D_
video::-webkit-media-controls-mute-button {}_x000D_
_x000D_
video::-webkit-media-controls-timeline {}_x000D_
_x000D_
video::-webkit-media-controls-current-time-display {}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<!-- Hiding HTML5 Video Controls using CSS Pseudo selectors -->_x000D_
_x000D_
<video width="800" autoplay controls="false">_x000D_
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">_x000D_
</video>
_x000D_
Using Brock Adams's method, with a simple class:
int get_cpu_ticks()
{
LARGE_INTEGER ticks;
QueryPerformanceFrequency(&ticks);
return ticks.LowPart;
}
__int64 get_cpu_clocks()
{
struct { int32 low, high; } counter;
__asm cpuid
__asm push EDX
__asm rdtsc
__asm mov counter.low, EAX
__asm mov counter.high, EDX
__asm pop EDX
__asm pop EAX
return *(__int64 *)(&counter);
}
class cbench
{
public:
cbench(const char *desc_in)
: desc(strdup(desc_in)), start(get_cpu_clocks()) { }
~cbench()
{
printf("%s took: %.4f ms\n", desc, (float)(get_cpu_clocks()-start)/get_cpu_ticks());
if(desc) free(desc);
}
private:
char *desc;
__int64 start;
};
Usage Example:
int main()
{
{
cbench c("test");
... code ...
}
return 0;
}
Result:
test took: 0.0002 ms
Has some function call overhead, but should be still more than fast enough :)
This is also possible: String.format("%n")
.
Or String.format("%n").intern()
to save some bytes.
You can use a ComboBox
with its ComboBoxStyle
(appears as DropDownStyle
in later versions) set to DropDownList
. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
Create a video thumbnail for a video. It may return null if the video is corrupted or the format is not supported.
private void makeVideoPreview() {
Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoAbsolutePath, MediaStore.Images.Thumbnails.MINI_KIND);
saveImage(thumbnail);
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
Another approach is to use an object for initial storage of the array information. Then convert back. For example:
var arr = ['0','1','1','2','3','3','3'];
var obj = {};
for(var i in arr)
obj[i] = true;
arr = [];
for(var i in obj)
arr.push(i);
Variable "arr" now contains ["0", "1", "2", "3", "4", "5", "6"]
For global installation : npm install webpack-dev-server -g
For local installation npm install --save-dev webpack
When you refer webpack in package.json file, it tries to look it in location node_modules\.bin\
After local installation, file wbpack will get created in location: \node_modules\.bin\webpack
Developing Android REST client applications has been an awesome resource for me. The speaker does not show any code, he just goes over design considerations and techniques in putting together a rock solid Rest Api in android. If your a podcast kinda person or not, I'd recommend giving this one at least one listen but, personally I've listened to it like 4 or five times thus far and I'm probably going to listen to it again.
Developing Android REST client applications
Author: Virgil Dobjanschi
Description:
This session will present architectural considerations for developing RESTful applications on the Android platform. It focuses on design patterns, platform integration and performance issues specific to the Android platform.
And there are so many considerations I really hadn't made in the first version of my api that I've had to refactor
Open preferences, in macOS ?; or in Windows/Linux Ctrl + Alt + S.
Go to Editor -> Code Style -> Python, and if you want to follow PEP-8, choose Tab size: 4, Indent: 4, and Continuation indent: 8 as shown below:
Apply the changes, and click on OK.
Option 1: You can choose in the navigation bar: Edit -> Convert Indent -> To Spaces. (see image below)
Option 2: You can execute "To Spaces" action by running the Find Action shortcut: ??A on macOS or ctrl?A on Windows/Linux. Then type "To Spaces", and run the action as shown in the image below.
findIndex works for modern browsers:
var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
var index = myArr.findIndex(function(o){
return o.id === 'myid';
})
if (index !== -1) myArr.splice(index, 1);
Just use the shell script git-submodule-move.
Update your apt-get:
$ sudo apt-get update
$ sudo apt-get install g++
Run your program.cpp:
$ g++ program.cpp
$ ./a.out
You can use $lookup
( multiple ) to get the records from multiple collections:
Example:
If you have more collections ( I have 3 collections for demo here, you can have more than 3 ). and I want to get the data from 3 collections in single object:
The collection are as:
db.doc1.find().pretty();
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma"
}
db.doc2.find().pretty();
{
"_id" : ObjectId("5901a5f83541b7d5d3293768"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"address" : "Gurgaon",
"mob" : "9876543211"
}
db.doc3.find().pretty();
{
"_id" : ObjectId("5901b0f6d318b072ceea44fb"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
Now your query will be as below:
db.doc1.aggregate([
{ $match: { _id: ObjectId("5901a4c63541b7d5d3293766") } },
{
$lookup:
{
from: "doc2",
localField: "_id",
foreignField: "userId",
as: "address"
}
},
{
$unwind: "$address"
},
{
$project: {
__v: 0,
"address.__v": 0,
"address._id": 0,
"address.userId": 0,
"address.mob": 0
}
},
{
$lookup:
{
from: "doc3",
localField: "_id",
foreignField: "userId",
as: "social"
}
},
{
$unwind: "$social"
},
{
$project: {
__v: 0,
"social.__v": 0,
"social._id": 0,
"social.userId": 0
}
}
]).pretty();
Then Your result will be:
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma",
"address" : {
"address" : "Gurgaon"
},
"social" : {
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
}
If you want all records from each collections then you should remove below line from query:
{
$project: {
__v: 0,
"address.__v": 0,
"address._id": 0,
"address.userId": 0,
"address.mob": 0
}
}
{
$project: {
"social.__v": 0,
"social._id": 0,
"social.userId": 0
}
}
After removing above code you will get total record as:
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma",
"address" : {
"_id" : ObjectId("5901a5f83541b7d5d3293768"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"address" : "Gurgaon",
"mob" : "9876543211"
},
"social" : {
"_id" : ObjectId("5901b0f6d318b072ceea44fb"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
}
I don't think gcc
has a flag for it, since it's primarily a compiler, but another of the GNU development tools does. objdump
takes a -d
/--disassemble
flag:
$ objdump -d /path/to/binary
The disassembly looks like this:
080483b4 <main>:
80483b4: 8d 4c 24 04 lea 0x4(%esp),%ecx
80483b8: 83 e4 f0 and $0xfffffff0,%esp
80483bb: ff 71 fc pushl -0x4(%ecx)
80483be: 55 push %ebp
80483bf: 89 e5 mov %esp,%ebp
80483c1: 51 push %ecx
80483c2: b8 00 00 00 00 mov $0x0,%eax
80483c7: 59 pop %ecx
80483c8: 5d pop %ebp
80483c9: 8d 61 fc lea -0x4(%ecx),%esp
80483cc: c3 ret
80483cd: 90 nop
80483ce: 90 nop
80483cf: 90 nop
git whatchanged
seems to be a good alternative.
To catch different patterns it is helpful to query with different patterns.
'[\d]+[.,\d]+'
'[\d]*[.][\d]+'
'[\d]+'
(Note: Put complex patterns first else simple patterns will return chunks of the complex catch instead of the complex catch returning the full catch).
p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
Below, we'll confirm a pattern is present with re.search()
, then return an iterable list of catches. Finally, we'll print each catch using bracket notation to subselect the match object return value from the match object.
s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
if re.search(p, s) is not None:
for catch in re.finditer(p, s):
print(catch[0]) # catch is a match object
Returns:
33
42
32
30
444.4
12,001
Following method is deprecated
sslSocketFactory(SSLSocketFactory sslSocketFactory)
Consider updating it to
sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)
The following solution to a struct is inspired by the namedtuple implementation and some of the previous answers. However, unlike the namedtuple it is mutable, in it's values, but like the c-style struct immutable in the names/attributes, which a normal class or dict isn't.
_class_template = """\
class {typename}:
def __init__(self, *args, **kwargs):
fields = {field_names!r}
for x in fields:
setattr(self, x, None)
for name, value in zip(fields, args):
setattr(self, name, value)
for name, value in kwargs.items():
setattr(self, name, value)
def __repr__(self):
return str(vars(self))
def __setattr__(self, name, value):
if name not in {field_names!r}:
raise KeyError("invalid name: %s" % name)
object.__setattr__(self, name, value)
"""
def struct(typename, field_names):
class_definition = _class_template.format(
typename = typename,
field_names = field_names)
namespace = dict(__name__='struct_%s' % typename)
exec(class_definition, namespace)
result = namespace[typename]
result._source = class_definition
return result
Usage:
Person = struct('Person', ['firstname','lastname'])
generic = Person()
michael = Person('Michael')
jones = Person(lastname = 'Jones')
In [168]: michael.middlename = 'ben'
Traceback (most recent call last):
File "<ipython-input-168-b31c393c0d67>", line 1, in <module>
michael.middlename = 'ben'
File "<string>", line 19, in __setattr__
KeyError: 'invalid name: middlename'
Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:
>>> x = "Dana Larose is playing with find()"
>>> x.find("Dana")
0
>>> x.find("ana")
1
>>> x.find("La")
5
>>> x.find("La", 6)
-1
Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)
From the manual:
-N or --LINE-NUMBERS Causes a line number to be displayed at the beginning of each line in the display.
You can also toggle line numbers without quitting less by typing -N
.
It is possible to toggle any of less's command line options in this way.
html {height: 101%;}
I use this cross browsers solution (note: I always use DOCTYPE declaration in 1st line, I don't know if it works in quirksmode, never tested it).
This will always show an ACTIVE vertical scroll bar in every page, vertical scrollbar will be scrollable only of few pixels.
When page contents is shorter than browser's visible area (view port) you will still see the vertical scrollbar active, and it will be scrollable only of few pixels.
In case you are obsessed with CSS validation (I'm obesessed only with HTML validation) by using this solution your CSS code would also validate for W3C because you are not using non standard CSS attributes like -moz-scrollbars-vertical
import numpy as np
mean_data = np.array([
[6.0, 315.0, 4.8123788544375692e-06],
[6.5, 0.0, 2.259217450023793e-06],
[6.5, 45.0, 9.2823565008402673e-06],
[6.5, 90.0, 8.309270169336028e-06],
[6.5, 135.0, 6.4709418114245381e-05],
[6.5, 180.0, 1.7227922423558414e-05],
[6.5, 225.0, 1.2308522579848724e-05],
[6.5, 270.0, 2.6905672894824344e-05],
[6.5, 315.0, 2.2727114437176048e-05]])
R = mean_data[:,0]
print R
print R.shape
EDIT
The reason why you had an invalid index
error is the lack of a comma between mean_data
and the values you wanted to add.
Also, np.append returns a copy of the array, and does not change the original array. From the documentation :
Returns : append : ndarray
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.
So you have to assign the np.append
result to an array (could be mean_data
itself, I think), and, since you don't want a flattened array, you must also specify the axis on which you want to append.
With that in mind, I think you could try something like
mean_data = np.append(mean_data, [[ur, ua, np.mean(data[samepoints,-1])]], axis=0)
Do have a look at the doubled [[
and ]]
: I think they are necessary since both arrays must have the same shape.
try this
http://www.ehow.com/how_6613143_convert-xml-code-sql.html
for downloading the tool http://www.xml-converter.com/
Another alternative to do the same thing is to filter on type=checkbox attribute:
$('input[type="checkbox"]').removeAttr('checked');
or
$('input[type="checkbox"]').prop('checked' , false);
Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Know more...
If you are using the plugin chartjs-plugin-datalabels then the following code options object will help
Make sure you import import 'chartjs-plugin-datalabels';
in your typescript file or add reference to <script src="chartjs-plugin-datalabels.js"></script>
in your javascript file.
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: Math.round,
font: {
weight: 'bold'
}
}
}
}
This is a good way of counting entries within .pivot_table
:
df2.pivot_table(values='X', index=['Y','Z'], columns='X', aggfunc='count')
X1 X2
Y Z
Y1 Z1 1 1
Z2 1 NaN
Y2 Z3 1 NaN
Whole XML structure is defined in $data Array:
function array2Xml($data, $xml = null)
{
if (is_null($xml)) {
$xml = simplexml_load_string('<' . key($data) . '/>');
$data = current($data);
$return = true;
}
if (is_array($data)) {
foreach ($data as $name => $value) {
array2Xml($value, is_numeric($name) ? $xml : $xml->addChild($name));
}
} else {
$xml->{0} = $data;
}
if (!empty($return)) {
return $xml->asXML();
}
}
Example:
\Large\begin{verbatim}
<how to set font size here to 10 px ? />
\end{verbatim}
\normalsize
\Large
can be obviously substituted by one of:
\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge
If you need arbitrary font sizes:
You can return dynamic
which will give you a runtime checked version of the anonymous type but only in .NET 4+
The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.
You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.
If you're running a jar file with java -jar
, the -classpath
argument is ignored. You need to set the classpath in the manifest file of your jar, like so:
Class-Path: jar1-name jar2-name directory-name/jar3-name
See the Java tutorials: Adding Classes to the JAR File's Classpath.
Edit: I see you already tried setting the class path in the manifest, but are you sure you used the correct syntax? If you skip the ':
' after "Class-Path
" like you showed, it would not work.
If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103
I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
enum NumberError: Error {
case NegativeNumber(number: Int)
case ZeroNumber
case OddNumber(number: Int)
}
extension NumberError: CustomStringConvertible {
var description: String {
switch self {
case .NegativeNumber(let number):
return "Negative number \(number) is Passed."
case .OddNumber(let number):
return "Odd number \(number) is Passed."
case .ZeroNumber:
return "Zero is Passed."
}
}
}
func validateEvenNumber(_ number: Int) throws ->Int {
if number == 0 {
throw NumberError.ZeroNumber
} else if number < 0 {
throw NumberError.NegativeNumber(number: number)
} else if number % 2 == 1 {
throw NumberError.OddNumber(number: number)
}
return number
}
Now Validate Number :
do {
let number = try validateEvenNumber(0)
print("Valid Even Number: \(number)")
} catch let error as NumberError {
print(error.description)
}
The nuget commandline tool does not come with the vsix file, it's a separate download
You are very close; currently you compare the row[2]
with integer 0
, make the comparison with the string "0"
. When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:
row[2]!="0":
Also, you can use the with
keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close
statements:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != "0":
writer.writerow(row)
Note that input
is a Python builtin, so I've used another variable name instead.
Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0"
would work, so you can either use strip(row[2]) != 0
, or check against " 0"
.
The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:
$ cat test.py
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != " 0":
writer.writerow(row)
$ cat first.csv
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py
$ cat first_edit.csv
6.5, 5.4, 1, 320
git pull
and git rebase
are not interchangeable, but they are closely connected.
git pull
fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull
is similar to git fetch & git merge
.
Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.
You can pull using rebase instead of merge (git pull --rebase
). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.
Atlassian has some excellent documentation on merging vs. rebasing.
You can create a custom class to modify the content type and add the file to the response.
If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.
you can use following command to create directory and give permissions at the same time
mkdir -m777 path/foldername
For drawing just the arrow, there is an easier method:-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)
plt.show()
quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]
quiver(X, Y, Z, U, V, W, **kwargs)
Arguments:
X, Y, Z: The x, y and z coordinates of the arrow locations
U, V, W: The x, y and z components of the arrow vectors
The arguments could be array-like or scalars.
Keyword arguments:
length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes
arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3
pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’
normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.
You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.
You could do an outer loop over the array
$.each(data.programs, function(index) {
// then loop over the object elements
$.each(data.programs[index], function(key, value) {
console.log(key + ": " + value);
}
}
hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)
minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)
similarly, seconds (s) by remainder of hour and minutes calculation.
Rest is just string formatting!
def hms(seconds):
h = seconds // 3600
m = seconds % 3600 // 60
s = seconds % 3600 % 60
return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
print(hms(7500)) # Should print 02h05m00s
strings = ("string1", "string2", "string3")
for line in file:
if any(s in line for s in strings):
print "yay!"
You can do like this:
#mydiv {
position: fixed;
height: 30px;
top: 0;
left: 0;
width: 100%;
}
This will create a div
, that will be fixed on top of your screen. - fixed
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.
Set up tryCatch as part of a function. For example:
irr2 <- function (x) {
out <- tryCatch(irr(x), error = function(e) NULL)
return(out)
}
For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL)
and ALL values came back null.
Remember to create a sub-output (like my "out") and to return(out)
.
I use
patch -p1 --merge < patchfile
This way, conflicts may be resolved as usual.
I found this solution. If you go to a new view the function gets executed.
var app = angular.module('hoofdModule', ['ngRoute']);
app.controller('indexController', function ($scope, $window) {
$scope.$on('$viewContentLoaded', function () {
$window.scrollTo(0, 0);
});
});
you can generate curl error after its execution
$url = 'http://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);
}
and here are curl error code
if someone need more information about curl errors
<?php
$error_codes=array(
[1] => 'CURLE_UNSUPPORTED_PROTOCOL',
[2] => 'CURLE_FAILED_INIT',
[3] => 'CURLE_URL_MALFORMAT',
[4] => 'CURLE_URL_MALFORMAT_USER',
[5] => 'CURLE_COULDNT_RESOLVE_PROXY',
[6] => 'CURLE_COULDNT_RESOLVE_HOST',
[7] => 'CURLE_COULDNT_CONNECT',
[8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
[9] => 'CURLE_REMOTE_ACCESS_DENIED',
[11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
[13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
[14]=>'CURLE_FTP_WEIRD_227_FORMAT',
[15] => 'CURLE_FTP_CANT_GET_HOST',
[17] => 'CURLE_FTP_COULDNT_SET_TYPE',
[18] => 'CURLE_PARTIAL_FILE',
[19] => 'CURLE_FTP_COULDNT_RETR_FILE',
[21] => 'CURLE_QUOTE_ERROR',
[22] => 'CURLE_HTTP_RETURNED_ERROR',
[23] => 'CURLE_WRITE_ERROR',
[25] => 'CURLE_UPLOAD_FAILED',
[26] => 'CURLE_READ_ERROR',
[27] => 'CURLE_OUT_OF_MEMORY',
[28] => 'CURLE_OPERATION_TIMEDOUT',
[30] => 'CURLE_FTP_PORT_FAILED',
[31] => 'CURLE_FTP_COULDNT_USE_REST',
[33] => 'CURLE_RANGE_ERROR',
[34] => 'CURLE_HTTP_POST_ERROR',
[35] => 'CURLE_SSL_CONNECT_ERROR',
[36] => 'CURLE_BAD_DOWNLOAD_RESUME',
[37] => 'CURLE_FILE_COULDNT_READ_FILE',
[38] => 'CURLE_LDAP_CANNOT_BIND',
[39] => 'CURLE_LDAP_SEARCH_FAILED',
[41] => 'CURLE_FUNCTION_NOT_FOUND',
[42] => 'CURLE_ABORTED_BY_CALLBACK',
[43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
[45] => 'CURLE_INTERFACE_FAILED',
[47] => 'CURLE_TOO_MANY_REDIRECTS',
[48] => 'CURLE_UNKNOWN_TELNET_OPTION',
[49] => 'CURLE_TELNET_OPTION_SYNTAX',
[51] => 'CURLE_PEER_FAILED_VERIFICATION',
[52] => 'CURLE_GOT_NOTHING',
[53] => 'CURLE_SSL_ENGINE_NOTFOUND',
[54] => 'CURLE_SSL_ENGINE_SETFAILED',
[55] => 'CURLE_SEND_ERROR',
[56] => 'CURLE_RECV_ERROR',
[58] => 'CURLE_SSL_CERTPROBLEM',
[59] => 'CURLE_SSL_CIPHER',
[60] => 'CURLE_SSL_CACERT',
[61] => 'CURLE_BAD_CONTENT_ENCODING',
[62] => 'CURLE_LDAP_INVALID_URL',
[63] => 'CURLE_FILESIZE_EXCEEDED',
[64] => 'CURLE_USE_SSL_FAILED',
[65] => 'CURLE_SEND_FAIL_REWIND',
[66] => 'CURLE_SSL_ENGINE_INITFAILED',
[67] => 'CURLE_LOGIN_DENIED',
[68] => 'CURLE_TFTP_NOTFOUND',
[69] => 'CURLE_TFTP_PERM',
[70] => 'CURLE_REMOTE_DISK_FULL',
[71] => 'CURLE_TFTP_ILLEGAL',
[72] => 'CURLE_TFTP_UNKNOWNID',
[73] => 'CURLE_REMOTE_FILE_EXISTS',
[74] => 'CURLE_TFTP_NOSUCHUSER',
[75] => 'CURLE_CONV_FAILED',
[76] => 'CURLE_CONV_REQD',
[77] => 'CURLE_SSL_CACERT_BADFILE',
[78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
[79] => 'CURLE_SSH',
[80] => 'CURLE_SSL_SHUTDOWN_FAILED',
[81] => 'CURLE_AGAIN',
[82] => 'CURLE_SSL_CRL_BADFILE',
[83] => 'CURLE_SSL_ISSUER_ERROR',
[84] => 'CURLE_FTP_PRET_FAILED',
[84] => 'CURLE_FTP_PRET_FAILED',
[85] => 'CURLE_RTSP_CSEQ_ERROR',
[86] => 'CURLE_RTSP_SESSION_ERROR',
[87] => 'CURLE_FTP_BAD_FILE_LIST',
[88] => 'CURLE_CHUNK_FAILED');
?>
I had the same issue, my problem was, that I had two different webservices with two different wsdl-files. I generated the sources in the same package for both webservices, which seems to be a problem. I guess it's because of the ObjectFactory and perhaps also because of the package-info.java - because those are only generated once.
I solved it, by generating the sources for each webservice in a different package. This way, you also have two different ObjectFactories and package-info.java files.
Create the Button
and add it to Form.Controls
list to display it on your form:
Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45); //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list
Create the button click method here:
void buttonOk_Click(object sender, EventArgs e)
{
MessageBox.Show("clicked");
this.Close(); //all your choice to close it or remove this line
}
Based on the accepted answer and the answer of @LeoCaseiro here is what I ended up using in my case :
@media (max-width: 767px) {
.table-responsive{
overflow-x: auto;
overflow-y: auto;
}
}
@media (min-width: 767px) {
.table-responsive{
overflow: inherit !important; /* Sometimes needs !important */
}
}
on big screens the dropdown won't be hidden behind the reponsive-table and in small screen it will be hidden but it's ok because there is scrolls bar in mobile anyway.
Hope this help someone.
For anyone else having the issue - none of the answers provided worked for me.
My case may be different to others but I had Android Studio
installed first which installs the SDK by default to: C:\Users\[user]\AppData\Local\Android\sdk
. We then decided to use Xamarin for our projects, so Xamarin was installed and installed an additional SDK by default, located here: C:\Program Files (x86)\Android\android-sdk
.
Changing Xamarin to match the same SDK path worked for me which I did in the registry (although through the VS settings I'd guess it's the same):
\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Android SDK Tools\Path
Change the path to match the Android Studio
SDK path, close everything, start the VS Emulator, run Android Studio, ensure ADB integration
is off and try. It worked for me.
Following are the ways to do Inter Process Communication asynchronously:
You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.
import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))
I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse()
and fromstring()
methods.
Yet another way to do it:
//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
As an extension of Anooj VM's answer, I suggest the following to refresh content size only when it changes.
This approach also disable scrolling properly and support larger lists and rotation. There is no need to dispatch_async because contentSize changes are dispatched on main thread.
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:NULL];
}
- (void)resizeTableAccordingToContentSize:(CGSize)newContentSize {
CGRect superviewTableFrame = self.tableView.superview.bounds;
CGRect tableFrame = self.tableView.frame;
BOOL shouldScroll = newContentSize.height > superviewTableFrame.size.height;
tableFrame.size = shouldScroll ? superviewTableFrame.size : newContentSize;
[UIView animateWithDuration:0.3
delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
self.tableView.frame = tableFrame;
} completion: nil];
self.tableView.scrollEnabled = shouldScroll;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([change[NSKeyValueChangeKindKey] unsignedIntValue] == NSKeyValueChangeSetting &&
[keyPath isEqualToString:@"contentSize"] &&
!CGSizeEqualToSize([change[NSKeyValueChangeOldKey] CGSizeValue], [change[NSKeyValueChangeNewKey] CGSizeValue])) {
[self resizeTableAccordingToContentSize:[change[NSKeyValueChangeNewKey] CGSizeValue]];
}
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[self resizeTableAccordingToContentSize:self.tableView.contentSize]; }
- (void)dealloc {
[self.tableView removeObserver:self forKeyPath:@"contentSize"];
}
Try like this.
You must give a function as value to onClick()
You button:
<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
refreshPage function:
function refreshPage(){
window.location.reload();
}
There is no equivalent to $scope.emit()
or $scope.broadcast()
from AngularJS.
EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.
In Angular, there are other alternatives which I'll try to explain below.
@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component.
Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.
To answer your questions:
What if I need to communicate between sibling components?
Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.
Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.
Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.
How can I communicate between a Root component and a component nested several levels deep?
$scope.broadcast()
from Angular 1. The next section describes this idea in more detail.Example of an Observable Service that uses Service Events to Propagate Changes
Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.
export class TodoItem {
constructor(public name: string, public done: boolean) {
}
}
export class TodoService {
public itemAdded$: EventEmitter<TodoItem>;
private todoList: TodoItem[] = [];
constructor() {
this.itemAdded$ = new EventEmitter();
}
public list(): TodoItem[] {
return this.todoList;
}
public add(item: TodoItem): void {
this.todoList.push(item);
this.itemAdded$.emit(item);
}
}
Here is how a root component would subscribe to the event:
export class RootComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
A child component nested several levels deep would subscribe to the event in the same way:
export class GrandChildComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):
@Component({
selector: 'todo-list',
template: `
<ul>
<li *ngFor="#item of model"> {{ item.name }}
</li>
</ul>
<br />
Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>
`
})
export class TriggeringComponent{
private model: TodoItem[];
constructor(private todoService: TodoService) {
this.model = todoService.list();
}
add(value: string) {
this.todoService.add(new TodoItem(value, false));
}
}
Reference: Change Detection in Angular
The only valid answer would be the pause
command.
Though this does not wait specifically for the 'ENTER' key, it waits for any key that is pressed.
And just in case you want it convenient for the user, pause
is the best option.
It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video>
element will be the way to go, but that will lack support for a little while.
([[][a-z \s]+[]])
Above should work given the following explaination
characters within square brackets[] defines characte class which means pattern should match atleast one charcater mentioned within square brackets
\s specifies a space
+ means atleast one of the character mentioned previously to +.
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
The simplest answer is add the ref="some name" in the input text element and call the below function.
componentDidMount(){
this.refs.field_name.focus();
}
// here field_name is ref name.
<input type="text" ref="field_name" />
This could be useful to others:
Using AccountPicker to get user's email address without any global permissions, and allowing the user to be aware and authorize or cancel the process.
The main reason is probably that a C++ string is a struct that includes a current-length value, not just the address of a sequence of chars terminated by a 0 byte. Printf and its relatives expect to find such a sequence, not a struct, and therefore get confused by C++ strings.
Speaking for myself, I believe that printf has a place that can't easily be filled by C++ syntactic features, just as table structures in html have a place that can't easily be filled by divs. As Dykstra wrote later about the goto, he didn't intend to start a religion and was really only arguing against using it as a kludge to make up for poorly-designed code.
It would be quite nice if the GNU project would add the printf family to their g++ extensions.
Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.
What this looks like:
private static someClass[] arr = new someClass[someNum];
and
public class someClass {
private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;
...
}
I have work it like this,
/** Open another app.
* @param context current Context, like Activity, App, or Service
* @param packageName the full package name of the app to open
* @return true if likely successful, false if unsuccessful
*/
public static boolean openApp(Context context, String packageName) {
PackageManager manager = context.getPackageManager();
try {
Intent i = manager.getLaunchIntentForPackage(packageName);
if (i == null) {
return false;
//throw new ActivityNotFoundException();
}
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
Example usage:
openApp(this, "com.google.android.maps.mytracks");
Hope it helps someone.
If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#
Let's see what happens if you want to round to the 3rd decimal:
double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.
This applies to negative numbers:
double result = -0.75 * 0.95; //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:
double Redondea(double value, int precision, bool roundUp = true)
{
if ((decimal)value == 0.0m)
return 0.0;
double corrector = 1 / Math.Pow(10, precision + 2);
if ((decimal)value < 0.0m)
{
if (roundUp)
return Math.Round(value, precision, MidpointRounding.ToEven);
else
return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
}
else
{
if (roundUp)
return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
else
return Math.Round(value, precision, MidpointRounding.ToEven);
}
}
The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.
My own library for working with ES6 iterables (blinq) allows (among other things) easy multi-level sorting
const blinq = window.blinq.blinq_x000D_
// or import { blinq } from 'blinq'_x000D_
// or const { blinq } = require('blinq')_x000D_
const dates = [{_x000D_
day: 1, month: 10, year: 2000_x000D_
},_x000D_
{_x000D_
day: 1, month: 1, year: 2000_x000D_
},_x000D_
{_x000D_
day: 2, month: 1, year: 2000_x000D_
},_x000D_
{_x000D_
day: 1, month: 1, year: 1999_x000D_
},_x000D_
{_x000D_
day: 1, month: 1, year: 2000_x000D_
}_x000D_
]_x000D_
const sortedDates = blinq(dates)_x000D_
.orderBy(x => x.year)_x000D_
.thenBy(x => x.month)_x000D_
.thenBy(x => x.day);_x000D_
_x000D_
console.log(sortedDates.toArray())_x000D_
// or console.log([...sortedDates])
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
_x000D_
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
Box shadows can use commas to have multiple effects, just like with background images (in CSS3).
use this Tutorial
<?php
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
}
else {
// Return object
return $d;
}
}
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
//OUTPUT
stdClass Object
(
[foo] => Test data
[bar] => stdClass Object
(
[baaz] => Testing
[fooz] => stdClass Object
(
[baz] => Testing again
)
)
[foox] => Just test
)
Array
(
[foo] => Test data
[bar] => Array
(
[baaz] => Testing
[fooz] => Array
(
[baz] => Testing again
)
)
[foox] => Just test
)
stdClass Object
(
[foo] => Test data
[bar] => stdClass Object
(
[baaz] => Testing
[fooz] => stdClass Object
(
[baz] => Testing again
)
)
[foox] => Just test
)
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
where status may be true
or false
add permission manifest: <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Note: This is some explanation and pseudocode as to how to implement a very trivial server that can handle incoming and outcoming WebSocket messages as per the definitive framing format. It does not include the handshaking process. Furthermore, this answer has been made for educational purposes; it is not a full-featured implementation.
(In other words, server → browser)
The frames you're sending need to be formatted according to the WebSocket framing format. For sending messages, this format is as follows:
The first byte will be 1000 0001
(or 129
) for a text frame.
The second byte has its first bit set to 0
because we're not encoding the data (encoding from server to client is not mandatory).
It is necessary to determine the length of the raw data so as to send the length bytes correctly:
0 <= length <= 125
, you don't need additional bytes126 <= length <= 65535
, you need two additional bytes and the second byte is 126
length >= 65536
, you need eight additional bytes, and the second byte is 127
The length has to be sliced into separate bytes, which means you'll need to bit-shift to the right (with an amount of eight bits), and then only retain the last eight bits by doing AND 1111 1111
(which is 255
).
After the length byte(s) comes the raw data.
This leads to the following pseudocode:
bytesFormatted[0] = 129
indexStartRawData = -1 // it doesn't matter what value is
// set here - it will be set now:
if bytesRaw.length <= 125
bytesFormatted[1] = bytesRaw.length
indexStartRawData = 2
else if bytesRaw.length >= 126 and bytesRaw.length <= 65535
bytesFormatted[1] = 126
bytesFormatted[2] = ( bytesRaw.length >> 8 ) AND 255
bytesFormatted[3] = ( bytesRaw.length ) AND 255
indexStartRawData = 4
else
bytesFormatted[1] = 127
bytesFormatted[2] = ( bytesRaw.length >> 56 ) AND 255
bytesFormatted[3] = ( bytesRaw.length >> 48 ) AND 255
bytesFormatted[4] = ( bytesRaw.length >> 40 ) AND 255
bytesFormatted[5] = ( bytesRaw.length >> 32 ) AND 255
bytesFormatted[6] = ( bytesRaw.length >> 24 ) AND 255
bytesFormatted[7] = ( bytesRaw.length >> 16 ) AND 255
bytesFormatted[8] = ( bytesRaw.length >> 8 ) AND 255
bytesFormatted[9] = ( bytesRaw.length ) AND 255
indexStartRawData = 10
// put raw data at the correct index
bytesFormatted.put(bytesRaw, indexStartRawData)
// now send bytesFormatted (e.g. write it to the socket stream)
(In other words, browser → server)
The frames you obtain are in the following format:
The first byte usually does not matter - if you're just sending text you are only using the text type. It will be 1000 0001
(or 129
) in that case.
The second byte and the additional two or eight bytes need some parsing, because you need to know how many bytes are used for the length (you need to know where the real data starts). The length itself is usually not necessary since you have the data already.
The first bit of the second byte is always 1
which means the data is masked (= encoded). Messages from the client to the server are always masked. You need to remove that first bit by doing secondByte AND 0111 1111
. There are two cases in which the resulting byte does not represent the length because it did not fit in the second byte:
0111 1110
, or 126
, means the following two bytes are used for the length0111 1111
, or 127
, means the following eight bytes are used for the lengthThe four mask bytes are used for decoding the actual data that has been sent. The algorithm for decoding is as follows:
decodedByte = encodedByte XOR masks[encodedByteIndex MOD 4]
where encodedByte
is the original byte in the data, encodedByteIndex
is the index (offset) of the byte counting from the first byte of the real data, which has index 0
. masks
is an array containing of the four mask bytes.
This leads to the following pseudocode for decoding:
secondByte = bytes[1]
length = secondByte AND 127 // may not be the actual length in the two special cases
indexFirstMask = 2 // if not a special case
if length == 126 // if a special case, change indexFirstMask
indexFirstMask = 4
else if length == 127 // ditto
indexFirstMask = 10
masks = bytes.slice(indexFirstMask, 4) // four bytes starting from indexFirstMask
indexFirstDataByte = indexFirstMask + 4 // four bytes further
decoded = new array
decoded.length = bytes.length - indexFirstDataByte // length of real data
for i = indexFirstDataByte, j = 0; i < bytes.length; i++, j++
decoded[j] = bytes[i] XOR masks[j MOD 4]
// now use "decoded" to interpret the received data
I put everything into:
<location path="." inheritInChildApplications="false">
....
</location>
except: <configSections/>
, <connectionStrings/>
and <runtime/>
.
There are some cases when we don't want to inherit some secions from <configSections />
, but we can't put <section/>
tag into <location/>
, so we have to create a <secionGroup />
and put our unwanted sections into that group. Section groups can be later inserted into a location tag.
So we have to change this:
<configSections>
<section name="unwantedSection" />
</configSections>
Into:
<configSections>
<sectionGroup name="myNotInheritedSections">
<section name="unwantedSection" />
</sectionGroup>
</configSections>
<location path="." inheritInChildApplications="false">
<myNotInheritedSections>
<unwantedSection />
</myNotInheritedSections>
</location>
The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123
As you will see in linked discussion there is no need for initializing char with special character as it's done for us and is represented by '\u0000' character code.
So if we want simply to check if specified char was initialized just write:
if(charVariable != '\u0000'){
actionsOnInitializedCharacter();
}
Link to question: what's the default value of char?
All answers are great, but they are talking about adding extension method to a specific type of enum.
What if you want to add a method to all enums like returning an int of current value instead of explicit casting?
public static class EnumExtensions
{
public static int ToInt<T>(this T soure) where T : IConvertible//enum
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return (int) (IConvertible) soure;
}
//ShawnFeatherly funtion (above answer) but as extention method
public static int Count<T>(this T soure) where T : IConvertible//enum
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetNames(typeof(T)).Length;
}
}
The trick behind IConvertible
is its Inheritance Hierarchy see MDSN
Thanks to ShawnFeatherly for his answer
Just install selinux latest version to fix it:
sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm
More versions at http://mirror.centos.org/centos/7/extras/x86_64/Packages/
Older versions of 2.9: http://ftp.riken.jp/Linux/cern/centos/7/extras/x86_64/Packages/
Use:
window.location.replace(...)
See this Stack Overflow question for more information:
How do I redirect to another webpage?
Or perhaps it was this you remember:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
The following code works on both Linux and Windows, and not depending on external modules
import os
import subprocess
import platform
import re
def pid_alive(pid:int):
""" Check For whether a pid is alive """
system = platform.uname().system
if re.search('Linux', system, re.IGNORECASE):
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
elif re.search('Windows', system, re.IGNORECASE):
out = subprocess.check_output(["tasklist","/fi",f"PID eq {pid}"]).strip()
# b'INFO: No tasks are running which match the specified criteria.'
if re.search(b'No tasks', out, re.IGNORECASE):
return False
else:
return True
else:
raise RuntimeError(f"unsupported system={system}")
It can be easily enhanced in case you need
firstarray
and secondarray
are converted to a pointer to int, when passed to printarray()
.
printarray(int arg[], ...)
is equivalent to printarray(int *arg, ...)
However, this is not specific to C++. C has the same rules for passing array names to a function.
I think you want to open
the ZipFile, which returns a file-like object, rather than read
:
In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))
In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN 24567 non-null values
REPORTDATETIME 24567 non-null values
SHIFT 24567 non-null values
OFFENSE 24567 non-null values
METHOD 24567 non-null values
LASTMODIFIEDDATE 24567 non-null values
BLOCKSITEADDRESS 24567 non-null values
BLOCKXCOORD 24567 non-null values
BLOCKYCOORD 24567 non-null values
WARD 24563 non-null values
ANC 24567 non-null values
DISTRICT 24567 non-null values
PSA 24567 non-null values
NEIGHBORHOODCLUSTER 24263 non-null values
BUSINESSIMPROVEMENTDISTRICT 3613 non-null values
dtypes: float64(4), int64(1), object(10)
Use the in
operator:
testArray = 'key1' in obj;
Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.
In theory everything is possible but reality you find the numbers much lower than you might expect. I have been trying to address huge spaces on servers often and found that even though a server can have huge amounts of memory it surprised me that most software actually never can address it in real scenario's simply because the cpu's are not fast enough to really address them. Why would you say right ?! . Timings thats the endless downfall of every enormous machine which i have worked on. So i would advise to not go overboard by addressing huge amounts just because you can, but use what you think could be used. Actual values are often much lower than what you expected. Ofcourse non of us really uses hp 9000 systems at home and most of you actually ever will go near the capacity of your home system ever. For instance most users do not have more than 16 Gb of memory in their system. Ofcourse some of the casual gamers use work stations for a game once a month but i bet that is a very small percentage. So coming down to earth means i would address on a 8 Gb 64 bit system not much more than 512 mb for heapspace or if you go overboard try 1 Gb. I am pretty sure its even with these numbers pure overkill. I have constant monitored the memory usage during gaming to see if the addressing would make any difference but did not notice any difference at all when i addressed much lower values or larger ones. Even on the server/workstations there was no visible change in performance no matter how large i set the values. That does not say some jave users might be able to make use of more space addressed, but this far i have not seen any of the applications needing so much ever. Ofcourse i assume that their would be a small difference in performance if java instances would run out of enough heapspace to work with. This far i have not found any of it at all, however lack of real installed memory showed instant drops of performance if you set too much heapspace. When you have a 4 Gb system you run quickly out of heapspace and then you will see some errors and slowdowns because people address too much space which actually is not free in the system so the os starts to address drive space to make up for the shortage hence it starts to swap.
I've seen your code in web.php as follows: Route::post('/edit/{id}','ProjectController@update');
Step 1: remove the {id} random parameter so it would be like this: Route::post('/edit','ProjectController@update');
Step 2: Then remove the @method('PUT') in your form, so let's say we'll just plainly use the POST method
Then how can I pass the ID to my method?
Step 1: make an input field in your form with the hidden attribute for example
<input type="hidden" value="{{$project->id}}" name="id">
Step 2: in your update method in your controller, fetch that ID for example:
$id = $request->input('id');
then you may not use it to find which project to edit
$project = Project::find($id)
//OR
$project = Project::where('id',$id);
This will remove all underlines from all links:
a {text-decoration: none; }
If you have specific links that you want to apply this to, give them a class name, like nounderline
and do this:
a.nounderline {text-decoration: none; }
That will apply only to those links and leave all others unaffected.
This code belongs in the <head>
of your document or in a stylesheet:
<head>
<style type="text/css">
a.nounderline {text-decoration: none; }
</style>
</head>
And in the body:
<a href="#" class="nounderline">Link</a>
You need to install this
https://pypi.python.org/pypi/six
If you still don't know what pip is , then please also google for pip install
Python has it's own package manager which is supposed to help you finding packages and their dependencies: http://www.pip-installer.org/en/latest/
You can simply chain as many split-path
as you need:
$rootPath = $scriptPath | split-path | split-path
If you are using Python3 the following module will help you: https://github.com/mahmoudadel2/pysed
wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py
Place the module file into your Python3 modules path, then:
import pysed
pysed.replace(<Old string>, <Replacement String>, <Text File>)
pysed.rmlinematch(<Unwanted string>, <Text File>)
pysed.rmlinenumber(<Unwanted Line Number>, <Text File>)
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub
Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!
For my Android projects I've used the Base64 library from here:
It's a very extensive library and so far I've had no problems with it.
Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class
REGEXP_REPLACE( my_value, '[[:space:]]', '' )
SQL> ed
Wrote file afiedt.buf
1 select '|' ||
2 regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
3 '|'
4* from dual
SQL> /
'|'||
-----
|foo|
If you want to leave one space in place for every set of continuous space characters, just add the +
to the regular expression and use a space as the replacement character.
with x as (
select 'abc 123 234 5' str
from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
from x
Like thousands of people, I'm looking for this question:
Can run multiple queries simultaneously, and if there was one error, none would run
I went to this page everywhere
But although the friends here gave good answers, these answers were not good for my problem
So I wrote a function that works well and has almost no problem with sql Injection.
It might be helpful for those who are looking for similar questions so I put them here to use
function arrayOfQuerys($arrayQuery)
{
$mx = true;
$conn->beginTransaction();
try {
foreach ($arrayQuery AS $item) {
$stmt = $conn->prepare($item["query"]);
$stmt->execute($item["params"]);
$result = $stmt->rowCount();
if($result == 0)
$mx = false;
}
if($mx == true)
$conn->commit();
else
$conn->rollBack();
} catch (Exception $e) {
$conn->rollBack();
echo "Failed: " . $e->getMessage();
}
return $mx;
}
for use(example):
$arrayQuery = Array(
Array(
"query" => "UPDATE test SET title = ? WHERE test.id = ?",
"params" => Array("aa1", 1)
),
Array(
"query" => "UPDATE test SET title = ? WHERE test.id = ?",
"params" => Array("bb1", 2)
)
);
arrayOfQuerys($arrayQuery);
and my connection:
try {
$options = array(
//For updates where newvalue = oldvalue PDOStatement::rowCount() returns zero. You can use this:
PDO::MYSQL_ATTR_FOUND_ROWS => true
);
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password, $options);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error connecting to SQL Server: " . $e->getMessage();
}
Note:
This solution helps you to run multiple statement together,
If an incorrect a statement occurs, it does not execute any other statement
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.
I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:
map(do_something, a_list_of_objects)
This replaces a bunch of code that looks like this:
do_something(a)
do_something(b)
do_something(c)
...
But can also be achieved with a pedestrian "for" loop:
for obj in a_list_of_objects:
do_something(obj)
The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.
You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):
[ do_something(x) for x in a_list_of_objects ]
For methods, I suppose either of these would work (with the same reservations):
map(lambda x: x.method_call(), a_list_of_objects)
or
[ x.method_call() for x in a_list_of_objects ]
So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.
As stated here about hot_standby_feedback = on
:
Well, the disadvantage of it is that the standby can bloat the master, which might be surprising to some people, too
And here:
With what setting of max_standby_streaming_delay? I would rather default that to -1 than default hot_standby_feedback on. That way what you do on the standby only affects the standby
So I added
max_standby_streaming_delay = -1
And no more pg_dump
error for us, nor master bloat :)
For AWS RDS instance, check http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html
Smart pointers will clean themselves up after they go out of scope (thereby removing fear of most memory leaks). Shared pointers are smart pointers that keep a count of how many instances of the pointer exist, and only clean up the memory when the count reaches zero. In general, only use shared pointers (but be sure to use the correct kind--there is a different one for arrays). They have a lot to do with RAII.
package com.test;
import java.util.ArrayList;
import java.util.List;
public class TEst {
public static void main(String[] args) {
List<Integer> ls=new ArrayList<>();
ls.add(1);
ls.add(2);
List<Integer> ls1=new ArrayList<>();
ls1.add(3);
ls1.add(4);
List<List<Integer>> ls2=new ArrayList<>();
ls2.add(ls);
ls2.add(ls1);
List<List<List<Integer>>> ls3=new ArrayList<>();
ls3.add(ls2);
m1(ls3);
}
private static void m1(List ls3) {
for(Object ls4:ls3)
{
if(ls4 instanceof List)
{
m1((List)ls4);
}else {
System.out.print(ls4);
}
}
}
}
log in as root user:
sudo su
password:
then go and do what you want to do in var/www
Take a look at http://www.csharp-examples.net/download-files/ and msdn docs on webclient http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
My suggestion is try the synchronous download as its more straightforward. you might get ideas on whether webclient parameters are wrong or the file is in incorrect format while trying this.
Here is a code sample..
private void btnDownload_Click(object sender, EventArgs e)
{
string filepath = textBox1.Text;
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), filepath);
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
You could try to "weight" certain columns, like this:
<table border="1" style="width: 100%;">
<colgroup>
<col width="80%" />
<col width="20%" />
</colgroup>
<tr>
<td>This cell has more content.</td>
<td>Less content here.</td>
</tr>
</table>
You can also try some more interesting tweaks, like using 0%-width columns and using some combination of the white-space
CSS property.
<table border="1" style="width: 100%;">
<colgroup>
<col width="100%" />
<col width="0%" />
</colgroup>
<tr>
<td>This cell has more content.</td>
<td style="white-space: nowrap;">Less content here.</td>
</tr>
</table>
You get the idea.
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" CssClass="CoolButtons"/>
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btnEdit = (Button)sender;
GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
//Get the gridview Row Details
}
And Same As for Delete button
Try this something like this:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.
Both are provided out of the box with visual studio.
For Adaptive UI(iOS8 or after) , Vertical Alignment of UILabel is to be set from StoryBoard by Changing the properties
noOfLines
=0` and
Constraints
Adjusting UILabel LefMargin, RightMargin and Top Margin Constraints.
Change
Content Compression Resistance Priority For Vertical
=1000` So that Vertical>Horizontal .
Edited:
noOfLines=0
and the following constraints are enough to achieve the desired results.
Try using the jquery.doubleScroll
plugin :
jQuery :
$(document).ready(function(){
$('#double-scroll').doubleScroll();
});
CSS :
#double-scroll{
width: 400px;
}
HTML :
<div id="double-scroll">
<table id="very-wide-element">
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
</div>
Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.
import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']
Go to VCS>Git>Remotes then remove your remote url from the list and add again. Git will ask for a password after next git operation (push, pull, etc). NOTE: Don't forget to specify username in url or you will get auth error.
The below code is the only thing worked for me
1. Use this class to declare a HeightWrappingViewPager:
public class HeightWrappingViewPager extends ViewPager {
public HeightWrappingViewPager(Context context) {
super(context);
}
public HeightWrappingViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
// Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
// At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
// super has to be called in the beginning so the child views can be initialized.
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
// super has to be called again so the new specs are treated as exact measurements
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
2. Insert the height wrapping view pager to your xml file:
<com.project.test.HeightWrappingViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.project.test.HeightWrappingViewPager>
3. Declare your view pager:
HeightWrappingViewPager mViewPager;
mViewPager = (HeightWrappingViewPager) itemView.findViewById(R.id.pager);
CustomAdapter adapter = new CustomAdapter(context);
mViewPager.setAdapter(adapter);
mViewPager.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).
Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.
Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.
Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:
namespace {
const int CONSTANT = 42;
}
This is basically the same as:
static const int CONSTANT = 42;
Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.
You can now simply do Instant.parse("2015-04-28T14:23:38.521Z")
and get the correct thing now, especially since you should be using Instant
instead of the broken java.util.Date
with the most recent versions of Java.
You should be using DateTimeFormatter
instead of SimpleDateFormatter
as well.
The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.
Z
as demonstrated:In the pattern the
T
is escaped with'
on either side.The pattern for the
Z
at the end is actuallyXXX
as documented in the JavaDoc forSimpleDateFormat
, it is just not very clear on actually how to use it sinceZ
is the marker for the oldTimeZone
information as well.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Q2597083
{
/**
* All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
*/
public static final TimeZone UTC;
/**
* @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
*/
public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
/**
* 0001-01-01T00:00:00.000Z
*/
public static final Date BEGINNING_OF_TIME;
/**
* 292278994-08-17T07:12:55.807Z
*/
public static final Date END_OF_TIME;
static
{
UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
}
public static void main(String[] args) throws Exception
{
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
}
}
sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994
#dimScreen{
position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
}
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator
. You can use auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
Note the use of cbegin()
and cend()
functions.
Easier still, you can use the range-based for loop:
for(auto elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
cd to the directory that contains the script, or put it in a bin folder that is in your $PATH
then type
./scriptname.sh
if in the same directory or
scriptname.sh
if it's in the bin folder.
You cannot use VBA (Interior.ColorIndex
) in a formula which is why you receive the error.
It is not possible to do this without VBA.
Function YellowIt(rng As Range) As Boolean
If rng.Interior.ColorIndex = 6 Then
YellowIt = True
Else
YellowIt = False
End If
End Function
However, I do not recommend this: it is not how user-defined VBA functions (UDFs) are intended to be used. They should reflect the behaviour of Excel functions, which cannot read the colour-formatting of a cell. (This function may not work in a future version of Excel.)
It is far better that you base a formula on the original condition (decision) that makes the cell yellow in the first place. Or, alternatively, run a Sub procedure to fill in the True or False values (although, of course, these values will no longer be linked to the original cell's formatting).
data = "abcdefg hi j 12345"
digits_count = 0
letters_count = 0
others_count = 0
for i in userinput:
if i.isdigit():
digits_count += 1
elif i.isalpha():
letters_count += 1
else:
others_count += 1
print("Result:")
print("Letters=", letters_count)
print("Digits=", digits_count)
Output:
Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5
By using str.isalpha()
you can check if it is a letter.
The answer above does not perform a recursive search into the directory though. Here's what I did for a recursive search (using node-walk: npm install walk
)
var walk = require('walk');
var files = [];
// Walker options
var walker = walk.walk('./test', { followLinks: false });
walker.on('file', function(root, stat, next) {
// Add this file to the list of files
files.push(root + '/' + stat.name);
next();
});
walker.on('end', function() {
console.log(files);
});
To use ES6 add babel-preset-env
and in your .babelrc
:
{
"presets": ["@babel/preset-env"]
}
Answer updated thanks to @ghanbari comment to apply babel 7.
You need to construct a date string. You're using /
or -
operators which do MATH/numeric operations on the numeric return values of DATEPART. Then DATENAME
is taking that numeric value and interpreting it as a date.
You need to convert it to a string. For example:
SELECT (
DATENAME(dw,
CAST(DATEPART(m, GETDATE()) AS VARCHAR)
+ '/'
+ CAST(DATEPART(d, myDateCol1) AS VARCHAR)
+ '/'
+ CAST(DATEPART(yy, getdate()) AS VARCHAR))
)
For me on my archlinux system the line was already uncommented. I had to replace "none" by "read | write " to make it work.
It's go to newline then add spaces to start second line at end of first line
Output
Hello
Goodbye
Guid? myGuidVar = (Guid?)null;
It could be. Unnecessary casting not required.
Guid? myGuidVar = null;
Git itself has no provision to specify the repository name. The root directory's name is the single source of truth pertaining to the repository name.
The .git/description
though is used only by some applications, like GitWeb.
Use jdbcTemplate.update(String sql, Object... args)
method:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
var1, var2
);
or jdbcTemplate.update(String sql, Object[] args, int[] argTypes)
, if you need to map arguments to SQL types manually:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);
Command:
netstat -aon | findstr 4723
Output:
TCP 0.0.0.0:4723 0.0.0.0:0 LISTENING 10396
Now cut the process ID, "10396", using the for
command in Windows.
Command:
for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
10396
If you want to cut the 4th number of the value means "LISTENING" then command in Windows.
Command:
for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
LISTENING
try chmod a+x /path/to/tomcat/bin/catalina.sh if you run it in intelliJ
Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
Instead of .First()
change it to .FirstOrDefault()
Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:
public Foo(int param1, int param2)
{
this.param1 = param1;
this.param2 = param2;
}
public Foo(int param1)
{
this(param1, 2);
}
Hey to make your image responsive is simple: here is an article i wrote about it. https://medium.com/@ashirazee/react-native-simple-responsive-images-for-all-screen-sizes-with-flex-69f8a96dbc6f
you can simply do this and it will scale
container: {
width: 200,
height: 220
},// container holding your image
image: {
width: '100%',
height: '100%',
resizeMode: cover,
},
});
_x000D_
this is because the container which holds the image determines the height and width, so by using percentages you will be able to make your image responsive to all screens size.
here is another example:
<View style={{
width: 180,
height: 200,
aspectRatio: 1 * 1.4,
}}>
<Image
source={{uri : item.image.url}}
style={{
resizeMode: ‘cover’,
width: ‘100%’,
height: ‘100%’
}}
/>
</View>
_x000D_
You can store the old innerHTML of the div in a variable. Set an interval to check if the old content matches the current content. When this isn't true do something.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
This is the quick and easy way to do it
<div>
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
</div>
css
div{
width:100%;
}
span{
display:inline-block;
width:33%;
text-align:center;
}
Then adjust the width
of the span
s for the number you have.
You can also get control of grand parent index by the following code
$parent.$parent.$index
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
You can try this...........
<Border BorderBrush="Black" Name="MyBorder"
Height="78"
Background="Red"
Width="74"
CornerRadius="3">
<Button Width="{Binding MyBorder.Width}"
Height="{Binding MyBorder.Height}"
Content="Hi" Background="Red"/>
</Border>
Before the closing body
tag add this (reference to jQuery library). Other hosted libraries can be found here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And this
<script>
//paste your code here
</script>
It should look something like this
<body>
........
........
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script> Your code </script>
</body>
This is "By Design". The parseFloat
function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.
To fix this convert the commas to decimal points.
var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));
At the moment, referencing the Google Android Map API v2 you can't run Google Maps v2 on the Android emulator; you must use a device for your tests.
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
I was having same problem where I wanted to run my react app on port 3000 and storybook on port 6006 both in the same containers.
I tried to start both as entrypoint commands from Dockerfile as well as using docker-compose command
option.
After spending time on this, decided to separate these services into separate containers and it worked like charm
I have found a solution which helped me to get it done. Setting cache-view="false"
on ion-view
tag resolved my problem.
<ion-view cache-view="false" view-title="My Title!">
....
</ion-view>
Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.
You can download from (https://npmjs.org/package/underscore)
$ npm install underscore
Here is small snippet to demonstrate how you can do it.
var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
newArray = [];
_.each(calendars, function (item, index) {
newArray.push(item);
});
console.log(newArray);
Ran to the same issue, Assuming your using anaconda3 and your using a venv
with >= python=3.6
:
python -m pip install keras
sudo python -m pip install --user tensorflow
In addition to previous post you can have
<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />
Jsf 2.0
I had the same issue on a remote windows environment. I tried many solutions found here or on other similars posts but nothing worked. Finally, the solution was quite simple. I had to set NO_PROXY
with cmd :
set NO_PROXY="<domain>\<username>:<password>@<host>:<port>"
pip install <packagename>
You have to use double quotes and set NO_PROXY
to upper case. You can also add NO_PROXY
as an environment variable instead of setting it each time you use the console.
I hope this will help if any other solution posted here works.
POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans
POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.
Just set the y to be always on top. Need to conform with UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
scrollView.contentOffset.y = 0.0
}
This will keep the Deceleration / Acceleration effect of the scrolling.
Just for information sake, in regards to my need... The answer I was looking for here was:
Mage::app()->getStore()->getGroup()->getName()
That is referenced on the admin page, where one can manage multiple stores... admin/system_store, I wanted to retrieve the store group title...
In my case I reached the solution in two steps:
You can open up terminal and simply type
java -version // this will check your jre version
javac -version // this will check your java compiler version if you installed
this should show you the version of java installed on the system (assuming that you have set the path of the java in system environment).
And if you haven't, add it via
export JAVA_HOME=/path/to/java/jdk1.x
and if you unsure if you have java at all on your system just use find
in terminal
i.e. find / -name "java"
How can I convert tabs to spaces in every file of a directory (possibly recursively)?
This is usually not what you want.
Do you want to do this for png images? PDF files? The .git directory? Your
Makefile
(which requires tabs)? A 5GB SQL dump?
You could, in theory, pass a whole lot of exlude options to find
or whatever
else you're using; but this is fragile, and will break as soon as you add other
binary files.
What you want, is at least:
expand
does this, sed
doesn't).As far as I know, there is no "standard" Unix utility that can do this, and it's not very easy to do with a shell one-liner, so a script is needed.
A while ago I created a little script called
sanitize_files which does exactly
that. It also fixes some other common stuff like replacing \r\n
with \n
,
adding a trailing \n
, etc.
You can find a simplified script without the extra features and command-line arguments below, but I recommend you use the above script as it's more likely to receive bugfixes and other updated than this post.
I would also like to point out, in response to some of the other answers here,
that using shell globbing is not a robust way of doing this, because sooner
or later you'll end up with more files than will fit in ARG_MAX
(on modern
Linux systems it's 128k, which may seem a lot, but sooner or later it's not
enough).
#!/usr/bin/env python
#
# http://code.arp242.net/sanitize_files
#
import os, re, sys
def is_binary(data):
return data.find(b'\000') >= 0
def should_ignore(path):
keep = [
# VCS systems
'.git/', '.hg/' '.svn/' 'CVS/',
# These files have significant whitespace/tabs, and cannot be edited
# safely
# TODO: there are probably more of these files..
'Makefile', 'BSDmakefile', 'GNUmakefile', 'Gemfile.lock'
]
for k in keep:
if '/%s' % k in path:
return True
return False
def run(files):
indent_find = b'\t'
indent_replace = b' ' * indent_width
for f in files:
if should_ignore(f):
print('Ignoring %s' % f)
continue
try:
size = os.stat(f).st_size
# Unresolvable symlink, just ignore those
except FileNotFoundError as exc:
print('%s is unresolvable, skipping (%s)' % (f, exc))
continue
if size == 0: continue
if size > 1024 ** 2:
print("Skipping `%s' because it's over 1MiB" % f)
continue
try:
data = open(f, 'rb').read()
except (OSError, PermissionError) as exc:
print("Error: Unable to read `%s': %s" % (f, exc))
continue
if is_binary(data):
print("Skipping `%s' because it looks binary" % f)
continue
data = data.split(b'\n')
fixed_indent = False
for i, line in enumerate(data):
# Fix indentation
repl_count = 0
while line.startswith(indent_find):
fixed_indent = True
repl_count += 1
line = line.replace(indent_find, b'', 1)
if repl_count > 0:
line = indent_replace * repl_count + line
data = list(filter(lambda x: x is not None, data))
try:
open(f, 'wb').write(b'\n'.join(data))
except (OSError, PermissionError) as exc:
print("Error: Unable to write to `%s': %s" % (f, exc))
if __name__ == '__main__':
allfiles = []
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
p = '%s/%s' % (root, f)
if do_add:
allfiles.append(p)
run(allfiles)
It might be helpful to know why this is so difficult. A stored procedure may only return text (print 'text'), or may return multiple tables, or may return no tables at all.
So something like SELECT * FROM (exec sp_tables) Table1
will not work
No command
sbt
found
It's saying that sbt
is not on your path. Try to run ./sbt
from ~/bin/sbt/bin
or wherever the sbt
executable is to verify that it runs correctly. Also check that you have execute permissions on the sbt
executable. If this works , then add ~/bin/sbt/bin
to your path and sbt
should run from anywhere.
See this question about adding a directory to your path.
To verify the path is set correctly use the which
command on LINUX. The output will look something like this:
$ which sbt
/usr/bin/sbt
Lastly, to verify sbt
is working try running sbt -help
or likewise. The output with -help will look something like this:
$ sbt -help
Usage: sbt [options]
-h | -help print this message
...
Follow the below
ng-click="anyFunction()"
anyFunction() {
// call another function here
anotherFunction();
}
This is a VERY old question and my answer is similar to some answers above but done MUCH faster. The script below is for Mac but I'm sure someone can modify it for Windows.
1) Open Script Editor on your Mac (you can just search for Script Editor in Spotlight)
2) Copy and paste the text below and modify it with your SDK path, package name, etc. (see below)
3) Save the script!!
Thats's it! Just press the play button on top to get the updated database file, which will be on your desktop.
replace the following things in the script below:
path_to_my_sdk ==>> put full path to your sdk
my_package_name ==>> package name of your application
myDbName.db ==>> file name of your database
set getLocalDb to "path_to_my_sdk/platform-tools/adb shell run-as my_package_name chmod 777 databases && path_to_my_sdk/platform-tools/adb shell run-as my_package_name chmod 777 databases/myDbName.db && path_to_my_sdk/platform-tools/adb shell run-as my_package_name cp databases/myDbName.db /sdcard/myDbName.db && path_to_my_sdk/platform-tools/adb pull /sdcard/myDbName.db /Users/User/Desktop/myDbName.db"
do shell script getLocalDb
Hope this helps someone.
here is simple solution i hope it will help you. here's a simple example to improve answer.
$('[type="radio"]').click(function () {
if ($(this).attr('checked')) {
$(this).removeAttr('checked');
$(this).prop('checked',false);
} else {
$(this).attr('checked', 'checked');
}
});
Demo sorry for too late.. :)
Not product-specific, but the SQL standard provides
SELECT COUNT() FILTER WHERE <condition-1>,
COUNT() FILTER WHERE <condition-2>, ...
FROM ...
for this purpose. Or something that closely resembles it, I don't know off the top of my hat.
And of course vendors will prefer to stick with their proprietary solutions.
If you are on Windows (Any Version)
Go to start -> then search character map
that's where you will find 1000s of characters with their Unicode in the advance view you can get more options that you can use for different encoding symbols.
In my case, that was caused by wrong comment symbols. This is wrong:
<Tag>
/*{ oldComponent }*/
{ newComponent }
</Tag>
This is correct:
<Tag>
{/*{ oldComponent }*/}
{ newComponent }
</Tag>
Notice the curly brackets
ifconfig interfacename create will create a virtual interface,
If you want to use those with columns in another work with col-*
classes, you can use order-*
classes.
You can control the order of your columns with order classes. see more in Bootstrap 4 documentation
A simple from bootstrap docs:
<div class="container">
<div class="row">
<div class="col">
First, but unordered
</div>
<div class="col order-12">
Second, but last
</div>
<div class="col order-1">
Third, but first
</div>
</div>
</div>
I had a similar problem and wrote a detailed article about it. If anyone has the same problem, feel free to read my article.
https://developer-blog.net/administration/ssl-zertifikat-installieren/
It is a detailed problem description in German language.
Remember if you want to give Text a backgroundcolor and then also borderRadius in that case also write overflow:'hidden' your text having a background colour will also get the radius otherwise it's impossible to achieve until unless you wrap it with View and give backgroundcolor and radius to it.
<Text style={{ backgroundColor: 'black', color:'white', borderRadius:10, overflow:'hidden'}}>Dummy</Text>
Try this workaround for the theming problem:
@Override
public void onBackPressed() {
NavUtils.navigateUpTo(this, new Intent(this,
MyNeedToBeRefreshed.class));
}
A bit offtopic but might help someone. If you need to pass password and port I suggest using sshpass
package. Command line command would look like this:
sshpass -p "password" rsync -avzh -e 'ssh -p PORT312' [email protected]:/dir_on_host/
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also: