You can use the he library, available from https://github.com/mathiasbynens/he
Example:
console.log(he.decode("Jörg & Jürgen rocked to & fro "));
// Logs "Jörg & Jürgen rocked to & fro"
I challenged the library's author on the question of whether there was any reason to use this library in clientside code in favour of the <textarea>
hack provided in other answers here and elsewhere. He provided a few possible justifications:
If you're using node.js serverside, using a library for HTML encoding/decoding gives you a single solution that works both clientside and serverside.
Some browsers' entity decoding algorithms have bugs or are missing support for some named character references. For example, Internet Explorer will both decode and render non-breaking spaces (
) correctly but report them as ordinary spaces instead of non-breaking ones via a DOM element's innerText
property, breaking the <textarea>
hack (albeit only in a minor way). Additionally, IE 8 and 9 simply don't support any of the new named character references added in HTML 5. The author of he also hosts a test of named character reference support at http://mathias.html5.org/tests/html/named-character-references/. In IE 8, it reports over one thousand errors.
If you want to be insulated from browser bugs related to entity decoding and/or be able to handle the full range of named character references, you can't get away with the <textarea>
hack; you'll need a library like he.
He just darn well feels like doing things this way is less hacky.
\r used for carriage return. (ASCII value is 13) \n used for new line. (ASCII value is 10)
Try PowerShell Type like:
$cn = new-object system.data.SqlClient.SQLConnection("Data Source=server1;Initial Catalog=db1;User ID=user1;Password=password1");
$cmd = new-object system.data.sqlclient.sqlcommand("exec Proc1", $cn);
$cn.Open();
$cmd.CommandTimeout = 0
$cmd.ExecuteNonQuery()
$cn.Close();
Ruby
Where do you want to see the output?
Messages being output via Debug.Print
will be displayed in the immediate window which you can open by pressing Ctrl+G.
You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar
Building on Ben Dolman's answer, this distributes the views more evenly (with padding, etc):
+(NSArray *)constraintsForEvenDistributionOfItems:(NSArray *)views
relativeToCenterOfItem:(id)toView vertically:(BOOL)vertically
{
NSMutableArray *constraints = [NSMutableArray new];
NSLayoutAttribute attr = vertically ? NSLayoutAttributeCenterY : NSLayoutAttributeCenterX;
CGFloat min = 0.25;
CGFloat max = 1.75;
CGFloat d = (max-min) / ([views count] - 1);
for (NSUInteger i = 0; i < [views count]; i++) {
id view = views[i];
CGFloat multiplier = i * d + min;
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view
attribute:attr
relatedBy:NSLayoutRelationEqual
toItem:toView
attribute:attr
multiplier:multiplier
constant:0];
[constraints addObject:constraint];
}
return constraints;
}
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
Try odbTools at http://odbtools.software.informer.com - it is free.
odbTools is set of integrated GUI tools to manage, administer, monitor and tune the Oracle database.
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()
). For example there is the class Car
, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null;
- s
is a reference, that currently references no instance, but can reference an instance of the String
class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
This code works for me:
$rootScope.$$listeners.nameOfYourEvent=[];
It is sample extension
public class GetModelErrors
{
//Usage return Json to View :
//return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
public class KeyMessages
{
public string Key { get; set; }
public string Message { get; set; }
}
private readonly ModelStateDictionary _entry;
public GetModelErrors(ModelStateDictionary entry)
{
_entry = entry;
}
public int Count()
{
return _entry.ErrorCount;
}
public string Exceptions(string sp = "\n")
{
return string.Join(sp, _entry.Values
.SelectMany(v => v.Errors)
.Select(e => e.Exception));
}
public string Messages(string sp = "\n")
{
string msg = string.Empty;
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
}
}
return msg;
}
public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
{
List<KeyMessages> list = new List<KeyMessages>();
foreach (var item in _entry)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
list.Add(new KeyMessages
{
Key = item.Key,
Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
});
}
}
return list;
}
}
If you are using React, make sure autoplay is set to,
autoPlay
React wants it to be camelcase!
Within the definition of the appender, I believe you can do something like this:
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO"/>
<param name="LevelMax" value="INFO"/>
</filter>
...
</appender>
Syntax:
transition: <property> || <duration> || <timing-function> || <delay> [, ...];
Note that the duration must come before the delay, if the latter is specified.
Individual transitions combined in shorthand declarations:
-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
Or just transition them all:
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
Here is a straightforward example. Here is another one with the delay property.
Edit: previously listed here were the compatibilities and known issues regarding transition
. Removed for readability.
Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.
If you still want to be sure, refer to http://caniuse.com/css-transitions
Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.
See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
The query()
function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql
If you have an error somewhere deep in the code, then either throw an exception or set the error code. It's always better to throw an exception instead of setting error codes.
User lodash javascript library and use _.debounce function
changeName: _.debounce(function (val) {
console.log(val)
}, 1000)
For the simple reason:
Andy-B-MacBook:~ l.admin$ brew install sshpass
Error: No available formula with the name "sshpass"
We won't add sshpass because it makes it too easy for novice SSH users to
ruin SSH's security.
Thus, the answer to do the curl / configure / install worked great for me on Mac.
We use a simple fail task to force the user to specify the Ansible limit option, so that we don't execute on all hosts by default/accident.
The easiest way I found is this:
---
- name: Force limit
# 'all' is okay here, because the fail task will force the user to specify a limit on the command line, using -l or --limit
hosts: 'all'
tasks:
- name: checking limit arg
fail:
msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
when: ansible_limit is not defined
run_once: true
Now we must use the -l
(= --limit
option) when we run the playbook, e.g.
ansible-playbook playbook.yml -l www.example.com
Limit to one or more hosts This is required when one wants to run a playbook against a host group, but only against one or more members of that group.
Limit to one host
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1"
Limit to multiple hosts
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1,host2"
Negated limit.
NOTE: Single quotes MUST be used to prevent bash interpolation.
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!host1'
Limit to host group
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'group1'
I used zxing-1.3 jar and I had to make some changes implementing code from other answers, so I will leave my solution for others. I did the following:
1) find zxing-1.3.jar, download it and add in properties (add external jar).
2) in my activity layout add ImageView and name it (in my example it was tnsd_iv_qr).
3) include code in my activity to create qr image (in this example I was creating QR for bitcoin payments):
QRCodeWriter writer = new QRCodeWriter();
ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.tnsd_iv_qr);
try {
ByteMatrix bitMatrix = writer.encode("bitcoin:"+btc_acc_adress+"?amount="+amountBTC, BarcodeFormat.QR_CODE, 512, 512);
int width = 512;
int height = 512;
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitMatrix.get(x, y)==0)
bmp.setPixel(x, y, Color.BLACK);
else
bmp.setPixel(x, y, Color.WHITE);
}
}
tnsd_iv_qr.setImageBitmap(bmp);
} catch (WriterException e) {
//Log.e("QR ERROR", ""+e);
}
If someone is wondering, variable "btc_acc_adress" is a String (with BTC adress), amountBTC is a double, with, of course, transaction amount.
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
If the remote server is using SNI (that is, sharing multiple SSL hosts on a single IP address) you will need to send the correct hostname in order to get the right certificate.
openssl s_client -showcerts -servername www.example.com -connect www.example.com:443 </dev/null
If the remote server is not using SNI, then you can skip -servername
parameter:
openssl s_client -showcerts -connect www.example.com:443 </dev/null
To view the full details of a site's cert you can use this chain of commands as well:
$ echo | \
openssl s_client -servername www.example.com -connect www.example.com:443 2>/dev/null | \
openssl x509 -text
You might get a performance boost if you use parallel LINQ for multi cores. See Parallel LINQ (PLINQ) (MSDN).
As per @kexik's suggestion using the UNIX time function as below :
time_t result = time(NULL);
NSLog([NSString stringWithFormat:@"The current Unix epoch time is %d",(int)result]);
.As per my experience - don't use timeIntervalSince1970 , it gives epoch timestamp - number of seconds you are behind GMT.
There used to be a bug with [[NSDate date]timeIntervalSince1970] , it used to add/subtract time based on the timezone of the phone but it seems to be resolved now.
The idea behind this solution is that the main activity of every system app does not have a custom activity icon. This method gives me an excellent result:
public static Set<PackageInfo> getInstalledApps(Context ctx) {
final PackageManager packageManager = ctx.getPackageManager();
final List<PackageInfo> allInstalledPackages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA);
final Set<PackageInfo> filteredPackages = new HashSet();
Drawable defaultActivityIcon = packageManager.getDefaultActivityIcon();
for(PackageInfo each : allInstalledPackages) {
if(ctx.getPackageName().equals(each.packageName)) {
continue; // skip own app
}
try {
// add only apps with application icon
Intent intentOfStartActivity = packageManager.getLaunchIntentForPackage(each.packageName);
if(intentOfStartActivity == null)
continue;
Drawable applicationIcon = packageManager.getActivityIcon(intentOfStartActivity);
if(applicationIcon != null && !defaultActivityIcon.equals(applicationIcon)) {
filteredPackages.add(each);
}
} catch (PackageManager.NameNotFoundException e) {
Log.i("MyTag", "Unknown package name " + each.packageName);
}
}
return filteredPackages;
}
Create the SqlParamObject which would give you control to access methods on the parameters
:
SqlParameter param = new SqlParameter();
SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)
: param.ParameterName = "@yourParamterName";
Clear the value holder to hold you output data
: param.Value = 0;
Set the Direction of your Choice (In your case it should be Output)
: param.Direction = System.Data.ParameterDirection.Output;
Now the finder window will be open with Provisioning Profiles folder. Delete all or any provisioning profiles from here and it will reflect in Xcode.
Just use the *args
parameter, which allows you to pass as many arguments as you want after your a,b,c
. You would have to add some logic to map args
->c,d,e,f
but its a "way" of overloading.
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
And it will print values of c,d,e,f
Similarly you could use the kwargs
argument and then you could name your parameters.
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
And then kwargs
would have a dictionary of all the parameters that are key valued after a,b
Thanks for Norfeldt's answer. I slightly changed its gradient for a better inner shadow effect.
<item android:state_pressed="false" android:state_focused="false">
<shape>
<gradient
android:centerY="0.2"
android:startColor="#D3D3D3"
android:centerColor="#65FFFFFF"
android:endColor="#00FFFFFF"
android:angle="270"
/>
<stroke
android:width="0.7dp"
android:color="#BDBDBD" />
<corners
android:radius="15dp" />
</shape>
</item>
Looks great in a light backgrounded layout..
Under your main views.py
add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.
With this solution, no custom code needs to be added to urls.py
Here's the code:
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request, *args, **argv):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request, *args, **argv):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Update
handler404
and handler500
are exported Django string configuration variables found in django/conf/urls/__init__.py
. That is why the above config works.
To get the above config to work, you should define the following variables in your urls.py
file and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:
# project/urls.py
handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'
Update for Django 2.0
Signatures for handler views were changed in Django 2.0: https://docs.djangoproject.com/en/2.0/ref/views/#error-views
If you use views as above, handler404 will fail with message:
"handler404() got an unexpected keyword argument 'exception'"
In such case modify your views like this:
def handler404(request, exception, template_name="404.html"):
response = render_to_response(template_name)
response.status_code = 404
return response
Here is my solution in java using liked list.
class Stack{
int min;
Node top;
static class Node{
private int data;
private Node next;
private int min;
Node(int data, int min){
this.data = data;
this.min = min;
this.next = null;
}
}
void push(int data){
Node temp;
if(top == null){
temp = new Node(data,data);
top = temp;
top.min = data;
}
if(top.min > data){
temp = new Node(data,data);
temp.next = top;
top = temp;
} else {
temp = new Node(data, top.min);
temp.next = top;
top = temp;
}
}
void pop(){
if(top != null){
top = top.next;
}
}
int min(){
return top.min;
}
}
System.Windows.Forms.Application.Exit()
- Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit()
method is typically called from within a message loop, and forces Run()
to return. To exit a message loop for the current thread only, call ExitThread()
. This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run()
.
System.Environment.Exit(exitCode)
- Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode
permissions. If you do not, a SecurityException
error occurs. This is the call to use if you are running a console application.
I hope it is best to use Application.Exit
See also these links:
In addition to the suggestions given, you can do this directly from your query like this -
SELECT ISNULL([Additional], -1) AS [Additional]
This way you can write the condition to check whether the field value is < 0 or >= 0.
If this seems inconsistent from machine to machine, have you made sure that some 3rd party app like virus scan isn't intercepting something?
-(NSMutableDictionary*)tableInfo:(NSString *)table
{
sqlite3_stmt *sqlStatement;
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
const char *sql = [[NSString stringWithFormat:@"pragma table_info('%s')",[table UTF8String]] UTF8String];
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement tableInfo %@",[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(db)]);
}
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
[result setObject:@"" forKey:[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
}
return result;
}
A solution is to use the include
statement with remote_user
var (describe there : http://docs.ansible.com/playbooks_roles.html) but it has to be done at playbook instead of task level.
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest() method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.For Server.Transfer, use the Server.Execute method instead.
If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.
This behavior is by design.
Article ID: 312629 - Last Review: August 30, 2012 - Revision: 4.0
Applies to
- Microsoft ASP.NET 4.5
- Microsoft ASP.NET 4
- Microsoft ASP.NET 3.5
- Microsoft ASP.NET 2.0
- Microsoft ASP.NET 1.1
- Microsoft ASP.NET 1.0
Keywords: kbexcepthandling kbprb KB312629
Source: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer
For anyone on Mac OS X, you can find netbeans.conf
here:
/Applications/NetBeans/NetBeans <version>.app/Contents/Resources/NetBeans/etc/netbeans.conf
In case anyone needs to know :)
In CakePHP 1.2 ..
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
If you insist on having this trivial function in pure batch I suggest this:
@echo off
set x=somestring
set n=0
set m=255
:loop
if "!x:~%m%,1!" == "" (
set /a "m>>=1"
goto loop
) else (
set /a n+=%m%+1
set x=!x:~%m%!
set x=!x:~1!
if not "!x!" == "" goto loop
)
echo %n%
PS. You must have delayed variable expansion enabled to run this.
EDIT. Now I have made an improved version:
@echo off
set x=somestring
set n=0
for %%m in (4095 2047 1023 511 255 127 63 31 15 7 3 1 0) do (
if not "!x:~%%m,1!" == "" (
set /a n+=%%m+1
set x=!x:~%%m!
set x=!x:~1!
if "!x!" == "" goto done
)
)
:done
echo %n%
EDIT2. If you have a C compiler or something on your system you can create the programs you need and miss on the fly if they don't exist. This method is very general. Take string length as an example:
@echo off
set x=somestring
if exist strlen.exe goto comp
echo #include "string.h" > strlen.c
echo int main(int argc, char* argv[]) { return strlen(argv[1]); } >> strlen.c
CL strlen.c
:comp
strlen "%x%"
set n=%errorlevel%
echo %n%
You have to set up PATH, INCLUDE and LIB appropriately. This too can be done on the fly from the batch script. Even if you don't know whether you've got a compiler or don't know where it is you can search for it in your script.
Wrap them in an extra pair of parens and you're good to go.
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
System.Diagnostics.Process.Start("Exe Name");
We can't say that it is possible of not their is some other way exist to perform update operation in user-defined Function. Directly DML is not possible in UDF it is for sure.
Below Query is working perfectly:
create table testTbl
(
id int identity(1,1) Not null,
name nvarchar(100)
)
GO
insert into testTbl values('ajay'),('amit'),('akhil')
Go
create function tblValued()
returns Table
as
return (select * from testTbl where id = 1)
Go
update tblValued() set name ='ajay sharma' where id = 1
Go
select * from testTbl
Go
If like me you had installed a MySQL on your server (Windows 2012), and when reinstalling the installer is unable to start the MySQL service. Then you have to completely erase MySQL! I had to do the following steps to be sure :
Got my info from the following blog :http://blogs.iis.net/rickbarber/completely-uninstall-mysql-from-windows
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
Adobe Flash Builder 4.6 Read Me.pdf recommendeds that you edit the eclipse.ini file for your Eclipse instance, so that it includes the following settings:
-vmargs -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:PermSize=64m
Debug.getNativeHeapSize()
will do the trick, I should think. It's been there since 1.0, though.
The Debug
class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory()
.
timeout /t <seconds> <options>
For example, to make the script perform a non-uninterruptible 2-second wait:
timeout /t 2 /nobreak >NUL
Which means the script will wait 2 seconds before continuing.
By default, a keystroke will interrupt the timeout, so use the /nobreak
switch if you don't want the user to be able to interrupt (cancel) the wait. Furthermore, the timeout will provide per-second notifications to notify the user how long is left to wait; this can be removed by piping the command to NUL
.
edit: As @martineau points out in the comments, the timeout
command is only available on Windows 7 and above. Furthermore, the ping
command uses less processor time than timeout
. I still believe in using timeout
where possible, though, as it is more readable than the ping
'hack'. Read more here.
Thanks to Rack Middleware and Rails 3 you can output pretty JSON for every request without changing any controller of your app. I have written such middleware snippet and I get nicely printed JSON in browser and curl
output.
class PrettyJsonResponse
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
if headers["Content-Type"] =~ /^application\/json/
obj = JSON.parse(response.body)
pretty_str = JSON.pretty_unparse(obj)
response = [pretty_str]
headers["Content-Length"] = pretty_str.bytesize.to_s
end
[status, headers, response]
end
end
The above code should be placed in app/middleware/pretty_json_response.rb
of your Rails project.
And the final step is to register the middleware in config/environments/development.rb
:
config.middleware.use PrettyJsonResponse
I don't recommend to use it in production.rb
. The JSON reparsing may degrade response time and throughput of your production app. Eventually extra logic such as 'X-Pretty-Json: true' header may be introduced to trigger formatting for manual curl requests on demand.
(Tested with Rails 3.2.8-5.0.0, Ruby 1.9.3-2.2.0, Linux)
You have updated the android sdk but not updated the adt to match with it.
You can update the adt from here
You might need to update the software source for your adt update
Go to eclipse > help > Check for updates.
It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:
Click on add
Add this url : https://dl-ssl.google.com/android/eclipse/
Give it any name.
It will list the updates available- which should ideally be adt 20.xx
Eclipse will restart and hopefully everything should work fine for you.
TEXT
and VarChar(MAX)
are Non-Unicode large Variable Length character data type, which can store maximum of 2147483647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).
As per MSDN link Microsoft is suggesting to avoid using the Text datatype and it will be removed in a future versions of Sql Server. Varchar(Max) is the suggested data type for storing the large string values instead of Text data type.
Data of a Text
type column is stored out-of-row in a separate LOB data pages. The row in the table data page will only have a 16 byte pointer to the LOB data page where the actual data is present. While Data of a Varchar(max)
type column is stored in-row if it is less than or equal to 8000 byte. If Varchar(max) column value is crossing the 8000 bytes then the Varchar(max) column value is stored in a separate LOB data pages and row will only have a 16 byte pointer to the LOB data page where the actual data is present. So In-Row
Varchar(Max) is good for searches and retrieval.
Some of the string functions, operators or the constructs which doesn’t work on the Text type column, but they do work on VarChar(Max) type column.
=
Equal to Operator on VarChar(Max) type columnGroup by clause on VarChar(Max) type column
As we know that the VarChar(Max) type column values are stored out-of-row only if the length of the value to be stored in it is greater than 8000 bytes or there is not enough space in the row, otherwise it will store it in-row. So if most of the values stored in the VarChar(Max) column are large and stored out-of-row, the data retrieval behavior will almost similar to the one that of the Text type column.
But if most of the values stored in VarChar(Max) type columns are small enough to store in-row. Then retrieval of the data where LOB columns are not included requires the more number of data pages to read as the LOB column value is stored in-row in the same data page where the non-LOB column values are stored. But if the select query includes LOB column then it requires less number of pages to read for the data retrieval compared to the Text type columns.
Conclusion
Use VarChar(MAX)
data type rather than TEXT
for good performance.
Most of the time you can have Android Studio automatically update the Gradle plugin.
If your Gradle plugin version is behind, Instant Run will mostly likely not work. Therefore if you go to the Instant Run settings (Preferences > Build, Execution, Deployment > Instant Run), you'll see an Update project button at the top right (image below). Clicking this will update both the Gradle wrapper and build tools.
document.getElementsByClassName
returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0];
should get you what you want.
Update #1:
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment() {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
Update #2: (with removeEventListener
incorporated as well)
var comments = document.getElementsByClassName('button');
var numComments = comments.length;
function showComment(e) {
var place = document.getElementById('textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
for (var i = 0; i < numComments; i++) {
comments[i].removeEventListener('click', showComment, false);
}
}
for (var i = 0; i < numComments; i++) {
comments[i].addEventListener('click', showComment, false);
}
In some cases this case occurs when you declare
Writer out=response.getWriter
after declaring or using RequestDispatcher
.
I encountered this similar problem while creating a simple LoginServlet
, where I have defined Writer
after declaring RequestDispatcher
.
Try defining Writer
class object before RequestDispatcher
class.
I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line
; On windows: extension_dir = "ext"
I changed it to:
; On windows: extension_dir = "C:\php\ext"
And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.
I'm a designer and our devs had this issue when dealing with Android initially, and our web devs are having the same problem. We found that the spacing between a line of text and another object (either a component like a button, or a separate line of text) that a design program spits out is incorrect. This is because the design program isn't accounting for diacritics when it is defining the "size" of a single line of text.
We ended up adding Êg
to every line of text and manually creating spacers (little blue rectangles) that act as the "measurement" from the actual top of the text (ie, the top of the accent mark on the E) or from the descender (the bottom of a "g").
For example, say you have a really boring top navigation that is just a rectangle, and a headline beneath it. The design program will say that the space between the bottom of the top nav and the top of the headline textbox 24px. However, when you measure from the bottom of the nav to the top of an Ê accent mark, the spacing is actually 20px.
While I realize that this isn't a code solution, it should help explain the discrepancies between the design specs and what the build looks like.
The str.isalpha()
function works. ie.
if my_string.isalpha():
print('it is letters')
This is against the very definition of an iterator, which is a pointer to an object, plus information about how to get to the next object.
An iterator does not know how many more times it will be able to iterate until terminating. This could be infinite, so infinity might be your answer.
I am not sure about gson but this is how you do it with Jon.sample hope there must be similar way using gson
{ "Players": [ "player 1", "player 2", "player 3", "player 4", "player 5" ] }
===============================================
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JosnFileDemo {
public static void main(String[] args) throws Exception
{
String jsonfile ="fileloaction/fileName.json";
FileReader reader = null;
JSONObject jsb = null;
try {
reader = new FileReader(jsonfile);
JSONParser jsonParser = new JSONParser();
jsb = (JSONObject) jsonParser.parse(reader);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (reader != null)
reader.close();
}
List<String> Players=(List<String>) jsb.get("Players");
for (String player : Players) {
System.out.println(player);
}
}
}
Log.v("blah", "blah blah");
You need to add the android Log view in eclipse to see them. There are also other methods depending on the severity of the message (error, verbose, warning, etc..).
I believe the right answer is "it depends".
As others have pointed out, if the web application that is processing your request is naively receiving and echoing back the received payload or URL parameters (for GET requests) then it might be subject to code injection.
However, if the web application sanitizes and/or filters payload/parameters, it shouldn't be a problem.
It also depends on the user agent (e.g. browser), a customized user agent might inject code without user notice if it detects any in the request (don't know of any public one, but that is also possible).
just replace your code:
old code:
$("#dateSelect").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd'
});
new code:
$("#dateSelect").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy-mm-dd',
minDate: 0
});
This answer is based on an article that no longer exists:
Summary of article:
"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.
You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?
Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."
... later ...
"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"
System.Data.SqlClient
is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.
I don't know where providerName=SqlServer
comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )
In the web.config you should have the System.Data.SqlClient
as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.
<connectionStrings>
<add
name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx
This error really just has to do with the file Path,thats all you have to check,for me my parent folder was "Layouts" but my actual file was layout.html
,my path had layouts on both,once i corrected that error was gone.
Here is a simple way
<div (click)="$event.preventDefault()">
<a href="#"></a>
</div>
capture the bubbling event and shoot it down
The CSS code would be:
box-shadow: 0 0 10px 5px white;
That will shadow the entire DIV no matter its shape!
I submit that it is better to leave your data stacked as it is:
df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])
Then it's a bit more intuitive to say
df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)
This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot
, it's purely based on column convention as to what semantic entity it is that you are reshaping.
As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
/* useful code here */
}
}
As an appendix to Clint's answer, you can simplify PackageResource
using contextlib.contextmanager
:
@contextlib.contextmanager
def packageResource():
class Package:
...
package = Package()
yield package
package.cleanup()
Alternatively, though probably not as Pythonic, you can override Package.__new__
:
class Package(object):
def __new__(cls, *args, **kwargs):
@contextlib.contextmanager
def packageResource():
# adapt arguments if superclass takes some!
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
yield package
package.cleanup()
def __init__(self, *args, **kwargs):
...
and simply use with Package(...) as package
.
To get things shorter, name your cleanup function close
and use contextlib.closing
, in which case you can either use the unmodified Package
class via with contextlib.closing(Package(...))
or override its __new__
to the simpler
class Package(object):
def __new__(cls, *args, **kwargs):
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
return contextlib.closing(package)
And this constructor is inherited, so you can simply inherit, e.g.
class SubPackage(Package):
def close(self):
pass
With the v3 API, you can easily close the InfoWindow
with the InfoWindow.close()
method. You simply need to keep a reference to the InfoWindow
object that you are using. Consider the following example, which opens up an InfoWindow
and closes it after 5 seconds:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API InfoWindow Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 500px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(-25.36388, 131.04492),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
infowindow.open(map, marker);
setTimeout(function () { infowindow.close(); }, 5000);
</script>
</body>
</html>
If you have a separate InfoWindow
object for each Marker
, you may want to consider adding the InfoWindow
object as a property of your Marker
objects:
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker.infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
Then you would be able to open and close that InfoWindow
as follows:
marker.infowindow.open(map, marker);
marker.infowindow.close();
The same applies if you have an array of markers:
var markers = [];
marker[0] = new google.maps.Marker({
position: map.getCenter(),
map: map
});
marker[0].infowindow = new google.maps.InfoWindow({
content: 'An InfoWindow'
});
// ...
marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();
The setting was disabled in Jupyter 5.X
and higher by adding below code
pylab = Unicode('disabled', config=True,
help=_("""
DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
""")
)
@observe('pylab')
def _update_pylab(self, change):
"""when --pylab is specified, display a warning and exit"""
if change['new'] != 'warn':
backend = ' %s' % change['new']
else:
backend = ''
self.log.error(_("Support for specifying --pylab on the command line has been removed."))
self.log.error(
_("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
)
self.exit(1)
And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels
and you can find kernel for your project by running below command
$ jupyter kernelspec list
Available kernels:
python3 /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3
This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json
file, I see something like below
{
"argv": [
"python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}",
],
"display_name": "Python 3",
"language": "python"
}
So you can see what command is executed to launch the kernel. So if you run the below command
$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.
Subcommands
-----------
Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.
install
Install the IPython kernel
Options
-------
Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.
....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
Default: None
Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
Pre-load matplotlib and numpy for interactive use, selecting a particular
matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
Default: None
Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
Configure matplotlib for interactive use with the default matplotlib
backend.
...
To see all available configurables, use `--help-all`
So now if we update our kernel.json
file to
{
"argv": [
"python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}",
"--pylab",
"inline"
],
"display_name": "Python 3",
"language": "python"
}
And if I run jupyter notebook
the graphs are automatically inline
Note the below approach also still works, where you create a file on below path
~/.ipython/profile_default/ipython_kernel_config.py
c = get_config()
c.IPKernelApp.matplotlib = 'inline'
But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.
So choose which approach you would like to use based on your requirement
The value
attribute of a checkbox
is what you set by:
<input type='checkbox' name='test' value='1'>
So when someone checks that box, the server receives a variable named test
with a value
of 1
- what you want to check for is not the value
of it (which will never change, whether it is checked or not) but the checked
status of the checkbox.
So, if you replace this code:
if (arrChecks[i].value == "on")
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
With this:
arrChecks[i].checked = !arrChecks[i].checked;
It should work. You should use true
and false
instead of 0
and 1
for this.
Sure, what do you want to use for the gid? a static value, PHP var, ...
A static value of 1234 could be like:
INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid
First thing, we need to understand why this is happening and the error message is clear:
Process finished with exit code 1 Class not found: "edu.macalester.comp124.hw0.AreaTest"Empty test suite.
So this mainly occurs when after the unit test class was created we run the methods (tests) individually before running them from the class level. That is all
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
Here is the most clear & intuitive way i know to allocate a dynamic 2d array in C++. Templated in this example covers all cases.
template<typename T> T** matrixAllocate(int rows, int cols, T **M)
{
M = new T*[rows];
for (int i = 0; i < rows; i++){
M[i] = new T[cols];
}
return M;
}
...
int main()
{
...
int** M1 = matrixAllocate<int>(rows, cols, M1);
double** M2 = matrixAllocate(rows, cols, M2);
...
}
$timeIn30Minutes = mktime(idate("H"), idate("i") + 30);
or
$timeIn30Minutes = time() + 30*60; // 30 minutes * 60 seconds/minute
The result will be a UNIX timestamp of the current time plus 30 minutes.
This is how i implemented strtok, Not that great but after working 2 hr on it finally got it worked. It does support multiple delimiters.
#include "stdafx.h"
#include <iostream>
using namespace std;
char* mystrtok(char str[],char filter[])
{
if(filter == NULL) {
return str;
}
static char *ptr = str;
static int flag = 0;
if(flag == 1) {
return NULL;
}
char* ptrReturn = ptr;
for(int j = 0; ptr != '\0'; j++) {
for(int i=0 ; filter[i] != '\0' ; i++) {
if(ptr[j] == '\0') {
flag = 1;
return ptrReturn;
}
if( ptr[j] == filter[i]) {
ptr[j] = '\0';
ptr+=j+1;
return ptrReturn;
}
}
}
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[200] = "This,is my,string.test";
char *ppt = mystrtok(str,", .");
while(ppt != NULL ) {
cout<< ppt << endl;
ppt = mystrtok(NULL,", .");
}
return 0;
}
First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.
Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.
Then compile your project and see the effect.
See: http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
Not in general but if you are using Github:
For me wget
to the raw url turned out to be the best and easiest way to download one particular file.
Open the file in the browser and click on "Raw" button. Now refresh your browser, copy the url and do a wget
or curl
on it.
wget example:
wget 'https://github.abc.abc.com/raw/abc/folder1/master/folder2/myfile.py?token=DDDDnkl92Kw8829jhXXoxBaVJIYW-h7zks5Vy9I-wA%3D%3D' -O myfile.py
Curl example:
curl 'https://example.com/raw.txt' > savedFile.txt
In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example,
object.__getattribute__(self, name)
.
Meaning:
def __getattribute__(self,name):
...
return self.__dict__[name]
You're calling for an attribute called __dict__
. Because it's an attribute, __getattribute__
gets called in search for __dict__
which calls __getattribute__
which calls ... yada yada yada
return object.__getattribute__(self, name)
Using the base classes __getattribute__
helps finding the real attribute.
your code :
AddTaskViewController *add = [[AddTaskViewController alloc] init];
[self presentViewController:add animated:YES completion:nil];
this code can goes to the other controller , but you get a new viewController , not the controller of your storyboard, you can do like this :
AddTaskViewController *add = [self.storyboard instantiateViewControllerWithIdentifier:@"YourStoryboardID"];
[self presentViewController:add animated:YES completion:nil];
For username and password protected services use the following
curl -u admin:password -X GET http://172.16.2.125:9200 -d '{"sort":[{"lastUpdateTime":{"order":"desc"}}]}'
Execute the following procedure for example as user system.
Set p_owner to the schema owner and p_readonly to the name of the readonly user.
create or replace
procedure createReadOnlyUser(p_owner in varchar2, p_readonly in varchar2)
AUTHID CURRENT_USER is
BEGIN
execute immediate 'create user '||p_readonly||' identified by '||p_readonly;
execute immediate 'grant create session to '||p_readonly;
execute immediate 'grant select any dictionary to '||p_readonly;
execute immediate 'grant create synonym to '||p_readonly;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
execute immediate 'grant select on '||p_owner||'.'||R.object_name||' to '||p_readonly;
END LOOP;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
execute immediate 'grant execute on '||p_owner||'.'||R.object_name||' to '||p_readonly;
END LOOP;
FOR R IN (SELECT owner, object_name FROM all_objects WHERE object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP
EXECUTE IMMEDIATE 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
END LOOP;
FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP
execute immediate 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"';
END LOOP;
END;
I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).
Add the permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Add receiver and service:
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name="Launcher" />
Create class Launcher:
public class Launcher extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new AsyncTask<Service, Void, Service>() {
@Override
protected Service doInBackground(Service... params) {
Service service = params[0];
PackageManager pm = service.getPackageManager();
try {
Intent target = pm.getLaunchIntentForPackage("your.package.id");
if (target != null) {
service.startActivity(target);
synchronized (this) {
wait(3000);
}
} else {
throw new ActivityNotFoundException();
}
} catch (ActivityNotFoundException | InterruptedException ignored) {
}
return service;
}
@Override
protected void onPostExecute(Service service) {
service.stopSelf();
}
}.execute(this);
return START_STICKY;
}
}
Create class BootUpReceiver
to do action after android reboot.
For example launch MainActivity:
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent target = new Intent(context, MainActivity.class);
target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(target);
}
}
I add credentials for HttpWebRequest
.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Just run
docker restart $(docker ps -q)
Update
For Docker 1.13.1
use docker restart $(docker ps -a -q)
as in answer lower.
Came across this question just now and have something to add
To go to the most recent commit:
git checkout $(git log --branches -1 --pretty=format:"%H")
Explanation:
git log --branches
shows log of commits from all local branches
-1
limit to one commit → most recent commit
--pretty=format:"%H"
format to only show commit hash
git checkout $(...)
use output of subshell as argument for checkout
Note:
This will result in a detached head though (because we checkout directly to the commit). This can be avoided by extracting the branch name using sed
, explained below.
To go to the branch of the most recent commit:
git checkout $(git log --branches -1 --pretty=format:'%D' | sed 's/.*, //g')
Explanation:
git log --branches
shows log of commits from all local branches
-1
limit to one commit → most recent commit
--pretty=format:"%D"
format to only show ref names
| sed 's/.*, //g'
ignore all but the last of multiple refs (*)
git checkout $(...)
use output of subshell as argument for checkout
*) HEAD and remote branches are listed first, local branches are listed last in alphabetically descending order, so the one remaining will be the alphabetically first branch name
Note:
This will always only use the (alphabetically) first branch name if there are multiple for that commit.
Anyway, I think the best solution would just be to display the ref names for the most recent commit to know where to checkout to:
git log --branches -1 --pretty=format:'%D'
E.g. create the alias git top
for that command.
File name should in under double quotes. Since i am using Mac->In my case content of batch file is
cd /Users/yourName/Documents/SeleniumServer
java -jar selenium-server-standalone-3.3.1.jar -role hub
It will work for sure
Are you sure you are not using a wrong path in the url
field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.
Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.
If you want the file from a particular commit (any branch) , say 06f8251f
git checkout 06f8251f path_to_file
for example , in windows:
git checkout 06f8251f C:\A\B\C\D\file.h
Just in case you forgot or avoided to copy through PHPMYADMIN export feature..
Procedure: You can manually copy: Procedure For MAC OS, for latest versions of XAMPP
Location : Find the database folders here /Users/XXXXUSER/XAMPP/xamppfiles/var/mysql..
Solution: Copy the entire folder with database names into your new xampp in similar folder.
Hope it helps, happy coding.
To compare two objects you can use:
angular.equals(obj1, obj2)
It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo
var obj1 = {
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return true
I was using something along the lines of the currently accepted answer in order to send emails with an attached binary error log file. GMail and K-9 send it just fine and it also arrives fine on my mail server. The only problem was my mail client of choice Thunderbird which had troubles with opening / saving the attached log file. In fact it simply didn't save the file at all without complaining.
I took a look at one of these mail's source codes and noticed that the log file attachment had (understandably) the mime type message/rfc822
. Of course that attachment is not an attached email. But Thunderbird cannot cope with that tiny error gracefully. So that was kind of a bummer.
After a bit of research and experimenting I came up with the following solution:
public Intent createEmailOnlyChooserIntent(Intent source,
CharSequence chooserTitle) {
Stack<Intent> intents = new Stack<Intent>();
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"[email protected]", null));
List<ResolveInfo> activities = getPackageManager()
.queryIntentActivities(i, 0);
for(ResolveInfo ri : activities) {
Intent target = new Intent(source);
target.setPackage(ri.activityInfo.packageName);
intents.add(target);
}
if(!intents.isEmpty()) {
Intent chooserIntent = Intent.createChooser(intents.remove(0),
chooserTitle);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
intents.toArray(new Parcelable[intents.size()]));
return chooserIntent;
} else {
return Intent.createChooser(source, chooserTitle);
}
}
It can be used as follows:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("*/*");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(crashLogFile));
i.putExtra(Intent.EXTRA_EMAIL, new String[] {
ANDROID_SUPPORT_EMAIL
});
i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");
startActivity(createEmailOnlyChooserIntent(i, "Send via email"));
As you can see, the createEmailOnlyChooserIntent method can be easily fed with the correct intent and the correct mime type.
It then goes through the list of available activities that respond to an ACTION_SENDTO mailto
protocol intent (which are email apps only) and constructs a chooser based on that list of activities and the original ACTION_SEND intent with the correct mime type.
Another advantage is that Skype is not listed anymore (which happens to respond to the rfc822 mime type).
Firefox Proxy: JAVA
String PROXY = "localhost:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)setFtpProxy(PROXY).setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
Try this
import pandas as pd
data=pd.read_csv('C:/Users/Downloads/winequality-red.csv')
Replace the file target location, with where your data set is found, refer this url https://medium.com/@kanchanardj/jargon-in-python-used-in-data-science-to-laymans-language-part-one-12ddfd31592f
in jQuery:
$("#strings").val(["Test", "Prof", "Off"]);
or in pure JavaScript:
var element = document.getElementById('strings');
var values = ["Test", "Prof", "Off"];
for (var i = 0; i < element.options.length; i++) {
element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}
jQuery does significant abstraction here.
as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?
This is meant half as a joke, since the question is kinda silly.
public static bool IsNull (this System.Object o)
{
return (o == null);
}
This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.
Then you can save tons of code by doing:
if (foo.IsNull())
instead of the super lame:
if (foo == null)
^([+-]?[0-9]\d*|0)$
will accept numbers with leading "+", leading "-" and leadings "0"
Embed this code in your css.
::-webkit-scrollbar {
width: 0px;
}
/* Track */
::-webkit-scrollbar-track {
-webkit-box-shadow: none;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: white;
-webkit-box-shadow: none;
}
::-webkit-scrollbar-thumb:window-inactive {
background: none;
}
Use the following query to see which rows have changes:
(select * from inserted) except (select * from deleted)
The results of this query should consist of all the new records that are different from the old ones.
PageView::select('id','title', DB::raw('DATE(created_at) as date'))
->get()
->groupBy('date');
Use
find \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
or
find \( -path "./tmp" -o -path "./scripts" \) -prune -false -o -name "*_peaks.bed"
or
find \( -path "./tmp" -path "./scripts" \) ! -prune -o -name "*_peaks.bed"
The order is important. It evaluates from left to right. Always begin with the path exclusion.
Do not use -not
(or !
) to exclude whole directory. Use -prune
.
As explained in the manual:
-prune The primary shall always evaluate as true; it
shall cause find not to descend the current
pathname if it is a directory. If the -depth
primary is specified, the -prune primary shall
have no effect.
and in the GNU find manual:
-path pattern
[...]
To ignore a whole
directory tree, use -prune rather than checking
every file in the tree.
Indeed, if you use -not -path "./pathname"
,
find will evaluate the expression for each node under "./pathname"
.
find expressions are just condition evaluation.
\( \)
- groups operation (you can use -path "./tmp" -prune -o -path "./scripts" -prune -o
, but it is more verbose).-path "./script" -prune
- if -path
returns true and is a directory, return true for that directory and do not descend into it.-path "./script" ! -prune
- it evaluates as (-path "./script") AND (! -prune)
. It revert the "always true" of prune to always false. It avoids printing "./script"
as a match.-path "./script" -prune -false
- since -prune
always returns true, you can follow it with -false
to do the same than !
.-o
- OR operator. If no operator is specified between two expressions, it defaults to AND operator.Hence, \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
is expanded to:
[ (-path "./tmp" OR -path "./script") AND -prune ] OR ( -name "*_peaks.bed" AND print )
The print is important here because without it is expanded to:
{ [ (-path "./tmp" OR -path "./script" ) AND -prune ] OR (-name "*_peaks.bed" ) } AND print
-print
is added by find - that is why most of the time, you do not need to add it in you expression. And since -prune
returns true, it will print "./script" and "./tmp".
It is not necessary in the others because we switched -prune
to always return false.
Hint: You can use find -D opt expr 2>&1 1>/dev/null
to see how it is optimized and expanded,
find -D search expr 2>&1 1>/dev/null
to see which path is checked.
To stop a python script using the keyboard: Ctrl
+ C
To stop it using code (This has worked for me on Python 3) :
import os
os._exit(0)
you can also use:
import sys
sys.exit()
or:
exit()
or:
raise SystemExit
Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.
Improved version of what Ustaman Sangat did
static inline uint64_t
log2(uint64_t n)
{
uint64_t val;
for (val = 0; n > 1; val++, n >>= 1);
return val;
}
Note that if you have two radio button with same "name" attribute and they have "required" attribute, then adding "checked" attribute to them won't make them checked.
Example: This makes both radio button remain unchecked.
<input type="radio" name="gender" value="male" required <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" required />
This will makes the "male" radio button checked.
<input type="radio" name="gender" value="male" <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" />
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
It hides the intention of the code.
It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.
Some use it as a faster alternative to Math.floor
, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.
With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~
instead of Math.floor
is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.
See: tilde vs floor
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
I just had the same issue with Font Awesome. Turned out this was caused by a problem with FTP. The file was uploaded as text (ASCII) instead of binary, which corrupted the file. I simply changed my FTP software to binary, re-uploaded the font files, and then it all worked.
https://css-tricks.com/forums/topic/custom-fonts-returns-failed-to-decode-downloaded-font/ this helped me in the end I had the same issue with FTP transferring files as text
Finally I Try with this. Its worked for me..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ebook);
//webview use to call own site
webview =(WebView)findViewById(R.id.webView1);
webview.setWebViewClient(new WebViewClient());
webview .getSettings().setJavaScriptEnabled(true);
webview .getSettings().setDomStorageEnabled(true);
webview.loadUrl("http://www.google.com");
}
and your entire main.xml(res/layout) look should like this:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
don't go to add layouts.
Try adding C:\Program Files\Nodejs
to your PATH
environment variable. The PATH
environment variable allows run executables or access files within the folders specified (separated by semicolons).
On the command prompt, the command would be set PATH=%PATH%;C:\Program Files\Nodejs
.
Function Copy-FilesBitsTransfer(
[Parameter(Mandatory=$true)][String]$sourcePath,
[Parameter(Mandatory=$true)][String]$destinationPath,
[Parameter(Mandatory=$false)][bool]$createRootDirectory = $true)
{
$item = Get-Item $sourcePath
$itemName = Split-Path $sourcePath -leaf
if (!$item.PSIsContainer){ #Item Is a file
$clientFileTime = Get-Item $sourcePath | select LastWriteTime -ExpandProperty LastWriteTime
if (!(Test-Path -Path $destinationPath\$itemName)){
Start-BitsTransfer -Source $sourcePath -Destination $destinationPath -Description "$sourcePath >> $destinationPath" -DisplayName "Copy Template file" -Confirm:$false
if (!$?){
return $false
}
}
else{
$serverFileTime = Get-Item $destinationPath\$itemName | select LastWriteTime -ExpandProperty LastWriteTime
if ($serverFileTime -lt $clientFileTime)
{
Start-BitsTransfer -Source $sourcePath -Destination $destinationPath -Description "$sourcePath >> $destinationPath" -DisplayName "Copy Template file" -Confirm:$false
if (!$?){
return $false
}
}
}
}
else{ #Item Is a directory
if ($createRootDirectory){
$destinationPath = "$destinationPath\$itemName"
if (!(Test-Path -Path $destinationPath -PathType Container)){
if (Test-Path -Path $destinationPath -PathType Leaf){ #In case item is a file, delete it.
Remove-Item -Path $destinationPath
}
New-Item -ItemType Directory $destinationPath | Out-Null
if (!$?){
return $false
}
}
}
Foreach ($fileOrDirectory in (Get-Item -Path "$sourcePath\*"))
{
$status = Copy-FilesBitsTransfer $fileOrDirectory $destinationPath $true
if (!$status){
return $false
}
}
}
return $true
}
If you have more than the last leaf directory to be created, you can either run a separate ssh ... mkdir -p
first, or use the --rsync-path
trick as explained here :
rsync -a --rsync-path="mkdir -p /tmp/x/y/z/ && rsync" $source user@remote:/tmp/x/y/z/
Or use the --relative
option as suggested by Tony. In that case, you only specify the root of the destination, which must exist, and not the directory structure of the source, which will be created:
rsync -a --relative /new/x/y/z/ user@remote:/pre_existing/dir/
This way, you will end up with /pre_existing/dir/new/x/y/z/
And if you want to have "y/z/" created, but not inside "new/x/", you can add ./
where you want --relative
to begin:
rsync -a --relative /new/x/./y/z/ user@remote:/pre_existing/dir/
would create /pre_existing/dir/y/z/.
Try this, it's called Firebug Lite and apparently works with the beta version of Chrome.
You can also find it at: https://chrome.google.com/extensions/
It is quite possible in HTML 5. Your options are: Embedded SVG and <canvas>
tag.
To draw circle in embedded SVG:
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
<circle cx="50" cy="50" r="50" fill="red" />_x000D_
</svg>
_x000D_
Circle in <canvas>
:
var canvas = document.getElementById("circlecanvas");_x000D_
var context = canvas.getContext("2d");_x000D_
context.arc(50, 50, 50, 0, Math.PI * 2, false);_x000D_
context.fillStyle = "red";_x000D_
context.fill()
_x000D_
<canvas id="circlecanvas" width="100" height="100"></canvas>
_x000D_
You could also try,
OIFS=$IFS;
IFS="\t";
animals=`cat animals.txt`
animalArray=$animals;
for animal in $animalArray
do
echo $animal
done
IFS=$OIFS;
In your script you can add the following to the lines that you know are going to give an output:
some_code 2>>/dev/null
Or else you can also try
some_code >>/dev/null
It is best to use two DateTimePickers for the Job One will be the default for the date section and the second DateTimePicker is for the time portion. Format the second DateTimePicker as follows.
timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
timePortionDateTimePicker.ShowUpDown = true;
The Two should look like this after you capture them
To get the DateTime from both these controls use the following code
DateTime myDate = datePortionDateTimePicker.Value.Date +
timePortionDateTimePicker.Value.TimeOfDay;
To assign the DateTime to both these controls use the following code
datePortionDateTimePicker.Value = myDate.Date;
timePortionDateTimePicker.Value = myDate.TimeOfDay;
If you're working with Visual Studio then follow these steps to access the IIS-Express over IP-Adress:
ipconfig
in Windows Command LineGoTo
$(SolutionDir)\.vs\config\applicationHost.config
Find
<site name="WebApplication3" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\Users\user.name\Source\Repos\protoype-one\WebApplication3" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:62549:localhost" />
</bindings>
</site>
Add:
<binding protocol="http" bindingInformation="*:62549:192.168.178.108"/>
with your IP-Adress
So, I've figured out the issue and it was a combination of bad logic and not being totally familiar with the automake/autotools world. I was adding the correct files to my Makefile.am template, but I wasn't sure which step in our build process actually created the makefile itself. So, I was compiling with an old makefile that had no idea about my new files whatsoever.
Thanks for the responses and the link to the GCC FAQ. I will be sure to read that to avoid this problem occurring for a real reason.
package com;
import java.io.File;
/**
*
* @author ?Mukesh
*/
public class ListFiles {
static File mainFolder = new File("D:\\Movies");
public static void main(String[] args)
{
ListFiles lf = new ListFiles();
lf.getFiles(lf.mainFolder);
long fileSize = mainFolder.length();
System.out.println("mainFolder size in bytes is: " + fileSize);
System.out.println("File size in KB is : " + (double)fileSize/1024);
System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
}
public void getFiles(File f){
File files[];
if(f.isFile())
System.out.println(f.getAbsolutePath());
else{
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
}
For those who are still stuck...
Using NetBeans 8.1 and GlassFish 4.1 with CDI, for some reason I had this issue only locally, not on the remote server. What did the trick:
-> using javaee-web-api 7.0 instead of the default pom version provided by NetBeans, which is javaee-web-api 6.0, so:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
-> upload this javaee-web-api-7.0.jar as a lib to on the server (lib folder in the domain1 folder) and restart the server.
Having a table with a foreign key to itself does make sense to me.
You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.
Alternatively you can create your own afxres.h:
#ifndef _AFXRES_H
#define _AFXRES_H
#if __GNUC__ >= 3
#pragma GCC system_header
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _WINDOWS_H
#include <windows.h>
#endif
/* IDC_STATIC is documented in winuser.h, but not defined. */
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif
#ifdef __cplusplus
}
#endif
#endif
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.
def load(fname):
''' Load the file using std open'''
f = open(fname,'r')
data = []
for line in f.readlines():
data.append(line.replace('\n','').split(' '))
f.close()
return data
For a text file with 4000x4000 words this is about 10 times faster than loadtxt
.
For my case (a small, personal project) https://www.lambdatest.com/ was very helpful. Free tier allows for 6 sessions per month.
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
For me I had to set the environment variable for a php application. I resloved it by adding the following code to my crontab.
$ sudo crontab -e
crontab:
ENVIRONMENT_VAR=production
* * * * * /home/deploy/my_app/cron/cron.doSomethingWonderful.php
and inside doSomethingWonderful.php I could get the environment value with:
<?php
echo $_SERVER['ENVIRONMENT_VAR']; # => "production"
I hope this helps!
Ok, this one is more complicated but it works in everything but IE<8
<div><span>text TEXT</span></div>
div {
text-align: center;
position: relative;
}
span {
display: inline-block;
}
span:before,
span:after {
border-top: 1px solid black;
display: block;
height: 1px;
content: " ";
width: 40%;
position: absolute;
left: 0;
top: 1.2em;
}
span:after {
right: 0;
left: auto;
}
The :before and :after elements are positioned absolutely so we can pull one to the left and one to the right. Also, the width (40% in this case) is very dependent of the width of the text inside.. have to think about a solution for that. At least the top: 1.2em
makes sure the lines stay more or less in the center of the text even if you have different font size.
It does seem to work well though: http://jsfiddle.net/tUGrf/3/
A nuanced explanation from the GitHub documentation on Duplicating a Repository:
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository.
Use the output annotation
@Directive({
selector: 'interval-dir',
})
class IntervalDir {
@Output() everySecond = new EventEmitter();
@Output('everyFiveSeconds') five5Secs = new EventEmitter();
constructor() {
setInterval(() => this.everySecond.emit("event"), 1000);
setInterval(() => this.five5Secs.emit("event"), 5000);
}
}
@Component({
selector: 'app',
template: `
<interval-dir (everySecond)="everySecond()" (everyFiveSeconds)="everyFiveSeconds()">
</interval-dir>
`,
directives: [IntervalDir]
})
class App {
everySecond() { console.log('second'); }
everyFiveSeconds() { console.log('five seconds'); }
}
bootstrap(App);
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
If I can give two practical examples (with a bit of "emotion").
This writes the name of all files ended with ".jpg" in the folder "img":
for f in *; do if [ "${f#*.}" == 'jpg' ]; then echo $f; fi; done
This deletes them:
for f in *; do if [ "${f#*.}" == 'jpg' ]; then rm -r $f; fi; done
Just trying to contribute.
def trim(x):
if x.dtype == object:
x = x.str.split(' ').str[0]
return(x)
df = df.apply(trim)
select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;
That's the simplest one without doing sub queries
For multiple elements, you should give it a class rather than id eg:
<input type="text" class="task" name="task[]" />
Now you can get those using jquery something like this:
$('.task').each(function(){
alert($(this).val());
});
#include <stdbool.h>
For someone like me here to copy and paste.
All JavaBeans are POJOs but not all POJOs are JavaBeans.
A JavaBean is a Java object that satisfies certain programming conventions:
There is some difference when we define the properties in the application.properties and application yaml.
In application.yml :
spring:
http:
multipart:
max-file-size: 256KB
max-request-size: 256KB
And in application.propeties :
spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB
Note : Spring version 4.3 and Spring boot 1.4
Don't use regexes, use BeautifulSoup. That, or be so crufty as to spawn it out to, say, w3m/lynx and pull back in what w3m/lynx renders. First is more elegant probably, second just worked a heck of a lot faster on some unoptimized code I wrote a while back.
with php you can use two redirections. It works same as refresh in some issues.
you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.
like this: your page:
<?php
header("location:redirec.php?ref=".$your_url);
?>
redirect.php:
<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>
that worked for me good.
The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.
Instead, use sos (second-order sections) output of filter design.
from scipy.signal import butter, sosfilt, sosfreqz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y
Also, you can plot frequency response by changing
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
to
sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)
Example without any XML
Put your image image_name.jpg
into res/drawable/image_name.jpg
and use:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.image_name);
setContentView(imageView);
}
}
Tested on Android 22.
If you are trying to view an extensionless file what worked for me was adding a MIME Type
: File name extension: .
MIME type: text/plain
This might have some MVC implications, especially if your Static File Handler
is above the Extensionless...
handlers (under IIS
/ Handler Mappings
) but might be a work around when you only need this temporarily, like activating SSL Certs.
Like this:
Set<T> mySet = new HashSet<>(Arrays.asList(someArray));
In Java 9+, if unmodifiable set is ok:
Set<T> mySet = Set.of(someArray);
In Java 10+, the generic type parameter can be inferred from the arrays component type:
var mySet = Set.of(someArray);
If you are using Windows,
make a folder and open git bash from there
in the git bash,
git clone [email protected]:Example/projectName.git
I figured this might come in handy for others as well :
find:
([A-Z])(.*)
replace:
\L$1$2
--> will convert all letters in $1
and $2
to lowercase\l$1$2
--> will only convert the first letter of $1
to lowercase and leave everything else as isThe same goes for uppercase with \U
and \u
If you wanted to make a global static variable:
var my_id = 123;
Replace the variable with the below:
Object.defineProperty(window, 'my_id', {
get: function() {
return 123;
},
configurable : false,
enumerable : false
});
^\d*[1-9]\d*$
this can include all positive values, even if it is padded by Zero in the front
Allows
1
01
10
11 etc
do not allow
0
00
000 etc..
First 10 customers inserted into db (table customers):
select * from customers where customer_id <=
(select min(customer_id)+10 from customers)
Last 10 customers inserted into db (table customers):
select * from customers where customer_id >=
(select max(customer_id)-10 from customers)
Hope this helps....
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
$_SERVER['HTTP_REFERER']
will give you incomplete url.
If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php
, $_SERVER['HTTP_REFERER']
will give you http://bawse.3owl.com/
only.
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
To see what's inside these HKCR\Licenses use API Monitor v2
API-Filter find
RegQueryValueExW
^-Enable all from Advapi32.dll
CryptUnprotectData
^- Enable all from Crypt32.dll
+ Breakpoint / after Call
sample data that'll come out from CryptUnprotectData:
HKEY_CLASSES_ROOT\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F\07078 [length 0x1C6 (0454.) ]
00322-20000-00000-AA450 <- PID2
7d3cbcbb-90b1-411f-9981-6e28039a9b82 <- Ver
7C3WXN74-VRMXH-J8X3H-M8F7W-CPQB8 <- PID3
HKEY_CLASSES_ROOT\Licenses\4D8CFBCB-2F6A-4AD2-BABF-10E28F6F2C8F\0bcad [length 0xbcad (0534.) ]
0000 00000025 ffffffff 7fffffff 07064. 00000007 07078. 00000007 ffffffff
0020 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
0040 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
0060 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
0080 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
00a0 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
00c0 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
00e0 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
0100 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff 7fffffff ffffffff
0120 7fffffff ffffffff 7fffffff 10.2015. c2a6 11.
0134 ^installation date^
Useful here is maybe the Installation timestamp (11.10.2015 here ) Change this would required to call 'CryptProtectData'. Doing so needs some efforts like written a small program OR stop with ollydebug at this place and manually 'crafting' a CryptProtectData call ...
Note: In this example I'm using Microsoft® Visual Studio 2015
-> For a quick'n'dirty sneak into an expired VS I recommend to read this post. However that's just good for occasional use, till you get all the sign up and login crap properly done again ;)
Okay the real meat is here:
%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\Licenses\
^- This path comes from HKCU\Software\Microsoft\VisualStudio\14.0\Licenses\715f10eb-9e99-11d2-bfc2-00c04f990235\1
1_3jdh3uyw**.crtok**
-after some Base64 decoding:
<ClientRightsContainer
xmlns="http://schemas.datacontract.org/2004/07/Microsoft.VisualStudio.Services.Licensing"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<CertificateBytes>
00000000 30 82 06 41 30 82 04 29 A0 03 02 01 02 02 13 5A 0‚ A0‚ ) Z
00000010 00 00 BC CB 23 AC 52 9C E8 93 F9 0A 00 01 00 00 ¼Ë#¬Rœè“ù
00000020 BC CB 30 0D 06 09 2A 86 48 86 F7 0D 01 01 0B 05 ¼Ë0 *†H†÷
00000030 00 30 81 8B 31 0B 30 09 06 03 55 04 06 13 02 55 0 ‹1 0 U U
00000040 53 31 13 30 11 06 03 55 04 08 13 0A 57 61 73 68 S1 0 U Wash
00000050 69 6E 67 74 6F 6E 31 10 30 0E 06 03 55 04 07 13 ington1 0 U
00000060 07 52 65 64 6D 6F 6E 64 31 1E 30 1C 06 03 55 04 Redmond1 0 U
00000070 0A 13 15 4D 69 63 72 6F 73 6F 66 74 20 43 6F 72 Microsoft Cor
00000080 70 6F 72 61 74 69 6F 6E 31 15 30 13 06 03 55 04 poration1 0 U
00000090 0B 13 0C 4D 69 63 72 6F 73 6F 66 74 20 49 54 31 Microsoft IT1
000000A0 1E 30 1C 06 03 55 04 03 13 15 4D 69 63 72 6F 73 0 U Micros
000000B0 6F 66 74 20 49 54 20 53 53 4C 20 53 48 41 32 30 oft IT SSL SHA20
000000C0 1E 17 0D 31 35 30 33 30 35 32 31 32 39 35 36 5A 150305212956Z
000000D0 17 0D 31 37 30 33 30 34 32 31 32 39 35 36 5A 30 170304212956Z0
000000E0 25 31 23 30 21 06 03 55 04 03 13 1A 61 70 70 2E %1#0! U app.
000000F0 76 73 73 70 73 2E 76 69 73 75 61 6C 73 74 75 64 vssps.visualstud
00000100 69 6F 2E 63 6F 6D 30 82 01 22 30 0D 06 09 2A 86 io.com0‚ "0 *†
...
000002B0 6E 86 36 68 74 74 70 3A 2F 2F 6D 73 63 72 6C 2E n†6http://mscrl.
000002C0 6D 69 63 72 6F 73 6F 66 74 2E 63 6F 6D 2F 70 6B microsoft.com/pk
000002D0 69 2F 6D 73 63 6F 72 70 2F 63 72 6C 2F 6D 73 69 i/mscorp/crl/msi
000002E0 74 77 77 77 32 2E 63 72 6C 86 34 68 74 74 70 3A twww2.crl†4http:
000002F0 2F 2F 63 72 6C 2E 6D 69 63 72 6F 73 6F 66 74 2E //crl.microsoft.
00000300 63 6F 6D 2F 70 6B 69 2F 6D 73 63 6F 72 70 2F 63 com/pki/mscorp/c
00000310 72 6C 2F 6D 73 69 74 77 77 77 32 2E 63 72 6C 30 rl/msitwww2.crl0
00000320 70 06 08 2B 06 01 05 05 07 01 01 04 64 30 62 30 p + d0b0
00000330 3C 06 08 2B 06 01 05 05 07 30 02 86 30 68 74 74 < + 0 †0htt
00000340 70 3A 2F 2F 77 77 77 2E 6D 69 63 72 6F 73 6F 66 p://www.microsof
00000350 74 2E 63 6F 6D 2F 70 6B 69 2F 6D 73 63 6F 72 70 t.com/pki/mscorp
00000360 2F 6D 73 69 74 77 77 77 32 2E 63 72 74 30 22 06 /msitwww2.crt0"
00000370 08 2B 06 01 05 05 07 30 01 86 16 68 74 74 70 3A + 0 † http:
00000380 2F 2F 6F 63 73 70 2E 6D 73 6F 63 73 70 2E 63 6F //ocsp.msocsp.co
00000390 6D 30 4E 06 03 55 1D 20 04 47 30 45 30 43 06 09 m0N U G0E0C
000003A0 2B 06 01 04 01 82 37 2A 01 30 36 30 34 06 08 2B + ‚7* 0604 +
000003B0 06 01 05 05 07 02 01 16 28 68 74 74 70 3A 2F 2F (http://
000003C0 77 77 77 2E 6D 69 63 72 6F 73 6F 66 74 2E 63 6F www.microsoft.co
000003D0 6D 2F 70 6B 69 2F 6D 73 63 6F 72 70 2F 63 70 73 m/pki/mscorp/cps
000003E0 00 30 27 06 09 2B 06 01 04 01 82 37 15 0A 04 1A 0' + ‚7
000003F0 30 18 30 0A 06 08 2B 06 01 05 05 07 03 01 30 0A 0 0 + 0
00000400 06 08 2B 06 01 05 05 07 03 02 30 25 06 03 55 1D + 0% U
00000410 11 04 1E 30 1C 82 1A 61 70 70 2E 76 73 73 70 73 0 ‚ app.vssps
00000420 2E 76 69 73 75 61 6C 73 74 75 64 69 6F 2E 63 6F .visualstudio.co
00000430 6D 30 0D 06 09 2A 86 48 86 F7 0D 01 01 0B 05 00 m0 *†H†÷
... U
</CertificateBytes>
<Token>
{
"typ":"JWT",
"alg":"RS256",
"x5t":"i7qX-NUrehXBYdQC5PSH-TdvzXA"
}
</Token>
</ClientRightsContainer>
Seems M$ is using JSON Web Token (JWT) to wrap in license data. I guess inside CertificateBytes will be somehow the payload - you're email and other details.
So far for the rough overview what's the data inside.
For more wishes get ILSpy + Reflexil (<- to changes/correct little things!) and then 'browser&correct' files like c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE**Microsoft.VisualStudio.Licensing.dll** or check out 'Microsoft.VisualStudio.Services.WebApi.dll'
This should work:
Regex.IsMatch("124", "^[0-9]+$", RegexOptions.Compiled)
int.Parse
or int.TryParse
won't always work, because the string might contain more digits that an int can hold.
If you are going to do this check more than once it is useful to use a compiled regex - it takes more time the first time, but is much faster after that.
I think you just have it backwards.
print ", ".join(set_3)
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
Nevermind. I was making this way more complicated than it really needed to be.
This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.
public override void Up()
{
RenameTable("ReportSections", "ReportPages");
RenameTable("ReportSectionGroups", "ReportSections");
RenameColumn("ReportPages", "Group_Id", "Section_Id");
}
public override void Down()
{
RenameColumn("ReportPages", "Section_Id", "Group_Id");
RenameTable("ReportSections", "ReportSectionGroups");
RenameTable("ReportPages", "ReportSections");
}
a[href^=tel]{
color:inherit;
text-decoration: inherit;
font-size:inherit;
font-style:inherit;
font-weight:inherit;
Try this:
$(document).ready(function(){
var yourArray = [];
$("span.HOEnZb").find("div").each(function(){
if(($.trim($(this).text()).length>0)){
yourArray.push($(this).text());
}
});
});
Also, if you have a variable,
CabRes::where('m_Id', 46)
->where('t_Id', 2)
->where(function($q) use ($variable){
$q->where('Cab', 2)
->orWhere('Cab', $variable);
})
->get();
If you need run code after 100% loaded with image and files, test this in mounted()
:
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log('Page completed with image and files!')
// fetch to next page or some code
}
}
More info: MDN Api onreadystatechange
I was also facing the same issue where I was receiving the Transaction_Date as YYYYMMDD in bigint format. So I converted it into Datetime format using below query and saved it in new column with datetime format. I hope this will help you as well.
SELECT
convert( Datetime, STUFF(STUFF(Transaction_Date, 5, 0, '-'), 8, 0, '-'), 120) As [Transaction_Date_New]
FROM mydb
"Select in project View"
Little to no memorization required, reusable for every action in Intellij:
Use Find Action:
+1 on S.Lott's suggestion of a named container class.
For Python 2.6 and up, a named tuple provides a useful way of easily creating these container classes, and the results are "lightweight and require no more memory than regular tuples".
It should be like that
public static void main(String[] args) {
EchoServer0 e = new EchoServer0();
// TODO Auto-generated method stub
e.listen();
}
Your variable of type Object
truly doesn't have such a method, but the type EchoServer0
you define above certainly has.
For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:
// Didn't work
<div>
<TroubledComponent/>
</div>
// Worked
<div key='uniqueKey'>
<TroubledComponent/>
</div>
You need to add your TextView in a ScrollView with something like this :
<ScrollView android:id="@+id/SCROLL_VIEW"
android:layout_height="150px"
android:layout_width="fill_parent">
<TextView
android:id="@+id/TEXT_VIEW"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="This text view should act as header This text view should act as header This text view should act as header This text view should act as header This text view should act as header This text view should act as header This text view should act as header" />
</ScrollView>
Right click your maven project in bottom of the drop down list Maven >> reimport
it works for me for the missing dependancyies
Move your .android
to wherever you want it to.
Then, create a symlink like this:
# In your home folder
$ ln -s /path/to/.android/ .
This simply tells Linux that whenever the path ~/.android
is referenced by any application, link it to /path/to/.android
.
String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)
In your case it will be:
String formatted = String.format("%03d", num);
Try this
<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>
You could also use this:
$('.slider').slick({
//other settings ................
respondTo: 'slider', //makes the slider to change width depending on the container it is in
adaptiveHeight: true //makes the height change depending on the height of the element inside
})
Since this question has become a standard question for breaking into a particular loop, I would like to give my answer with example using Exception
.
Although there exists no label named breaking of loop in multipally looped construct, we can make use of User-defined Exceptions to break into a particular loop of our choice. Consider the following example where let us print all numbers upto 4 digits in base-6 numbering system:
class BreakLoop(Exception):
def __init__(self, counter):
Exception.__init__(self, 'Exception 1')
self.counter = counter
for counter1 in range(6): # Make it 1000
try:
thousand = counter1 * 1000
for counter2 in range(6): # Make it 100
try:
hundred = counter2 * 100
for counter3 in range(6): # Make it 10
try:
ten = counter3 * 10
for counter4 in range(6):
try:
unit = counter4
value = thousand + hundred + ten + unit
if unit == 4 :
raise BreakLoop(4) # Don't break from loop
if ten == 30:
raise BreakLoop(3) # Break into loop 3
if hundred == 500:
raise BreakLoop(2) # Break into loop 2
if thousand == 2000:
raise BreakLoop(1) # Break into loop 1
print('{:04d}'.format(value))
except BreakLoop as bl:
if bl.counter != 4:
raise bl
except BreakLoop as bl:
if bl.counter != 3:
raise bl
except BreakLoop as bl:
if bl.counter != 2:
raise bl
except BreakLoop as bl:
pass
When we print the output, we will never get any value whose unit place is with 4. In that case, we don't break from any loop as BreakLoop(4)
is raised and caught in same loop. Similarly, whenever ten place is having 3, we break into third loop using BreakLoop(3)
. Whenever hundred place is having 5, we break into second loop using BreakLoop(2)
and whenver the thousand place is having 2, we break into first loop using BreakLoop(1)
.
In short, raise your Exception (in-built or user defined) in the inner loops, and catch it in the loop from where you want to resume your control to. If you want to break from all loops, catch the Exception outside all the loops. (I have not shown this case in example).
Delete the line /*# sourceMappingURL=bootstrap.css.map */
from bootstrap.css
After going back into the installer & checking off "Management Tools", ssms.exe was available under "C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio" (thanks to everyone for pointing out where to find it).
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
Or you can use
public void setSupportedMediaTypes(List supportedMediaTypes)
method which belongs to AbstractHttpMessageConverter<T>
, to add some ContentTypes
you like. This way can let the MappingJackson2HttpMessageConverter
canRead()
your response, and transform it to your desired Class, which on this case,is ProductList Class.
and I think this step should hooked up with the Spring Context initializing. for example, by using
implements ApplicationListener { ... }
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE @strInt varchar(255)
SET @strInt = CAST(@int as varchar(255))
RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
I just have the same situation as you and I have just fixed this problem.
my conf/zoo.cfg
just like this:
server.1=10.194.236.32:2888:3888
server.2=10.194.236.33:2888:3888
server.3=10.208.177.15:2888:3888
server.4=10.210.154.23:2888:3888
server.5=10.210.154.22:2888:3888
then i set data/myid
file content like this:
1 //at host 10.194.236.32
2 //at host 10.194.236.33
3 //at host 10.208.177.15
4 //at host 10.210.154.23
5 //at host 10.210.154.22
finally restart zookeeper
if (file.split(".")[1] == "mp3"):
print "its mp3"
elif (file.split(".")[1] == "flac"):
print "its flac"
else:
print "not compat"
In addition to the excellent answers, I would like to emphasize here when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.
The answer is really simple
res.end() is used to quickly end the response without sending any data.
An example for this would be starting a process on a server
app.get(/start-service, (req, res) => {
// Some logic here
exec('./application'); // dummy code
res.end();
});
If you would like to send data in your response then you should use res.send() instead
app.get(/start-service, (req, res) => {
res.send('{"age":22}');
});
Here you can read more
It is possible to use setOnKeyListener
. In this method, we can customize the input edittext
!
I noticed no one has mentioned achieving this through environment variables (CI/CD friendly).
export PLAY_HTTP_PORT=1234
export PLAY_HTTPS_PORT=1235
Once set, Play will read from those environment variables to determine the port when doing sbt run
, sbt start
, or when running the executable for prod deployment. See the docs for more.
According to the book PHP and MySQL for Dynamic Web Sites (4th edition)
Example:
$r = mysqli_query($dbc, $q);
For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r
variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.
Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.
Then how to test?
While the mysqli_num_rows()
function will return the number of rows generated by a SELECT query, mysqli_affected_rows()
returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:
$num = mysqli_affected_rows($dbc);
Unlike mysqli_num_rows()
, the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).
If you aren't using an auto-filter (i.e. you have manually hidden rows), you will need to use the AGGREGATE
function instead of SUBTOTAL
.
db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}})
You can also use NumberLong.
check out
http://www.thesitewizard.com/general/set-cron-job.shtml
for the specifics of setting your crontab directives.
45 10 * * *
will run in the 10th hour, 45th minute of every day.
for midnight... maybe
0 0 * * *
The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:
var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
The code above depends on the nuget package RestSharp, which you can easily install.
First of all, your dao.find()
should either return an Optional<Obj>
or you will have to create one.
e.g.
Optional<Obj> = dao.find();
or you can do it yourself like:
Optional<Obj> = Optional.ofNullable(dao.find());
this one will return Optional<Obj>
if present or Optional.empty()
if not present.
So now let's get to the solution,
public Obj getObjectFromDB() {
return Optional.ofNullable(dao.find()).flatMap(ob -> {
ob.setAvailable(true);
return Optional.of(ob);
}).orElseGet(() -> {
logger.fatal("Object not available");
return null;
});
}
This is the one liner you're looking for :)