Go to project properties -> Project Facets. Make sure the Dynamic Web Module and Java is checked.
Apart from it, "Cloud Foundry Standalone Application" needs to be un-checked, if it is already selected. By default, few IDEs preselect this option.
ok so what if it say this: between the gt/lt signs
Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight\v3.0\Microsoft.Silverlight.CSharp.targets" /
how do i fix the targets error?
I also found that import string in a demo project (specifically "Build your own MVVM Framework" by Rob Eisenburg).
If you replace that import with the one suggested by lomaxx VS2010 RTM reports that you need to install this.
Yet another example...
from __future__ import print_function #Only for Python2
with open('file1.txt') as f1, open('file2.txt') as f2, open('outfile.txt', 'w') as outfile:
for line1, line2 in zip(f1, f2):
if line1 == line2:
print(line1, end='', file=outfile)
And if you want to eliminate common blank lines, just change the if statement to:
if line1.strip() and line1 == line2:
.strip()
removes all leading and trailing whitespace, so if that's all that's on a line, it will become an empty string ""
, which is considered false.
You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml
They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.
Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.
Now... main (or little) differences you can see right now are:
SCAFFOLDING AND BOILERPLATE GENERATION
Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators
MODULARITY
Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...
BUILD SYSTEM
Mean.io has recently moved to gulp
Mean.js uses grunt
DEPLOYMENT
Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.
DOCUMENTATION
Mean.io has ok docs
Mean.js has AWESOME docs
COMMUNITY
Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth
On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.
MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:
You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..
Have fun!
From the documentation:
Return date object with same year, month and day.
just add onclick handler for anchor tag
onclick="this.parentNode.style.display = 'none'"
or change onclick handler for img tag
onclick="this.parentNode.parentNode.style.display = 'none'"
KOUT[i] is a single element of a list. But you are assigning a list to this element. your func is generating a list.
Run this command if your ufw(Uncomplicatd Firewall) is enabled . Add for Example port 8080
$ sudo ufw allow 8080/tcp
And you can check the status by running
$ sudo ufw status
For more info check : https://linuxhint.com/ubuntu_allow_port_firewall
Atlassian posted a good explanation about Continuous integration vs. continuous delivery vs. continuous deployment.
In a nutshell:
Continuous Integration - is an automation to build and test application whenever new commits are pushed into the branch.
Continuous Delivery - is Continuous Integration + Deploy application to production by "clicking on a button" (Release to customers is often, but on demand).
Continuous Deployment - is Continuous Delivery but without human intervention (Release to customers is on-going).
Within code you will now have access to read the variable as
string myString = Variables.MyVariableName.ToString();
Rico Mariani, the .NET Performance guru, had an article on this very subject. It's not as simple as one might suspect. The basic advice is this:
If your pattern looks like:
x = f1(...) + f2(...) + f3(...) + f4(...)
that's one concat and it's zippy, StringBuilder probably won't help.
If your pattern looks like:
if (...) x += f1(...)
if (...) x += f2(...)
if (...) x += f3(...)
if (...) x += f4(...)
then you probably want StringBuilder.
Yet another article to support this claim comes from Eric Lippert where he describes the optimizations performed on one line +
concatenations in a detailed manner.
67
Reserved.objects.filter(client=client_id).order_by('-check_in')
'-' is indicates Descending order and for Ascending order just give class attribute
My problem was my Target profile didn't have the proper code signing option selected:
Target Menu -> Code Signing -> Code Signing Identity
Choose "iPhone developer" then select the provisional profile you created.
Twitter's bootstrap .span
classes are floated to the left so they won't center by usual means. So, if you want it to center your span
simply add float:none
to your #main
rule.
CSS
#main {
margin:0 auto;
float:none;
}
I faced the same issue, I deleted all provisioning assets from xcode & added them back, and just relaunched Xcode.
My App was loaded on to the device and it worked.
I know this post is old, but if any of you still looking for a simpler solution.
#container .left,
#container .right {
display: inline-block;
}
#container .left {
width: 20%;
float: left;
}
#container .right {
width: 80%;
float: right;
}
I figured out the method I have written below, and it works perfectly for me
in eclipse, follow these simple steps: File -> Import -> type svn -> project from svn -> next -> Create a new repository location -> Next - > You would see "Secure Storage" below the Authentication Menu. Click on this button "Secure Storage" . This is the place where we can delete all the password caches. Now once you are here, follow these:
All the stored passwords are now gone, and you can use your new svn password to sync
There's a great guide here:
https://discussions.apple.com/docs/DOC-3083
However, it didn't work for me first try. I found this tip: run "httpd -t" in Terminao to check the syntax of your config files. Turns out using copy & paste from the tutorial introduced some strange characters. After fixing this, it worked great. There are some links from the guide for adding MySQL as well.
This worked much better for me than MAMP. With MAMP, I was having delays of about 20 seconds or so before changes to the .php file would be reflected in the browser when you refresh, even if you cleared the cache, history, cookies, etc.
This problem was resolved in MAMP PRO, but MAMP PRO had a new issue of its own: the .php files would be downloaded instead of being rendered as a page in the browser! I contacted support and they didn't know what was going on.
The built-in Apache server didn't have any of these issues. Definitely the way to go. The guide below is almost identical to the one above, but it has user comments that are helpful:
http://osxdaily.com/2012/09/02/start-apache-web-server-mac-os-x/#comment-572991
$watch
returns a deregistration function. Calling it would deregister the $watcher
.
var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a '\n'
as the last character, and therefore doing line = line[:-1]
would incorrectly strip off the last character of the line.
The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:
def strip_trailing_newlines(file):
for line in file:
if line[-1] == '\n':
yield line[:-1]
else:
yield line
f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
# do something with line
Make the DropDownStyle to DropDownList
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
Now W3c provides an official difference on their site:
I had this issue too, after following this guide, it was simply 1 additional patch that was required to get past the
Rule "Prior Visual Studio 2010 instances requiring update." failed.
Was to locate this file, and patch my machine
VS10sp1-KB983509.msp
Simply do a file search on the installation media for SQL Server 2012, in my case it was in \redist\VisualStudioShell (whereas in the guide it's listed as being in a different location).
Then hit 're-run'.
if (jsonObj != null && jsonObj.length > 0)
To check if a nested JSON object is empty within a JSONObject:
if (!jsonObject.isNull("key") && jsonObject.getJSONObject("key").length() > 0)
filter_by
is used for simple queries on the column names using regular kwargs, like
db.users.filter_by(name='Joe')
The same can be accomplished with filter
, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:
db.users.filter(db.users.name=='Joe')
You can also write more powerful queries using filter
, such as expressions like:
db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))
When doing pan_list.append(p.last)
you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None
).
You should do something like this :
last_list=[]
if p.last_name==None or p.last_name=="":
pass
last_list.append(p.last) # Here I modify the last_list, no affectation
print last_list
I had the same error message so I went googling a bit I managed to fix it with the following code.
df<-data.frame(words = unlist(words))
words is a character list.
This just in case somebody else needs the output to be a data frame.
Thats work for me:
var jsScripts = [];
jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );
$(jsScripts).each(function( index, value ) {
$.holdReady( true );
$.getScript( value ).done(function(script, status) {
console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');
$.holdReady( false );
});
});
Install registry:2.1.1 or later (you can check the last one, here) and use GET /v2/_catalog to get list.
https://github.com/docker/distribution/blob/master/docs/spec/api.md#listing-repositories
Lista all images by Shell script example: https://gist.github.com/OndrejP/a2386d08e5308b0776c0
GUIDs are 128bits, or
0 through ffffffffffffffffffffffffffffffff (hex) or
0 through 340282366920938463463374607431768211455 (decimal) or
0 through 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 (binary, base 2) or
0 through 91"<b.PX48m!wVmVA?1y (base 95)
So yes, min 20 characters long, which is actually wasting more than 4.25 bits, so you can be just as efficient using smaller bases than 95 as well; base 85 being the smallest possible one that still fits into 20 chars:
0 through -r54lj%NUUO[Hi$c2ym0 (base 85, using 0-9A-Za-z!"#$%&'()*+,- chars)
:-)
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"
StringBuilder builder = new StringBuilder();
Enumerable
.Range(65, 26)
.Select(e => ((char)e).ToString())
.Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
.Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
.OrderBy(e => Guid.NewGuid())
.Take(11)
.ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();
It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.
0.001% duplicates in 100 million.
Using ES6 backticks ``: template literals!
let nick = "Castor", name = "Moon", nuts = 1_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h1>Hello ${nick} ${name}!</h1>_x000D_
_x000D_
You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it and get ${nuts + nuts} nuts!!_x000D_
_x000D_
`
_x000D_
<div id="more"></div>
_x000D_
This way we can include html without encoding quotes, include variables from the DOM, and so on.
It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:
let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);
Use request.get_data()
to get the raw data, regardless of content type. The data is cached and you can subsequently access request.data
, request.json
, request.form
at will.
If you access request.data
first, it will call get_data
with an argument to parse form data first. If the request has a form content type (multipart/form-data
, application/x-www-form-urlencoded
, or application/x-url-encoded
) then the raw data will be consumed. request.data
and request.json
will appear empty in this case.
Miguel de Icaza's announced on his blog on the 17th of Feb 2010 that they are starting work on mono for android which will be called MonoDroid.
This will be similar to MonoTouch on the iphone but for android instead.
It will provide binding to the android UI, so apps will look and feel live native android apps. This will require you to write an android specific UI.
You will however be able to reuse you existing lower level libraries without the need to recompile.
Per Jquery docs
The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.
In order to retrieve the value store in the text box with id txtEmail, you can use
$("#txtEmail").val()
Looking at the source code of the page I took the reCaptcha part and changed the code a bit. Here's the code:
HTML:
<div class="tabs">
<ul class="product-tabs">
<li id="product_tabs_new" class="active"><a href="#">Detailed Description</a></li>
<li id="product_tabs_what"><a href="#">Request Information</a></li>
<li id="product_tabs_wha"><a href="#">Make Offer</a></li>
</ul>
</div>
<div class="tab_content">
<li class="wide">
<div id="product_tabs_new_contents">
<?php $_description = $this->getProduct()->getDescription(); ?>
<?php if ($_description): ?>
<div class="std">
<h2><?php echo $this->__('Details') ?></h2>
<?php echo $this->helper('catalog/output')->productAttribute($this->getProduct(), $_description, 'description') ?>
</div>
<?php endif; ?>
</div>
</li>
<li class="wide">
<label for="recaptcha">Captcha</label>
<div id="more_info_recaptcha_box" class="input-box more_info_recaptcha_box"></div>
</li>
<li class="wide">
<label for="recaptcha">Captcha</label>
<div id="make_offer_recaptcha_box" class="input-box make_offer_recaptcha_box"></div>
</li>
</div>
jQuery:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
var recapExist = false;
// Create our reCaptcha as needed
jQuery('#product_tabs_what').click(function() {
if(recapExist == false) {
Recaptcha.create("<?php echo $publickey; ?>", "more_info_recaptcha_box");
recapExist = "make_offer_recaptcha_box";
} else if(recapExist == 'more_info_recaptcha_box') {
Recaptcha.destroy(); // Don't really need this, but it's the proper way
Recaptcha.create("<?php echo $publickey; ?>", "more_info_recaptcha_box");
recapExist = "make_offer_recaptcha_box";
}
});
jQuery('#product_tabs_wha').click(function() {
if(recapExist == false) {
Recaptcha.create("<?php echo $publickey; ?>", "make_offer_recaptcha_box");
recapExist = "more_info_recaptcha_box";
} else if(recapExist == 'make_offer_recaptcha_box') {
Recaptcha.destroy(); // Don't really need this, but it's the proper way (I think :)
Recaptcha.create("<?php echo $publickey; ?>", "make_offer_recaptcha_box");
recapExist = "more_info_recaptcha_box";
}
});
});
</script>
I am using here simple javascript tab functionality. So, didn't included that code.
When user would click on "Request Information" (#product_tabs_what)
then JS will check if recapExist
is false
or has some value. If it has a value then this will call Recaptcha.destroy();
to destroy the old loaded reCaptcha and will recreate it for this tab. Otherwise this will just create a reCaptcha and will place into the #more_info_recaptcha_box
div. Same as for "Make Offer" #product_tabs_wha
tab.
I'm using version 4.0.3 of MAMP along with phpmyadmin. The top of /Applications/MAMP/bin/phpMyAdmin/libraries/config.default.php reads:
DO NOT EDIT THIS FILE, EDIT config.inc.php INSTEAD !!!
Changing the following line in /Applications/MAMP/bin/phpMyAdmin/config.inc.php and restarting MAMP worked for me.
$cfg['ExecTimeLimit'] = 0;
I set up Visual Studio Code as a default to open .txt file. And next I did use simple command: git config --global core.editor "'C:\Users\UserName\AppData\Local\Code\app-0.7.10\Code.exe\'"
. And everything works pretty well.
I think this will do it:
SELECT * FROM MyTable WHERE mydate > now()::date - 365;
Either use literal non-breaking space symbol (yes, you can copy/paste it), HTML entity, or, if you're dealing with big pre-formatted block, use white-space
CSS property.
Neither. You should NOT use a KeyLIstener.
Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.
Xcode 5.1 no longer provides command line tools in the Preferences section. You now go to https://developer.apple.com/downloads/index.action, and select the command line tools version for your OS X release. The installer puts them in /usr/bin.
To clear things up: FLAG_ACTIVITY_NO_ANIMATION (or android:windowAnimationStyle = @null in the theme) work perfectly fine for both, enter and exit. The problem is, that the enter animation checks if the animation is enabled in the one activity and the exit animation checks it for the other one. So make sure to disable it in both activities.
The default kill
command accepts command names as an alternative to PID. See kill (1). An often occurring trouble is that bash
provides its own kill
which accepts job numbers, like kill %1
, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the bash
version by calling
enable -n kill
For more info see kill
and enable
entries in bash (1).
In my case the error states that the assemly
Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342
is missing.
When I run gacutil.exe /l 'Oracle.DataAccess'
the result was:
The Global Assembly Cache contains the following assemblies:
Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Number of items = 1
At this moment I have just installed the oracle client: win32_11gR2_client
Then I installed oracle developer tools ODTwithODAC112030_deleloper_tool
Now gacutil
is saying:
The Global Assembly Cache contains the following assemblies:
Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Number of items = 2
Fixed, one totally missing assembly case
You may use Map.entrySet()
method:
for (Map.Entry entry : objectSet.entrySet())
{
System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}
Place dependency in pubspec.yaml
flutter_responsive_screen: ^1.0.0
Function hp = Screen(MediaQuery.of(context).size).hp;
Function wp = Screen(MediaQuery.of(context).size).wp;
Example :
return Container(height: hp(27),weight: wp(27));
To clear a permanent redirect, go to chrome://settings/clearBrowserData and from there only clearing "cached images and files" cleared the redirect.
Go to chrome://net-internals. On the right of the top red status bar, click on the down arrow ? to open the drop-down menu, and under the "Tools" group, choose "Clear cache".
As of version 48, this was the only thing that worked for me to clear a cached 301.
open with encoding UTF 16 because of lat and long.
with open(csv_name_here, 'r', encoding="utf-16") as f:
All official methods only tells whether a device is open for network or not,
If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt network detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail
new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {
@Override
public void onConnectionSuccess() {
Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFail(String msg) {
Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
}
}).execute();
Network Call from async Task
public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
private OnConnectionCallback onConnectionCallback;
private Context context;
public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
super();
this.onConnectionCallback = onConnectionCallback;
this.context = con;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void...params) {
if (context == null)
return false;
boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
return isConnected;
}
@Override
protected void onPostExecute(Boolean b) {
super.onPostExecute(b);
if (b) {
onConnectionCallback.onConnectionSuccess();
} else {
String msg = "No Internet Connection";
if (context == null)
msg = "Context is null";
onConnectionCallback.onConnectionFail(msg);
}
}
public interface OnConnectionCallback {
void onConnectionSuccess();
void onConnectionFail(String errorMsg);
}
}
Actual Class which will ping to server
class NetWorkInfoUtility {
public boolean isWifiEnable() {
return isWifiEnable;
}
public void setIsWifiEnable(boolean isWifiEnable) {
this.isWifiEnable = isWifiEnable;
}
public boolean isMobileNetworkAvailable() {
return isMobileNetworkAvailable;
}
public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}
private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;
public boolean isNetWorkAvailableNow(Context context) {
boolean isNetworkAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());
if (isWifiEnable() || isMobileNetworkAvailable()) {
/*Sometime wifi is connected but service provider never connected to internet
so cross check one more time*/
if (isOnline())
isNetworkAvailable = true;
}
return isNetworkAvailable;
}
public boolean isOnline() {
/*Just to check Time delay*/
long t = Calendar.getInstance().getTimeInMillis();
Runtime runtime = Runtime.getRuntime();
try {
/*Pinging to Google server*/
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
long t2 = Calendar.getInstance().getTimeInMillis();
Log.i("NetWork check Time", (t2 - t) + "");
}
return false;
}
}
Checking the Options Over Write Database worked for me :)
You can't do what you ask (and the linked site does not do exactly that either).
You can, however, modify the part of the url after the #
sign, which is called the fragment, like this:
window.location.hash = 'something';
Fragments do not get sent to the server (so, for example, Google itself cannot tell the difference between http://www.google.com/
and http://www.google.com/#something
), but they can be read by Javascript on your page. In turn, this Javascript can decide to perform a different AJAX request based on the value of the fragment, which is how the site you linked to probably does it.
I would go with the System.Environment.NewLine
or a StringBuilder
Then you could add lines with a string builder like this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("brown");
sb.AppendLine("brwn");
textbox1.Text += sb.ToString();
or NewLine like this:
textbox1.Text += System.Environment.NewLine + "brown";
Better:
StringBuilder sb = new StringBuilder(textbox1.Text);
sb.AppendLine("brown");
sb.AppendLine("brwn");
textbox1.Text = sb.ToString();
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.
One option is to create a script file.
Right click on the database -> Tasks -> Generate Scripts
Then you can select all the stored procedures and generate the script with all the sps. So you can find the reference from there.
Or
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'CreatedDate' + '%'
GO
-- Search in Stored Procedure Only
SELECT DISTINCT OBJECT_NAME(OBJECT_ID),
object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'CreatedDate' + '%'
GO
Source SQL SERVER – Find Column Used in Stored Procedure – Search Stored Procedure for Column Name
img
{
max-width: 100%;
min-width: 300px;
height: auto;
}
_tmain
does not exist in C++. main
does.
_tmain
is a Microsoft extension.
main
is, according to the C++ standard, the program's entry point.
It has one of these two signatures:
int main();
int main(int argc, char* argv[]);
Microsoft has added a wmain which replaces the second signature with this:
int wmain(int argc, wchar_t* argv[]);
And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined _tmain
which, if Unicode is enabled, is compiled as wmain
, and otherwise as main
.
As for the second part of your question, the first part of the puzzle is that your main function is wrong. wmain
should take a wchar_t
argument, not char
. Since the compiler doesn't enforce this for the main
function, you get a program where an array of wchar_t
strings are passed to the main
function, which interprets them as char
strings.
Now, in UTF-16, the character set used by Windows when Unicode is enabled, all the ASCII characters are represented as the pair of bytes \0
followed by the ASCII value.
And since the x86 CPU is little-endian, the order of these bytes are swapped, so that the ASCII value comes first, then followed by a null byte.
And in a char string, how is the string usually terminated? Yep, by a null byte. So your program sees a bunch of strings, each one byte long.
In general, you have three options when doing Windows programming:
-W
version of the function. Instead of CreateWindow, call CreateWindowW). And instead of using char
use wchar_t
, and so onchar
for strings.The same applies to the string types defined by windows.h: LPCTSTR resolves to either LPCSTR or LPCWSTR, and for every other type that includes char or wchar_t, a -T- version always exists which can be used instead.
Note that all of this is Microsoft specific. TCHAR is not a standard C++ type, it is a macro defined in windows.h. wmain and _tmain are also defined by Microsoft only.
You can use Boost's lexical_cast
, which wraps this in a more generic interface.
lexical_cast<Target>(Source)
throws bad_lexical_cast
on failure.
If you're using Homebrew /usr/local/bin should already be at the front of $PATH
or at least come before /usr/bin. If you now run brew link --force openssl
in your terminal window, open a new one and run which openssl
in it. It should now show openssl
under /usr/local/bin.
Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists()
function called.
<?php
if(array_key_exists('button1', $_POST)) {
button1();
}
else if(array_key_exists('button2', $_POST)) {
button2();
}
function button1() {
echo "This is Button1 that is selected";
}
function button2() {
echo "This is Button2 that is selected";
}
?>
<form method="post">
<input type="submit" name="button1" class="button" value="Button1" />
<input type="submit" name="button2" class="button" value="Button2" />
</form>
source: geeksforgeeks.org
Try this CSS:
h1 {
left: 0;
line-height: 200px;
margin-top: -100px;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
}
jsFiddle: http://jsfiddle.net/wprw3/
It is possible to do (in the deployed repository)
git fetch
git checkout origin/master -- path/to/file
The fetch will download all the recent changes, but it will not put it in your current checked out code (working area).
The checkout will update the working tree with the particular file from the downloaded changes (origin/master
).
At least this works for me for those little small typo fixes, where it feels weird to create a branch etc just to change one word in a file.
To do this, you will use the %
(mod) operator.
int number; // = some int
while (number > 0) {
print( number % 10);
number = number / 10;
}
The mod operator will give you the remainder of doing int division on a number.
So,
10012 % 10 = 2
Because:
10012 / 10 = 1001, remainder 2
Note: As Paul noted, this will give you the numbers in reverse order. You will need to push them onto a stack and pop them off in reverse order.
Code to print the numbers in the correct order:
int number; // = and int
LinkedList<Integer> stack = new LinkedList<Integer>();
while (number > 0) {
stack.push( number % 10 );
number = number / 10;
}
while (!stack.isEmpty()) {
print(stack.pop());
}
I was using XSSFWorkbook to read .xls, which resulted in InvalidFormatException. I have to use a more generic Workbook and Sheet to make it work.
This post helped me solved my problem.
For security reasons you should never return all the model's fields. I prefer to selectively choose them.
Flask's json encoding now supports UUID, datetime and relationships (and added query
and query_class
for flask_sqlalchemy db.Model
class). I've updated the encoder as follows:
app/json_encoder.py
from sqlalchemy.ext.declarative import DeclarativeMeta
from flask import json
class AlchemyEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o.__class__, DeclarativeMeta):
data = {}
fields = o.__json__() if hasattr(o, '__json__') else dir(o)
for field in [f for f in fields if not f.startswith('_') and f not in ['metadata', 'query', 'query_class']]:
value = o.__getattribute__(field)
try:
json.dumps(value)
data[field] = value
except TypeError:
data[field] = None
return data
return json.JSONEncoder.default(self, o)
app/__init__.py
# json encoding
from app.json_encoder import AlchemyEncoder
app.json_encoder = AlchemyEncoder
With this I can optionally add a __json__
property that returns the list of fields I wish to encode:
app/models.py
class Queue(db.Model):
id = db.Column(db.Integer, primary_key=True)
song_id = db.Column(db.Integer, db.ForeignKey('song.id'), unique=True, nullable=False)
song = db.relationship('Song', lazy='joined')
type = db.Column(db.String(20), server_default=u'audio/mpeg')
src = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
def __init__(self, song):
self.song = song
self.src = song.full_path
def __json__(self):
return ['song', 'src', 'type', 'created_at']
I add @jsonapi to my view, return the resultlist and then my output is as follows:
[
{
"created_at": "Thu, 23 Jul 2015 11:36:53 GMT",
"song":
{
"full_path": "/static/music/Audioslave/Audioslave [2002]/1 Cochise.mp3",
"id": 2,
"path_name": "Audioslave/Audioslave [2002]/1 Cochise.mp3"
},
"src": "/static/music/Audioslave/Audioslave [2002]/1 Cochise.mp3",
"type": "audio/mpeg"
}
]
f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')
Use '\\' for python program in Python version 3 and above.. Error will be resolved..
By the RFC7231 it does not matter and may be empty
How we implement json api standard based solution in the project:
post/put: outputs object attributes as in get (field filter/relations applies the same)
delete: data only contains null (for its a representation of missing object)
status for standard delete: 200
I fixed this programmatically in my software, using C++ Builder.
Before I assign the CHM help file, Application->HelpFile = HelpFileName
, I check to see if it contains the "Zone.Identifier" stream, and when it does, I simply remove it.
String ZIStream(HelpFileName + ":Zone.Identifier") ;
if (FileExists(ZIStream))
{ DeleteFile(ZIStream) ; }
To me it seems like you want the fourth span. If so, you can just do this:
document.getElementById("test").childNodes[3]
or
document.getElementById("test").getElementsByTagName("span")[3]
This last one ensures that there are not any hidden nodes that could mess it up.
In javascript you can do something like this
<input
ref="fileInput"
multiple
type="file"
style="display: none"
@change="trySubmitFile"
>
and the function can be something like this.
trySubmitFile(e) {
if (this.disabled) return;
const files = e.target.files || e.dataTransfer.files;
if (files.length > 5) {
alert('You are only allowed to upload a maximum of 2 files at a time');
}
if (!files.length) return;
for (let i = 0; i < Math.min(files.length, 2); i++) {
this.fileCallback(files[i]);
}
}
I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.
If you're trying to load a DataTable
, then leverage the SqlDataAdapter
instead:
DataTable dt = new DataTable();
using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
{
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.AddWithValue("@parm1", val1);
...
sda.Fill(dt);
}
You don't even need to define the columns. Just create the DataTable
and Fill
it.
Here, cString
is your connection string and sql
is the stored procedure command.
clock() has a often a pretty lousy resolution. If you want to measure time at the millisecond level, one alternative is to use clock_gettime(), as explained in this question.
(Remember that you need to link with -lrt on Linux).
A div can can hold more than one classes either using bootstrap or not
<div class="active dropdown-toggle my-class">Multiple Classes</div>
For applying multiple classes just separate the classes by space.
Take a look at this links you will find many examples
http://getbootstrap.com/css/
http://css-tricks.com/un-bloat-css-by-using-multiple-classes/
As of today, there is an official Android-hosted copy of Volley available on JCenter:
compile 'com.android.volley:volley:1.0.0'
This was compiled from the AOSP volley source code.
You can either use the $_SERVER['REQUEST_TIME']
variable (available since PHP 5.1.0) or the time()
function to get the current Unix timestamp.
If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.
I think you can safely call -= on the event with your handler even if it's not added (if not, you could catch it) -- to make sure it isn't in there before adding.
You may use PopupController for the same one the SDK which shows UIViewController as subview You may check PopupController
Here is sample code for the same
popup = PopupController
.create(self.navigationController!)
.customize(
[
.layout(.center),
.animation(.fadeIn),
.backgroundStyle(.blackFilter(alpha: 0.8)),
.dismissWhenTaps(true),
.scrollable(true)
]
)
.didShowHandler { popup in
}
.didCloseHandler { popup in
}
let container = MTMPlayerAndCardSelectionVC.instance()
container.closeHandler = {() in
self.popup.dismiss()
}
popup.show(container)
I like to use
git stash
This stores all uncommitted changes in the stash. If you want to discard these changes later just git stash drop
(or git stash pop
to restore them).
Though this is technically not the "proper" way to discard changes (as other answers and comments have pointed out).
SourceTree: On the top bar click on icon 'Stash', type its name and create. Then in left vertical menu you can "show" all Stash and delete in right-click menu. There is probably no other way in ST to discard all files at once.
What you describe for the second method only gives you a 1D array:
int *board = new int[10];
This just allocates an array with 10 elements. Perhaps you meant something like this:
int **board = new int*[4];
for (int i = 0; i < 4; i++) {
board[i] = new int[10];
}
In this case, we allocate 4 int*
s and then make each of those point to a dynamically allocated array of 10 int
s.
So now we're comparing that with int* board[4];
. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*
s, as the array will be destroyed at the end of its scope.
The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:
for (int i = 0; i < 4; i++) {
delete[] board[i];
}
delete[] board;
I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4>
or perhaps a std::vector<std::vector<int>>
which you initialise to the appropriate size.
For publicly access use like below:
public arr: Criminal[] = [];
Edit: fixed the problem that @ryryguy pointed out. (Thanks!)
If you want it to be fast, Kaito has the right idea. math.pow
is slow, though. For any standard use you're better off with a recursive function:
def trunc(x: Double, n: Int) = {
def p10(n: Int, pow: Long = 10): Long = if (n==0) pow else p10(n-1,pow*10)
if (n < 0) {
val m = p10(-n).toDouble
math.round(x/m) * m
}
else {
val m = p10(n).toDouble
math.round(x*m) / m
}
}
This is about 10x faster if you're within the range of Long
(i.e 18 digits), so you can round at anywhere between 10^18 and 10^-18.
Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.
The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService
" as the service reference name, that will generate the type TestUploaderWebService.Service1
. That class will have a method named GetFileListOnWebServer
, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:
string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
proxy = new TestUploaderWebService.Service1();
files = proxy.GetFileListOnWebServer();
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.
What exactly do you want to know?
The shared library soname? That's part of the filename, libstdc++.so.6
, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname
.
The minor revision number? You should be able to get that by simply checking what the symlink points to:
$ ls -l /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16
That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6
version, which corresponds to the GLIBCXX_3.4.16
symbol versions.
Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++
and libstdc++.so
you can get that from:
$ g++ -dumpversion
4.6.3
Or, on most distros, you can just ask the package manager. On my Fedora host that's
$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686
As other answers have said, you can map releases to library versions by checking the ABI docs
Be careful with rebase. If you're sharing your develop branch with anybody, rebase can make a mess of things. Rebase is good only for your own local branches.
Rule of thumb, if you've pushed the branch to origin, don't use rebase. Instead, use merge.
It is possible to construct a struct inside the function arguments:
function({ .variable = PUT_DATA_HERE });
We have just been going through this same issue, but the other way around. That is, we store dollar amounts as DECIMAL, but now we're finding that, for example, MySQL was calculating a value of 4.389999999993, but when storing this into the DECIMAL field, it was storing it as 4.38 instead of 4.39 like we wanted it to. So, though DOUBLE may cause rounding issues, it seems that DECIMAL can cause some truncating issues as well.
IEnumerable: IEnumerable is best suitable for working with in-memory collection (or local queries). IEnumerable doesn’t move between items, it is forward only collection.
IQueryable: IQueryable best suits for remote data source, like a database or web service (or remote queries). IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).
So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable
You can use a backslash at the end of a line.
So this:
a\
b\
c
will then look like:
a
b
c
Notice that there is no backslash at the end of the last line (after the 'c' character).
Because most of the answer here didn't work, or only partially worked:
body.modal-open .modal[style]:not([style='display: none;']) {
display: flex !important;
height: 100%;
}
body.modal-open .modal[style]:not([style='display: none;']) .modal-dialog {
margin: auto;
}
You have to use the [style] selector to only apply the style on the modal that is currently active instead of all the modals. .in
would have been great, but it appears to be added only after the transition is complete which is too late and makes for some really bad transitions. Fortunately it appears bootstrap always applies a style attribute on the modal just as it is starting to show so this is a bit hacky, but it works.
The :not([style='display: none;'])
portion is a workaround to bootstrap not correctly removing the style attribute and instead setting the style display to none when you close the dialog.
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
You might also find it useful to know generally what these data types are used for:
:string
- is for small data types such as a title. (Should you choose string or text?):text
- is for longer pieces of textual data, such as a paragraph of information:binary
- is for storing data such as images, audio, or movies.:boolean
- is for storing true or false values.:date
- store only the date:datetime
- store the date and time into a column. :time
- is for time only:timestamp
- for storing date and time into a column.(What's the difference between datetime and timestamp?):decimal
- is for decimals (example of how to use decimals).:float
- is for decimals. (What's the difference between decimal and float?):integer
- is for whole numbers.:primary_key
- unique key that can uniquely identify each row in a tableThere's also references used to create associations. But, I'm not sure this is an actual data type.
New Rails 4 datatypes available in PostgreSQL:
:hstore
- storing key/value pairs within a single value (learn more about this new data type):array
- an arrangement of numbers or strings in a particular row (learn more about it and see examples):cidr_address
- used for IPv4 or IPv6 host addresses:inet_address
- used for IPv4 or IPv6 host addresses, same as cidr_address but it also accepts values with nonzero bits to the right of the netmask:mac_address
- used for MAC host addressesLearn more about the address datatypes here and here.
Also, here's the official guide on migrations: http://edgeguides.rubyonrails.org/migrations.html
If you want to delete all subdirectories under /path/to/base
, for example
/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3
but you don't want to delete the root /path/to/base
, you have to add -mindepth 1
and -maxdepth 1
options, which will access only the subdirectories under /path/to/base
-mindepth 1
excludes the root /path/to/base
from the matches.
-maxdepth 1
will ONLY match subdirectories immediately under /path/to/base
such as /path/to/base/dir1
, /path/to/base/dir2
and /path/to/base/dir3
but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:
/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1
and so forth.
So , to delete all the sub-directories under /path/to/base
which are older than 10 days;
find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf
In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.
glutSolidSphere
is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?
#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>
// your framework of choice here
class SolidSphere
{
protected:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
public:
SolidSphere(float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = x;
*n++ = y;
*n++ = z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
}
}
void draw(GLfloat x, GLfloat y, GLfloat z)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,z);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();
}
};
SolidSphere sphere(1, 12, 24);
void display()
{
int const win_width = …; // retrieve window dimensions from
int const win_height = …; // framework of choice here
float const win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#ifdef DRAW_WIREFRAME
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
sphere.draw(0, 0, -5);
swapBuffers();
}
int main(int argc, char *argv[])
{
// initialize and register your framework of choice here
return 0;
}
I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"
Hope it helps
In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.
According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.
You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com
NB: this is a copy of my answer on this thread Synchronous XMLHttpRequest warning and <script> (I visited both when looking for a solution)
I have one real-world example where I have used Node.js. The company where I work got one client who wanted to have a simple static HTML website. This website is for selling one item using PayPal and the client also wanted to have a counter which shows the amount of sold items. Client expected to have huge amount of visitors to this website. I decided to make the counter using Node.js and the Express.js framework.
The Node.js application was simple. Get the sold items amount from a Redis database, increase the counter when item is sold and serve the counter value to users via the API.
Some reasons why I chose to use Node.js in this case
In this case, Node.js was an awesome choice.
Short answer: Yes, it can be NULL or duplicate.
I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.
Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.
Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.
Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK.
I just put into constructor something by reference, so the subform can change its value and main form can get new or modified object from subform.
delete
will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
Note that it is not in fact set to the value undefined
, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty
when logging the array.
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
myArray.splice(start, deleteCount)
actually removes the element, reindexes the array, and changes its length.
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
Append the following parameter to the Youtube-URL:
144p: &vq=tiny
240p: &vq=small
360p: &vq=medium
480p: &vq=large
720p: &vq=hd720
For instance:
src="http://www.youtube.com/watch?v=oDOXeO9fAg4"
becomes:
src="http://www.youtube.com/watch?v=oDOXeO9fAg4&vq=large"
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
I spent a few hours on this too ... and agree that FLAG_ACTIVITY_CLEAR_TOP sounds like what you'd want: clear the entire stack, except for the activity being launched, so the Back button exits the application. Yet as Mike Repass mentioned, FLAG_ACTIVITY_CLEAR_TOP only works when the activity you're launching is already in the stack; when the activity's not there, the flag doesn't do anything.
What to do? Put the activity being launching in the stack with FLAG_ACTIVITY_NEW_TASK, which makes that activity the start of a new task on the history stack. Then add the FLAG_ACTIVITY_CLEAR_TOP flag.
Now, when FLAG_ACTIVITY_CLEAR_TOP goes to find the new activity in the stack, it'll be there and be pulled up before everything else is cleared.
Here's my logout function; the View parameter is the button to which the function's attached.
public void onLogoutClick(final View view) {
Intent i = new Intent(this, Splash.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
Use the Font Class to set the control's font and styles.
Try Font Constructor (String, Single)
Label lab = new Label();
lab.Text ="Font Bold at 24";
lab.Font = new Font("Arial", 20);
or
lab.Font = new Font(FontFamily.GenericSansSerif,
12.0F, FontStyle.Bold);
To get installed fonts refer this - .NET System.Drawing.Font - Get Available Sizes and Styles
Well it does this because you are converting a 64 bits pointer to an 32 bits integer so you loose information.
You can use a 64 bits integer instead howerver I usually use a function with the right prototype and I cast the function type : eg.
void thread_func(int arg){
...
}
and I create the thread like this :
pthread_create(&tid, NULL, (void*(*)(void*))thread_func, (void*)arg);
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
If you want to use the version of Javascript called ES 2015 (aka ES6) or later, you can use template strings introduced by ES 2015 and recommended by some guidelines (like Airbnb's style guide):
const after = "test";
const mystr = `This is: ${after}`;
I manage to apply gradient border using this code..
public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int newW = w - (leftRightThk * 2);
int newH = h - (bottomThk + padTop);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(w, h, conf);
Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas c = new Canvas(bmp);
// Left
int leftMargin = (leftRightThk + 7)/2;
Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
paint.setShader(lshader);
c.drawRect(0, padTop, leftMargin, newH, paint);
// Right
Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
paint.setShader(rshader);
c.drawRect(newW, padTop, w, newH, paint);
// Bottom
Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
paint.setShader(bshader);
c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
c.drawBitmap(sbmp, leftRightThk, 0, null);
return bmp;
}
hope this helps !
Have you instaled the J2EE? If you installed just de standard (J2SE) it won´t find.
this will solve, it will accept empty string or exact an email id
"^$|^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
you need to fill only starting 2-3 numbers (or text for that matter) and then drag the range down using fill handle. MS Excel will identify the series by itself and will fill the range till where you drag down the range. The below image shows the ‘Fill Handle’.
With kudos to all the answers that correctly suggest removing the Ubuntu yarn
package and installing Yarn through NPM, here is a detailed answer with explanation (and, be warned, opinions):
The reason for the No such file or directory
error from yarn install
is that you are not using the "correct" Yarn: the software you get when you install yarn
using the Ubuntu software sources is the "yarn" scenario testing tool from the cmdtest blackbox testing suite. This is likely not what you meant as Yarn is also a popular development lifecycle tool for Javascript application (similar to Make, Maven and friends).
The Javascript Yarn tool is not available from Ubuntu software sources but can be installed by NPM (which is another development lifecycle tool that Yarn aims to replace - so that's awkward...).
To make Yarn available in Ubuntu, start by removing cmdtest
and its tools:
$ sudo apt purge cmdtest
Then make sure NPM is installed:
$ sudo apt install npm
Then use NPM to install Yarn:
$ npm install -g yarn
Note: using npm install -g
will install a Javascript package for your current user account, which should be fine for most purposes. If you want to install Yarn for all users, you can use sudo
for the NPM command, but that is not recommended: NPM packages are rarely audited for security in the context of a multi-user operating system and installing some packages might even break when installing them as "root". NPM used to warn against running it with sudo
and the main reason it is not doing so today is that it annoys people that use sandboxed "root-like" environments (such as Docker) for building and deploying Javascript applications for single-user servers.
My issue was that I was using 'React.PureComponent' when I should have been using 'React.Component'.
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
As mentioned, you cannot cast it directly. One possible solution is to have those generic types inherit from a non-generic interface, in which case you can still invoke methods on it without reflection. Using reflection, you can pass the mapped object to any method expecting it, then the cast will be performed for you. So if you have a method called Accept expecting a MessageProcessor as a parameter, then you can find it and invoke it dynamically.
Try this:
try
{
throw new InvalidEmployeeTypeException();
input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
//do error handling
}
continue;
Use getch()
:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
Windows alternative should be _getch().
If you're using Windows, this should be the full example:
#include <conio.h>
#include <ctype.h>
int main( void )
{
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
_getch();
}
P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.
And if you want to create the list with some elements to start with:
var emailList = new List<EmailData>
{
new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
new EmailData {.......}
};
Yes.
ThisWorkbook.RefreshAll
Or, if your Excel version is old enough,
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
For Each Pivot in Sheet.PivotTables
Pivot.RefreshTable
Pivot.Update
Next
Next
On RHEL6.6 only this works (note the use of export
):
/etc/sysconfig/docker
export http_proxy="http://myproxy.example.com:8080"
export https_proxy="http://myproxy.example.com:8080"
NOTE: Both can use the http
protocol.)
Nice solutions, but I wonder why nobody is giving the solution for windows.
If you are using windows you just have to "Run as Administrator" the cmd.
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
Here is how you do it:
In .h
#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif
extern "C" // Only if you are using C++ rather than C
{
EXPORT int __stdcall add2(int num);
EXPORT int __stdcall mult(int num1, int num2);
}
in .cpp
extern "C" // Only if you are using C++ rather than C
{
EXPORT int __stdcall add2(int num)
{
return num + 2;
}
EXPORT int __stdcall mult(int num1, int num2)
{
int product;
product = num1 * num2;
return product;
}
}
The macro tells your module (i.e your .cpp files) that they are providing the dll stuff to the outside world. People who incude your .h file want to import the same functions, so they sell EXPORT as telling the linker to import. You need to add BUILD_DLL to the project compile options, and you might want to rename it to something obviously specific to your project (in case a dll uses your dll).
You might also need to create a .def file to rename the functions and de-obfuscate the names (C/C++ mangles those names). This blog entry might be an interesting launching off point about that.
Loading your own custom dlls is just like loading system dlls. Just ensure that the DLL is on your system path. C:\windows\ or the working dir of your application are an easy place to put your dll.
Try this:
re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)
I think your biggest problem is that you're expecting the ^
and $
anchors to match linefeeds, but they don't. In multiline mode, ^
matches the position immediately following a newline and $
matches the position immediately preceding a newline.
Be aware, too, that a newline can consist of a linefeed (\n
), a carriage-return (\r
), or a carriage-return+linefeed (\r\n
). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:
re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)
BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.
Official Ruby FAQ: What is the difference between class variables and class instance variables?
The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.
Class variables in some way can be seen as global variables within the context of an inheritance hierarchy, with all the problems that come with global variables. For instance, a class variable might (accidentally) be reassigned by any of its subclasses, affecting all other classes:
class Woof
@@sound = "woof"
def self.sound
@@sound
end
end
Woof.sound # => "woof"
class LoudWoof < Woof
@@sound = "WOOF"
end
LoudWoof.sound # => "WOOF"
Woof.sound # => "WOOF" (!)
Or, an ancestor class might later be reopened and changed, with possibly surprising effects:
class Foo
@@var = "foo"
def self.var
@@var
end
end
Foo.var # => "foo" (as expected)
class Object
@@var = "object"
end
Foo.var # => "object" (!)
So, unless you exactly know what you are doing and explicitly need this kind of behavior, you better should use class instance variables.
If you just want to view the changes to a particular file between the working copy and a particular commit using GitLens, the currently accepted answer can make it difficult to find the file you're interested in if many files have changed between the versions.
Instead, go to the file explorer in the side bar and right click on the file, go to Open Changes > Open Changes with Revision... (or Open Changes with Branch or Tag...).
I think todays, it is better to use, but only with C++17.
#include <type_traits>
template <typename T>
void foo() {
if constexpr (std::is_same_v<T, animal>) {
// use type specific operations...
}
}
If you use some type specific operations in if expression body without constexpr
, this code will not compile.
Some times you may make silly mistakes like writing insert query on the same .sql file (in the same workspace/tab) so once you execute the insert query where your create query was written just above and already executed, it will again start executing along with the insert query.
This is the reason why we are getting the object name (table name) exists already, since it's getting executed for the second time.
So go to a separate tab to write the insert or drop or whatever queries you are about to execute.
Or else use comment lines preceding all queries in the same workspace like
CREATE -- …
-- Insert query
INSERT INTO -- …
Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.
For i = 0 To d.Count - 1
s = d.Items()(i)
Debug.Print s
Next i()
KEYS works the same way
For i = 0 To d.Count - 1
Debug.Print d.Keys()(i), d.Items()(i)
Next i
This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".
Debug.Print Split("A,B,C,D", ",")(2)
SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.
Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.
Add this to your css:
html, body {
height:100%;
}
If you say height:100%, you mean '100% of the parent element'. If the parent element has no specified height, nothing will happen. You only set 100% on body, but you also need to add it to html.
This is one way to do it:
SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
2 /
Type created
SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
2 BEGIN
3 FOR i IN 1..t_in.count LOOP
4 dbms_output.put_line(t_in(i));
5 END LOOP;
6 END;
7 /
Procedure created
SQL> DECLARE
2 v_t MyType;
3 BEGIN
4 v_t := MyType();
5 v_t.EXTEND(10);
6 v_t(1) := 'this is a test';
7 v_t(2) := 'A second test line';
8 testing(v_t);
9 END;
10 /
this is a test
A second test line
To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:
SQL> CREATE OR REPLACE PACKAGE p IS
2 TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
3
4 PROCEDURE pp (inp p_type);
5 END p;
6 /
Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
2 PROCEDURE pp (inp p_type) IS
3 BEGIN
4 FOR i IN 1..inp.count LOOP
5 dbms_output.put_line(inp(i));
6 END LOOP;
7 END pp;
8 END p;
9 /
Package body created
SQL> DECLARE
2 v_t p.p_type;
3 BEGIN
4 v_t(1) := 'this is a test of p';
5 v_t(2) := 'A second test line for p';
6 p.pp(v_t);
7 END;
8 /
this is a test of p
A second test line for p
PL/SQL procedure successfully completed
SQL>
This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.
For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient
. Make sure that you import javax.persistence.transient
and not some other package.
It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.
However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")
So as long as the method is present in xInterface
, and your class implements xInterface
, you won't be able to make the method static.
If you can't change the interface (or don't want to), there are several things you can do:
xInterface
), and a static method. The instance method will consist of a single line that delegates to the static method.On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:
\i /usr/share/postgresql/8.4/contrib/dblink.sql
you might need to install the contrib packages: sudo apt-get install postgresql-contrib
For kotlin you can use:
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
Note: for parameters of onItemSelected
method I use custom variable names
If you declare the method as synchronized (as you're doing by typing public synchronized void addA()
) you synchronize on the whole object, so two thread accessing a different variable from this same object would block each other anyway.
If you want to synchronize only on one variable at a time, so two threads won't block each other while accessing different variables, you have synchronize on them separately in synchronized ()
blocks. If a
and b
were object references you would use:
public void addA() {
synchronized( a ) {
a++;
}
}
public void addB() {
synchronized( b ) {
b++;
}
}
But since they're primitives you can't do this.
I would suggest you to use AtomicInteger instead:
import java.util.concurrent.atomic.AtomicInteger;
class X {
AtomicInteger a;
AtomicInteger b;
public void addA(){
a.incrementAndGet();
}
public void addB(){
b.incrementAndGet();
}
}
It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html
and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.
It's an iterator returned by the filter function.
If you want a list, just do
list(filter(f, range(2, 25)))
Nonetheless, you can just iterate over this object with a for
loop.
for e in filter(f, range(2, 25)):
do_stuff(e)
From Java 9 there is some optimizations in replace method.
In Java 8 it uses a regex.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
From Java 9 and on.
And Stringlatin implementation.
Which perform way better.
This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).
I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.
Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
well the only thing that will work is
python -m pip install pip==
you can and should run it under IDE terminal (mine was pycharm)
the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.
Either put it on one line or append on each line :o)
Sqlyog must be trimming white spaces on each line which explains why its working.
Example:
$qr2="INSERT INTO wp_bp_activity
(
user_id,
(this stuff)component,
(is) `type`,
(a) `action`,
(problem) content,
primary_link,
item_id,....
There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:
cat /proc/cpuinfo
Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.
Try this..
select starttime,endtime, case
when DATEDIFF(minute,starttime,endtime) < 60 then DATEDIFF(minute,starttime,endtime)
when DATEDIFF(minute,starttime,endtime) >= 60
then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416
All You need is DateDiff..
If you want a pure CSS solution, this trick works very well - use the transform object. This also works with images when they're cached or not:
CSS:
.main_container{
position: relative;
width: 500px;
height: 300px;
background-color: #cccccc;
}
.center_horizontally{
position: absolute;
width: 100px;
height: 100px;
background-color: green;
left: 50%;
top: 0;
transform: translate(-50%,0);
}
.center_vertically{
position: absolute;
top: 50%;
left: 0;
width: 100px;
height: 100px;
background-color: blue;
transform: translate(0,-50%);
}
.center{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
transform: translate(-50%,-50%);
}
HTML:
<div class="main_container">
<div class="center_horizontally"></div>
<div class="center_vertically"></div>
<div class="center"></div>
</div>
</div
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
For List<List<List<x>>>
and so on, use
list.SelectMany(x => x.SelectMany(y => y)).ToList();
This has been posted in a comment, but it does deserves a separate reply in my opinion.
You can compare two images using functions from PIL.
import Image
import ImageChops
im1 = Image.open("splash.png")
im2 = Image.open("splash2.png")
diff = ImageChops.difference(im2, im1)
The diff object is an image in which every pixel is the result of the subtraction of the color values of that pixel in the second image from the first image. Using the diff image you can do several things. The simplest one is the diff.getbbox()
function. It will tell you the minimal rectangle that contains all the changes between your two images.
You can probably implement approximations of the other stuff mentioned here using functions from PIL as well.
In .NET 4 you can now write:
flags.HasFlag(FlagsEnum.Bit4)
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
If you have a code like
int arr[10] = {0, 5, 3, 64};
, and you want to append or add a value to next index, you can simply add it by typing a[5] = 5
.
The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8
to index 9, I can do it by the above concept prior to filling up before indices.
But in python by using list.append()
you can do it by continued indices.
All of the responses refer to BootStrap 2 typeahead, which is no longer present in BootStrap 3.
For anyone else directed here looking for an AJAX example using the new post-Bootstrap Twitter typeahead.js, here's a working example. The syntax is a little different:
$('#mytextquery').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
limit: 12,
async: true,
source: function (query, processSync, processAsync) {
processSync(['This suggestion appears immediately', 'This one too']);
return $.ajax({
url: "/ajax/myfilter.php",
type: 'GET',
data: {query: query},
dataType: 'json',
success: function (json) {
// in this example, json is simply an array of strings
return processAsync(json);
}
});
}
});
This example uses both synchronous (the call to processSync) and asynchronous suggestion, so you'd see some options appear immediately, then others are added. You can just use one or the other.
There are lots of bindable events and some very powerful options, including working with objects rather than strings, in which case you'd use your own custom display function to render your items as text.
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
What finally worked for me was:
[self.tabBar setTintColor:[UIColor redColor]];
[self.tabBar setBarTintColor:[UIColor yellowColor]];
It because every time
void pthread_exit(void *ret);
will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().
Now at
int pthread_join(pthread_t tid, void **ret);
will be always called from where thread is created so here to accept that returned pointer you need double pointer ..
i think this code will help you to understand this
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
void* thread_function(void *ignoredInThisExample)
{
char *a = malloc(10);
strcpy(a,"hello world");
pthread_exit((void*)a);
}
int main()
{
pthread_t thread_id;
char *b;
pthread_create (&thread_id, NULL,&thread_function, NULL);
pthread_join(thread_id,(void**)&b); //here we are reciving one pointer
value so to use that we need double pointer
printf("b is %s\n",b);
free(b); // lets free the memory
}
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
From proper way to do uitextfield text change call back:
I catch the characters sent to a UITextField control something like this:
// Add a "textFieldDidChange" notification method to the text field control.
In Objective-C:
[textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
In Swift:
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
Then in the
textFieldDidChange
method you can examine the contents of the textField, and reload your table view as needed.
You could use that and put calculateAndUpdateTextFields as your selector
.
If you use spring this a better way
Is there any way to create form with multiple submit buttons on Spring MVC using annotations?
How about a bitwise operator? Instead of strings, you're dealing with "enums", which looks more "elegant."
// Declare slider's state "enum"
var SliderOne = {
A: 1,
B: 2,
C: 4,
D: 8,
E: 16
};
var SliderTwo = {
A: 32,
B: 64,
C: 128,
D: 256,
E: 512
};
// Set state
var s1 = SliderOne.A,
s2 = SliderTwo.B;
// Switch state
switch (s1 | s2) {
case SliderOne.A | SliderTwo.A :
case SliderOne.A | SliderTwo.C :
// Logic when State #1 is A, and State #2 is either A or C
break;
case SliderOne.B | SliderTwo.C :
// Logic when State #1 is B, and State #2 is C
break;
case SliderOne.E | SliderTwo.E :
default:
// Logic when State #1 is E, and State #2 is E or
// none of above match
break;
}
I however agree with others, 25 cases in a switch-case logic is not too pretty, and if-else might, in some cases, "look" better. Anyway.
np.isnan
can be applied to NumPy arrays of native dtype (such as np.float64):
In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)
but raises TypeError when applied to object arrays:
In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Since you have Pandas, you could use pd.isnull
instead -- it can accept NumPy arrays of object or native dtypes:
In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)
In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)
Note that None
is also considered a null value in object arrays.
The following code will set the media stream volume to max:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
Try this, by for Loop
<form method="post">
<?php
for ($i=1; $i <5 ; $i++)
{
echo'<input type="checkbox" value="'.$i.'" name="checkbox[]"/>';
}
?>
<input type="submit" name="submit" class="form-control" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
$check=implode(", ", $_POST['checkbox']);
print_r($check);
}
?>
What about this:
otherfunction(thing_collection, thing)
Rather than expose something so implementation-dependent like a list index in a function interface, pass the collection and the thing and let otherfunction deal with the "test for membership" issues. If otherfunction is written to be collection-type-agnostic, then it would probably start with:
if thing in thing_collection:
... proceed with operation on thing
which will work if thing_collection is a list, tuple, set, or dict.
This is possibly clearer than:
if thing_index != MAGIC_VALUE_INDICATING_NOT_A_MEMBER:
which is the code you already have in otherfunction.
A generic solution with a timeout:
import time
def onerror_retry(exception, callback, timeout=2, timedelta=.1):
end_time = time.time() + timeout
while True:
try:
yield callback()
break
except exception:
if time.time() > end_time:
raise
elif timedelta > 0:
time.sleep(timedelta)
Usage:
for retry in onerror_retry(SomeSpecificException, do_stuff):
retry()
There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.
Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!
let resizerForCenter = new Resizer('center')
resizerForCenter.initResizer()
See it in action with CodeSandbox:
In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:
Or with the code snippet:
const html = document.querySelector('html')_x000D_
_x000D_
class Resizer {_x000D_
constructor(elemId) {_x000D_
this._elem = document.getElementById(elemId)_x000D_
/**_x000D_
* Stored binded context handlers for method passed to eventListeners!_x000D_
* _x000D_
* See: https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions_x000D_
*/_x000D_
this._checkBorderHandler = this._checkBorder.bind(this)_x000D_
this._doResizeHandler = this._doResize.bind(this)_x000D_
this._initResizerHandler = this.initResizer.bind(this)_x000D_
this._onResizeHandler = this._onResize.bind(this)_x000D_
}_x000D_
_x000D_
initResizer() {_x000D_
this.stopResizer()_x000D_
this._beginResizer()_x000D_
}_x000D_
_x000D_
_beginResizer() {_x000D_
this._elem.addEventListener('mousemove', this._checkBorderHandler, false)_x000D_
}_x000D_
_x000D_
stopResizer() {_x000D_
html.style.cursor = 'default'_x000D_
this._elem.style.cursor = 'default'_x000D_
_x000D_
window.removeEventListener('mousemove', this._doResizeHandler, false)_x000D_
window.removeEventListener('mouseup', this._initResizerHandler, false)_x000D_
_x000D_
this._elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)_x000D_
}_x000D_
_x000D_
_doResize(e) {_x000D_
let elem = this._elem_x000D_
_x000D_
let boxSizing = getComputedStyle(elem).boxSizing_x000D_
let borderRight = 0_x000D_
let borderLeft = 0_x000D_
let borderTop = 0_x000D_
let borderBottom = 0_x000D_
_x000D_
let paddingRight = 0_x000D_
let paddingLeft = 0_x000D_
let paddingTop = 0_x000D_
let paddingBottom = 0_x000D_
_x000D_
switch (boxSizing) {_x000D_
case 'content-box':_x000D_
paddingRight = parseInt(getComputedStyle(elem).paddingRight)_x000D_
paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)_x000D_
paddingTop = parseInt(getComputedStyle(elem).paddingTop)_x000D_
paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)_x000D_
break_x000D_
case 'border-box':_x000D_
borderRight = parseInt(getComputedStyle(elem).borderRight)_x000D_
borderLeft = parseInt(getComputedStyle(elem).borderLeft)_x000D_
borderTop = parseInt(getComputedStyle(elem).borderTop)_x000D_
borderBottom = parseInt(getComputedStyle(elem).borderBottom)_x000D_
break_x000D_
default: break_x000D_
}_x000D_
_x000D_
let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)_x000D_
let verticalAdjustment = (paddingTop + paddingBottom) - (borderTop + borderBottom)_x000D_
_x000D_
let newWidth = elem.clientWidth + e.movementX - horizontalAdjustment + 'px'_x000D_
let newHeight = elem.clientHeight + e.movementY - verticalAdjustment + 'px'_x000D_
_x000D_
let cursorType = getComputedStyle(elem).cursor_x000D_
switch (cursorType) {_x000D_
case 'all-scroll':_x000D_
elem.style.width = newWidth_x000D_
elem.style.height = newHeight_x000D_
break_x000D_
case 'col-resize':_x000D_
elem.style.width = newWidth_x000D_
break_x000D_
case 'row-resize':_x000D_
elem.style.height = newHeight_x000D_
break_x000D_
default: break_x000D_
}_x000D_
}_x000D_
_x000D_
_onResize(e) {_x000D_
// On resizing state!_x000D_
let elem = e.target_x000D_
let newCursorType = undefined_x000D_
let cursorType = getComputedStyle(elem).cursor_x000D_
switch (cursorType) {_x000D_
case 'nwse-resize':_x000D_
newCursorType = 'all-scroll'_x000D_
break_x000D_
case 'ew-resize':_x000D_
newCursorType = 'col-resize'_x000D_
break_x000D_
case 'ns-resize':_x000D_
newCursorType = 'row-resize'_x000D_
break_x000D_
default: break_x000D_
}_x000D_
_x000D_
html.style.cursor = newCursorType // Avoid cursor's flickering _x000D_
elem.style.cursor = newCursorType_x000D_
_x000D_
// Remove what is not necessary, and could have side effects!_x000D_
elem.removeEventListener('mousemove', this._checkBorderHandler, false);_x000D_
_x000D_
// Events on resizing state_x000D_
/**_x000D_
* We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position_x000D_
*/_x000D_
window.addEventListener('mousemove', this._doResizeHandler, false);_x000D_
window.addEventListener('mouseup', this._initResizerHandler, false);_x000D_
}_x000D_
_x000D_
_checkBorder(e) {_x000D_
const elem = e.target_x000D_
const borderSensitivity = 5_x000D_
const coor = getCoordenatesCursor(e)_x000D_
const onRightBorder = ((coor.x + borderSensitivity) > elem.scrollWidth)_x000D_
const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)_x000D_
const onBottomRightCorner = (onRightBorder && onBottomBorder)_x000D_
_x000D_
if (onBottomRightCorner) {_x000D_
elem.style.cursor = 'nwse-resize'_x000D_
} else if (onRightBorder) {_x000D_
elem.style.cursor = 'ew-resize'_x000D_
} else if (onBottomBorder) {_x000D_
elem.style.cursor = 'ns-resize'_x000D_
} else {_x000D_
elem.style.cursor = 'auto'_x000D_
}_x000D_
_x000D_
if (onRightBorder || onBottomBorder) {_x000D_
elem.addEventListener('mousedown', this._onResizeHandler, false)_x000D_
} else {_x000D_
elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
function getCoordenatesCursor(e) {_x000D_
let elem = e.target;_x000D_
_x000D_
// Get the Viewport-relative coordinates of cursor._x000D_
let viewportX = e.clientX_x000D_
let viewportY = e.clientY_x000D_
_x000D_
// Viewport-relative position of the target element._x000D_
let elemRectangle = elem.getBoundingClientRect()_x000D_
_x000D_
// The function returns the largest integer less than or equal to a given number._x000D_
let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth_x000D_
let y = Math.floor(viewportY - elemRectangle.top) // - elem.scrollHeight_x000D_
_x000D_
return {x, y}_x000D_
}_x000D_
_x000D_
let resizerForCenter = new Resizer('center')_x000D_
resizerForCenter.initResizer()_x000D_
_x000D_
let resizerForLeft = new Resizer('left')_x000D_
resizerForLeft.initResizer()_x000D_
_x000D_
setTimeout(handler, 10000, true); // 10s_x000D_
_x000D_
function handler() {_x000D_
resizerForCenter.stopResizer()_x000D_
}
_x000D_
body {_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
/* box-sizing: border-box; */_x000D_
position: relative;_x000D_
float:left;_x000D_
overflow: hidden;_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
background-color: blueviolet;_x000D_
}_x000D_
#center {_x000D_
background-color:lawngreen ;_x000D_
}_x000D_
#right {_x000D_
background: blueviolet;_x000D_
}_x000D_
#wrapper {_x000D_
border: 5px solid hotpink;_x000D_
display: inline-block;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
<title>Resizer v0.0.1</title>_x000D_
</head>_x000D_
<body>_x000D_
<div id="wrapper">_x000D_
<div id="left">Left</div>_x000D_
<div id="center">Center</div>_x000D_
<div id="right">Right</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
bigint
)?Most of these answers fail on large integers (253 and larger): Bitwise tests(e.g. (x | 0) === x
), testing typeof x === 'number'
, regular int functions (e.g. parseInt
), regular arithmetics fail on large integers. This can be resolved by using BigInt
.
I've compiled several answers into one snippet to show the results. Most outright fail with large integers, while others work, except when passed the type BigInt
(e.g. 1n
). I've not included duplicate answers and have also left out any answers that allow decimals or don't attempt to test type)
// these all fail
n = 1000000000000000000000000000000
b = 1n
// These all fail on large integers
//https://stackoverflow.com/a/14636652/3600709
console.log('fail',1,n === parseInt(n, 10))
//https://stackoverflow.com/a/14794066/3600709
console.log('fail',2,!isNaN(n) && parseInt(Number(n)) == n && !isNaN(parseInt(n, 10)))
console.log('fail',2,!isNaN(n) && (parseFloat(n) | 0) === parseFloat(n))
console.log('fail',2,!isNaN(n) && (function(x) { return (x | 0) === x; })(parseFloat(n)))
//https://stackoverflow.com/a/21742529/3600709
console.log('fail',3,n == ~~n)
//https://stackoverflow.com/a/28211631/3600709
console.log('fail',4,!isNaN(n) && parseInt(n) == parseFloat(n))
//https://stackoverflow.com/a/41854178/3600709
console.log('fail',5,String(parseInt(n, 10)) === String(n))
// These ones work for integers, but not BigInt types (e.g. 1n)
//https://stackoverflow.com/a/14636725/3600709
console.log('partial',1,typeof n==='number' && (n%1)===0) // this one works
console.log('partial',1,typeof b==='number' && (b%1)===0) // this one fails
//https://stackoverflow.com/a/27424770/3600709
console.log('partial',2,Number.isInteger(n)) // this one works
console.log('partial',2,Number.isInteger(b)) // this one fails
//https://stackoverflow.com/a/14636638/3600709
console.log('partial',3,n % 1 === 0)
console.log('partial',3,b % 1 === 0) // gives uncaught type on BigInt
_x000D_
If you actually want to test the incoming value's type to ensure it's an integer, use this instead:
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return !['string','object','boolean'].includes(typeof value)
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(''))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt([]))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(true))
console.log(isInt(NaN))
console.log(isInt('1'))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
_x000D_
If you don't care if the incoming type is actually boolean, string, etc. converted into a number, then just use the following:
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
function isInt(value) {
try {
BigInt(value)
return true
} catch(e) {
return false
}
}
console.log('--- should be false')
console.log(isInt(undefined))
console.log(isInt(null))
console.log(isInt({}))
console.log(isInt(1.1e-1))
console.log(isInt(1.1))
console.log(isInt(NaN))
console.log(isInt(function(){}))
console.log(isInt(Infinity))
console.log('--- should be true')
console.log(isInt(10))
console.log(isInt(0x11))
console.log(isInt(0))
console.log(isInt(-10000))
console.log(isInt(100000000000000000000000000000000000000))
console.log(isInt(1n))
// gets converted to number
console.log(isInt(''))
console.log(isInt([]))
console.log(isInt(true))
console.log(isInt('1'))
_x000D_
Hey i always make methods for custom stuff that is usually not implemented in java. Here is a simple method i made for removing character from String Fast
public static String removeChar(String str, char c){
StringBuilder strNew=new StringBuilder(str.length());
char charRead;
for(int i=0;i<str.length();i++){
charRead=str.charAt(i);
if(charRead!=c)
strNew.append(charRead);
}
return strNew.toString();
}
For explaintion, yes there is no null character for replacing, but you can remove character like this. I know its a old question, but i am posting this answer because this code may be helpful for some persons.
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
You cannot have a class that extends two base classes. You could not have.
// this is NOT allowed (for all you google speeders)
Matron extends Nurse, HumanEntity
You could however have a hierarchy as follows...
Matron extends Nurse
Consultant extends Doctor
Nurse extends HumanEntity
Doctor extends HumanEntity
HumanEntity extends DatabaseTable
DatabaseTable extends AbstractTable
and so on.
If you don't want all of your SQL statements to be echoed, but you only want to see the easily identifiable results of your script, do it this way:
set echo on
REM MyFirstTable
set echo off
delete from MyFirstTable;
set echo on
REM MySecondTable
set echo off
delete from MySecondTable;
The output from the above example will look something like this:
-REM MyFirstTable
13 rows deleted.
-REM MySecondTable
27 rows deleted.
now Application-Level Rate Limiting 200 calls per hour !
jsonVariable = {}
for(i=1; i<3; i++) {
var jsonKey = i+'name';
jsonVariable[jsonKey] = 'name1'
}
this will be similar to
jsonVariable = {
1name : 'name1'
2name : 'name1'
}
Try This
var data = 'allow~5';
var result=data.split('~');
RESULT
alert(result[0]);
Following are the most commonly used calls for downloading files in python:
urllib.urlretrieve ('url_to_file', file_name)
urllib2.urlopen('url_to_file')
requests.get(url)
wget.download('url', file_name)
Note: urlopen
and urlretrieve
are found to perform relatively bad with downloading large files (size > 500 MB). requests.get
stores the file in-memory until download is complete.
Converting to a DATE
or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand
From that article:
DECLARE @dateVar datetime = '19700204';
-- Quickest when there is an index on t.[DateColumn],
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);
-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn]
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND
t.[DateColumn] < @dateEnd;
Also from that article: using BETWEEN
, DATEDIFF
or CONVERT(CHAR(8)...
are all slower.
How often do you need to refresh the view? I have a similar case where the new data comes once a month; then I have to load it, and during the loading processes I have to create new tables. At that moment I alter my view to consider the changes. I used as base the information in this other question:
Create View Dynamically & synonyms
In there, it is proposed to do it 2 ways:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" multiple name="img[]"/>
<input type="submit">
</form>
<?php
print_r($_FILES['img']['name']);
?>
It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:
$(document).ready(function(){
$("a").click(function(){
alert("hohoho");
});
});
If you want to do it using .map()
or just want to know how it works you can do it like this:
var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
if (elementOfArray.id == productID) {
elementOfArray.price = productPrice;
added = true;
}
}
if (!added) {
arr.push({id: productID, price: productPrice})
}
The function handles each element separately. The .inArray()
proposed in other answers is probably the more efficient way to do it.
This my extension, this is an example of change image with FadIn and FadOut :
fun ImageView.setImageDrawableWithAnimation(@DrawableRes() resId: Int, duration: Long = 300) {
if (drawable != null) {
animate()
.alpha(0f)
.setDuration(duration)
.withEndAction {
setImageResource(resId)
animate()
.alpha(1f)
.setDuration(duration)
}
} else if (drawable == null) {
setAlpha(0f)
setImageResource(resId)
animate()
.alpha(1f)
.setDuration(duration)
}
}
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
you can return a FileResult from your MVC action.
*********************MVC action************
public FileResult OpenPDF(parameters)
{
//code to fetch your pdf byte array
return File(pdfBytes, "application/pdf");
}
**************js**************
Use formpost to post your data to action
var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
var form = document.createElement("form");
jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
jQuery(form).append(inputTag);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
You need to create a form to post your data, append it your dom, post your data and remove the form your document body.
However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.
w/o flip:
<?php
foreach ($items as $key => $value) {
if ($id === $value) {
unset($items[$key]);
}
}
you can use this.
<html>
<head>
<title>Demo</title>
<script>
function passBtnID(id) {
alert("You Pressed: " + id);
}
</script>
</head>
<body>
<button id="mybtn1" onclick="passBtnID('mybtn1')">Press me</button><br><br>
<button id="mybtn2" onclick="passBtnID('mybtn2')">Press me</button>
</body>
</html>
Since Java 9, you can create instances of Map.Entry
easier than before:
Entry<Integer, String> pair = Map.entry(1, "a");
Map.entry
returns an unmodifiable Entry
and forbids nulls.
Although @CommonsWare's solution works, it can't be used e. g. in a layer-list
drawable. The options combining <rotate>
and <shape>
cause the problems with size. Here is a solution using the Android Vector Drawable. This Drawable is a 1x10dp white line (can be adjusted by modifying the width
, height
and strokeColor
properties):
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:viewportWidth="1"
android:viewportHeight="10"
android:width="1dp"
android:height="10dp">
<path
android:strokeColor="#FFFFFF"
android:strokeWidth="1"
android:pathData="M0.5,0 V10" />
</vector>
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
Was facing the same problem In my case I changed the option parameter of cert to pfx & removed utf8 encoding.
before:
var options = {
hostname : 'localhost',
path : '/',
method : 'POST',
cert: fs.readFileSync(testCert, 'utf8'),
passphrase:passphrase,
agent:false,
rejectUnauthorized:false
};
after:
var options = {
hostname : 'localhost',
path : '/',
method : 'POST',
pfx: fs.readFileSync(testCert),
passphrase:passphrase,
agent:false,
rejectUnauthorized:false
};
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]);
- to check if the parameter is null
. To check if each element is not null just use
if(null != books[i]){/*do stuff*/}
Example:
public static double calculateInventoryTotal(Book[] books){
Objects.requireNotNull(books, "Books must not be null");
double total = 0;
for (int i = 0; i < books.length; i++){
if(null != book[i]){
total += books[i].getPrice();
}
}
return total;
}
Although I don't know what RDBMS you are using, you probably need to give the whole column specification, not just say that you now want it to be nullable. For example, if it's currently INT NOT NULL
, you should issue ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations INT
.
Example for replacing LI elements
function (element) {
let li = element.parentElement;
let ul = li.parentNode;
if (li.nextSibling.nodeName === 'LI') {
let li_replaced = ul.replaceChild(li, li.nextSibling);
ul.insertBefore(li_replaced, li);
}
}
In the solution below I used python3.4
as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget
obviously but just save the file locally and run it with python).
This is great if you have multiple versions of python installed, so you can manage external libraries per python version.
So first, I'd recommend get-pip.py
, it's great to install pip :
wget https://bootstrap.pypa.io/get-pip.py
Then you need to install pip for your version of python, I have python3.4
so for me this is the command :
python3.4 get-pip.py
Now pip is installed for python3.4
and in order to get libraries for python3.4
one need to call it within this version, like this :
python3.4 -m pip
So if you want to install numpy you would use :
python3.4 -m pip install numpy
Note that numpy
is quite the heavy library. I thought my system was hanging and failing.
But using the verbose option, you can see that the system is fine :
python3.4 -m pip install numpy -v
This may tell you that you lack python.h but you can easily get it :
On RHEL (Red hat, CentOS, Fedora) it would be something like this :
yum install python34-devel
On debian-like (Debian, Ubuntu, Kali, ...) :
apt-get install python34-dev
Then rerun this :
python3.4 -m pip install numpy -v