As of now, Postman comes with its own "Console." Click the terminal-like icon on the bottom left to open the console. Send a request, and you can inspect the request from within Postman's console.
I had the same error, though the problem was that I had a typo in the url
url: 'http://api.example.com/TYPO'
The API had a redirect to another domain for all URL's that is wrong (404 errors).
So fixing the typo to the correct URL fixed it for me.
I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.
I also had a similar question, sharing the below example if it helps.
My Controller:
@RequestMapping(value = {"/batchDeleteIndex"}, method = RequestMethod.POST)
@ResponseBody
public BaseResponse batchDeleteIndex(@RequestBody List<String> datasetQnames)
Postman: Set the Body type to raw and add header Content-Type: application/json
["aaa","bbb","ccc"]
The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.
The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.
Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.
In case you wanted to do it with NodeJS: make a GET to JSON endpoint with Authorization
header and get a Promise
back:
First
npm install --save request request-promise
(see on npm) and then in your .js
file:
var requestPromise = require('request-promise');
var user = 'user';
var password = 'password';
var base64encodedData = Buffer.from(user + ':' + password).toString('base64');
requestPromise.get({
uri: 'https://example.org/whatever',
headers: {
'Authorization': 'Basic ' + base64encodedData
},
json: true
})
.then(function ok(jsonData) {
console.dir(jsonData);
})
.catch(function fail(error) {
// handle error
});
You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.
ALTER TABLE
can do multiple table alterations in one statement, but MODIFY COLUMN
can only work on one column at a time, so you need to specify MODIFY COLUMN
for each column you want to change:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100);
Also, note this warning from the manual:
When you use CHANGE or MODIFY,
column_definition
must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.
There is also W3Techs, which shows you much of that information.
The best way I have found to manage keyboard input on a Windows Forms form is to process it after the keystroke and before the focused control receives the event. Microsoft maintains a built-in Form
-level property named .KeyPreview to facilitate this precise thing:
public frmForm()
{
// ...
frmForm.KeyPreview = true;
// ...
}
Then the form's _KeyDown, _KeyPress, and / or _KeyUp events can be marshaled to access input events before the focused form control ever sees them, and you can apply handler logic to capture the event there or allow it to pass through to the focused form control.
Although not as structurally graceful as XAML's event-routing architecture, it makes management of form-level functions in Winforms far simpler. See the MSDN notes on KeyPreview for caveats.
If you specify the disabled
attribute then the value you give it must be disabled
. (In HTML 5 you may leave off everything except the attribute value. In HTML 4 you may leave off everything except the attribute name.)
If you do not want the control to be disabled then do not specify the attribute at all.
Disabled:
<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">
Enabled:
<input type="checkbox">
Invalid (but usually error recovered to be treated as disabled):
<input type="checkbox" disabled="1">
<input type="checkbox" disabled="true">
<input type="checkbox" disabled="false">
So, without knowing your template language, I guess you are looking for:
<td><input type="checkbox" name="repriseCheckBox" {checkStat == 1 ? disabled : }/></td>
Don't use a service for this. Create a normal application and create a scheduled task to run it.
This is the commonly held best practice. Jon Galloway agrees with me. Or maybe its the other way around. Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.
"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."
–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero
Just set the property directly: .
eleman.disabled = false;
Try this, I've used it in a personal wiki-like app:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("foo://")) {
// magic
return true;
}
return false;
}
});
if you want to delete the whole table, you must follow the next SQL instruction
Delete FROM TABLE Where PRIMARY_KEY_ is Not NULL;
The functional way, with a generator.
def split(path):
(drive, head) = os.path.splitdrive(path)
while (head != os.sep):
(head, tail) = os.path.split(head)
yield tail
In action:
>>> print([x for x in split(os.path.normpath('/path/to/filename'))])
['filename', 'to', 'path']
gradle-wrapper.properties
Change this line:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
with
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
build.gradle
(Project: your_app_name)Change this line
classpath 'com.android.tools.build:gradle:XXX'
to this
classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
or
classpath 'com.android.tools.build:gradle:1.5.0'
Sync Now
File -> Invalidate Caches/Restart...
Invalidate and Restart
Android Studio would restart. After this, it should work normally
Hope it help
Putting the comment of EaterOfCode here as an answer.
grep itself also has the -c flag which just returns the count
So the command and output could look like this.
$ grep -Rl "curl" ./ -c
24
EDIT:
Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc
). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l
is much more useful as you can use it with other programs than grep
as well.
There are several ways of consoling out the variable within a string.
Method 1 :
console.log("story", name, "story");
Benefit : if name is a JSON object, it will not be printed as "story" [object Object] "story"
Method 2 :
console.log("story " + name + " story");
Method 3: When using ES6 as mentioned above
console.log(`story ${name} story`);
Benefit: No need of extra , or +
Method 4:
console.log('story %s story',name);
Benefit: the string becomes more readable.
In Active Directory environment, it's important to know:
All member machines synchronizes with any domain controller.
In a domain, all domain controllers synchronize from the PDC Emulator (PDCe) of that domain.
The PDC Emulator of a domain should synchronize with local or NTP.
It's important to consider this when setting the time in vmware or configuring the time sync.
Extracted from: http://www.sysadmit.com/2016/12/vmware-esxi-configurar-hora.html
Angular and Django Rest Framework.
I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.
If these two div
elements are basically your main layout elements, and nothing follows them in the html, then there is a pure HMTL/CSS solution that takes the normal order shown in this fiddle and is able to flip it vertically as shown in this fiddle using one additional wrapper div
like so:
HTML
<div class="wrapper flipit">
<div id="first_div">first div</div>
<div id="second_div">second div</div>
</div>
CSS
.flipit {
position: relative;
}
.flipit #first_div {
position: absolute;
top: 100%;
width: 100%;
}
This would not work if elements follow these div's, as this fiddle illustrates the issue if the following elements are not wrapped (they get overlapped by #first_div
), and this fiddle illustrates the issue if the following elements are also wrapped (the #first_div
changes position with both the #second_div
and the following elements). So that is why, depending on your use case, this method may or may not work.
For an overall layout scheme, where all other elements exist inside the two div's, it can work. For other scenarios, it will not.
Here is a solution that works with only the standard packages. matplotlib
has a PDF backend to save figures to PDF. You can create a figures with subplots, where each subplot is one of your images. You have full freedom to mess with the figure: Adding titles, play with position, etc. Once your figure is done, save to PDF. Each call to savefig
will create another page of PDF.
Example below plots 2 images side-by-side, on page 1 and page 2.
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from scipy.misc import imread
import os
import numpy as np
files = [ "Column0_Line16.jpg", "Column0_Line47.jpg" ]
def plotImage(f):
folder = "C:/temp/"
im = imread(os.path.join(folder, f)).astype(np.float32) / 255
plt.imshow(im)
a = plt.gca()
a.get_xaxis().set_visible(False) # We don't need axis ticks
a.get_yaxis().set_visible(False)
pp = PdfPages("c:/temp/page1.pdf")
plt.subplot(121)
plotImage(files[0])
plt.subplot(122)
plotImage(files[1])
pp.savefig(plt.gcf()) # This generates page 1
pp.savefig(plt.gcf()) # This generates page 2
pp.close()
You're comparing strings. JavaScript compares the ASCII code for each character of the string.
To see why you get false, look at the charCodes:
"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57
The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.
The fix is to treat the strings as numbers. You can use a number of methods:
parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes
+"1300"
> 1300
Number("1300")
> 1300
I believe the correct answer is actually a combination of both approaches: viewWIllTransition(toSize:)
and NotificationCenter
's UIDeviceOrientationDidChange
.
viewWillTransition(toSize:)
notifies you before the transition.
NotificationCenter
UIDeviceOrientationDidChange
notifies you after.
You have to be very careful. For example, in UISplitViewController
when the device rotates into certain orientations, the DetailViewController
gets popped off the UISplitViewController
's viewcontrollers
array, and pushed onto the master's UINavigationController
. If you go searching for the detail view controller before the rotation has finished, it may not exist and crash.
class Foo(object):
bar = 1
def bah(self):
print Foo.bar
f = Foo()
f.bah()
Subversion implicitly has the remote repository associated with it at all times. Git, on the other hand, allows many "remotes", each of which represents a single remote place you can push to or pull from.
You need to add a remote for the GitHub repository to your local repository, then use git push ${remote}
or git pull ${remote}
to push and pull respectively - or the GUI equivalents.
Pro Git discusses remotes here: http://git-scm.com/book/ch2-5.html
The GitHub help also discusses them in a more "task-focused" way here: http://help.github.com/remotes/
Once you have associated the two you will be able to push or pull branches.
Many of the answers here are wrong. It seems people figure out what was causing status==0 in their particular case and then generalize that as the answer.
Practically speaking, status==0 for a failed XmlHttpRequest should be considered an undefined error.
The actual W3C spec defines the conditions for which zero is returned here: https://fetch.spec.whatwg.org/#concept-network-error
As you can see from the spec (fetch or XmlHttpRequest) this code could be the result of an error that happened even before the server is contacted.
Some of the common situations that produce this status code are reflected in the other answers but it could be any or none of these problems:
What would be helpful would be for browsers to provide detailed error reporting for more of these status==0 scenarios. Indeed, sometimes status==0 will accompany a helpful console message, but in others there is no other information.
Even shorter and with json-functions:
JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
JSON only allows key names to be strings. Those strings can consist of numerical values.
You aren't using JSON though. You have a JavaScript object literal. You can use identifiers for keys, but an identifier can't start with a number. You can still use strings though.
var Game={
"status": [
{
"0": "val",
"1": "val",
"2": "val"
},
{
"0": "val",
"1": "val",
"2": "val"
}
]
}
If you access the properties with dot-notation, then you have to use identifiers. Use square bracket notation instead: Game.status[0][0]
.
But given that data, an array would seem to make more sense.
var Game={
"status": [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
]
}
If you use a unary plus to convert a string to a number as documented on MDN.
For example:+discount.toFixed(2)
a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }
I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.
Looking for faster solution? Here you go!
def find_one_using_hash_map(array)
map = {}
dup = nil
array.each do |v|
map[v] = (map[v] || 0 ) + 1
if map[v] > 1
dup = v
break
end
end
return dup
end
It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.
If you need an even faster solution, maybe try C instead.
And here is the gist comparing different solutions: https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e
If you want the two div
s to be displayed one above the other, the simplest answer is to remove the float: left;
from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.
Alternatively, you could simply add clear:both;
to the div
s, which will force the floated content to clear previous floats.
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)]
and further in component file assign default
value to it.
In your_component_file.ts
this.selectedCountry = default;
In your_component_template.html
<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
I have a smae issue. in my scenario there is kubernetes API server is not responding. so check you kubernetes API server and controller as well as.
How was the database exported?
If it was exported using exp
and a full schema was exported, then
Create the user:
create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
Grant the rights:
grant connect, create session, imp_full_database to <username>;
Start the import with imp
:
imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
If it was exported using expdp
, then start the import with impdp
:
impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp
file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\
).
Either move the export file to the above path or create a directory object to pointing to the path where the dmp
file is present and pass the object name to the impdp
command above.
background-image
and use text-indent
or a padding
to shift the text to the right.Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(
The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.
CSS:
input#search {
background-image: url(bg.jpg);
background-repeat: no-repeat;
text-indent: 20px;
}
HTML:
<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />
Javascript:
function hideIcon(self) {
self.style.backgroundImage = 'none';
}
I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.
The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active
pseudo-class.
#search:active { background-image: none; }
Heck, using CSS3 you can make it fade away!
Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!
Chrome Firefox IE Opera Safari
:before (yes) 1.0 8.0 4 4.0
::before (yes) 1.5 9.0 7 4.0
In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController
.
I think you can use async void
for kicking off background operations as well, so long as you're careful to catch exceptions. Thoughts?
class Program {
static bool isFinished = false;
static void Main(string[] args) {
// Kick off the background operation and don't care about when it completes
BackgroundWork();
Console.WriteLine("Press enter when you're ready to stop the background operation.");
Console.ReadLine();
isFinished = true;
}
// Using async void to kickoff a background operation that nobody wants to be notified about when it completes.
static async void BackgroundWork() {
// It's important to catch exceptions so we don't crash the appliation.
try {
// This operation will end after ten interations or when the app closes. Whichever happens first.
for (var count = 1; count <= 10 && !isFinished; count++) {
await Task.Delay(1000);
Console.WriteLine($"{count} seconds of work elapsed.");
}
Console.WriteLine("Background operation came to an end.");
} catch (Exception x) {
Console.WriteLine("Caught exception:");
Console.WriteLine(x.ToString());
}
}
}
var ctx = document.getElementById('pie-chart').getContext('2d');
var myPieChart = new Chart(ctx, {
// The type of chart we want to create
type: 'pie',
});
//define click event
$("#pie-chart").click(
function (evt) {
var activePoints = myPieChart.getElementsAtEvent(evt);
var labeltag = activePoints[0]._view.label;
});
git checkout stash@{N} <File(s)/Folder(s) path>
Eg. To restore only ./test.c file and ./include folder from last stashed,
git checkout stash@{0} ./test.c ./include
you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]
css
.even{background: red; color:white;}
.odd{background: darkred; color:white;}
html
<div class="container">
<ul class="list-unstyled">
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
</ul>
</div>
Don't forget to seed the RNG with srand() first.
I tested the performance difference between x*x*...
vs pow(x,i)
for small i
using this code:
#include <cstdlib>
#include <cmath>
#include <boost/date_time/posix_time/posix_time.hpp>
inline boost::posix_time::ptime now()
{
return boost::posix_time::microsec_clock::local_time();
}
#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
double x = 0.0; \
\
boost::posix_time::ptime startTime = now(); \
for (long i=0; i<loops; ++i) \
{ \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
} \
boost::posix_time::time_duration elapsed = now() - startTime; \
\
std::cout << elapsed << " "; \
\
return x; \
}
TEST(1, b)
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)
template <int exponent>
double testpow(double base, long loops)
{
double x = 0.0;
boost::posix_time::ptime startTime = now();
for (long i=0; i<loops; ++i)
{
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
}
boost::posix_time::time_duration elapsed = now() - startTime;
std::cout << elapsed << " ";
return x;
}
int main()
{
using std::cout;
long loops = 100000000l;
double x = 0.0;
cout << "1 ";
x += testpow<1>(rand(), loops);
x += test1(rand(), loops);
cout << "\n2 ";
x += testpow<2>(rand(), loops);
x += test2(rand(), loops);
cout << "\n3 ";
x += testpow<3>(rand(), loops);
x += test3(rand(), loops);
cout << "\n4 ";
x += testpow<4>(rand(), loops);
x += test4(rand(), loops);
cout << "\n5 ";
x += testpow<5>(rand(), loops);
x += test5(rand(), loops);
cout << "\n" << x << "\n";
}
Results are:
1 00:00:01.126008 00:00:01.128338
2 00:00:01.125832 00:00:01.127227
3 00:00:01.125563 00:00:01.126590
4 00:00:01.126289 00:00:01.126086
5 00:00:01.126570 00:00:01.125930
2.45829e+54
Note that I accumulate the result of every pow calculation to make sure the compiler doesn't optimize it away.
If I use the std::pow(double, double)
version, and loops = 1000000l
, I get:
1 00:00:00.011339 00:00:00.011262
2 00:00:00.011259 00:00:00.011254
3 00:00:00.975658 00:00:00.011254
4 00:00:00.976427 00:00:00.011254
5 00:00:00.973029 00:00:00.011254
2.45829e+52
This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.
So in C, yes x*x*x
will be faster than pow(x, 3)
, because there is no pow(double, int)
overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)
This is in response to the comment made by An Markm:
Even if a using namespace std
directive was issued, if the second parameter to pow
is an int
, then the std::pow(double, int)
overload from <cmath>
will be called instead of ::pow(double, double)
from <math.h>
.
This test code confirms that behavior:
#include <iostream>
namespace foo
{
double bar(double x, int i)
{
std::cout << "foo::bar\n";
return x*i;
}
}
double bar(double x, double y)
{
std::cout << "::bar\n";
return x*y;
}
using namespace foo;
int main()
{
double a = bar(1.2, 3); // Prints "foo::bar"
std::cout << a << "\n";
return 0;
}
Posting a string:
curl -d "String to post" "http://www.example.com/target"
Posting the contents of a file:
curl -d @soap.xml "http://www.example.com/target"
The solution for me was to update guest additions
(click Devices -> Insert Guest Additions CD image)
XPath has a contains-token function, specifically designed for this situation:
//div[contains-token(@class, 'Test')]
It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.
ls | xargs find 2>/dev/null | egrep /\.git$ | xargs rm -rf
This command (and it is just one command) will recursively remove .git directories (and files) that are in a directory without deleting the top-level git repo, which is handy if you want to commit all of your files without managing any submodules.
find 2>/dev/null | egrep /\.git$ | xargs rm -rf
This command will do the same thing, but will also delete the .git folder from the top-level directory.
Useful for build systems: there is a file generated with your APK file called output.json
which contains an array of information for each generated APK file, including the versionName and versionCode.
For example,
[
{
"apkInfo": {
"baseName": "x86-release",
"enabled": true,
"filterName": "x86",
"fullName": "86Release",
"outputFile": "x86-release-1.0.apk",
"splits": [
{
"filterType": "ABI",
"value": "x86"
}
],
"type": "FULL_SPLIT",
"versionCode": 42,
"versionName": "1.0"
},
"outputType": {
"type": "APK"
},
"path": "app-x86-release-1.0.apk",
"properties": {}
}
]
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
If anyone would like the answer in Swift :
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!
Update :
As of now, it's available under the IB so you don't have to code anything for it :)
For those still interested, I have come up with a bash script that does (more or less) what the author wanted. I had to make a daily business database copy on a production system, this script seems to do the trick. Remember to change the database name/user/pw values.
#!/bin/bash
if [ 1 -ne $# ]
then
echo "Usage `basename $0` {tar.gz database file}"
exit 65;
fi
if [ -f "$1" ]
then
EXTRACTED=`tar -xzvf $1`
echo "using database archive: $EXTRACTED";
else
echo "file $1 does not exist"
exit 1
fi
PGUSER=dbuser
PGPASSWORD=dbpw
export PGUSER PGPASSWORD
datestr=`date +%Y%m%d`
dbname="dbcpy_$datestr"
createdbcmd="CREATE DATABASE $dbname WITH OWNER = postgres ENCODING = 'UTF8' TABLESPACE = pg_default LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8' CONNECTION LIMIT = -1;"
dropdbcmp="DROP DATABASE $dbname"
echo "creating database $dbname"
psql -c "$createdbcmd"
rc=$?
if [[ $rc != 0 ]] ; then
rm -rf "$EXTRACTED"
echo "error occured while creating database $dbname ($rc)"
exit $rc
fi
echo "loading data into database"
psql $dbname < $EXTRACTED > /dev/null
rc=$?
rm -rf "$EXTRACTED"
if [[ $rc != 0 ]] ; then
psql -c "$dropdbcmd"
echo "error occured while loading data to database $dbname ($rc)"
exit $rc
fi
echo "finished OK"
You need
$('body').click(function(e) {
if (!$(e.target).closest('.popup').length){
$(".popup").hide();
}
});
ERROR: flake8 3.7.9 has requirement pycodestyle<2.6.0,>=2.5.0, but you'll have pycodestyle 2.3.1 which is incompatible.
ERROR: nuscenes-devkit 1.0.8 has requirement motmetrics<=1.1.3, but you'll have motmetrics 1.2.0 which is incompatible.
Installing collected packages: descartes, future, torch, cachetools, torchvision, flake8-import-order, xmltodict, entrypoints, flake8, motmetrics, nuscenes-devkit
Attempting uninstall: torch
Found existing installation: torch 1.0.0
Uninstalling torch-1.0.0:
Successfully uninstalled torch-1.0.0
Attempting uninstall: torchvision
Found existing installation: torchvision 0.2.1
Uninstalling torchvision-0.2.1:
Successfully uninstalled torchvision-0.2.1
Attempting uninstall: entrypoints
Found existing installation: entrypoints 0.2.3
ERROR: Cannot uninstall 'entrypoints'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
Then I type:
conda uninstall entrypoints
pip install --upgrade pycodestyle
pip install nuscenes-devkit
Done!
Right click on project --> properties --> Android.
Change the checkbox for project build target.
Press apply.
Change it back to your original build target.
Press apply --> ok
Worked for me
In new Smarty it is:
<pre>
{var_dump($variable)}
</pre>
Object equality check:JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())
The above test also works with arrays of objects in which case use a sort function as documented in http://www.w3schools.com/jsref/jsref_sort.asp
Might suffice for small arrays with flat JSON schemas.
As the others have said already, your first line should be
#!/usr/bin/env ruby
And you also have to make it executable: (in the shell)
chmod +x test.rb
Then follows the ruby code. If you open a file
File.open("file", "r") do |io|
# do something with io
end
the file is opened in the current directory you'd get with pwd
in the shell.
The path to your script is also simple to get. With $0
you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:
#!/usr/bin/env ruby
require 'pathname'
p Pathname.new($0).realpath()
For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...
JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP
is an array and contains elements with a value
property.
To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space
<View
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1" />
Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.
<ImageButton
android:id="@+id/btnGenesis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_marginBottom="2dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="2dp"
android:background="@null"
android:gravity="left"
android:src="@drawable/prev" />
<View
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1" />
<TextView
android:id="@+id/lblVerseHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="25sp" />
<Spinner
android:id="@+id/spinnerVerses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center"
android:textSize="25sp" />
<View
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1" />
<ImageButton
android:id="@+id/btnExodus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_marginBottom="2dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="2dp"
android:background="@null"
android:gravity="right"
android:src="@drawable/next" />
</LinearLayout>
The year()
function just retrieves the year component of the underlying Date
object, so it returns a number.
Calling format('YYYY')
will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY
, then the result will be a string containing the year.
If all you need is the year, then use the year()
function. It will be faster, as there is less work to do.
Do note that while years are the same in this regard, months are not! Calling format('M')
will return months in the range 1-12. Calling month()
will return months in the range 0-11. This is due to the same behavior of the underlying Date
object.
On Windows 10, with Python 3.6.X version I was facing same then after checking deliberately , I noticed I had Python-32 bit installation on my 64 bit machine. Remember TensorFlow is only compatible with 64bit installation of python. Not 32 bit of Python
If we download Python from python.org , the default installation would be 32 bit. So we have to download 64 bit installer manually to install Python 64 bit. And then add
Then run gpupdate /Force
on command prompt. If python command doesnt work for 64 bit restart your machine.
Then run python on command prompt. It should show 64 bit
C:\Users\YOURNAME>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Then run below command to install tensorflow CPU version(recommended)
pip3 install --upgrade tensorflow
My solution is to use the debugger command and/or Log Message in breakpoints.
And change the output of console from All Output to Debugger Output like
Hmm... i do it in one of my batch files like this, without using CALL or START :
%SystemRoot%\notepad.exe ..\%URI%
GOTO ENDF
I don't have Cygwin installed though and I am on Windows XP.
Node's answer is really great, but it left open the question how can get stdout and stderr redirected. I found a solution on Unix & Linux, but it is also not complete. I would like to merge these two solutions. Here it is:
For my test I made a small bash script called loop.sh, which prints the pid of itself with a minute sleep in an infinite loop.
$./loop.sh
Now get the PID of this process somehow. Usually ps -C loop.sh
is good enough, but it is printed in my case.
Now we can switch to another terminal (or press ^Z and in the same terminal). Now gdb
should be attached to this process.
$ gdb -p <PID>
This stops the script (if running). Its state can be checked by ps -f <PID>
, where the STAT
field is 'T+' (or in case of ^Z 'T'), which means (man ps(1))
T Stopped, either by a job control signal or because it is being traced
+ is in the foreground process group
(gdb) call close(1)
$1 = 0
Close(1) returns zero on success.
(gdb) call open("loop.out", 01102, 0600)
$6 = 1
Open(1) returns the new file descriptor if successful.
This open is equal with open(path, O_TRUNC|O_CREAT|O_RDWR, S_IRUSR|S_IWUSR)
.
Instead of O_RDWR
O_WRONLY
could be applied, but /usr/sbin/lsof
says 'u' for all std* file handlers (FD
column), which is O_RDWR
.
I checked the values in /usr/include/bits/fcntl.h header file.
The output file could be opened with O_APPEND
, as nohup
would do, but this is not suggested by man open(2)
, because of possible NFS problems.
If we get -1 as a return value, then call perror("")
prints the error message. If we need the errno, use p errno
gdb comand.
Now we can check the newly redirected file. /usr/sbin/lsof -p <PID>
prints:
loop.sh <PID> truey 1u REG 0,26 0 15008411 /home/truey/loop.out
If we want, we can redirect stderr to another file, if we want to using call close(2)
and call open(...)
again using a different file name.
Now the attached bash
has to be released and we can quit gdb
:
(gdb) detach
Detaching from program: /bin/bash, process <PID>
(gdb) q
If the script was stopped by gdb
from an other terminal it continues to run. We can switch back to loop.sh's terminal. Now it does not write anything to the screen, but running and writing into the file. We have to put it into the background. So press ^Z
.
^Z
[1]+ Stopped ./loop.sh
(Now we are in the same state as if ^Z
was pressed at the beginning.)
Now we can check the state of the job:
$ ps -f 24522
UID PID PPID C STIME TTY STAT TIME CMD
<UID> <PID><PPID> 0 11:16 pts/36 S 0:00 /bin/bash ./loop.sh
$ jobs
[1]+ Stopped ./loop.sh
So process should be running in the background and detached from the terminal. The number in the jobs
command's output in square brackets identifies the job inside bash
. We can use in the following built in bash
commands applying a '%' sign before the job number :
$ bg %1
[1]+ ./loop.sh &
$ disown -h %1
$ ps -f <PID>
UID PID PPID C STIME TTY STAT TIME CMD
<UID> <PID><PPID> 0 11:16 pts/36 S 0:00 /bin/bash ./loop.sh
And now we can quit from the calling bash. The process continues running in the background. If we quit its PPID become 1 (init(1) process) and the control terminal become unknown.
$ ps -f <PID>
UID PID PPID C STIME TTY STAT TIME CMD
<UID> <PID> 1 0 11:16 ? S 0:00 /bin/bash ./loop.sh
$ /usr/bin/lsof -p <PID>
...
loop.sh <PID> truey 0u CHR 136,36 38 /dev/pts/36 (deleted)
loop.sh <PID> truey 1u REG 0,26 1127 15008411 /home/truey/loop.out
loop.sh <PID> truey 2u CHR 136,36 38 /dev/pts/36 (deleted)
COMMENT
The gdb stuff can be automatized creating a file (e.g. loop.gdb) containing the commands and run gdb -q -x loop.gdb -p <PID>
. My loop.gdb looks like this:
call close(1)
call open("loop.out", 01102, 0600)
# call close(2)
# call open("loop.err", 01102, 0600)
detach
quit
Or one can use the following one liner instead:
gdb -q -ex 'call close(1)' -ex 'call open("loop.out", 01102, 0600)' -ex detach -ex quit -p <PID>
I hope this is a fairly complete description of the solution.
It means you should use logging framework like logback or log4j and instead of printing exceptions directly:
e.printStackTrace();
you should log them using this frameworks' API:
log.error("Ops!", e);
Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.
map(lambda s: s.strip(), mylist)
would be a little better than explicitly looping. Or for the whole thing at once: map(lambda s:s.strip(), string.split(','))
TL;DR ...and late to the party, but that short explanation might help future googlers..
In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.
A minimal example:
df <- data.frame(a = 1:2); df$a <- 1:3
throws the error
Error in
$<-.data.frame
(*tmp*
, a, value = 1:3) : replacement has 3 rows, data has 2
which is clear, because the vector a
of df
has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).
Add an input id to the element and do something like that:
document.getElementById('inputId').value.split(/[\\$]/).pop()
Has --show-toplevel
only recently been added to git rev-parse
or why is nobody mentioning it?
From the git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
This isn't quite the answer you were looking for, but it's the solution I came to when I had the same question.
I'm a pretty serious Notepad++ user, so don't take this the wrong way. I have started using NetBeans 8
to develop websites in addition to Notepad++ because you can set it to autoformat on save for all your languages, and there are a ton of configuration options for how the formatting looks, down to the most minute detail. You might look into it and find it is a worthy tool to use in conjunction with notepad++. It's also open source, completely free, and has a bunch of plugins and other useful things like automatically compiling Sass if you use that too. It's definitely not as quick as NP++ so it's not great for small edits, but it can be nice for a long coding session.
I was facing the similar error. It was solved when I did these three things:
Update to the latest rxjs:
npm install rxjs@6 rxjs-compat@6 --save
Import map and promise:
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
Added a new import statement:
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
execute the below code to get the foreign key constraint name which blocks your drop. For example, I take the roles
table.
SELECT *
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('roles');
SELECT name AS 'Foreign Key Constraint Name',
OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id)
AS 'Child Table' FROM sys.foreign_keys
WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo'
AND OBJECT_NAME(referenced_object_id) = 'dbo.roles'
you will get the FK name something as below : FK__Table1__roleId__1X1H55C1
now run the below code to remove the FK reference got from above.
ALTER TABLE dbo.users drop CONSTRAINT FK__Table1__roleId__1X1H55C1;
Done!
Using .multiply() (ufunc multiply)
a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0
np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])
Did you see this - http://kb.discountasp.net/KB/a799/error-accessing-wcf-service-this-collection-already.aspx
You can resolve this error by changing the web.config file.
With ASP.NET 4.0, add the following lines to your web.config:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
With ASP.NET 2.0/3.0/3.5, add the following lines to your web.config:
<system.serviceModel>
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://www.YourHostedDomainName.com"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
Run below command into the current branch folder to merge from this <commit-id>
to current branch, --no-commit
do not make a new commit automatically
git merge --no-commit <commit-id>
git merge --continue
can only be run after the merge has resulted in conflicts.
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
I stumbled upon this question when was actually searching for an answer to this one (how to add a visual line/guideline at char limit). So I would like to leave a ref to it here for anyone like myself.
Is there a command that does?
thread apply all where
When implementing the constructor()
function inside a React component, super()
is a requirement. Keep in mind that your MyComponent
component is extending or borrowing functionality from the React.Component
base class.
This base class has a constructor()
function of its own that has some code inside of it, to setup our React component for us.
When we define a constructor()
function inside our MyComponent
class, we are essentially, overriding or replacing the constructor()
function that is inside the React.Component
class, but we still need to ensure that all the setup code inside of this constructor()
function still gets called.
So to ensure that the React.Component
’s constructor()
function gets called, we call super(props)
. super(props)
is a reference to the parents constructor()
function, that’s all it is.
We have to add super(props)
every single time we define a constructor()
function inside a class-based component.
If we don’t we will see an error saying that we have to call super(props)
.
The entire reason for defining this constructor()
funciton is to initialize our state object.
So in order to initialize our state object, underneath the super call I am going to write:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
// React says we have to define render()
render() {
return <div>Hello world</div>;
}
};
So we have defined our constructor()
method, initialized our state object by creating a JavaScript object, assigning a property or key/value pair to it, assigning the result of that to this.state
. Now of course this is just an example here so I have not really assigned a key/value pair to the state object, its just an empty object.
You should use datetime.datetime.strptime
:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
In project ':app' you can add the following to your app/build.gradle file :
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
you can use setAttribute
function in Model to add a custom attribute
There are a few problems here.
First of all, there is no such thing as <button type="cancel">
, so it is treated as just a <button>
. This means that your form will be submitted, instead of the button taking you elsewhere.
Second, javascript:
is only needed in href
or action
attributes, where a URL is expected, to designate JavaScript code. Inside onclick
, where JavaScript is already expected, it merely acts as a label and serves no real purpose.
Finally, it's just generally better design to have a cancel link rather than a cancel button. So you can just do this:
<a href="http://stackoverflow.com/">Cancel</a>
With CSS you can even make it look the same as a button, but with this HTML there is absolutely no confusion as to what it is supposed to do.
If you want to save the ASCII value of the character: (I did this in BASH and it worked)
{
char="A"
testing=$( printf "%d" "'${char}" )
echo $testing}
output: 65
empty()
needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.
However, the real problem you have is that you use empty()
at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing
. When the thing you're checking always exists (in PHP results of function calls always exist), the empty()
function is nothing but a negation operator.
PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:
$x = something();
if (empty($x)) …
and this:
$x = something();
if (!$x) …
has always the same result, in all cases, for all datatypes (because $x
is defined empty()
is redundant).
Return value from the method always exists (even if you don't have return
statement, return value exists and contains null
). Therefore:
if (!empty($r->getError()))
is logically equivalent to:
if ($r->getError())
While Orion Edwards Answer works for any situation, it may be a pain to add the border and set the properties of the border every time you want to do this. Another quick way is to set the padding of the text block:
<TextBlock Height="22" Padding="3" />
You should override Equals
and GetHashCode
meaningfully, in this case to compare the ID:
public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
public override bool Equals(object obj)
{
LinqTest obj2 = obj as LinqTest;
if (obj2 == null) return false;
return id == obj2.id;
}
public override int GetHashCode()
{
return id;
}
}
Now you can use Distinct
:
List<LinqTest> uniqueIDs = myList.Distinct().ToList();
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
git reset --hard HEAD^
Use the above command to revert merge changes.
Try
/etc/init.d/tomcat stop
(maybe you have to write something after tomcat
, just press tab one time)
Edit: And you also need to do it as root.
LTrim function and RTrim function :
It uses the Trim function to remove both types of spaces.
select LTRIM(RTRIM(' SQL Server '))
output:
SQL Server
You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.
To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.
Have a look at this link about installing self-signed certificates.
Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.
Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
Create a setenv.(sh|bat) file in the tomcat/bin directory with the environment variables that you want modified.
The catalina script checks if the setenv script exists and runs it to set the environment variables. This way you can change the parameters to only one instance of tomcat and is easier to copy it to another instance.
Probably your configuration app has created the setenv script and thats why tomcat is ignoring the environment variables.
The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path
Error: "Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"
Solution: Adding the tomcat server in the server runtime will do the job : Project Properties-> Java Build Path-> Add Library -> Select "Server Runtime" from the list-> Next->Select "Apache Tomcat"-> Finish
This solution work for me.
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
If you want that warm and fuzzy feeling just go with with.
For python 3.6 I ran these two programs under a fresh start of IDLE, giving runtimes of:
0.002000093460083008 Test A
0.0020003318786621094 Test B: with guaranteed close
So not much of a difference.
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Test A for reading a text file line-by-line into a list
#--------*---------*---------*---------*---------*---------*---------*---------*
import sys
import time
# # MAINLINE
if __name__ == '__main__':
print("OK, starting program...")
inTextFile = '/Users/Mike/Desktop/garbage.txt'
# # Test: A: no 'with;
c=[]
start_time = time.time()
c = open(inTextFile).read().splitlines()
print("--- %s seconds ---" % (time.time() - start_time))
print("OK, program execution has ended.")
sys.exit() # END MAINLINE
OUTPUT:
OK, starting program...
--- 0.002000093460083008 seconds ---
OK, program execution has ended.
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Test B for reading a text file line-by-line into a list
#--------*---------*---------*---------*---------*---------*---------*---------*
import sys
import time
# # MAINLINE
if __name__ == '__main__':
print("OK, starting program...")
inTextFile = '/Users/Mike/Desktop/garbage.txt'
# # Test: B: using 'with'
c=[]
start_time = time.time()
with open(inTextFile) as D: c = D.read().splitlines()
print("--- %s seconds ---" % (time.time() - start_time))
print("OK, program execution has ended.")
sys.exit() # END MAINLINE
OUTPUT:
OK, starting program...
--- 0.0020003318786621094 seconds ---
OK, program execution has ended.
ListaServizi.Sort();
Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.
Use this php switcher
You can control php version to any your project you want via vhost config.
For linux:
$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'open.*tnsnames.ora'
shows something like this:
open("/opt/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora",O_RDONLY)=7
Changing to
$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'tnsnames.ora'
will show all the file paths that are failing.
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.
select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;
Result:
-------------------
| String | Count |
-------------------
| table1 | 123 |
| table2 | 234 |
| table3 | 345 |
| table4 | 456 |
| table5 | 567 |
-------------------
You may use the typescript getter method for this scenario. Like this
public get height() {
return window.innerHeight;
}
public get width() {
return window.innerWidth;
}
And use that in template like this:
<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>
Print the value
console.log(this.height, this.width);
You won't need any event handler to check for resizing of window, this method will check for size every time automatically.
Unfortunately as I am forced to use a windows server I have been unable to get openssl working in the way the above answer suggests.
However I was able to get a similar program called stunnel (which can be downloaded from here) to work. I got the idea from www.tech-and-dev.com but I had to change the instructions slightly. Here is what I did:
stunnel.conf
config file, which in my case I installed to C:\Program Files (x86)\stunnel
Then, you need to open this file in a text viewer such as notepad. Look for [gmail-smtp]
and remove the semicolon on the client line below (in the stunnel.conf file, every line that starts with a semicolon is a comment). You should end up with something like:
[gmail-smtp]
client = yes
accept = 127.0.0.1:25
connect = smtp.gmail.com:465
Once you have done this save the stunnel.conf
file and reload the config (to do this use the stunnel GUI program, and click on configuration=>Reload).
Now you should be ready to send email in the windows telnet client!
Go to Start=>run=>cmd.
Once cmd is open type in the following and press Enter:
telnet localhost 25
You should then see something similar to the following:
220 mx.google.com ESMTP f14sm1400408wbe.2
You will then need to reply by typing the following and pressing enter:
helo google
This should give you the following response:
250 mx.google.com at your service
If you get this you then need to type the following and press enter:
ehlo google
This should then give you the following response:
250-mx.google.com at your service, [212.28.228.49]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
Now you should be ready to authenticate with your Gmail details. To do this type the following and press enter:
AUTH LOGIN
This should then give you the following response:
334 VXNlcm5hbWU6
This means that we are ready to authenticate by using our gmail address and password.
However since this is an encrypted session, we're going to have to send the email and password encoded in base64. To encode your email and password, you can use a converter program or an online website to encode it (for example base64 or search on google for ’base64 online encoding’). I reccomend you do not touch the cmd/telnet session again until you have done this.
For example [email protected] would become dGVzdEBnbWFpbC5jb20= and password would become cGFzc3dvcmQ=
Once you have done this copy and paste your converted base64 username into the cmd/telnet session and press enter. This should give you following response:
334 UGFzc3dvcmQ6
Now copy and paste your converted base64 password into the cmd/telnet session and press enter. This should give you following response if both login credentials are correct:
235 2.7.0 Accepted
You should now enter the sender email (should be the same as the username) in the following format and press enter:
MAIL FROM:<[email protected]>
This should give you the following response:
250 2.1.0 OK x23sm1104292weq.10
You can now enter the recipient email address in a similar format and press enter:
RCPT TO:<[email protected]>
This should give you the following response:
250 2.1.5 OK x23sm1104292weq.10
Now you will need to type the following and press enter:
DATA
Which should give you the following response:
354 Go ahead x23sm1104292weq.10
Now we can start to compose the message! To do this enter your message in the following format (Tip: do this in notepad and copy the entire message into the cmd/telnet session):
From: Test <[email protected]>
To: Me <[email protected]>
Subject: Testing email from telnet
This is the body
Adding more lines to the body message.
When you have finished the email enter a dot:
.
This should give you the following response:
250 2.0.0 OK 1288307376 x23sm1104292weq.10
And now you need to end your session by typing the following and pressing enter:
QUIT
This should give you the following response:
221 2.0.0 closing connection x23sm1104292weq.10
Connection to host lost.
And your email should now be in the recipient’s mailbox!
You need to install a so-called Instance of MSSQL server on your computer. That is, installing all the needed files and services and database files. By default, there should be no MSSQL Server installed on your machine, assuming that you use a desktop Windows (7,8,10...).
You can start off with Microsoft SQL Server Express, which is a 10GB-limited, free version of MSSQL. It also lacks some other features (Server Agents, AFAIR), but it's good for some experiments.
Download it from the Microsoft Website and go through the installer process by choosing New SQL Server stand-alone installation ..
after running the installer.
Click through the steps. For your scenario (it sounds like you mainly want to test some stuff), the default options should suffice.
Just give attention to the step Instance Configuration
. There you will set the name of your MSSQL Server Instance. Call it something unique/descriptive like MY_TEST_INSTANCE
or the like. Also, choose wisely the Instance root directory
. In it, the database files will be placed, so it should be on a drive that has enough space.
Click further through the wizard, and when it's finished, your MSSQL instance will be up and running. It will also run at every boot if you have chosen the default settings for the services.
As soon as it's running in the background, you can connect to it with Management Studio by connecting to .\MY_TEST_INSTANCE
, given that that's the name you chose for the instance.
Please read the Android Documentation regarding screen sizes.
From a base image size, there is a 3:4:6:8:12:16 scaling ratio in drawable size by DPI.
LDPI - 0.75x
MDPI - Original size // means 1.0x here
HDPI - 1.5x
XHDPI - 2.0x
XXHDPI - 3x
XXXHDPI - 4.0x
For example, 100x100px image on a MDPI will be the same size of a 200x200px on a XHDPI screen.
I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.
complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone
CRM.$( 'input[id^=custom_78]' ).autocomplete({
autoFill: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
// Update subject field to add book year and book product
var book_year_value = CRM.$('select[id^=custom_77] option:selected').text().replace('Book Year ','');
//book_year_value.replace('Book Year ','');
var subject_value = book_year_value + '/' + ui.item.label;
CRM.$('#subject').val(subject_value);
CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
CRM.$('input[id^=custom_78]').val(ui.item.label);
return false;
},
source: function(request, response) {
CRM.$.ajax({
url: productUrl,
data: {
'subCategory' : cj('select[id^=custom_77]').val(),
's': request.term,
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function(result){
result = jQuery.parseJSON( result);
//console.log(result);
response(CRM.$.map(result, function (val,key) {
//console.log(key);
//console.log(val);
return {
label: val,
value: key
};
}));
}
})
.done(function( data ) {
if ( console && console.log ) {
// console.log( "Sample of dataas:", data.slice( 0, 100 ) );
}
});
}
});
PHP code on how I'm returning data to this jquery ajax call in autocomplete:
/**
* This class contains all product related functions that are called using AJAX (jQuery)
*/
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
static function getProductList() {
$name = CRM_Utils_Array::value( 's', $_GET );
$name = CRM_Utils_Type::escape( $name, 'String' );
$limit = '10';
$strSearch = "description LIKE '%$name%'";
$subCategory = CRM_Utils_Array::value( 'subCategory', $_GET );
$subCategory = CRM_Utils_Type::escape( $subCategory, 'String' );
if (!empty($subCategory))
{
$strSearch .= " AND sub_category = ".$subCategory;
}
$query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
$resultArray = array();
$dao = CRM_Core_DAO::executeQuery( $query );
while ( $dao->fetch( ) ) {
$resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
}
echo json_encode($resultArray);
CRM_Utils_System::civiExit();
}
}
With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem.
Character
s into a String
with no separator:let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
String
s into a String
with no separator:let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")
print(string) // prints: "BobDanBryan"
String
s into a String
with a separator between words:let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")
print(string) // prints: "Bob Dan Bryan"
String
s into a String
with a separator between characters:let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")
print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"
Float
s into a String
with a separator between numbers:let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")
print(string)
// prints "12.0-14.6-35.0"
I don't recommend changing apaches port itself, because it will need you remember changed port. Its also headache to tell your co-developers about port change.
Go to windows features(By searching turn on or off windows features) -> Find Internet information services(IIS) and uncheck if it checked. Please make a note when you disable it FTP server/ client will not work.(incase you are using it, change httpd.conf as giovannipds 's answer) -> If still port is not free, then change skype port through skype settings.
Quick fix: Change how excel converts imported files. Go to 'File', then 'Options', then 'Advanced'. Scroll down and uncheck 'Use system seperators'. Also change 'Decimal separator' to '.' and 'Thousands separator' to ',' . Then simply 're-save' your file in the CSV (Comma delimited) format. The root cause is usually associated with how the csv file is created. Trust that helps. Point is, why use extra code if not necessary? Cross-platform understanding and integration is key in engineering/development.
mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
| 4.000 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
| 4.500 |
+------------------------------+
1 row in set (0.00 sec)
mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
| 0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)
Sometimes you just need to suppress only some warnings and you want to keep other warnings, just to be safe. In your code, you can suppress the warnings for variables and even formal parameters by using GCC's unused attribute. Lets say you have this code snippet:
void func(unsigned number, const int version)
{
unsigned tmp;
std::cout << number << std::endl;
}
There might be a situation, when you need to use this function as a handler - which (imho) is quite common in C++ Boost library. Then you need the second formal parameter version, so the function's signature is the same as the template the handler requires, otherwise the compilation would fail. But you don't really need it in the function itself either...
The solution how to mark variable or the formal parameter to be excluded from warnings is this:
void func(unsigned number, const int version __attribute__((unused)))
{
unsigned tmp __attribute__((unused));
std::cout << number << std::endl;
}
GCC has many other parameters, you can check them in the man pages. This also works for the C programs, not only C++, and I think it can be used in almost every function, not just handlers. Go ahead and try it! ;)
P.S.: Lately I used this to suppress warnings of Boosts' serialization in template like this:
template <typename Archive>
void serialize(Archive &ar, const unsigned int version __attribute__((unused)))
EDIT: Apparently, I didn't answer your question as you needed, drak0sha done it better. It's because I mainly followed the title of the question, my bad. Hopefully, this might help other people, who get here because of that title... :)
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"
Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3
This is what I went with. Its a modified version of Abbbas khan's post:
<?php
function calculate_time_span($post_time)
{
$seconds = time() - strtotime($post);
$year = floor($seconds /31556926);
$months = floor($seconds /2629743);
$week=floor($seconds /604800);
$day = floor($seconds /86400);
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60) $time = $secs." seconds ago";
else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
else $time = ($year==1)? $year." year ago":$year." years ago";
return $time;
}
// uses
// $post_time="2017-12-05 02:05:12";
// echo calculate_time_span($post_time);
If you know the (maximum) number of rows and columns beforehand, you can use resize()
to initialize a vector of vectors and then modify (and access) elements with operator[]
. Example:
int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;
std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));
// Read from matrix.
int value = matrix[1][2];
// Save to matrix.
matrix[3][1] = 5;
Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column]
.
Set the default console colors and fonts:
http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)
Set-StrictMode -Version Latest
Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
I expand on the top of @gezdy's answer.
In every Activities, instead of having to "register" itself with Application
with manual coding, we can make use of the following API since level 14, to help us achieve similar purpose with less manual coding.
public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)
In Application.ActivityLifecycleCallbacks
, you can get which Activity
is "attached" to or "detached" to this Application
.
However, this technique is only available since API level 14.
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
I had the same problem when I changed from Websphere 8.5 to WebSphere Liberty.
I utilized FileInputStream
instead of getResourceAsStream()
, because for some reason WebSphere Liberty can't locate the file in the WEB-INF
folder.
The script was :
FileInputStream fis = new FileInputStream(getServletContext().getRealPath("/")
+ "\WEBINF\properties\myProperties.properties")
Note: I used this script only for development.
I'm on Gson 2.8.6 and discovered this bug today.
My approach allows all our existing clients (mobile/web/etc) to continue functioning as they were, but adds some handling for those using 24h formats and allows millis too, for good measure.
Gson rawGson = new Gson();
SimpleDateFormat fmt = new SimpleDateFormat("MMM d, yyyy HH:mm:ss")
private class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
return new rawGson.fromJson(json, Date.class);
} catch (JsonSyntaxException e) {}
String timeString = json.getAsString();
log.warning("Standard date deserialization didn't work:" + timeString);
try {
return fmt.parse(timeString);
} catch (ParseException e) {}
log.warning("Parsing as json 24 didn't work:" + timeString);
return new Date(json.getAsLong());
}
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
I kept serialization the same as all clients understand the standard json date format.
Ordinarily, I don't think it's good practice to use try/catch blocks, but this should be a fairly rare case.
I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.
you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters
in ur appender section add
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="Info" />
<acceptOnMatch value="true" />
</filter>
the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
I experienced this while working with nested RelativeLayouts. My solution ended up being simple, but it's a little gotcha that's worth being aware of.
My layout was defined with...
android:layout_height="fill_parent"
android:layout_below="@id/someLayout
android:gravity="center"
...however, I didn't think that the layout below this one was placed on top of it. Everything inside this layout was shifted towards the bottom instead of centered. Adding...
android:layout_above="@id/bottomLayout"
...fixed my issue.
Fastest approach, if you need to perform more than just one or two such removal operations (or even just one, but on a very long string!-), is to rely on the translate
method of strings, even though it does need some prep:
>>> import string
>>> allchars = ''.join(chr(i) for i in xrange(256))
>>> identity = string.maketrans('', '')
>>> nondigits = allchars.translate(identity, string.digits)
>>> s = 'abc123def456'
>>> s.translate(identity, nondigits)
'123456'
The translate
method is different, and maybe a tad simpler simpler to use, on Unicode strings than it is on byte strings, btw:
>>> unondig = dict.fromkeys(xrange(65536))
>>> for x in string.digits: del unondig[ord(x)]
...
>>> s = u'abc123def456'
>>> s.translate(unondig)
u'123456'
You might want to use a mapping class rather than an actual dict, especially if your Unicode string may potentially contain characters with very high ord values (that would make the dict excessively large;-). For example:
>>> class keeponly(object):
... def __init__(self, keep):
... self.keep = set(ord(c) for c in keep)
... def __getitem__(self, key):
... if key in self.keep:
... return key
... return None
...
>>> s.translate(keeponly(string.digits))
u'123456'
>>>
Try this :
$('.close-button').on('click', function(){
$('.element').removeClass('grown');
$('.element').addClass('spot');
});
$('.element').on('click', function(){
$(this).removeClass('spot');
$(this).addClass('grown');
});
I hope I understood your question.
If you're using PHP 5.5 or PHP 7 above, you may want to use:
function isTodayWeekend() {
return in_array(date("l"), ["Saturday", "Sunday"]);
}
and it will return "true" if today is weekend and "false" if not.
a new Q how to By a keys chain
dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}},'anotherLevel1':{'anotherLevel2':{'anotherLevelA':0,'anotherLevelB':1}}}
update={'anotherLevel1':{'anotherLevel2':1014}}
dictionary1.update(update)
print dictionary1
{'level1':{'level2':{'levelA':0,'levelB':1}},'anotherLevel1':{'anotherLevel2':1014}}
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name,*
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%YOUR_COLUMN%'
ORDER BY schema_name, table_name;
driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension");
You can do this by reading from the boolean property at:
System.Web.Security.Roles.Enabled
This is a direct read from the enabled
attribute of the roleManager
element in the web.config
:
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx
You can also set the color individually for each point/bar if you change the data array to be configuration objects instead of numbers.
data: [
{y: 34.4, color: 'red'}, // this point is red
21.8, // default blue
{y: 20.1, color: '#aaff99'}, // this will be greenish
20] // default blue
fopen vs open in C
1) fopen
is a library function while open
is a system call.
2) fopen
provides buffered IO which is faster compare to open
which is non buffered.
3) fopen
is portable while open
not portable (open is environment specific).
4) fopen
returns a pointer to a FILE structure(FILE *); open
returns an integer that identifies the file.
5) A FILE *
gives you the ability to use fscanf and other stdio functions.
MSDN: Header: Winbase.h (include Windows.h)
You can just use sun.awt.OSInfo#getOSType() method
There's another function call implied in there if you're going to use std::endl
a) std::cout << "Hello\n";
b) std::cout << "Hello" << std::endl;
a) calls operator <<
once.
b) calls operator <<
twice.
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.
jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/
"o" format is different for DateTime vs DateTimeOffset :(
DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"
DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"
My final answer is
DateTimeOffset.UtcDateTime.ToString("o") //for DateTimeOffset type
DateTime.UtcNow.ToString("o") //for DateTime type
The problem is described (among other) in this article.
#box
is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".
Page flow means that the positioning of an element effects other elements in the flow.
In other words, as #box
now sees the dom, .a and .b are no longer "inside" #box
.
To fix this, you would want to make everything relative, or everything absolute.
One way would be:
.a {
position:relative;
margin-top:10px;
margin-left:10px;
background-color:red;
width:210px;
padding: 5px;
}
It would be nice to have full support for set methods for dictionaries (and not the unholy mess we're getting with Python 3.9) so that you could simply "remove" a set of keys. However, as long as that's not the case, and you have a large dictionary with potentially a large number of keys to remove, you might want to know about the performance. So, I've created some code that creates something large enough for meaningful comparisons: a 100,000 x 1000 matrix, so 10,000,00 items in total.
from itertools import product
from time import perf_counter
# make a complete worksheet 100000 * 1000
start = perf_counter()
prod = product(range(1, 100000), range(1, 1000))
cells = {(x,y):x for x,y in prod}
print(len(cells))
print(f"Create time {perf_counter()-start:.2f}s")
clock = perf_counter()
# remove everything above row 50,000
keys = product(range(50000, 100000), range(1, 100))
# for x,y in keys:
# del cells[x, y]
for n in map(cells.pop, keys):
pass
print(len(cells))
stop = perf_counter()
print(f"Removal time {stop-clock:.2f}s")
10 million items or more is not unusual in some settings. Comparing the two methods on my local machine I see a slight improvement when using map
and pop
, presumably because of fewer function calls, but both take around 2.5s on my machine. But this pales in comparison to the time required to create the dictionary in the first place (55s), or including checks within the loop. If this is likely then its best to create a set that is a intersection of the dictionary keys and your filter:
keys = cells.keys() & keys
In summary: del
is already heavily optimised, so don't worry about using it.
mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,
If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),
if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319
if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:
if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way
:)
One way to do this is by changing the parent of the overlapping picture box to the PictureBox over which it is lapping. Since the Visual Studio designer doesn't allow you to add a PictureBox to a PictureBox, this will have to be done in your code (Form1.cs) and within the Intializing function:
public Form1()
{
InitializeComponent();
pictureBox7.Controls.Add(pictureBox8);
pictureBox8.Location = new Point(0, 0);
pictureBox8.BackColor = Color.Transparent;
}
Just change the picture box names to what ever you need. This should return:
The solution to when you're using XMLWriter
(native to PHP 5.2.x
<) is using $xml->startElement('itemName');
this will replace the arrays key.
server.session.timeout=1200
server.servlet.session.timeout=10m
If you are using MacPorts you can upgrade your VIM to include clipboard support via:
port install vim +x +x11
Now you use the "+
register to yank your text directly to your Mac clipboard. Works like a charm.
:m.+1 or :m.-2 would do if you're moving a single line. Here's my script to move multiple lines. In visual mode, Alt-up/Alt-down will move the lines containing the visual selection up/down by one line. In insert mode or normal mode, Alt-up/Alt-down will move the current line if no count prefix is given. If there's a count prefix, Alt-up/Alt-down will move that many lines beginning from the current line up/down by one line.
function! MoveLines(offset) range
let l:col = virtcol('.')
let l:offset = str2nr(a:offset)
exe 'silent! :' . a:firstline . ',' . a:lastline . 'm'
\ . (l:offset > 0 ? a:lastline + l:offset : a:firstline + l:offset)
exe 'normal ' . l:col . '|'
endf
imap <silent> <M-up> <C-O>:call MoveLines('-2')<CR>
imap <silent> <M-down> <C-O>:call MoveLines('+1')<CR>
nmap <silent> <M-up> :call MoveLines('-2')<CR>
nmap <silent> <M-down> :call MoveLines('+1')<CR>
vmap <silent> <M-up> :call MoveLines('-2')<CR>gv
vmap <silent> <M-down> :call MoveLines('+1')<CR>gv
I came across this, tot it would be nice to share...
What do you guys think?
$(document).ready(function() {
window.mousemove = function(e) {
p = $(e).position(); //remember $(e) - could be any html tag also..
left = e.left; //retrieving the left position of the div...
top = e.top; //get the top position of the div...
}
});
and boom, there we have it..
Change 1D array into 2D array without using Numpy.
l = [i for i in range(1,21)]
part = 3
new = []
start, end = 0, part
while end <= len(l):
temp = []
for i in range(start, end):
temp.append(l[i])
new.append(temp)
start += part
end += part
print("new values: ", new)
# for uneven cases
temp = []
while start < len(l):
temp.append(l[start])
start += 1
new.append(temp)
print("new values for uneven cases: ", new)
new SimpleDateFormat("EEE MMM dd kk:mm:ss ZZZ yyyy");
and
new SimpleDateFormat("EEE MMM dd kk:mm:ss Z yyyy");
still runs. However, if your code throws an exception it is because your tool or jdk or any other reason. Because I got same error in my IDE but please check these http://ideone.com/Y2cRr (online ide) with ZZZ and with Z
output is : Thu Sep 28 11:29:30 GMT 2000
we can use \b as a word boundary and then; \b\d+\b
You can use this in the bat
script:
rd /s /q "c:\folder a"
Now, just change c:\folder a
to your folder's location. Quotation is only needed when your folder name contains spaces.
just do this:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
a * b
I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.
http://technet.microsoft.com/en-us/library/bb490986.aspx
Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.
Use the /i with xcopy and if the directory doesn't exist it will create the directory for you.
I know its stupid but in my case i was outside of my project folder i didn't have spark file.
There are functions to round numbers. For example:
var x = 5.0364342423;
print(x.toFixed(2));
will print 5.04.
EDIT: Fiddle
[Update: As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]
I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:
Node.js itself offers an http module, whose createServer
method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server
prototype.
Connect also offers a createServer
method, which returns an object that inherits an extended version of http.Server
. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.
Express does to Connect what Connect does to the http module: It offers a createServer
method that extends Connect's Server
prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.
Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.
Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static
(a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.static
is the same as connect.static
. (Both were known as staticProvider
until recently.)
My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.
If you don't care about the ordering of the keys, you could do the following:
$array = YOUR_ARRAY
$unique = array();
foreach ($array as $a) {
$unique[$a] = $a;
}
Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.
http://docs.python.org/reference/expressions.html
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
Not exactly a setting but you can override the default TrustManager and HostnameVerifier to accept anything. Not a safe approach but in your situation, it can be acceptable.
Complete example : Fix certificate problem in HTTPS
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head>
of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1
to user_group-10
, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
You can also count on multiple groups and their intersection:
self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()
The query above will return counts for all possible combinations of values from both columns.
I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S
:
# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80 is a NameVirtualHost
default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
[...]
11.22.33.44:443 is a NameVirtualHost
default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80 hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001 hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000 hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443 hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001 hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000 hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK
Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).
Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default
on line 33 and /etc/apache2/sites-enabled/default-ssl
on line 163. Likewise *:30000
is listed in 2 places. The solution (in my case) was simply to delete one of the entries.
I love the answer from @Bert F but this is the way my brain sees it.
I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...
List<? super X>
If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X
List<? extends X>
Hope this helps.
import UIKit
// MARK: - IdentifiableCell protocol will generate cell identifire based on the class name
protocol Identifiable: class {}
extension Identifiable { static var identifier: String { return "\(self)"} }
// MARK: - Functions which will use a cell class (conforming Identifiable protocol) to `dequeueReusableCell`
extension UITableView {
typealias IdentifiableCell = UITableViewCell & Identifiable
func register<T: IdentifiableCell>(class: T.Type) { register(T.self, forCellReuseIdentifier: T.identifier) }
func register(classes: [Identifiable.Type]) { classes.forEach { register($0.self, forCellReuseIdentifier: $0.identifier) } }
func dequeueReusableCell<T: IdentifiableCell>(aClass: T.Type, initital closure: ((T) -> Void)?) -> UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier) as? T else { return UITableViewCell() }
closure?(cell)
return cell
}
func dequeueReusableCell<T: IdentifiableCell>(aClass: T.Type, for indexPath: IndexPath, initital closure: ((T) -> Void)?) -> UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else { return UITableViewCell() }
closure?(cell)
return cell
}
}
extension Array where Element == UITableViewCell.Type {
var onlyIdentifiables: [Identifiable.Type] { return compactMap { $0 as? Identifiable.Type } }
}
// Define cells classes
class TableViewCell1: UITableViewCell, Identifiable { /*....*/ }
class TableViewCell2: TableViewCell1 { /*....*/ }
// .....
// Register cells
tableView.register(classes: [TableViewCell1.self, TableViewCell2.self]. onlyIdentifiables)
// Create/Reuse cells
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.row % 2) == 0 {
return tableView.dequeueReusableCell(aClass: TableViewCell1.self, for: indexPath) { cell in
// ....
}
} else {
return tableView.dequeueReusableCell(aClass: TableViewCell2.self, for: indexPath) { cell in
// ...
}
}
}
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
}
// MARK: - Setup(init) subviews
extension ViewController {
private func setupTableView() {
let tableView = UITableView()
view.addSubview(tableView)
self.tableView = tableView
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.register(classes: [TableViewCell1.self, TableViewCell2.self, TableViewCell3.self].onlyIdentifiables)
tableView.dataSource = self
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (indexPath.row % 3) {
case 0:
return tableView.dequeueReusableCell(aClass: TableViewCell1.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
case 1:
return tableView.dequeueReusableCell(aClass: TableViewCell2.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
default:
return tableView.dequeueReusableCell(aClass: TableViewCell3.self, for: indexPath) { cell in
cell.textLabel?.text = "\(cell.classForCoder)"
}
}
}
}
I'd download PuTTY and run a telnet session on port 80 to the webserver you want
HEAD /resource HTTP/1.1
Host: www.example.com
You could alternatively download Perl and try LWP's HEAD command. Or write your own script.
1:list name of all employee who earn more than RS.100000 in a year.
2:give the name of employee who earn heads the department where employee with employee I.D
Use mcrypt_encrypt()
and mcrypt_decrypt()
with corresponding parameters. Really easy and straight forward, and you use a battle-tested encryption package.
EDIT
5 years and 4 months after this answer, the mcrypt
extension is now in the process of deprecation and eventual removal from PHP.
@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error. it will only work if you let JPA create your tables
Example
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {
@Column(name = "person_id")
private Long personId;
@ManyToOne
@JoinColumn(name = "company_id")
private Company company;
}
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html
On the other hand To ensure a field value is unique you can write
@Column(unique=true)
String username;
<RatingBar
android:id="@+id/ratingBar1"
android:numStars="5"
android:stepSize=".5"
android:rating="3.5"
style="@android:style/Widget.DeviceDefault.RatingBar.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Make sure that your log4j is configured correctly, there's probably an exception that is being thrown, but you're only seeing half of the picture.
Please see https://stackoverflow.com/a/16817018/1249304
I just tested a couple paths using Excel 2013 on on Windows 7. I found the overall pathname limit to be 213 and the basename length to be 186. At least the error dialog for exceeding basename length is clear:
And trying to move a not-too-long basename to a too-long-pathname is also very clear:
The pathname error is deceptive, though. Quite unhelpful:
This is a lazy Microsoft restriction. There's no good reason for these arbitrary length limits, but in the end, it’s a real bug in the error dialog.
In a word - yes.
Actually, many classes in the JDK implement multiple interfaces. E.g., ArrayList
implements List
, RandomAccess
, Cloneable
, and Serializable
.
If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:
var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});
$.post("api/comment", formData, function(data) {
// request has finished, check for errors
// and then for example redirect to another page
});
See .serializeArray()
and $.post()
documentation.
I think that you are looking for the ngCloak
directive: https://docs.angularjs.org/api/ng/directive/ngCloak
From the documentation:
The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.
The directive can be applied to the
<body>
element, but the preferred usage is to apply multiplengCloak
directives to small portions of the page to permit progressive rendering of the browser view
Try something like
find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)
and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.
Note that -(NSString *)tableView:
titleForHeaderInSection:
is not called by UITableView if - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
is implemented in delegate of UITableView;
Take a look at this article on Simple-talk.com by Pop Rivett. It walks you through creating a generic trigger that will log the OLDVALUE and the NEWVALUE for all updated columns. The code is very generic and you can apply it to any table you want to audit, also for any CRUD operation i.e. INSERT, UPDATE and DELETE. The only requirement is that your table to be audited should have a PRIMARY KEY (which most well designed tables should have anyway).
Here's the code relevant for your GUESTS Table.
IF NOT EXISTS
(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE Audit
(Type CHAR(1),
TableName VARCHAR(128),
PK VARCHAR(1000),
FieldName VARCHAR(128),
OldValue VARCHAR(1000),
NewValue VARCHAR(1000),
UpdateDate datetime,
UserName VARCHAR(128))
GO
CREATE TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE
AS
DECLARE @bit INT ,
@field INT ,
@maxfield INT ,
@char INT ,
@fieldname VARCHAR(128) ,
@TableName VARCHAR(128) ,
@PKCols VARCHAR(1000) ,
@sql VARCHAR(2000),
@UpdateDate VARCHAR(21) ,
@UserName VARCHAR(128) ,
@Type CHAR(1) ,
@PKSelect VARCHAR(1000)
--You will need to change @TableName to match the table to be audited.
-- Here we made GUESTS for your example.
SELECT @TableName = 'GUESTS'
-- date and user
SELECT @UserName = SYSTEM_USER ,
@UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)
-- Action
IF EXISTS (SELECT * FROM inserted)
IF EXISTS (SELECT * FROM deleted)
SELECT @Type = 'U'
ELSE
SELECT @Type = 'I'
ELSE
SELECT @Type = 'D'
-- get list of columns
SELECT * INTO #ins FROM inserted
SELECT * INTO #del FROM deleted
-- Get primary key columns for full outer join
SELECT @PKCols = COALESCE(@PKCols + ' and', ' on')
+ ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT @PKSelect = COALESCE(@PKSelect+'+','')
+ '''<' + COLUMN_NAME
+ '=''+convert(varchar(100),
coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>'''
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF @PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, @TableName)
RETURN
END
SELECT @field = 0,
@maxfield = MAX(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
WHILE @field < @maxfield
BEGIN
SELECT @field = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION > @field
SELECT @bit = (@field - 1 )% 8 + 1
SELECT @bit = POWER(2,@bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(),@char, 1) & @bit > 0
OR @Type IN ('I','D')
BEGIN
SELECT @fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION = @field
SELECT @sql = '
insert Audit ( Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
select ''' + @Type + ''','''
+ @TableName + ''',' + @PKSelect
+ ',''' + @fieldname + ''''
+ ',convert(varchar(1000),d.' + @fieldname + ')'
+ ',convert(varchar(1000),i.' + @fieldname + ')'
+ ',''' + @UpdateDate + ''''
+ ',''' + @UserName + ''''
+ ' from #ins i full outer join #del d'
+ @PKCols
+ ' where i.' + @fieldname + ' <> d.' + @fieldname
+ ' or (i.' + @fieldname + ' is null and d.'
+ @fieldname
+ ' is not null)'
+ ' or (i.' + @fieldname + ' is not null and d.'
+ @fieldname
+ ' is null)'
EXEC (@sql)
END
END
GO
Stephan T. Lavavej (stl) from Microsoft did a talk at Going Native about how to use the new C++11 random functions and why not to use rand()
. In it, he included a slide that basically solves your question. I've copied the code from that slide below.
You can see his full talk here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(1.0, 10.0);
for (int i=0; i<16; ++i)
std::cout << dist(mt) << "\n";
}
We use random_device
once to seed the random number generator named mt
. random_device()
is slower than mt19937
, but it does not need to be seeded because it requests random data from your operating system (which will source from various locations, like RdRand for example).
Looking at this question / answer, it appears that uniform_real_distribution
returns a number in the range [a, b)
, where you want [a, b]
. To do that, our uniform_real_distibution
should actually look like:
std::uniform_real_distribution<double> dist(1, std::nextafter(10, DBL_MAX));
Cloning involves making a copy of the git repository to a local machine, while forking is cloning the repository into another repository. Cloning is for personal use only (although future merges may occur), but with forking you are copying and opening a new possible project path
In my project, the view controller is involved with lots of Constraints and StackView, and I set the TextView height as a constraint, and it varies based on the textView.contentSize.height value.
step1: get a IB outlet
@IBOutlet weak var textViewHeight: NSLayoutConstraint!
step2: use the delegation method below.
extension NewPostViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
textViewHeight.constant = self.textView.contentSize.height + 10
}
}
In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.
What did the trick was:
bfg -b 100M # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive
Then, you need to push force on your branch:
git push origin <your_branch_name> --force
Note: bfg is a tool that can be installed on Linux and macOS using brew:
brew install bfg
Unit Testing is one of the most adopted methodologies for high quality code. Its contribution to a more stable, independent and documented code is well proven . Unit test code is considered and handled as an a integral part of your repository, and as such requires development and maintenance. However, developers often encounter a situation where the resources invested in unit tests where not as fruitful as one would expect. In an ideal world every method we code will have a series of tests covering it’s code and validating it’s correctness. However, usually due to time limitations we either skip some tests or write poor quality ones. In such reality, while keeping in mind the amount of resources invested in unit testing development and maintenance, one must ask himself, given the available time, which code deserve testing the most? And from the existing tests, which tests are actually worth keeping and maintaining? See here
Many frameworks use ThreadLocals to maintain some context related to the current thread. For example when the current transaction is stored in a ThreadLocal, you don't need to pass it as a parameter through every method call, in case someone down the stack needs access to it. Web applications might store information about the current request and session in a ThreadLocal, so that the application has easy access to them. With Guice you can use ThreadLocals when implementing custom scopes for the injected objects (Guice's default servlet scopes most probably use them as well).
ThreadLocals are one sort of global variables (although slightly less evil because they are restricted to one thread), so you should be careful when using them to avoid unwanted side-effects and memory leaks. Design your APIs so that the ThreadLocal values will always be automatically cleared when they are not needed anymore and that incorrect use of the API won't be possible (for example like this). ThreadLocals can be used to make the code cleaner, and in some rare cases they are the only way to make something work (my current project had two such cases; they are documented here under "Static Fields and Global Variables").
Use --single-branch
option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.
git clone <repo_url> --branch <tag_name> --single-branch
I would like Web applications to not override my default shortcut keys, honestly. Ctrl+S already does something in browsers. Having that change abruptly depending on the site I'm viewing is disruptive and frustrating, not to mention often buggy. I've had sites hijack Ctrl+Tab because it looked the same as Ctrl+I, both ruining my work on the site and preventing me from switching tabs as usual.
If you want shortcut keys, use the accesskey
attribute. Please don't break existing browser functionality.
You can get height using below code
You have to pass
text 2. font 3. label width
func heightForLabel(text: String, font: UIFont, width: CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>
I use this script in bash:
#!/bin/bash
now=$(date +"%b%d-%Y-%H%M%S")
FILE="$1"
name="${FILE%.*}"
ext="${FILE##*.}"
cp -v $FILE $name-$now.$ext
This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!
Use String#next
as the counter.
>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003
next
is relatively 'clever', meaning you can even go for
>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003
When you open the file you want to write to, open it with a specific encoding that can handle all the characters.
with open('filename', 'w', encoding='utf-8') as f:
print(r['body'], file=f)
It means that the number of values specified in your VALUES
clause on the INSERT
statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.
Another one, since you are using ADO.Net
, always parameterized your query to avoid SQL Injection
. What you are doing right now is you are defeating the use of sqlCommand
.
ex
Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= " colBranch, colCourse, coldblFee) "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"
Using conn as New SqlConnection("connectionStringHere")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@colName", strName)
.Parameters.AddWithValue("@colID", strId)
.Parameters.AddWithValue("@colPhone", strPhone)
.Parameters.AddWithValue("@colBranch", strBranch)
.Parameters.AddWithValue("@colCourse", strCourse)
.Parameters.AddWithValue("@coldblFee", dblFee)
End With
Try
conn.open()
comm.ExecuteNonQuery()
Catch(ex as SqlException)
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
End USing
PS: Please change the column names specified in the query to the original column found in your table.
If you have integers in your file fscanf returns 1 until integer occurs. For example:
FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;
for ( int i = 0; i < 10; i++ ) {
counter = fscanf(in, "%d", &sequence);
if ( counter == 1 ) {
length += 1;
}
}
To find out the end of the file with symbols you can use EOF. For example:
char symbol;
FILE *in = fopen("./task.in", "r");
for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
printf("%c", symbol);
}
Look into using the ToString()
method with a specified format.
UPDATE Feb. 2021
As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs
have been introduced.
The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.
So there is no need of using startActivityForResult
and onActivityResult
anymore.
In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:
private val intentLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.getStringExtra("streetkey")
result.data?.getStringExtra("citykey")
result.data?.getStringExtra("homekey")
}
}
and then, launching your intent whenever you need to:
intentLauncher.launch(Intent(this, YourActivity::class.java))
And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult()
method:
val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")
setResult(Activity.RESULT_OK, data)
finish()
For any additional information, please refer to Android Documentation
I should mention that if you are using Mac, downloading and running an app from the App Store (like "iBoostUp" etc.) which will clean out unused system files can speed up your computer dramatically, including AS.
I also found that adding more memory to my Mac sped up AS as well.
None of the other answers worked for me but this did:
SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer